epics-base-rs 0.20.4

Pure Rust EPICS IOC core — record system, database, iocsh, calc engine
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
use crate::error::{CaError, CaResult};
use crate::server::record::{FieldDesc, FieldMetadataOverride, ProcessOutcome, Record};
use crate::types::{DbFieldType, EpicsValue, PvString};

/// Number of aSub channels. C `aSubRecord.c`: `NUM_ARGS == 21`
/// (inputs `A..U`, outputs `VALA..VALU`).
const NUM_ARGS: usize = 21;

/// `menuFtype` index for `DOUBLE`. C `aSubRecord` initialises every
/// `FTx`/`FTVx` to `DOUBLE`.
const FTYPE_DOUBLE: i16 = 10;

/// The per-channel suffix letters `A..U`.
const SUFFIX: [char; NUM_ARGS] = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
    'T', 'U',
];

/// `EFLG` (`menu(aSubEFLG)`) — when the record posts output-array DB events.
/// C `aSubRecord.c::monitor` (the `switch (prec->eflg)`).
const EFLG_NEVER: i16 = 0;
const EFLG_ON_CHANGE: i16 = 1;
const EFLG_ALWAYS: i16 = 2;

/// `menu(aSubEFLG)` choice labels (`aSubRecord.dbd.pod`).
const ASUB_EFLG_CHOICES: &[&str] = &["NEVER", "ON CHANGE", "ALWAYS"];

/// `menu(aSubLFLG)` choice labels (`aSubRecord.dbd.pod`): IGNORE=0 (resolve
/// SNAM once at init), READ=1 (re-read the name from the SUBL link every
/// process). The READ behaviour is owned by the processing path
/// (`fetch_values`), which holds the link + subroutine registry.
const ASUB_LFLG_CHOICES: &[&str] = &["IGNORE", "READ"];

/// The output-array fields whose monitor posting `EFLG` gates: `VALA..VALU`
/// (the output values) and `NEVA..NEVU` (their element counts). C
/// `aSubRecord.c::monitor` posts `vala[i]` and `neva[i]` together inside the
/// `EFLG` switch. Leaked once for the `'static` lifetime the posting hooks
/// require (mirrors `multi_input_links`).
fn asub_output_event_fields() -> &'static [&'static str] {
    use std::sync::OnceLock;
    static FIELDS: OnceLock<Vec<&'static str>> = OnceLock::new();
    FIELDS.get_or_init(|| {
        SUFFIX
            .iter()
            .flat_map(|&c| {
                [
                    Box::leak(format!("VAL{c}").into_boxed_str()) as &'static str,
                    Box::leak(format!("NEV{c}").into_boxed_str()) as &'static str,
                ]
            })
            .collect()
    })
}

/// aSub (array subroutine) record.
///
/// C `aSubRecord.c` exposes 21 input channels `A..U` (fed from
/// `INPA..INPU`) and 21 output channels `VALA..VALU` (driven to
/// `OUTA..OUTU`). Each channel has:
///   * `FTx` / `FTVx` — `menuFtype` element type;
///   * `NOx` / `NOVx` — maximum element count;
///   * `NEx` / `NEVx` — elements actually used;
///
/// so a channel can carry CHAR/SHORT/LONG/FLOAT/DOUBLE/STRING data,
/// not only `DOUBLE`. The per-channel value is stored as an
/// [`EpicsValue`], which represents any scalar or array type — the
/// `FTx` field selects the interpretation. The subroutine itself is
/// invoked by the framework (`RecordInstance::subroutine`).
pub struct ASubRecord {
    pub val: f64,
    pub snam: PvString,
    pub inam: PvString,
    /// Input links `INPA..INPU`.
    pub inp: [String; NUM_ARGS],
    /// Input values `A..U` — native typed via `fta`.
    pub a: [EpicsValue; NUM_ARGS],
    /// Output values `VALA..VALU` — native typed via `ftva`.
    pub vala: [EpicsValue; NUM_ARGS],
    /// Output links `OUTA..OUTU`.
    pub out: [String; NUM_ARGS],
    /// Input element-type menu `FTA..FTU` (`menuFtype`).
    pub fta: [i16; NUM_ARGS],
    /// Output element-type menu `FTVA..FTVU` (`menuFtype`).
    pub ftva: [i16; NUM_ARGS],
    /// Input max-element counts `NOA..NOU`.
    pub noa: [i32; NUM_ARGS],
    /// Output max-element counts `NOVA..NOVU`.
    pub nova: [i32; NUM_ARGS],
    /// Input elements-used `NEA..NEU`.
    pub nea: [i32; NUM_ARGS],
    /// Output elements-used `NEVA..NEVU`.
    pub neva: [i32; NUM_ARGS],
    /// Bad-return severity (`menuAlarmSevr`, default NO_ALARM). C
    /// `aSubRecord.c::do_sub` raises `SOFT_ALARM` at this severity when the
    /// subroutine returns a negative status (applied by the framework's
    /// `run_registered_subroutine`, which also publishes the status as VAL).
    pub brsv: i16,
    /// Display precision `PREC` for VAL. C `aSubRecord.c::get_precision`
    /// returns `prec->prec` as the precision of VAL (and any non-link field);
    /// the per-channel value fields use their link's precision, which the port
    /// does not track.
    pub prec: i16,
    /// Output event flag `EFLG` (`menu(aSubEFLG)`, default ON CHANGE). C
    /// `aSubRecord.c::monitor` gates `VALA..VALU`/`NEVA..NEVU` event posting:
    /// NEVER (never post), ON CHANGE (post on change — the framework default),
    /// ALWAYS (post every process).
    pub eflg: i16,
    /// Subroutine-name input mode `LFLG` (`menu(aSubLFLG)`, default IGNORE). C
    /// `aSubRecord.c::fetch_values`: READ re-reads SNAM from the SUBL link
    /// each process and re-resolves the subroutine when it changes (the
    /// framework's processing path performs the read + re-resolution, as it
    /// owns the link and subroutine registry).
    pub lflg: i16,
    /// Subroutine-name input link `SUBL` (`DBF_INLINK`). C `init_record`
    /// seeds SNAM from a constant SUBL; with LFLG=READ, `fetch_values` reads
    /// the current name from this link every process.
    pub subl: String,
    /// Old subroutine name `ONAM`. C `fetch_values` re-resolves the
    /// subroutine only when SNAM differs from ONAM; ONAM is set to SNAM on a
    /// successful swap.
    pub onam: PvString,
}

impl Default for ASubRecord {
    fn default() -> Self {
        Self {
            val: 0.0,
            snam: PvString::new(),
            inam: PvString::new(),
            inp: std::array::from_fn(|_| String::new()),
            a: std::array::from_fn(|_| EpicsValue::Double(0.0)),
            vala: std::array::from_fn(|_| EpicsValue::DoubleArray(Vec::new())),
            out: std::array::from_fn(|_| String::new()),
            fta: [FTYPE_DOUBLE; NUM_ARGS],
            ftva: [FTYPE_DOUBLE; NUM_ARGS],
            noa: [1; NUM_ARGS],
            nova: [1; NUM_ARGS],
            nea: [1; NUM_ARGS],
            neva: [1; NUM_ARGS],
            brsv: 0,
            prec: 0,
            eflg: EFLG_ON_CHANGE,
            lflg: 0,
            subl: String::new(),
            onam: PvString::new(),
        }
    }
}

/// Parse a per-channel field name into `(prefix, channel index)`.
/// E.g. `"INPC"` -> `("INP", 2)`, `"VALU"` -> `("VAL", 20)`,
/// `"M"` -> `("", 12)`.
fn parse_channel(name: &str) -> Option<(&'static str, usize)> {
    const PREFIXES: [&str; 7] = ["INP", "OUT", "VAL", "FTV", "FT", "NOV", "NO"];
    // Single-letter input value field A..U.
    if name.len() == 1 {
        let c = name.chars().next().unwrap();
        return SUFFIX.iter().position(|&s| s == c).map(|i| ("", i));
    }
    // NEA..NEU and NEVA..NEVU.
    if let Some(rest) = name.strip_prefix("NEV") {
        if rest.len() == 1 {
            let c = rest.chars().next().unwrap();
            return SUFFIX.iter().position(|&s| s == c).map(|i| ("NEV", i));
        }
        return None;
    }
    if let Some(rest) = name.strip_prefix("NE") {
        if rest.len() == 1 {
            let c = rest.chars().next().unwrap();
            return SUFFIX.iter().position(|&s| s == c).map(|i| ("NE", i));
        }
        return None;
    }
    for prefix in PREFIXES {
        if let Some(rest) = name.strip_prefix(prefix) {
            if rest.len() == 1 {
                let c = rest.chars().next().unwrap();
                if let Some(i) = SUFFIX.iter().position(|&s| s == c) {
                    return Some((prefix, i));
                }
            }
        }
    }
    None
}

/// Surface an output array channel: empty -> scalar 0.0, single
/// element -> scalar, otherwise the array (matching the legacy
/// access shape clients expect).
fn channel_get(v: &EpicsValue) -> EpicsValue {
    match v {
        EpicsValue::DoubleArray(a) if a.is_empty() => EpicsValue::Double(0.0),
        EpicsValue::DoubleArray(a) if a.len() == 1 => EpicsValue::Double(a[0]),
        other => other.clone(),
    }
}

impl ASubRecord {
    /// Build the static field-descriptor table (21 of each per-channel
    /// field plus VAL/SNAM/INAM).
    fn descriptors() -> Vec<FieldDesc> {
        let mut v = vec![
            FieldDesc {
                name: "VAL",
                dbf_type: DbFieldType::Double,
                read_only: false,
            },
            FieldDesc {
                name: "SNAM",
                dbf_type: DbFieldType::String,
                read_only: false,
            },
            FieldDesc {
                // INAM: init-routine name, SPC_NOMOD (config; .db-load only).
                name: "INAM",
                dbf_type: DbFieldType::String,
                read_only: true,
            },
            FieldDesc {
                name: "BRSV",
                dbf_type: DbFieldType::Short,
                read_only: false,
            },
            FieldDesc {
                name: "PREC",
                dbf_type: DbFieldType::Short,
                read_only: false,
            },
            FieldDesc {
                name: "EFLG",
                dbf_type: DbFieldType::Short,
                read_only: false,
            },
            FieldDesc {
                name: "LFLG",
                dbf_type: DbFieldType::Short,
                read_only: false,
            },
            // SUBL/ONAM are `special(SPC_NOMOD)` in C: client runtime puts are
            // blocked (read_only), but the `.db` loader and the framework's
            // own processing writes go through `put_field` directly.
            FieldDesc {
                name: "SUBL",
                dbf_type: DbFieldType::String,
                read_only: true,
            },
            FieldDesc {
                name: "ONAM",
                dbf_type: DbFieldType::String,
                read_only: true,
            },
        ];
        // Per-channel field families. Names are leaked to obtain the
        // 'static lifetime FieldDesc requires; the table is built once.
        for &c in SUFFIX.iter() {
            let mk = |s: String| -> &'static str { Box::leak(s.into_boxed_str()) };
            v.push(FieldDesc {
                name: mk(format!("INP{c}")),
                dbf_type: DbFieldType::String,
                read_only: false,
            });
            v.push(FieldDesc {
                name: mk(c.to_string()),
                dbf_type: DbFieldType::Double,
                read_only: false,
            });
            v.push(FieldDesc {
                name: mk(format!("VAL{c}")),
                dbf_type: DbFieldType::Double,
                read_only: false,
            });
            v.push(FieldDesc {
                name: mk(format!("OUT{c}")),
                dbf_type: DbFieldType::String,
                read_only: false,
            });
            v.push(FieldDesc {
                name: mk(format!("FT{c}")),
                dbf_type: DbFieldType::Short,
                read_only: false,
            });
            v.push(FieldDesc {
                name: mk(format!("FTV{c}")),
                dbf_type: DbFieldType::Short,
                read_only: false,
            });
            v.push(FieldDesc {
                name: mk(format!("NO{c}")),
                dbf_type: DbFieldType::Long,
                read_only: false,
            });
            v.push(FieldDesc {
                name: mk(format!("NOV{c}")),
                dbf_type: DbFieldType::Long,
                read_only: false,
            });
            v.push(FieldDesc {
                name: mk(format!("NE{c}")),
                dbf_type: DbFieldType::Long,
                read_only: true,
            });
            v.push(FieldDesc {
                name: mk(format!("NEV{c}")),
                dbf_type: DbFieldType::Long,
                read_only: true,
            });
        }
        v
    }
}

impl Record for ASubRecord {
    fn record_type(&self) -> &'static str {
        "aSub"
    }

    fn process(&mut self) -> CaResult<ProcessOutcome> {
        // Subroutine is invoked externally via RecordInstance.subroutine.
        Ok(ProcessOutcome::complete())
    }

    fn get_field(&self, name: &str) -> Option<EpicsValue> {
        match name {
            "VAL" => return Some(EpicsValue::Double(self.val)),
            "SNAM" => return Some(EpicsValue::String(self.snam.clone())),
            "INAM" => return Some(EpicsValue::String(self.inam.clone())),
            "BRSV" => return Some(EpicsValue::Short(self.brsv)),
            "PREC" => return Some(EpicsValue::Short(self.prec)),
            "EFLG" => return Some(EpicsValue::Short(self.eflg)),
            "LFLG" => return Some(EpicsValue::Short(self.lflg)),
            "SUBL" => return Some(EpicsValue::String(self.subl.clone().into())),
            "ONAM" => return Some(EpicsValue::String(self.onam.clone())),
            _ => {}
        }
        let (prefix, idx) = parse_channel(name)?;
        Some(match prefix {
            "" => self.a[idx].clone(), // input value A..U
            "INP" => EpicsValue::String(self.inp[idx].clone().into()),
            "VAL" => channel_get(&self.vala[idx]),
            "OUT" => EpicsValue::String(self.out[idx].clone().into()),
            "FT" => EpicsValue::Short(self.fta[idx]),
            "FTV" => EpicsValue::Short(self.ftva[idx]),
            "NO" => EpicsValue::Long(self.noa[idx]),
            "NOV" => EpicsValue::Long(self.nova[idx]),
            "NE" => EpicsValue::Long(self.nea[idx]),
            "NEV" => EpicsValue::Long(self.neva[idx]),
            _ => return None,
        })
    }

    fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
        match name {
            "VAL" => {
                self.val = value
                    .to_f64()
                    .ok_or_else(|| CaError::TypeMismatch(name.into()))?;
                return Ok(());
            }
            "SNAM" => {
                return match value {
                    EpicsValue::String(s) => {
                        self.snam = s;
                        Ok(())
                    }
                    _ => Err(CaError::TypeMismatch(name.into())),
                };
            }
            "INAM" => {
                return match value {
                    EpicsValue::String(s) => {
                        self.inam = s;
                        Ok(())
                    }
                    _ => Err(CaError::TypeMismatch(name.into())),
                };
            }
            "BRSV" => {
                self.brsv = value
                    .to_f64()
                    .ok_or_else(|| CaError::TypeMismatch("BRSV".into()))?
                    as i16;
                return Ok(());
            }
            "PREC" => {
                self.prec = value
                    .to_f64()
                    .ok_or_else(|| CaError::TypeMismatch("PREC".into()))?
                    as i16;
                return Ok(());
            }
            "EFLG" => {
                self.eflg = value
                    .to_f64()
                    .ok_or_else(|| CaError::TypeMismatch("EFLG".into()))?
                    as i16;
                return Ok(());
            }
            "LFLG" => {
                self.lflg = value
                    .to_f64()
                    .ok_or_else(|| CaError::TypeMismatch("LFLG".into()))?
                    as i16;
                return Ok(());
            }
            "SUBL" => {
                return match value {
                    EpicsValue::String(s) => {
                        self.subl = s.as_str_lossy().into_owned();
                        Ok(())
                    }
                    _ => Err(CaError::TypeMismatch(name.into())),
                };
            }
            "ONAM" => {
                return match value {
                    EpicsValue::String(s) => {
                        self.onam = s;
                        Ok(())
                    }
                    _ => Err(CaError::TypeMismatch(name.into())),
                };
            }
            _ => {}
        }
        let (prefix, idx) =
            parse_channel(name).ok_or_else(|| CaError::FieldNotFound(name.to_string()))?;
        match prefix {
            // Input value A..U — store native; track NEx (elements used).
            "" => {
                self.nea[idx] = value.count().max(1) as i32;
                self.a[idx] = value;
            }
            "INP" | "OUT" => {
                let s = match value {
                    EpicsValue::String(s) => s.as_str_lossy().into_owned(),
                    _ => return Err(CaError::TypeMismatch(name.into())),
                };
                if prefix == "INP" {
                    self.inp[idx] = s;
                } else {
                    self.out[idx] = s;
                }
            }
            // Output value VALA..VALU — store native; track NEVx.
            "VAL" => {
                self.neva[idx] = value.count().max(1) as i32;
                self.vala[idx] = value;
            }
            "FT" | "FTV" | "NO" | "NOV" | "NE" | "NEV" => {
                let v = match value {
                    EpicsValue::Short(v) => v as i32,
                    EpicsValue::Long(v) => v,
                    other => other
                        .to_f64()
                        .map(|f| f as i32)
                        .ok_or_else(|| CaError::TypeMismatch(name.into()))?,
                };
                match prefix {
                    "FT" => self.fta[idx] = v as i16,
                    "FTV" => self.ftva[idx] = v as i16,
                    "NO" => self.noa[idx] = v,
                    "NOV" => self.nova[idx] = v,
                    "NE" => self.nea[idx] = v,
                    "NEV" => self.neva[idx] = v,
                    _ => unreachable!(),
                }
            }
            _ => return Err(CaError::FieldNotFound(name.to_string())),
        }
        Ok(())
    }

    fn field_list(&self) -> &'static [FieldDesc] {
        use std::sync::OnceLock;
        static FIELDS: OnceLock<Vec<FieldDesc>> = OnceLock::new();
        FIELDS.get_or_init(ASubRecord::descriptors)
    }

    fn menu_field_choices(&self, field: &str) -> Option<&'static [&'static str]> {
        // EFLG is `menu(aSubEFLG)`, LFLG is `menu(aSubLFLG)`; serve their
        // labels so a `.db` `field(EFLG,"ON CHANGE")` / `field(LFLG,"READ")`
        // resolves and a client reads them as DBR_ENUM.
        match field {
            "EFLG" => Some(ASUB_EFLG_CHOICES),
            "LFLG" => Some(ASUB_LFLG_CHOICES),
            _ => None,
        }
    }

    fn force_posted_fields(&self) -> &'static [&'static str] {
        // EFLG=ALWAYS: C `monitor()` posts every `vala[i]`/`neva[i]` each
        // process regardless of change — the framework's force-post path.
        if self.eflg == EFLG_ALWAYS {
            asub_output_event_fields()
        } else {
            &[]
        }
    }

    fn event_posted_fields(&self) -> &'static [&'static str] {
        // EFLG=NEVER: C `monitor()` posts no `vala[i]`/`neva[i]` events.
        // Excluding them from generic change-detection suppresses the post.
        // (VAL, the scalar return status, is not in this set — C posts it on
        // change independent of EFLG.)
        if self.eflg == EFLG_NEVER {
            asub_output_event_fields()
        } else {
            &[]
        }
    }

    fn field_metadata_override(&self, field: &str) -> Option<FieldMetadataOverride> {
        // C `aSubRecord.c::get_precision` reports `prec->prec` as VAL's display
        // precision. (The per-channel value fields use their link's precision
        // in C; the port does not model per-link precision, so only VAL is
        // served here.)
        if field.eq_ignore_ascii_case("VAL") {
            return Some(FieldMetadataOverride {
                precision: Some(self.prec),
                ..Default::default()
            });
        }
        None
    }

    fn multi_input_links(&self) -> &[(&'static str, &'static str)] {
        use std::sync::OnceLock;
        static PAIRS: OnceLock<Vec<(&'static str, &'static str)>> = OnceLock::new();
        PAIRS.get_or_init(|| {
            SUFFIX
                .iter()
                .map(|&c| {
                    let link: &'static str = Box::leak(format!("INP{c}").into_boxed_str());
                    let val: &'static str = Box::leak(c.to_string().into_boxed_str());
                    (link, val)
                })
                .collect()
        })
    }
}

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

    /// input/output channels M..U exist (C `NUM_ARGS == 21`).
    #[test]
    fn channels_m_through_u_present() {
        let mut rec = ASubRecord::default();
        for name in ["M", "Q", "U"] {
            rec.put_field(name, EpicsValue::Double(3.0)).unwrap();
            assert_eq!(rec.get_field(name), Some(EpicsValue::Double(3.0)));
        }
        for name in ["VALM", "VALU"] {
            rec.put_field(name, EpicsValue::DoubleArray(vec![1.0, 2.0]))
                .unwrap();
            assert_eq!(
                rec.get_field(name),
                Some(EpicsValue::DoubleArray(vec![1.0, 2.0]))
            );
        }
        for name in ["NOM", "NOVU", "INPR", "OUTT"] {
            assert!(rec.get_field(name).is_some(), "channel field must exist");
        }
    }

    /// a non-double channel keeps its native type. `FTVA=STRING`
    /// with a string output value is represented faithfully.
    #[test]
    fn non_double_channel_keeps_native_type() {
        let mut rec = ASubRecord::default();
        rec.put_field("FTA", EpicsValue::Short(0)).unwrap(); // STRING
        rec.put_field("A", EpicsValue::String("hello".into()))
            .unwrap();
        assert_eq!(rec.get_field("A"), Some(EpicsValue::String("hello".into())));
        assert_eq!(rec.fta[0], 0);

        rec.put_field("FTC", EpicsValue::Short(5)).unwrap(); // LONG
        rec.put_field("C", EpicsValue::LongArray(vec![10, 20, 30]))
            .unwrap();
        assert_eq!(
            rec.get_field("C"),
            Some(EpicsValue::LongArray(vec![10, 20, 30]))
        );
        // NEC tracks elements used.
        assert_eq!(rec.get_field("NEC"), Some(EpicsValue::Long(3)));
    }

    /// All 21 input channels feed `multi_input_links`.
    #[test]
    fn twenty_one_multi_input_links() {
        let rec = ASubRecord::default();
        assert_eq!(rec.multi_input_links().len(), 21);
    }

    /// PREC round-trips and is served as VAL's display precision (C
    /// `aSubRecord.c::get_precision` returns `prec->prec` for VAL).
    #[test]
    fn prec_round_trips_and_serves_val_precision() {
        let mut rec = ASubRecord::default();
        assert_eq!(rec.get_field("PREC"), Some(EpicsValue::Short(0)));
        assert_eq!(
            rec.field_metadata_override("VAL").and_then(|o| o.precision),
            Some(0)
        );

        rec.put_field("PREC", EpicsValue::Short(4)).unwrap();
        assert_eq!(rec.get_field("PREC"), Some(EpicsValue::Short(4)));
        assert_eq!(
            rec.field_metadata_override("VAL").and_then(|o| o.precision),
            Some(4),
            "PREC must be served as VAL display precision"
        );
        // Non-VAL fields carry no precision override.
        assert!(rec.field_metadata_override("SNAM").is_none());
    }

    /// EFLG gates output-array posting. C `aSubRecord.c::monitor`:
    /// NEVER posts no `VALx`/`NEVx`; ON CHANGE (default) leaves them to the
    /// framework's change-detection; ALWAYS force-posts them every process.
    #[test]
    fn eflg_drives_output_event_posting_policy() {
        let mut rec = ASubRecord::default();
        // Default ON CHANGE: neither force-post nor suppress.
        assert_eq!(rec.eflg, EFLG_ON_CHANGE);
        assert!(rec.force_posted_fields().is_empty());
        assert!(rec.event_posted_fields().is_empty());

        // ALWAYS: VALx/NEVx force-posted every cycle (21 + 21 = 42 fields).
        rec.put_field("EFLG", EpicsValue::Short(EFLG_ALWAYS))
            .unwrap();
        assert_eq!(rec.get_field("EFLG"), Some(EpicsValue::Short(2)));
        assert_eq!(rec.force_posted_fields().len(), NUM_ARGS * 2);
        assert!(rec.force_posted_fields().contains(&"VALA"));
        assert!(rec.force_posted_fields().contains(&"NEVU"));
        assert!(rec.event_posted_fields().is_empty());

        // NEVER: VALx/NEVx excluded from posting; VAL scalar not in the set.
        rec.put_field("EFLG", EpicsValue::Short(EFLG_NEVER))
            .unwrap();
        assert!(rec.force_posted_fields().is_empty());
        assert_eq!(rec.event_posted_fields().len(), NUM_ARGS * 2);
        assert!(rec.event_posted_fields().contains(&"VALA"));
        assert!(!rec.event_posted_fields().contains(&"VAL"));
    }

    /// EFLG loads from a `.db` menu label (C `field(EFLG,"ALWAYS")`).
    #[test]
    fn eflg_loads_from_menu_label() {
        use crate::server::db_loader::{apply_fields, create_record};
        let mut rec = create_record("aSub").unwrap();
        let mut common = Vec::new();
        apply_fields(&mut rec, &[("EFLG".into(), "ALWAYS".into())], &mut common)
            .expect("EFLG menu label must load");
        assert_eq!(rec.get_field("EFLG"), Some(EpicsValue::Short(2)));
    }

    /// BRSV round-trips as a `menuAlarmSevr` index (C `aSubRecord.c` BRSV,
    /// the severity used when the subroutine returns a negative status).
    #[test]
    fn brsv_round_trips() {
        let mut rec = ASubRecord::default();
        assert_eq!(rec.get_field("BRSV"), Some(EpicsValue::Short(0)));
        rec.put_field("BRSV", EpicsValue::Short(3)).unwrap();
        assert_eq!(rec.get_field("BRSV"), Some(EpicsValue::Short(3)));
    }

    /// LFLG/SUBL/ONAM round-trip and default to IGNORE / empty / empty
    /// (C `aSubRecord.c` defaults; ONAM init-copies the empty SNAM).
    #[test]
    fn lflg_subl_onam_round_trip() {
        let mut rec = ASubRecord::default();
        assert_eq!(rec.get_field("LFLG"), Some(EpicsValue::Short(0)));
        assert_eq!(rec.get_field("SUBL"), Some(EpicsValue::String("".into())));
        assert_eq!(rec.get_field("ONAM"), Some(EpicsValue::String("".into())));

        rec.put_field("LFLG", EpicsValue::Short(1)).unwrap();
        rec.put_field("SUBL", EpicsValue::String("HOLDER".into()))
            .unwrap();
        rec.put_field("ONAM", EpicsValue::String("prev".into()))
            .unwrap();
        assert_eq!(rec.get_field("LFLG"), Some(EpicsValue::Short(1)));
        assert_eq!(
            rec.get_field("SUBL"),
            Some(EpicsValue::String("HOLDER".into()))
        );
        assert_eq!(
            rec.get_field("ONAM"),
            Some(EpicsValue::String("prev".into()))
        );
    }

    /// `field(LFLG,"READ")` resolves via the `menu(aSubLFLG)` labels;
    /// `field(SUBL,"...")` loads even though SUBL is `special(SPC_NOMOD)`
    /// (the loader writes through `put_field`, bypassing the runtime gate).
    #[test]
    fn lflg_subl_load_from_db() {
        use crate::server::db_loader::{apply_fields, create_record};
        let mut rec = create_record("aSub").unwrap();
        let mut common = Vec::new();
        apply_fields(
            &mut rec,
            &[
                ("LFLG".into(), "READ".into()),
                ("SUBL".into(), "NAME_HOLDER".into()),
            ],
            &mut common,
        )
        .expect("LFLG menu label and SUBL link must load");
        assert_eq!(rec.get_field("LFLG"), Some(EpicsValue::Short(1)));
        assert_eq!(
            rec.get_field("SUBL"),
            Some(EpicsValue::String("NAME_HOLDER".into()))
        );
    }
}