epics-base-rs 0.18.6

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
use crate::error::{CaError, CaResult};

// DBR type ranges (matches db_access.h):
//   native (0..=6), STS (7..=13), TIME (14..=20), GR (21..=27),
//   CTRL (28..=34), special PUT_ACKT (35), PUT_ACKS (36),
//   STSACK_STRING (37), CLASS_NAME (38).

// Native scalar types (also exposed via DbFieldType enum)
pub const DBR_STRING: u16 = 0;
pub const DBR_SHORT: u16 = 1;
pub const DBR_FLOAT: u16 = 2;
pub const DBR_ENUM: u16 = 3;
pub const DBR_CHAR: u16 = 4;
pub const DBR_LONG: u16 = 5;
pub const DBR_DOUBLE: u16 = 6;
// `DBR_INT` is the libca alias for `DBR_SHORT`.
pub const DBR_INT: u16 = DBR_SHORT;

// Status-only metadata layer (CA-261)
pub const DBR_STS_STRING: u16 = 7;
pub const DBR_STS_SHORT: u16 = 8;
pub const DBR_STS_FLOAT: u16 = 9;
pub const DBR_STS_ENUM: u16 = 10;
pub const DBR_STS_CHAR: u16 = 11;
pub const DBR_STS_LONG: u16 = 12;
pub const DBR_STS_DOUBLE: u16 = 13;
pub const DBR_STS_INT: u16 = DBR_STS_SHORT;

// Status + timestamp layer (CA-262)
pub const DBR_TIME_STRING: u16 = 14;
pub const DBR_TIME_SHORT: u16 = 15;
pub const DBR_TIME_FLOAT: u16 = 16;
pub const DBR_TIME_ENUM: u16 = 17;
pub const DBR_TIME_CHAR: u16 = 18;
pub const DBR_TIME_LONG: u16 = 19;
pub const DBR_TIME_DOUBLE: u16 = 20;
pub const DBR_TIME_INT: u16 = DBR_TIME_SHORT;

// Status + graphic (display limits / units / precision) layer (CA-263)
pub const DBR_GR_STRING: u16 = 21;
pub const DBR_GR_SHORT: u16 = 22;
pub const DBR_GR_FLOAT: u16 = 23;
pub const DBR_GR_ENUM: u16 = 24;
pub const DBR_GR_CHAR: u16 = 25;
pub const DBR_GR_LONG: u16 = 26;
pub const DBR_GR_DOUBLE: u16 = 27;
pub const DBR_GR_INT: u16 = DBR_GR_SHORT;

// Status + graphic + control limits layer (CA-264)
pub const DBR_CTRL_STRING: u16 = 28;
pub const DBR_CTRL_SHORT: u16 = 29;
pub const DBR_CTRL_FLOAT: u16 = 30;
pub const DBR_CTRL_ENUM: u16 = 31;
pub const DBR_CTRL_CHAR: u16 = 32;
pub const DBR_CTRL_LONG: u16 = 33;
pub const DBR_CTRL_DOUBLE: u16 = 34;
pub const DBR_CTRL_INT: u16 = DBR_CTRL_SHORT;

// Special alarm-acknowledgement / introspection types
pub const DBR_PUT_ACKT: u16 = 35;
pub const DBR_PUT_ACKS: u16 = 36;
pub const DBR_STSACK_STRING: u16 = 37;
/// Returns the IOC's record-type class name as a 40-byte string
/// (CA-268, db_access.h: `DBR_CLASS_NAME`).
pub const DBR_CLASS_NAME: u16 = 38;

/// Last allocated DBR type code, matching the C `LAST_BUFFER_TYPE` macro.
pub const LAST_BUFFER_TYPE: u16 = DBR_CLASS_NAME;

/// EPICS DBR field types (native types only)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum DbFieldType {
    String = 0,
    Short = 1, // aka Int16
    Float = 2,
    Enum = 3,
    Char = 4, // aka UInt8
    Long = 5, // aka Int32
    Double = 6,
    /// Internal-only type for int64in/int64out records.
    /// No CA wire type 7 exists; over CA these PVs appear as Double (type 6).
    Int64 = 7,
    /// Internal-only type for unsigned 64-bit EPICS fields (C `DBF_UINT64`,
    /// dbStatic `dbfType` index 8). The CA wire protocol has no 64-bit
    /// type, so over CA these PVs appear as Double (type 6); over PVA they
    /// are served natively as `ulong`. Mirrors `Int64`'s CA handling.
    UInt64 = 8,
}

impl DbFieldType {
    pub fn from_u16(v: u16) -> CaResult<Self> {
        match v {
            0 => Ok(Self::String),
            1 => Ok(Self::Short),
            2 => Ok(Self::Float),
            3 => Ok(Self::Enum),
            4 => Ok(Self::Char),
            5 => Ok(Self::Long),
            6 => Ok(Self::Double),
            _ => Err(CaError::UnsupportedType(v)),
        }
    }

    /// Size in bytes for a single element of this type
    pub fn element_size(&self) -> usize {
        match self {
            Self::String => 40, // MAX_STRING_SIZE
            Self::Short | Self::Enum => 2,
            Self::Float | Self::Long => 4,
            Self::Char => 1,
            Self::Double | Self::Int64 | Self::UInt64 => 8,
        }
    }

    /// Return the wire type code as a `u16`. Int64/UInt64 have no CA wire
    /// type and are reported as `DBR_DOUBLE` (6) for over-the-wire purposes.
    fn ca_wire_type(&self) -> u16 {
        match self {
            Self::Int64 | Self::UInt64 => Self::Double as u16,
            other => *other as u16,
        }
    }

    /// Return the `DBR_STS_xxx` type code for this native type
    /// (Int64 maps to `DBR_STS_DOUBLE`).
    pub fn sts_dbr_type(&self) -> u16 {
        self.ca_wire_type() + 7
    }

    /// Return the `DBR_TIME_xxx` type code for this native type
    /// (Int64 maps to `DBR_TIME_DOUBLE`).
    pub fn time_dbr_type(&self) -> u16 {
        self.ca_wire_type() + 14
    }

    /// Return the `DBR_GR_xxx` type code for this native type
    /// (Int64 maps to `DBR_GR_DOUBLE`).
    pub fn gr_dbr_type(&self) -> u16 {
        self.ca_wire_type() + 21
    }

    /// Return the `DBR_CTRL_xxx` type code for this native type
    /// (Int64 maps to `DBR_CTRL_DOUBLE`).
    pub fn ctrl_dbr_type(&self) -> u16 {
        self.ca_wire_type() + 28
    }

    /// Calculate total buffer size for N elements of this type.
    /// Equivalent to C EPICS dbValueSize(type) * count.
    pub fn buffer_size(&self, count: usize) -> usize {
        self.element_size() * count
    }

    /// Map field type to request type (C EPICS mapDBFToDBR).
    /// DBF_MENU and DBF_DEVICE map to DBR_ENUM in C EPICS.
    /// In Rust these are already represented as DbFieldType::Enum,
    /// so this is an identity mapping for documentation/completeness.
    pub fn to_dbr_type(&self) -> DbFieldType {
        *self
    }
}

/// Calculate buffer size for a DBR type including metadata, matching C
/// `dbr_size_n(TYPE, COUNT) = dbr_size[TYPE] + (COUNT-1)*dbr_value_size[TYPE]`.
///
/// the metadata length is taken from
/// [`crate::types::codec::dbr_meta_size`] — the single owner that the
/// serializers (`serialize_dbr` / `encode_dbr`) emit against — so the
/// explicit-count pad/truncate and no-read-access frame paths size
/// TIME / GR / CTRL bodies exactly as the encoder writes them. A
/// `metadata_matches_encoded_length` test pins `encoded_len ==
/// dbr_buffer_size` across the whole (dbr_type, native) matrix, so the
/// sizer can no longer drift from the encoder.
pub fn dbr_buffer_size(dbr_type: u16, native_type: DbFieldType, count: usize) -> usize {
    // DBR_CLASS_NAME (38) is always one MAX_STRING_SIZE (40) string,
    // regardless of `count` or `native_type` — it carries no value[]
    // array, so the generic meta+value formula does not apply.
    if dbr_type == DBR_CLASS_NAME {
        return 40;
    }
    let value_size = native_type.element_size() * count;
    crate::types::codec::dbr_meta_size(dbr_type, native_type) + value_size
}

/// Extract the native DBF type index (0-6) from any DBR type code.
fn dbr_native_index(dbr_type: u16) -> Option<u16> {
    match dbr_type {
        0..=6 => Some(dbr_type),
        7..=13 => Some(dbr_type - 7),
        14..=20 => Some(dbr_type - 14),
        21..=27 => Some(dbr_type - 21),
        28..=34 => Some(dbr_type - 28),
        // Alarm-acknowledge writes carry a single u16, so map them to
        // Short for codec purposes. STSACK_STRING returns a string body
        // so it maps to String.
        35 | 36 => Some(1), // DBR_PUT_ACKT / DBR_PUT_ACKS — u16
        37 => Some(0),      // DBR_STSACK_STRING — value is a string
        // DBR_CLASS_NAME is a single fixed 40-byte string carrying the
        // record's recordType. Treat as String for codec purposes.
        38 => Some(0),
        _ => None,
    }
}

pub fn native_type_for_dbr(dbr_type: u16) -> CaResult<DbFieldType> {
    match dbr_native_index(dbr_type) {
        Some(idx) => DbFieldType::from_u16(idx),
        None => Err(CaError::UnsupportedType(dbr_type)),
    }
}

/// DBR request-type names indexed by type code, mirroring the C
/// `dbr_text[]` table (`ca/src/client/access.cpp`). Index 0 =
/// `DBR_STRING` … index 38 = `DBR_CLASS_NAME`.
const DBR_TEXT: [&str; (LAST_BUFFER_TYPE + 1) as usize] = [
    "DBR_STRING",
    "DBR_SHORT",
    "DBR_FLOAT",
    "DBR_ENUM",
    "DBR_CHAR",
    "DBR_LONG",
    "DBR_DOUBLE",
    "DBR_STS_STRING",
    "DBR_STS_SHORT",
    "DBR_STS_FLOAT",
    "DBR_STS_ENUM",
    "DBR_STS_CHAR",
    "DBR_STS_LONG",
    "DBR_STS_DOUBLE",
    "DBR_TIME_STRING",
    "DBR_TIME_SHORT",
    "DBR_TIME_FLOAT",
    "DBR_TIME_ENUM",
    "DBR_TIME_CHAR",
    "DBR_TIME_LONG",
    "DBR_TIME_DOUBLE",
    "DBR_GR_STRING",
    "DBR_GR_SHORT",
    "DBR_GR_FLOAT",
    "DBR_GR_ENUM",
    "DBR_GR_CHAR",
    "DBR_GR_LONG",
    "DBR_GR_DOUBLE",
    "DBR_CTRL_STRING",
    "DBR_CTRL_SHORT",
    "DBR_CTRL_FLOAT",
    "DBR_CTRL_ENUM",
    "DBR_CTRL_CHAR",
    "DBR_CTRL_LONG",
    "DBR_CTRL_DOUBLE",
    "DBR_PUT_ACKT",
    "DBR_PUT_ACKS",
    "DBR_STSACK_STRING",
    "DBR_CLASS_NAME",
];

/// Resolve a DBR request-type name to its type code, mirroring the C
/// `dbr_text_to_type` macro (`db_access.h`): an exact, **case-sensitive**
/// `strcmp` search of the `dbr_text[]` table. Returns the matching code
/// (`0..=38`) or `None` when no name matches.
///
/// The case sensitivity is faithful to C — the `caget`/`caput` tools
/// feed `-d <type>` straight through this search, so `-d DBR_TIME_FLOAT`
/// resolves while `-d dbr_time_float` does not (the C tool then reverts
/// to its plain/native request). Callers that accept the bare family
/// (`caget -d TIME_FLOAT`) retry with a `DBR_` prefix, exactly as
/// `caget.c` does.
pub fn dbr_text_to_type(text: &str) -> Option<u16> {
    DBR_TEXT.iter().position(|&n| n == text).map(|i| i as u16)
}

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

    /// STS meta size is per-type. `dbr_sts_double` carries a
    /// 4-byte `dbr_long_t` RISC_pad (db_access.h:233-238) → meta 8.
    #[test]
    fn sts_double_meta_is_8() {
        // scalar: 8 (meta) + 8 (value) = 16
        assert_eq!(dbr_buffer_size(DBR_STS_DOUBLE, DbFieldType::Double, 1), 16);
        // n elements: 8 + 8*n
        assert_eq!(
            dbr_buffer_size(DBR_STS_DOUBLE, DbFieldType::Double, 5),
            8 + 8 * 5
        );
    }

    /// `dbr_sts_char` carries a 1-byte RISC_pad
    /// (db_access.h:218-223) → meta 5.
    #[test]
    fn sts_char_meta_is_5() {
        assert_eq!(dbr_buffer_size(DBR_STS_CHAR, DbFieldType::Char, 1), 6);
        assert_eq!(dbr_buffer_size(DBR_STS_CHAR, DbFieldType::Char, 10), 5 + 10);
    }

    /// types with no STS RISC pad keep the flat 4-byte meta.
    #[test]
    fn sts_short_meta_is_4() {
        assert_eq!(dbr_buffer_size(DBR_STS_SHORT, DbFieldType::Short, 1), 6);
        assert_eq!(dbr_buffer_size(DBR_STS_LONG, DbFieldType::Long, 1), 8);
        assert_eq!(dbr_buffer_size(DBR_STS_FLOAT, DbFieldType::Float, 1), 8);
    }

    /// Plain values carry no metadata.
    #[test]
    fn plain_value_size_only() {
        assert_eq!(dbr_buffer_size(DBR_DOUBLE, DbFieldType::Double, 3), 24);
    }

    /// TIME structs carry a per-type RISC pad before `value[0]`
    /// (C `dbr_time_*`, db_access.h:250-300). The pre-fix flat 12-byte
    /// TIME meta truncated double/short/enum/char bodies.
    #[test]
    fn time_meta_includes_risc_pad() {
        // double: 12 + RISC_pad(4) + value(8) = 24 (was wrongly 20).
        assert_eq!(dbr_buffer_size(DBR_TIME_DOUBLE, DbFieldType::Double, 1), 24);
        // short/enum: 12 + pad(2) + value(2) = 16.
        assert_eq!(dbr_buffer_size(DBR_TIME_SHORT, DbFieldType::Short, 1), 16);
        assert_eq!(dbr_buffer_size(DBR_TIME_ENUM, DbFieldType::Enum, 1), 16);
        // char: 12 + pad(3) + value(1) = 16.
        assert_eq!(dbr_buffer_size(DBR_TIME_CHAR, DbFieldType::Char, 1), 16);
        // float/long: no pad (value already 4-aligned at offset 12).
        assert_eq!(dbr_buffer_size(DBR_TIME_FLOAT, DbFieldType::Float, 1), 16);
        assert_eq!(dbr_buffer_size(DBR_TIME_LONG, DbFieldType::Long, 1), 16);
        // Explicit count scales the value array after the pad.
        assert_eq!(
            dbr_buffer_size(DBR_TIME_DOUBLE, DbFieldType::Double, 4),
            16 + 8 * 4
        );
    }

    /// GR/CTRL metadata is per native type (the pre-fix single
    /// broad formula over-padded short/char/float/long and dropped the
    /// enum `no_str` word).
    #[test]
    fn gr_ctrl_meta_is_per_type() {
        // GR (6 limits): head(4) + layout.
        assert_eq!(dbr_buffer_size(DBR_GR_SHORT, DbFieldType::Short, 1), 24 + 2);
        assert_eq!(dbr_buffer_size(DBR_GR_FLOAT, DbFieldType::Float, 1), 40 + 4);
        assert_eq!(
            dbr_buffer_size(DBR_GR_DOUBLE, DbFieldType::Double, 1),
            64 + 8
        );
        assert_eq!(dbr_buffer_size(DBR_GR_CHAR, DbFieldType::Char, 1), 19 + 1);
        assert_eq!(dbr_buffer_size(DBR_GR_LONG, DbFieldType::Long, 1), 36 + 4);
        // Enum: head(4) + no_str(2) + 16*26 strings = 422, value(2).
        assert_eq!(dbr_buffer_size(DBR_GR_ENUM, DbFieldType::Enum, 1), 422 + 2);
        // CTRL adds two control limits.
        assert_eq!(
            dbr_buffer_size(DBR_CTRL_DOUBLE, DbFieldType::Double, 1),
            80 + 8
        );
        assert_eq!(
            dbr_buffer_size(DBR_CTRL_SHORT, DbFieldType::Short, 1),
            28 + 2
        );
        assert_eq!(dbr_buffer_size(DBR_CTRL_CHAR, DbFieldType::Char, 1), 21 + 1);
    }
}

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

    #[test]
    fn resolves_every_type_name_to_its_code() {
        // Round-trip the whole table: each name resolves to its index.
        for (code, name) in DBR_TEXT.iter().enumerate() {
            assert_eq!(
                dbr_text_to_type(name),
                Some(code as u16),
                "{name} should resolve to {code}"
            );
        }
        // Boundary names spot-check (the cited High-finding values).
        assert_eq!(dbr_text_to_type("DBR_STRING"), Some(DBR_STRING));
        assert_eq!(dbr_text_to_type("DBR_TIME_FLOAT"), Some(DBR_TIME_FLOAT));
        assert_eq!(
            dbr_text_to_type("DBR_STSACK_STRING"),
            Some(DBR_STSACK_STRING)
        );
        assert_eq!(dbr_text_to_type("DBR_CLASS_NAME"), Some(DBR_CLASS_NAME));
    }

    #[test]
    fn is_case_sensitive_like_c_strcmp() {
        // C `dbr_text_to_type` uses `strcmp`, so lowercase does not
        // match — the C tools then revert to their plain request.
        assert_eq!(dbr_text_to_type("dbr_time_float"), None);
        assert_eq!(dbr_text_to_type("DBR_Time_Float"), None);
    }

    #[test]
    fn unknown_and_bare_family_names_do_not_match() {
        // Bare family names need the caller's `DBR_` retry — the raw
        // search rejects them, matching C's first-pass `strcmp`.
        assert_eq!(dbr_text_to_type("TIME_FLOAT"), None);
        assert_eq!(dbr_text_to_type("DOUBLE"), None);
        assert_eq!(dbr_text_to_type("DBR_NONSENSE"), None);
        assert_eq!(dbr_text_to_type(""), None);
    }
}