Skip to main content

viva_genapi/
nodes.rs

1//! Node type definitions for the GenApi node system.
2
3use std::cell::RefCell;
4use std::collections::HashMap;
5
6use viva_genapi_xml::{
7    AccessMode, Addressing, BitField, ByteOrder, CommandValueSrc, EnumEntryDecl, FloatEncoding,
8    IndexedValue, Sign, Slope,
9};
10use viva_genapi_xml::{NodeMeta, PredicateRefs, Representation, SkOutput, Visibility};
11
12use crate::swissknife::{AstNode, Value, VarAttr};
13
14/// Node kinds supported by the Tier-1 subset.
15#[derive(Debug)]
16#[non_exhaustive]
17pub enum Node {
18    /// Signed integer feature stored in a fixed-width register block.
19    Integer(IntegerNode),
20    /// Floating point feature with optional scale/offset conversion.
21    Float(FloatNode),
22    /// Enumeration feature mapping integers to symbolic names.
23    Enum(EnumNode),
24    /// Boolean feature represented as an integer register.
25    Boolean(BooleanNode),
26    /// Command feature triggering a device-side action when written.
27    Command(CommandNode),
28    /// Category organising related features.
29    Category(CategoryNode),
30    /// SwissKnife expression producing a computed value.
31    SwissKnife(SkNode),
32    /// Converter transforming raw values to/from float values via formulas.
33    Converter(ConverterNode),
34    /// IntConverter transforming raw values to/from integer values via formulas.
35    IntConverter(IntConverterNode),
36    /// A string feature: a `<StringReg>`, or a `<String>` holding a value or
37    /// delegating through `<pValue>`.
38    String(StringNode),
39    /// Raw byte-array register access.
40    Register(RegisterNode),
41}
42
43impl Node {
44    /// Return the GenICam node type name (e.g. "Integer", "Float", "Enumeration").
45    pub fn kind_name(&self) -> &'static str {
46        match self {
47            Node::Integer(_) => "Integer",
48            Node::Float(_) => "Float",
49            Node::Enum(_) => "Enumeration",
50            Node::Boolean(_) => "Boolean",
51            Node::Command(_) => "Command",
52            Node::Category(_) => "Category",
53            Node::SwissKnife(_) => "SwissKnife",
54            Node::Converter(_) => "Converter",
55            Node::IntConverter(_) => "IntConverter",
56            Node::String(_) => "StringReg",
57            Node::Register(_) => "Register",
58        }
59    }
60
61    /// Return the access mode of the node, if applicable.
62    ///
63    /// A converter declares none; it is as writable as its `<pValue>`, which
64    /// the node alone cannot see, so it reports `RO` here. Ask
65    /// [`NodeMap::declared_access_mode`](crate::NodeMap::declared_access_mode)
66    /// for the inherited mode.
67    pub fn access_mode(&self) -> Option<viva_genapi_xml::AccessMode> {
68        match self {
69            Node::Integer(n) => Some(n.access),
70            Node::Float(n) => Some(n.access),
71            Node::Enum(n) => Some(n.access),
72            Node::Boolean(n) => Some(n.access),
73            Node::Command(_) => Some(viva_genapi_xml::AccessMode::WO),
74            Node::Category(_) => None,
75            Node::SwissKnife(_) => Some(viva_genapi_xml::AccessMode::RO),
76            Node::Converter(_) => Some(viva_genapi_xml::AccessMode::RO),
77            Node::IntConverter(_) => Some(viva_genapi_xml::AccessMode::RO),
78            Node::String(n) => Some(n.access),
79            Node::Register(n) => Some(n.access),
80        }
81    }
82
83    /// Return the node name.
84    pub fn name(&self) -> &str {
85        match self {
86            Node::Integer(n) => &n.name,
87            Node::Float(n) => &n.name,
88            Node::Enum(n) => &n.name,
89            Node::Boolean(n) => &n.name,
90            Node::Command(n) => &n.name,
91            Node::Category(n) => &n.name,
92            Node::SwissKnife(n) => &n.name,
93            Node::Converter(n) => &n.name,
94            Node::IntConverter(n) => &n.name,
95            Node::String(n) => &n.name,
96            Node::Register(n) => &n.name,
97        }
98    }
99
100    /// Return the shared metadata for this node.
101    pub fn meta(&self) -> &NodeMeta {
102        match self {
103            Node::Integer(n) => &n.meta,
104            Node::Float(n) => &n.meta,
105            Node::Enum(n) => &n.meta,
106            Node::Boolean(n) => &n.meta,
107            Node::Command(n) => &n.meta,
108            Node::Category(n) => &n.meta,
109            Node::SwissKnife(n) => &n.meta,
110            Node::Converter(n) => &n.meta,
111            Node::IntConverter(n) => &n.meta,
112            Node::String(n) => &n.meta,
113            Node::Register(n) => &n.meta,
114        }
115    }
116
117    /// `<pSelected>`: the features this node selects, when it is a selector
118    /// (GenICam Standard v2.1.1 §2.8.4). Empty otherwise.
119    pub fn selected(&self) -> &[String] {
120        match self {
121            Node::Integer(n) => &n.selected,
122            Node::Enum(n) => &n.selected,
123            _ => &[],
124        }
125    }
126
127    /// Return the visibility level of this node.
128    pub fn visibility(&self) -> Visibility {
129        self.meta().visibility
130    }
131
132    /// Return the description of this node, if any.
133    pub fn description(&self) -> Option<&str> {
134        self.meta().description.as_deref()
135    }
136
137    /// Return the tooltip of this node, if any.
138    pub fn tooltip(&self) -> Option<&str> {
139        self.meta().tooltip.as_deref()
140    }
141
142    /// Return the display name of this node, if any.
143    pub fn display_name(&self) -> Option<&str> {
144        self.meta().display_name.as_deref()
145    }
146
147    /// Return the recommended representation for this node, if any.
148    pub fn representation(&self) -> Option<Representation> {
149        self.meta().representation
150    }
151
152    /// `<Unit>`: the engineering unit an Integer, Float, Converter or
153    /// IntConverter declares, such as `"us"`.
154    pub fn unit(&self) -> Option<&str> {
155        match self {
156            Node::Integer(n) => n.unit.as_deref(),
157            Node::Float(n) => n.unit.as_deref(),
158            Node::Converter(n) => n.unit.as_deref(),
159            Node::IntConverter(n) => n.unit.as_deref(),
160            _ => None,
161        }
162    }
163
164    /// `<Min>` as the XML declares it, typed as the node is: an Integer's is
165    /// [`Value::Int`], a Float's [`Value::Float`]. A bound given through
166    /// `<pMin>`, or by the node `<pValue>` delegates to, is the device's to
167    /// say: read it with [`NodeMap::feature_state`](crate::NodeMap::feature_state).
168    pub fn min(&self) -> Option<Value> {
169        match self {
170            Node::Integer(n) => n.min.map(Value::Int),
171            Node::Float(n) => n.min.map(Value::Float),
172            _ => None,
173        }
174    }
175
176    /// `<Max>` as the XML declares it; see [`Node::min`].
177    pub fn max(&self) -> Option<Value> {
178        match self {
179            Node::Integer(n) => n.max.map(Value::Int),
180            Node::Float(n) => n.max.map(Value::Float),
181            _ => None,
182        }
183    }
184
185    /// `<Inc>` as the XML declares it; see [`Node::min`]. Only an Integer
186    /// declares one: a Float's increment is not verified on writing (GenICam
187    /// Standard v2.1.1 §2.8.9) and is not stored.
188    pub fn inc(&self) -> Option<Value> {
189        match self {
190            Node::Integer(n) => n.inc.map(Value::Int),
191            _ => None,
192        }
193    }
194
195    /// Return the predicate references (`pIsImplemented`, `pIsAvailable`,
196    /// `pIsLocked`) declared on this node.
197    pub fn predicates(&self) -> &PredicateRefs {
198        match self {
199            Node::Integer(n) => &n.predicates,
200            Node::Float(n) => &n.predicates,
201            Node::Enum(n) => &n.predicates,
202            Node::Boolean(n) => &n.predicates,
203            Node::Command(n) => &n.predicates,
204            Node::Category(n) => &n.predicates,
205            Node::SwissKnife(n) => &n.predicates,
206            Node::Converter(n) => &n.predicates,
207            Node::IntConverter(n) => &n.predicates,
208            Node::String(n) => &n.predicates,
209            Node::Register(n) => &n.predicates,
210        }
211    }
212
213    pub(crate) fn invalidate_cache(&self) {
214        match self {
215            Node::Integer(node) => {
216                node.cache.replace(None);
217                node.raw_cache.replace(None);
218            }
219            Node::Float(node) => {
220                node.cache.replace(None);
221            }
222            Node::Enum(node) => node.invalidate(),
223            Node::Boolean(node) => {
224                node.cache.replace(None);
225                node.raw_cache.replace(None);
226            }
227            Node::SwissKnife(node) => {
228                node.cache.replace(None);
229            }
230            Node::Converter(node) => {
231                node.cache.replace(None);
232            }
233            Node::IntConverter(node) => {
234                node.cache.replace(None);
235            }
236            Node::String(node) => {
237                node.cache.replace(None);
238            }
239            Node::Register(node) => {
240                node.cache.replace(None);
241            }
242            Node::Command(_) | Node::Category(_) => {}
243        }
244    }
245}
246
247/// Integer feature metadata extracted from the XML description.
248#[derive(Debug)]
249pub struct IntegerNode {
250    /// Unique feature name.
251    pub name: String,
252    /// Shared metadata (visibility, description, tooltip, etc.).
253    pub meta: NodeMeta,
254    /// Register addressing (absent when delegated via `pvalue`); resolve it
255    /// with [`NodeMap::register_address`](crate::NodeMap::register_address).
256    pub(crate) addressing: Option<Addressing>,
257    /// Nominal register length in bytes; `0` when a `<pLength>` node gives
258    /// it, which is read at each access.
259    pub len: u32,
260    /// Declared access rights.
261    pub access: AccessMode,
262    /// `<Min>`, when declared. The bound in force — which `<pMin>` and the
263    /// `<pValue>` target also decide — is what
264    /// [`NodeMap::feature_state`](crate::NodeMap::feature_state) reports.
265    pub min: Option<i64>,
266    /// `<Max>`, when declared.
267    pub max: Option<i64>,
268    /// `<Inc>`, when declared.
269    pub inc: Option<i64>,
270    /// Optional engineering unit such as "us".
271    pub unit: Option<String>,
272    /// Optional bitfield metadata restricting active bits.
273    pub bitfield: Option<BitField>,
274    /// Whether the register payload is signed. GenICam defaults to unsigned.
275    pub sign: Sign,
276    /// Byte order of the register payload. GenICam defaults to big-endian.
277    pub byte_order: ByteOrder,
278    /// `<pSelected>`: the features this node selects.
279    pub selected: Vec<String>,
280    /// Node providing the value (delegates read/write).
281    pub pvalue: Option<String>,
282    /// Node providing the dynamic maximum.
283    pub p_max: Option<String>,
284    /// Node providing the dynamic minimum.
285    pub p_min: Option<String>,
286    /// Node providing the dynamic increment.
287    pub p_inc: Option<String>,
288    /// `<Value>`: the start value of a "floating" integer, one with no
289    /// register behind it (GenICam Standard v2.1.1 §2.8.5).
290    pub value: Option<i64>,
291    /// A value picked from a table by an index node (§2.8.5).
292    pub(crate) indexed: Option<Indexed<i64>>,
293    /// Predicate refs gating implementation / availability / lock state.
294    pub predicates: PredicateRefs,
295    pub(crate) cache: RefCell<Option<i64>>,
296    pub(crate) raw_cache: RefCell<Option<Vec<u8>>>,
297    /// What was last written to a floating integer. Its state, not a cache of
298    /// the device's: invalidation leaves it alone.
299    pub(crate) floating: RefCell<Option<i64>>,
300}
301
302/// Floating point feature metadata.
303#[derive(Debug)]
304pub struct FloatNode {
305    /// Unique feature name.
306    pub name: String,
307    /// Shared metadata (visibility, description, tooltip, etc.).
308    pub meta: NodeMeta,
309    /// Register addressing (absent when delegated via `pvalue`); resolve it
310    /// with [`NodeMap::register_address`](crate::NodeMap::register_address).
311    pub(crate) addressing: Option<Addressing>,
312    /// Declared access rights.
313    pub access: AccessMode,
314    /// `<Min>`, when declared. The bound in force is what
315    /// [`NodeMap::feature_state`](crate::NodeMap::feature_state) reports.
316    pub min: Option<f64>,
317    /// `<Max>`, when declared.
318    pub max: Option<f64>,
319    /// Optional engineering unit such as "us".
320    pub unit: Option<String>,
321    /// Optional rational scale `(numerator, denominator)` applied to the raw value.
322    pub scale: Option<(i64, i64)>,
323    /// Optional offset added after scaling.
324    pub offset: Option<f64>,
325    /// Node providing the value (delegates read/write).
326    pub pvalue: Option<String>,
327    /// Node providing the dynamic minimum.
328    pub p_min: Option<String>,
329    /// Node providing the dynamic maximum.
330    pub p_max: Option<String>,
331    /// `<Value>`: the start value of a floating `<Float>`, one with no
332    /// register behind it (GenICam Standard v2.1.1 §2.8.9).
333    pub value: Option<f64>,
334    /// A value picked from a table by an index node (§2.8.9).
335    pub(crate) indexed: Option<Indexed<f64>>,
336    /// How the register payload is encoded (IEEE 754 or scaled integer).
337    pub encoding: FloatEncoding,
338    /// Byte order of the register payload.
339    pub byte_order: ByteOrder,
340    /// Predicate refs gating implementation / availability / lock state.
341    pub predicates: PredicateRefs,
342    pub(crate) cache: RefCell<Option<f64>>,
343    /// What was last written to a floating `<Float>`. Its state, not a cache
344    /// of the device's: invalidation leaves it alone.
345    pub(crate) floating: RefCell<Option<f64>>,
346}
347
348/// An indexed `<Integer>` or `<Float>`'s table, and what was written to the
349/// constants in it.
350#[derive(Debug)]
351pub(crate) struct Indexed<T> {
352    pub(crate) table: IndexedValue<T>,
353    /// A constant written, by the index of its entry, or `None` for the
354    /// default. Each constant is floating, as a `<Value>` is: the host's
355    /// state, which invalidation leaves alone.
356    pub(crate) written: RefCell<HashMap<Option<i64>, T>>,
357}
358
359impl<T> Indexed<T> {
360    pub(crate) fn new(table: IndexedValue<T>) -> Self {
361        Self {
362            table,
363            written: RefCell::new(HashMap::new()),
364        }
365    }
366}
367
368/// Enumeration feature metadata and mapping tables.
369#[derive(Debug)]
370pub struct EnumNode {
371    /// Unique feature name.
372    pub name: String,
373    /// Shared metadata (visibility, description, tooltip, etc.).
374    pub meta: NodeMeta,
375    /// Register addressing (absent when delegated via `pvalue`); resolve it
376    /// with [`NodeMap::register_address`](crate::NodeMap::register_address).
377    pub(crate) addressing: Option<Addressing>,
378    /// Declared access rights.
379    pub access: AccessMode,
380    /// Node providing the integer value (delegates register read/write).
381    pub pvalue: Option<String>,
382    /// The entries, in document order.
383    pub entries: Vec<EnumEntryDecl>,
384    /// The entry selected when nothing else says.
385    pub default: Option<String>,
386    /// `<pSelected>`: the features this enumeration selects.
387    pub selected: Vec<String>,
388    /// The nodes the entries' `<pValue>`s read.
389    pub providers: Vec<String>,
390    /// `<Value>`: the start value of an enumeration with no register behind
391    /// it — a selector the host keeps, as AVT's `GainSelector` is.
392    pub value: Option<i64>,
393    /// Predicate refs gating implementation / availability / lock state.
394    pub predicates: PredicateRefs,
395    pub(crate) value_cache: RefCell<Option<String>>,
396    pub(crate) mapping_cache: RefCell<Option<EnumMapping>>,
397    /// The entry value last written to a floating enumeration. Its state,
398    /// not a cache of the device's: invalidation leaves it alone.
399    pub(crate) floating: RefCell<Option<i64>>,
400}
401
402#[derive(Debug, Clone)]
403pub(crate) struct EnumMapping {
404    pub by_value: HashMap<i64, String>,
405    pub by_name: HashMap<String, i64>,
406}
407
408impl EnumNode {
409    pub(crate) fn invalidate(&self) {
410        self.value_cache.replace(None);
411        self.mapping_cache.replace(None);
412    }
413}
414
415/// Boolean feature metadata.
416#[derive(Debug)]
417pub struct BooleanNode {
418    /// Unique feature name.
419    pub name: String,
420    /// Shared metadata (visibility, description, tooltip, etc.).
421    pub meta: NodeMeta,
422    /// Register addressing (absent when delegated via `pvalue`); resolve it
423    /// with [`NodeMap::register_address`](crate::NodeMap::register_address).
424    pub(crate) addressing: Option<Addressing>,
425    /// Register length in bytes.
426    pub len: u32,
427    /// Declared access rights.
428    pub access: AccessMode,
429    /// Optional bitfield (absent for pValue-backed booleans).
430    pub bitfield: Option<BitField>,
431    /// Node providing the value (delegates read/write).
432    pub pvalue: Option<String>,
433    /// On value for pValue-backed booleans.
434    pub on_value: Option<i64>,
435    /// Off value for pValue-backed booleans.
436    pub off_value: Option<i64>,
437    /// `<Value>`: the start value of a boolean with no register behind it,
438    /// compared with `on_value` — a variable the host sets, as AVT's
439    /// `TLParamsLocked` is.
440    pub value: Option<i64>,
441    /// Predicate refs gating implementation / availability / lock state.
442    pub predicates: PredicateRefs,
443    pub(crate) cache: RefCell<Option<bool>>,
444    pub(crate) raw_cache: RefCell<Option<Vec<u8>>>,
445    /// What was last written to a floating boolean, as its raw value. Its
446    /// state, not a cache of the device's: invalidation leaves it alone.
447    pub(crate) floating: RefCell<Option<i64>>,
448}
449
450/// One variable a formula reads: the identifier it appears as, the node
451/// behind it, and which property of that node it denotes.
452///
453/// A plain `<pVariable Name="V1">Gain</pVariable>` becomes
454/// `{ name: "V1", provider: "Gain", attr: Value }`. `V1.Max` in the formula
455/// adds `{ name: "V1.Max", provider: "Gain", attr: Max }`, and so does a
456/// declaration spelled `<pVariable Name="V1.Max">Gain</pVariable>`.
457#[derive(Debug, Clone, PartialEq, Eq)]
458pub struct FormulaVar {
459    /// Identifier as written in the formula.
460    pub name: String,
461    /// Node the `<pVariable>` points at.
462    pub provider: String,
463    /// Property of `provider` the identifier reads.
464    pub attr: VarAttr,
465}
466
467/// SwissKnife node evaluating an arithmetic expression referencing other nodes.
468///
469/// `<IntSwissKnife>` (`output` = [`SkOutput::Integer`]) evaluates in integer
470/// arithmetic, where `/` truncates and 64-bit values stay exact;
471/// `<SwissKnife>` evaluates in floating point.
472#[derive(Debug)]
473pub struct SkNode {
474    /// Unique feature name.
475    pub name: String,
476    /// Shared metadata (visibility, description, tooltip, etc.).
477    pub meta: NodeMeta,
478    /// Desired output type as declared in the XML.
479    pub output: SkOutput,
480    /// Parsed expression AST.
481    pub ast: AstNode,
482    /// The variables the formula reads, qualified ones included.
483    pub vars: Vec<FormulaVar>,
484    /// Predicate refs gating implementation / availability.
485    pub predicates: PredicateRefs,
486    /// Cached value alongside the generation it was computed in.
487    pub(crate) cache: RefCell<Option<(Value, u64)>>,
488}
489
490/// Command feature metadata.
491#[derive(Debug)]
492pub struct CommandNode {
493    /// Unique feature name.
494    pub name: String,
495    /// Shared metadata (visibility, description, tooltip, etc.).
496    pub meta: NodeMeta,
497    /// Fixed register address (absent when delegated via `pvalue`).
498    pub address: Option<u64>,
499    /// Register length in bytes.
500    pub len: u32,
501    /// Node providing the command register.
502    pub pvalue: Option<String>,
503    /// The value executing the command writes: `<CommandValue>`, or the
504    /// node `<pCommandValue>` names, read when the command executes.
505    pub command_value: CommandValueSrc,
506    /// Predicate refs gating implementation / availability / lock state.
507    pub predicates: PredicateRefs,
508}
509
510/// Category node describing child feature names.
511#[derive(Debug)]
512pub struct CategoryNode {
513    /// Unique category name.
514    pub name: String,
515    /// Shared metadata (visibility, description, tooltip, etc.).
516    pub meta: NodeMeta,
517    /// The features and categories it contains, in document order.
518    pub children: Vec<String>,
519    /// Predicate refs gating implementation / availability.
520    pub predicates: PredicateRefs,
521}
522
523/// Converter node transforming a raw register value to/from a float feature
524/// value via two formulas.
525///
526/// The GenICam direction names read backwards at first glance, and getting
527/// them the wrong way round is silent — the identity converter behaves the
528/// same either way. They are named after the *target* of the conversion:
529///
530/// - `<FormulaFrom>` converts **from the raw value to the feature value** and
531///   is what a **read** evaluates. Its `TO` variable is bound to `p_value`.
532/// - `<FormulaTo>` converts **from the feature value to the raw value** and is
533///   what a **write** evaluates. Its `FROM` variable is bound to the incoming
534///   value and `OLD`, where declared, to the current raw value.
535#[derive(Debug)]
536pub struct ConverterNode {
537    /// Unique feature name.
538    pub name: String,
539    /// Shared metadata (visibility, description, tooltip, etc.).
540    pub meta: NodeMeta,
541    /// Name of the node providing the raw register value.
542    pub p_value: String,
543    /// Parsed `<FormulaTo>`: feature value → raw value, evaluated on write.
544    pub ast_to: AstNode,
545    /// Parsed `<FormulaFrom>`: raw value → feature value, evaluated on read.
546    pub ast_from: AstNode,
547    /// Variable mappings for `<FormulaTo>` (the write direction).
548    pub vars_to: Vec<FormulaVar>,
549    /// Variable mappings for `<FormulaFrom>` (the read direction).
550    pub vars_from: Vec<FormulaVar>,
551    /// Optional engineering unit.
552    pub unit: Option<String>,
553    /// Desired output type.
554    pub output: SkOutput,
555    /// `<Slope>`: how the value moves with the raw one, which decides how
556    /// the raw bounds map onto this node's.
557    pub slope: Slope,
558    /// Predicate refs gating implementation / availability / lock state.
559    pub predicates: PredicateRefs,
560    /// Cached user-facing value alongside the generation it was computed in.
561    pub(crate) cache: RefCell<Option<(Value, u64)>>,
562}
563
564/// IntConverter node transforming a raw register value to/from an integer
565/// feature value via two formulas.
566///
567/// Same direction convention as [`ConverterNode`], evaluated in integer
568/// arithmetic.
569#[derive(Debug)]
570pub struct IntConverterNode {
571    /// Unique feature name.
572    pub name: String,
573    /// Shared metadata (visibility, description, tooltip, etc.).
574    pub meta: NodeMeta,
575    /// Name of the node providing the raw register value.
576    pub p_value: String,
577    /// Parsed `<FormulaTo>`: feature value → raw value, evaluated on write.
578    pub ast_to: AstNode,
579    /// Parsed `<FormulaFrom>`: raw value → feature value, evaluated on read.
580    pub ast_from: AstNode,
581    /// Variable mappings for `<FormulaTo>` (the write direction).
582    pub vars_to: Vec<FormulaVar>,
583    /// Variable mappings for `<FormulaFrom>` (the read direction).
584    pub vars_from: Vec<FormulaVar>,
585    /// Optional engineering unit.
586    pub unit: Option<String>,
587    /// `<Slope>`: how the value moves with the raw one.
588    pub slope: Slope,
589    /// Predicate refs gating implementation / availability / lock state.
590    pub predicates: PredicateRefs,
591    /// Cached user-facing value alongside the generation it was computed in.
592    pub(crate) cache: RefCell<Option<(i64, u64)>>,
593}
594
595/// A string feature: a `<StringReg>`, which reads a register, or a
596/// `<String>`, which holds a value or reads and writes the node its
597/// `<pValue>` names (GenICam Standard v2.1.1 §2.8.11, §2.8.12).
598#[derive(Debug)]
599pub struct StringNode {
600    /// Unique feature name.
601    pub name: String,
602    /// Shared metadata (visibility, description, tooltip, etc.).
603    pub meta: NodeMeta,
604    /// A `<StringReg>`'s register; `None` for a `<String>`.
605    pub(crate) addressing: Option<Addressing>,
606    /// `<pValue>`: the node a `<String>` delegates to.
607    pub(crate) pvalue: Option<String>,
608    /// `<Value>`: a floating `<String>`'s start value.
609    pub(crate) value: Option<String>,
610    /// What was last written to a floating `<String>`.
611    pub(crate) floating: RefCell<Option<String>>,
612    /// Declared access rights.
613    pub access: AccessMode,
614    /// Predicate refs gating implementation / availability / lock state.
615    pub predicates: PredicateRefs,
616    /// Cached string value alongside the generation it was computed in.
617    pub(crate) cache: RefCell<Option<(String, u64)>>,
618}
619
620/// `<Register>` node: raw byte-array access to a register block.
621///
622/// The base register type — an address, a byte count, and no interpretation of
623/// the bytes. `StringNode` is this plus UTF-8/NUL decoding.
624#[derive(Debug)]
625pub struct RegisterNode {
626    /// Unique feature name.
627    pub name: String,
628    /// Shared metadata (visibility, description, tooltip, etc.).
629    pub meta: NodeMeta,
630    /// Register addressing metadata, including the block length.
631    pub(crate) addressing: Addressing,
632    /// Declared access rights.
633    pub access: AccessMode,
634    /// Predicate refs gating implementation / availability / lock state.
635    pub predicates: PredicateRefs,
636    /// Cached payload alongside the generation it was read in.
637    pub(crate) cache: RefCell<Option<(Vec<u8>, u64)>>,
638}
639
640impl StringNode {
641    /// Declared length of a `<StringReg>` in bytes: the longest string it
642    /// holds, its terminating NUL included. `None` for a `<String>`, which
643    /// has no register, and `Some(0)` for a register whose length is read
644    /// from a `<pLength>` node.
645    pub fn declared_len(&self) -> Option<u32> {
646        self.addressing.as_ref().map(Addressing::byte_len)
647    }
648
649    /// The `<pPort>` the register's address is relative to; `None` means the
650    /// device, or a `<String>`, which has no register.
651    pub fn port(&self) -> Option<&str> {
652        self.addressing.as_ref().and_then(Addressing::port)
653    }
654
655    /// The node a `<String>` reads and writes through, if it delegates.
656    pub fn pvalue(&self) -> Option<&str> {
657        self.pvalue.as_deref()
658    }
659
660    /// The `<pLength>` node a `<StringReg>`'s length is read from, if any.
661    pub fn length_node(&self) -> Option<&str> {
662        self.addressing.as_ref().and_then(Addressing::length_node)
663    }
664}
665
666impl RegisterNode {
667    /// Declared length of the register block in bytes; `0` when a
668    /// `<pLength>` node gives it ([`RegisterNode::length_node`]).
669    ///
670    /// This exists so a consumer can report a register's size without naming
671    /// `Addressing`, which is not re-exported (backlog `API-02`).
672    pub fn declared_len(&self) -> u32 {
673        self.addressing.byte_len()
674    }
675
676    /// The `<pPort>` the register's address is relative to; `None` means the
677    /// device.
678    pub fn port(&self) -> Option<&str> {
679        self.addressing.port()
680    }
681
682    /// The `<pLength>` node the length is read from at runtime, if any.
683    pub fn length_node(&self) -> Option<&str> {
684        self.addressing.length_node()
685    }
686}
687
688/// The addressing of a register-backed node, if it has its own.
689pub(crate) fn node_addressing(node: &Node) -> Option<&Addressing> {
690    match node {
691        Node::Integer(n) => n.addressing.as_ref(),
692        Node::Float(n) => n.addressing.as_ref(),
693        Node::Enum(n) => n.addressing.as_ref(),
694        Node::Boolean(n) => n.addressing.as_ref(),
695        Node::String(n) => n.addressing.as_ref(),
696        Node::Register(n) => Some(&n.addressing),
697        _ => None,
698    }
699}