epics-ca-rs 0.16.2

EPICS Channel Access protocol client and server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Helpers shared across the `caget` / `caput` / `cainfo` / `camonitor`
//! command-line binaries.

use epics_base_rs::types::EpicsValue;

/// Read `EPICS_CLI_TIMEOUT` from the environment, falling back to 1.0 s
/// when unset or unparsable. Mirrors C `tool_lib.c:use_ca_timeout_env`
/// (commit 1d056c6) — the env var is consulted only when the caller
/// did not pass `-w`/`--wait` on the command line.
pub fn env_default_timeout() -> f64 {
    std::env::var("EPICS_CLI_TIMEOUT")
        .ok()
        .and_then(|s| s.parse::<f64>().ok())
        .unwrap_or(1.0)
}

/// Field width the C tools (`caget` / `camonitor` / `caput -l`) use
/// when printing the PV name column: `printf("%-30s ...", name)` —
/// 30 chars left-aligned, then one space before the value. Mirrors
/// `epics-base/modules/ca/src/tools/tool_lib.c::print_value`'s width.
pub const PV_NAME_WIDTH: usize = 30;

/// Float number representation requested via `-e` / `-f` / `-g`.
#[derive(Debug, Clone, Copy)]
pub enum FloatStyle {
    /// `%g` — shortest of `%f` / `%e`. C tools default. Precision is
    /// the count of *significant* digits.
    G,
    /// `%e` — scientific notation. Precision is digits after decimal.
    E,
    /// `%f` — fixed-point. Precision is digits after decimal.
    F,
}

/// Float formatting options. C precision defaults to 6 for all three
/// styles per `printf(3)`.
#[derive(Debug, Clone, Copy)]
pub struct FloatFormat {
    pub style: FloatStyle,
    pub precision: u32,
}

impl Default for FloatFormat {
    fn default() -> Self {
        Self {
            style: FloatStyle::G,
            precision: 6,
        }
    }
}

/// Integer formatting requested via `-0x` / `-0o` / `-0b` (base for
/// integer types) and `-lx` / `-lo` / `-lb` (round-float-to-long
/// then print in base). C tool default is decimal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IntStyle {
    Dec,
    Hex,
    Oct,
    Bin,
}

/// Per-tool CLI formatting state.
#[derive(Debug, Clone)]
pub struct ValueFormat {
    pub float: FloatFormat,
    pub int_style: IntStyle,
    /// Round-float-to-long-and-render in `int_style` (the `-lx` / `-lo`
    /// / `-lb` C-tool flags). Only applies to floating-point values.
    pub float_as_int: bool,
    /// `-n` flag: print enum value as its integer index instead of
    /// the menu string.
    pub enum_as_number: bool,
    /// `-S` flag: render `DBR_CHAR` arrays as a NUL-terminated string
    /// (long-string CA convention).
    pub char_array_as_string: bool,
    /// `-# <count>` flag: cap displayed array elements; `None` means
    /// "all". Acts on display only — the request still asks for the
    /// requested count from the IOC.
    pub max_elements: Option<usize>,
    /// `-F <ofs>` flag: replacement field separator. Defaults to a
    /// single space.
    pub field_separator: char,
}

impl Default for ValueFormat {
    fn default() -> Self {
        Self {
            float: FloatFormat::default(),
            int_style: IntStyle::Dec,
            float_as_int: false,
            enum_as_number: false,
            char_array_as_string: false,
            max_elements: None,
            field_separator: ' ',
        }
    }
}

/// Render `EpicsValue` for CA tool output, matching C `tool_lib.c::
/// print_value`. Scalars are bare (no count prefix); arrays are
/// `count<sep>v0<sep>v1...` (the count is part of the value, not the
/// PV-name column). Enum strings are NOT resolved here — caller passes
/// `enum_strings = Some(&["off","on",...])` when it has them, else
/// the integer index is used (matches `-n` flag default when no enum
/// metadata is available). `format_value` does not emit a trailing
/// newline.
pub fn format_value(v: &EpicsValue, fmt: &ValueFormat, enum_strings: Option<&[String]>) -> String {
    let sep = fmt.field_separator;
    match v {
        EpicsValue::String(s) => s.clone(),
        EpicsValue::Short(n) => format_int_i64(*n as i64, fmt.int_style),
        EpicsValue::Long(n) => format_int_i64(*n as i64, fmt.int_style),
        EpicsValue::Int64(n) => format_int_i64(*n, fmt.int_style),
        EpicsValue::Char(n) => format_int_i64((*n as i8) as i64, fmt.int_style),
        EpicsValue::Enum(idx) => format_enum(*idx as i64, fmt, enum_strings),
        EpicsValue::Float(x) => format_float(*x as f64, fmt),
        EpicsValue::Double(x) => format_float(*x, fmt),
        EpicsValue::ShortArray(arr) => {
            render_array_int(arr.iter().map(|&n| n as i64), arr.len(), fmt, sep)
        }
        EpicsValue::LongArray(arr) => {
            render_array_int(arr.iter().map(|&n| n as i64), arr.len(), fmt, sep)
        }
        EpicsValue::Int64Array(arr) => render_array_int(arr.iter().copied(), arr.len(), fmt, sep),
        EpicsValue::EnumArray(arr) => {
            let mut parts = Vec::with_capacity(arr.len() + 1);
            parts.push(arr.len().to_string());
            let take = fmt.max_elements.unwrap_or(arr.len()).min(arr.len());
            for &idx in &arr[..take] {
                parts.push(format_enum(idx as i64, fmt, enum_strings));
            }
            parts.join(&sep.to_string())
        }
        EpicsValue::FloatArray(arr) => render_array_iter(
            arr.iter().map(|&x| format_float(x as f64, fmt)),
            arr.len(),
            fmt,
            sep,
        ),
        EpicsValue::DoubleArray(arr) => render_array_iter(
            arr.iter().map(|&x| format_float(x, fmt)),
            arr.len(),
            fmt,
            sep,
        ),
        EpicsValue::CharArray(arr) => {
            if fmt.char_array_as_string {
                // Long-string convention: bytes up to first NUL.
                let end = arr.iter().position(|&b| b == 0).unwrap_or(arr.len());
                String::from_utf8_lossy(&arr[..end]).into_owned()
            } else {
                render_array_int(arr.iter().map(|&b| (b as i8) as i64), arr.len(), fmt, sep)
            }
        }
        EpicsValue::StringArray(arr) => {
            let mut parts = Vec::with_capacity(arr.len() + 1);
            parts.push(arr.len().to_string());
            let take = fmt.max_elements.unwrap_or(arr.len()).min(arr.len());
            parts.extend(arr[..take].iter().cloned());
            parts.join(&sep.to_string())
        }
    }
}

fn render_array_int<I: Iterator<Item = i64>>(
    iter: I,
    total: usize,
    fmt: &ValueFormat,
    sep: char,
) -> String {
    let take = fmt.max_elements.unwrap_or(total).min(total);
    let mut parts = Vec::with_capacity(take + 1);
    parts.push(total.to_string());
    for n in iter.take(take) {
        parts.push(format_int_i64(n, fmt.int_style));
    }
    parts.join(&sep.to_string())
}

fn render_array_iter<I: Iterator<Item = String>>(
    iter: I,
    total: usize,
    fmt: &ValueFormat,
    sep: char,
) -> String {
    let take = fmt.max_elements.unwrap_or(total).min(total);
    let mut parts = Vec::with_capacity(take + 1);
    parts.push(total.to_string());
    parts.extend(iter.take(take));
    parts.join(&sep.to_string())
}

fn format_enum(idx: i64, fmt: &ValueFormat, enum_strings: Option<&[String]>) -> String {
    if !fmt.enum_as_number
        && let Some(strs) = enum_strings
        && idx >= 0
        && (idx as usize) < strs.len()
    {
        return strs[idx as usize].clone();
    }
    format_int_i64(idx, fmt.int_style)
}

fn format_int_i64(n: i64, style: IntStyle) -> String {
    match style {
        IntStyle::Dec => n.to_string(),
        // C `%lx` / `%lo` / `%lb` print the bit pattern of a signed
        // integer reinterpreted as unsigned of the same width. We
        // emulate that with the `as u64` cast.
        IntStyle::Hex => format!("0x{:x}", n as u64),
        IntStyle::Oct => format!("0o{:o}", n as u64),
        IntStyle::Bin => format!("0b{:b}", n as u64),
    }
}

fn format_float(x: f64, fmt: &ValueFormat) -> String {
    if fmt.float_as_int {
        // C tool: round-half-to-even via `lroundl`, then format as int.
        let rounded = if x.is_nan() { 0i64 } else { x.round() as i64 };
        return format_int_i64(rounded, fmt.int_style);
    }
    if !x.is_finite() {
        // C printf prints "nan" / "inf" / "-inf"; Rust matches by
        // default (`{}` on f64 yields the same lowercase forms).
        return format!("{x}");
    }
    let p = fmt.float.precision as usize;
    match fmt.float.style {
        FloatStyle::F => format!("{x:.p$}"),
        FloatStyle::E => format_e(x, p),
        FloatStyle::G => format_g(x, p.max(1)),
    }
}

/// `%g`-equivalent formatter. C semantics: choose `%e` or `%f`
/// depending on the exponent, drop trailing zeros and the trailing
/// decimal point. Precision is the *significant-digit* count.
fn format_g(x: f64, precision: usize) -> String {
    if x == 0.0 {
        return "0".to_string();
    }
    let abs = x.abs();
    let exp = abs.log10().floor() as i32;
    // C `%g` uses fixed-point when `precision > exp >= -4`. Compare as
    // i32 to avoid the silent `i32 → usize` wrap for negative `exp`.
    if exp >= -4 && exp < precision as i32 {
        // Fixed-point. Digits after the decimal point = precision-1-exp.
        let digits = (precision as i32 - 1 - exp).max(0) as usize;
        let s = format!("{x:.digits$}");
        trim_g_fixed(&s)
    } else {
        format_g_scientific(x, precision)
    }
}

fn trim_g_fixed(s: &str) -> String {
    if !s.contains('.') {
        return s.to_string();
    }
    s.trim_end_matches('0').trim_end_matches('.').to_string()
}

fn format_g_scientific(x: f64, precision: usize) -> String {
    // Rust `{:e}` precision means digits after the decimal in the
    // mantissa. C `%g` with N significant digits is mantissa
    // precision N-1.
    let s = format!("{:.*e}", precision - 1, x);
    rewrite_rust_e_as_c(&s, true)
}

/// Pure `%e`: precision is digits AFTER the decimal point.
fn format_e(x: f64, precision: usize) -> String {
    let s = format!("{x:.precision$e}");
    rewrite_rust_e_as_c(&s, false)
}

/// Rust formats scientific as `1.23e2`; C as `1.23e+02` (signed,
/// 2-digit exponent minimum). Optionally also strips the trailing
/// zeros from the mantissa (the `%g` post-trim behaviour).
fn rewrite_rust_e_as_c(s: &str, trim_mantissa: bool) -> String {
    let Some(e_pos) = s.find('e') else {
        return s.to_string();
    };
    let mantissa = &s[..e_pos];
    let exp_part = &s[e_pos + 1..];
    let mantissa_out = if trim_mantissa && mantissa.contains('.') {
        let t = mantissa.trim_end_matches('0').trim_end_matches('.');
        t.to_string()
    } else {
        mantissa.to_string()
    };
    let (sign, digits) = if let Some(d) = exp_part.strip_prefix('-') {
        ('-', d)
    } else if let Some(d) = exp_part.strip_prefix('+') {
        ('+', d)
    } else {
        ('+', exp_part)
    };
    let exp_padded = if digits.len() < 2 {
        format!("{sign}0{digits}")
    } else {
        format!("{sign}{digits}")
    };
    format!("{mantissa_out}e{exp_padded}")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fmt_default() -> ValueFormat {
        ValueFormat::default()
    }

    #[test]
    fn g_default_precision_matches_c() {
        // C `printf("%g", 475.123)` → "475.123"
        assert_eq!(format_g(475.123, 6), "475.123");
        // C `printf("%g", 1.0)` → "1"
        assert_eq!(format_g(1.0, 6), "1");
        // C `printf("%g", 0.0)` → "0"
        assert_eq!(format_g(0.0, 6), "0");
        // C `printf("%g", 1e-5)` → "1e-05"
        assert_eq!(format_g(1e-5, 6), "1e-05");
        // C `printf("%g", 1e10)` → "1e+10"
        assert_eq!(format_g(1e10, 6), "1e+10");
        // C `printf("%g", 0.0001)` → "0.0001" (boundary)
        assert_eq!(format_g(0.0001, 6), "0.0001");
        // C `printf("%g", 1234567.0)` → "1.23457e+06"
        assert_eq!(format_g(1234567.0, 6), "1.23457e+06");
    }

    #[test]
    fn e_format_matches_c() {
        // C `printf("%e", 1.5)` → "1.500000e+00"
        assert_eq!(format_e(1.5, 6), "1.500000e+00");
        // C `printf("%.2e", 1234.5)` → "1.23e+03"
        assert_eq!(format_e(1234.5, 2), "1.23e+03");
    }

    #[test]
    fn negative_int_hex_matches_c() {
        // C `printf("%lx", (long)-1)` → "ffffffffffffffff"
        assert_eq!(format_int_i64(-1, IntStyle::Hex), "0xffffffffffffffff");
    }

    #[test]
    fn array_renders_count_then_values() {
        let v = EpicsValue::DoubleArray(vec![1.0, 2.5, 3.0]);
        let s = format_value(&v, &fmt_default(), None);
        // C: `3 1 2.5 3` (count + space-separated %g values)
        assert_eq!(s, "3 1 2.5 3");
    }

    #[test]
    fn enum_with_strings_renders_string() {
        let strs = vec!["off".to_string(), "on".to_string()];
        let v = EpicsValue::Enum(1);
        let s = format_value(&v, &fmt_default(), Some(&strs));
        assert_eq!(s, "on");
    }

    #[test]
    fn enum_n_flag_renders_index() {
        let strs = vec!["off".to_string(), "on".to_string()];
        let v = EpicsValue::Enum(1);
        let mut fmt = fmt_default();
        fmt.enum_as_number = true;
        let s = format_value(&v, &fmt, Some(&strs));
        assert_eq!(s, "1");
    }

    #[test]
    fn char_array_long_string_strips_at_nul() {
        let v = EpicsValue::CharArray(b"hello\0xxxx".to_vec());
        let mut fmt = fmt_default();
        fmt.char_array_as_string = true;
        assert_eq!(format_value(&v, &fmt, None), "hello");
    }

    #[test]
    fn float_as_int_rounds_then_renders() {
        let v = EpicsValue::Double(1234.6);
        let mut fmt = fmt_default();
        fmt.float_as_int = true;
        fmt.int_style = IntStyle::Hex;
        // 1235 = 0x4d3
        assert_eq!(format_value(&v, &fmt, None), "0x4d3");
    }

    #[test]
    fn pv_name_width_constant_is_30() {
        // Lock the pad width so a future tweak gets caught.
        assert_eq!(PV_NAME_WIDTH, 30);
    }

    #[test]
    fn max_elements_caps_array() {
        let v = EpicsValue::LongArray((0..10).collect());
        let mut fmt = fmt_default();
        fmt.max_elements = Some(3);
        let s = format_value(&v, &fmt, None);
        // Total count is full (10) per C `caget -# 3` behaviour:
        //   "10 0 1 2"
        assert_eq!(s, "10 0 1 2");
    }
}