Skip to main content

nros_params/
types.rs

1//! Parameter types for ROS 2 compatible parameter handling
2//!
3//! This module provides types for representing ROS 2 parameters including
4//! scalar values, arrays, and parameter descriptors.
5
6use heapless::{String, Vec};
7
8// phase-359 W8 — `alloc`, not `std`: `ToString`, `String` and `Vec` all live in
9// `alloc`, so gating them on `std` withheld the `ParameterVariant` impls below
10// from `no_std + alloc` targets that can use them.
11#[cfg(feature = "alloc")]
12use alloc::string::ToString;
13
14pub use crate::config::*;
15
16/// Which node a parameter belongs to.
17///
18/// Upstream's parameters belong to a NODE, not to a process:
19/// `ros2 param list` enumerates per node and `/<node>/get_parameters` is a
20/// per-node service. An image composes several nodes onto one executor,
21/// so a store with no node key makes `/talker`'s `rate` and
22/// `/listener`'s `rate` the same parameter.
23///
24/// The key is the executor's node INDEX, not a name: `nros_node::NodeId` is
25/// already a `u8` index into the executor's node table, it is already the
26/// identity the FFI persists (`rcl_node_t.node_id`, `nros_cpp_node_t.node_id`),
27/// and one byte per slot keeps the store's arena the size it was. A name would
28/// cost `MAX_PARAM_NAME_LEN` bytes per slot and would need a second answer to
29/// "which node is this" that could disagree with the table.
30///
31/// `nros-params` sits below `nros-node`, so this is the local spelling and
32/// `nros-node` converts (`impl From<NodeId> for NodeKey`).
33#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
34pub struct NodeKey(u8);
35
36impl NodeKey {
37    /// The executor's implicit primary node — `nros_node::NodeId::PRIMARY`.
38    pub const PRIMARY: NodeKey = NodeKey(0);
39
40    /// Build a key from a node table index.
41    pub const fn new(index: u8) -> Self {
42        NodeKey(index)
43    }
44
45    /// The node table index this key names.
46    pub const fn index(self) -> usize {
47        self.0 as usize
48    }
49
50    /// The raw index, for FFI persistence.
51    pub const fn raw(self) -> u8 {
52        self.0
53    }
54}
55
56/// A per-node bool, bounded by the key's own range.
57///
58/// `allow_undeclared` is a NODE option upstream
59/// (`rclcpp::NodeOptions::allow_undeclared_parameters`, rclrs's
60/// `allow_undeclared`), so one node switching it on must not decide what a
61/// remote set may do to its sibling. [`NodeKey`] is a `u8`, so 256 bits covers
62/// the whole key space exactly: no ceiling to discover at runtime, 32 bytes,
63/// `const`-constructible, no allocation.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
65pub struct NodeFlags {
66    bits: [u64; 4],
67}
68
69impl NodeFlags {
70    /// All nodes off.
71    pub const fn new() -> Self {
72        Self { bits: [0; 4] }
73    }
74
75    /// Is the flag set for `node`?
76    pub const fn get(&self, node: NodeKey) -> bool {
77        let raw = node.raw() as usize;
78        self.bits[raw >> 6] & (1u64 << (raw & 63)) != 0
79    }
80
81    /// The lowest-numbered node whose flag is set, if any.
82    pub fn first(&self) -> Option<NodeKey> {
83        for (word, bits) in self.bits.iter().enumerate() {
84            if *bits != 0 {
85                return Some(NodeKey::new(
86                    (word * 64 + bits.trailing_zeros() as usize) as u8,
87                ));
88            }
89        }
90        None
91    }
92
93    /// Set or clear the flag for `node`.
94    pub fn set(&mut self, node: NodeKey, on: bool) {
95        let raw = node.raw() as usize;
96        let mask = 1u64 << (raw & 63);
97        if on {
98            self.bits[raw >> 6] |= mask;
99        } else {
100            self.bits[raw >> 6] &= !mask;
101        }
102    }
103}
104
105/// ROS 2 parameter types
106///
107/// These match the parameter types defined in rcl_interfaces/msg/ParameterType
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
109#[repr(u8)]
110pub enum ParameterType {
111    /// Parameter value not set
112    #[default]
113    NotSet = 0,
114    /// Boolean parameter
115    Bool = 1,
116    /// 64-bit signed integer parameter
117    Integer = 2,
118    /// 64-bit floating point parameter
119    Double = 3,
120    /// String parameter
121    String = 4,
122    /// Byte array parameter
123    ByteArray = 5,
124    /// Boolean array parameter
125    BoolArray = 6,
126    /// Integer array parameter
127    IntegerArray = 7,
128    /// Double array parameter
129    DoubleArray = 8,
130    /// String array parameter
131    StringArray = 9,
132}
133
134/// Parameter value container
135///
136/// Holds a parameter value of any supported type.
137/// Note: This enum is intentionally large to support all parameter types
138/// without heap allocation in embedded systems.
139#[derive(Debug, Clone, Default)]
140#[allow(clippy::large_enum_variant)]
141pub enum ParameterValue {
142    /// Value not set
143    #[default]
144    NotSet,
145    /// Boolean value
146    Bool(bool),
147    /// 64-bit signed integer value
148    Integer(i64),
149    /// 64-bit floating point value
150    Double(f64),
151    /// String value
152    String(String<MAX_STRING_VALUE_LEN>),
153    /// Byte array value
154    ByteArray(Vec<u8, MAX_BYTE_ARRAY_LEN>),
155    /// Boolean array value
156    BoolArray(Vec<bool, MAX_ARRAY_LEN>),
157    /// Integer array value
158    IntegerArray(Vec<i64, MAX_ARRAY_LEN>),
159    /// Double array value
160    DoubleArray(Vec<f64, MAX_ARRAY_LEN>),
161    /// String array value (array of fixed-size strings)
162    ///
163    /// Its element count is its OWN bound, [`MAX_STRING_ARRAY_LEN`], not
164    /// [`MAX_ARRAY_LEN`] (issue 2647): this variant is the product of two
165    /// bounds and sizes every slot, so it is paid only by an image that
166    /// declares a string array.
167    StringArray(Vec<String<MAX_STRING_VALUE_LEN>, MAX_STRING_ARRAY_LEN>),
168}
169
170impl ParameterValue {
171    /// Copy `src` into `self` in place.
172    ///
173    /// `*self = src.clone()` builds the clone on the stack first, and a
174    /// `ParameterValue` is as large as its largest variant (~8 KiB at the
175    /// default capacities). This switches `self` to `src`'s variant with an
176    /// empty payload and copies the payload element by element, so no
177    /// full-size temporary exists. Both values share the capacities, so every
178    /// copy fits.
179    pub fn assign_from(&mut self, src: &ParameterValue) {
180        macro_rules! fill {
181            ($variant:ident, $dst:ident, $body:expr) => {{
182                if !matches!(self, Self::$variant(_)) {
183                    *self = Self::$variant(Default::default());
184                }
185                if let Self::$variant($dst) = self {
186                    $dst.clear();
187                    $body;
188                }
189            }};
190        }
191        match src {
192            Self::NotSet => *self = Self::NotSet,
193            Self::Bool(v) => *self = Self::Bool(*v),
194            Self::Integer(v) => *self = Self::Integer(*v),
195            Self::Double(v) => *self = Self::Double(*v),
196            Self::String(v) => fill!(String, d, {
197                let _ = d.push_str(v);
198            }),
199            Self::ByteArray(v) => fill!(ByteArray, d, {
200                let _ = d.extend_from_slice(v);
201            }),
202            Self::BoolArray(v) => fill!(BoolArray, d, {
203                let _ = d.extend_from_slice(v);
204            }),
205            Self::IntegerArray(v) => fill!(IntegerArray, d, {
206                let _ = d.extend_from_slice(v);
207            }),
208            Self::DoubleArray(v) => fill!(DoubleArray, d, {
209                let _ = d.extend_from_slice(v);
210            }),
211            Self::StringArray(v) => fill!(StringArray, d, {
212                for e in v {
213                    let mut s = String::new();
214                    let _ = s.push_str(e);
215                    let _ = d.push(s);
216                }
217            }),
218        }
219    }
220
221    /// Get the parameter type for this value
222    pub fn param_type(&self) -> ParameterType {
223        match self {
224            Self::NotSet => ParameterType::NotSet,
225            Self::Bool(_) => ParameterType::Bool,
226            Self::Integer(_) => ParameterType::Integer,
227            Self::Double(_) => ParameterType::Double,
228            Self::String(_) => ParameterType::String,
229            Self::ByteArray(_) => ParameterType::ByteArray,
230            Self::BoolArray(_) => ParameterType::BoolArray,
231            Self::IntegerArray(_) => ParameterType::IntegerArray,
232            Self::DoubleArray(_) => ParameterType::DoubleArray,
233            Self::StringArray(_) => ParameterType::StringArray,
234        }
235    }
236
237    /// Check if the value is set
238    pub fn is_set(&self) -> bool {
239        !matches!(self, Self::NotSet)
240    }
241
242    /// Try to get the value as a bool
243    pub fn as_bool(&self) -> Option<bool> {
244        match self {
245            Self::Bool(v) => Some(*v),
246            _ => None,
247        }
248    }
249
250    /// Try to get the value as an integer
251    pub fn as_integer(&self) -> Option<i64> {
252        match self {
253            Self::Integer(v) => Some(*v),
254            _ => None,
255        }
256    }
257
258    /// Try to get the value as a double
259    pub fn as_double(&self) -> Option<f64> {
260        match self {
261            Self::Double(v) => Some(*v),
262            _ => None,
263        }
264    }
265
266    /// Try to get the value as a string slice
267    pub fn as_string(&self) -> Option<&str> {
268        match self {
269            Self::String(v) => Some(v.as_str()),
270            _ => None,
271        }
272    }
273
274    /// Try to get the value as a byte array slice
275    pub fn as_byte_array(&self) -> Option<&[u8]> {
276        match self {
277            Self::ByteArray(v) => Some(v.as_slice()),
278            _ => None,
279        }
280    }
281
282    /// Try to get the value as a bool array slice
283    pub fn as_bool_array(&self) -> Option<&[bool]> {
284        match self {
285            Self::BoolArray(v) => Some(v.as_slice()),
286            _ => None,
287        }
288    }
289
290    /// Try to get the value as an integer array slice
291    pub fn as_integer_array(&self) -> Option<&[i64]> {
292        match self {
293            Self::IntegerArray(v) => Some(v.as_slice()),
294            _ => None,
295        }
296    }
297
298    /// Try to get the value as a double array slice
299    pub fn as_double_array(&self) -> Option<&[f64]> {
300        match self {
301            Self::DoubleArray(v) => Some(v.as_slice()),
302            _ => None,
303        }
304    }
305
306    /// Create a bool value
307    pub fn from_bool(value: bool) -> Self {
308        Self::Bool(value)
309    }
310
311    /// Create an integer value
312    pub fn from_integer(value: i64) -> Self {
313        Self::Integer(value)
314    }
315
316    /// Create a double value
317    pub fn from_double(value: f64) -> Self {
318        Self::Double(value)
319    }
320
321    /// Create a string value from a str slice
322    pub fn from_string(value: &str) -> Option<Self> {
323        let mut s = String::new();
324        s.push_str(value).ok()?;
325        Some(Self::String(s))
326    }
327
328    /// Create a bool-array value from a slice.
329    ///
330    /// `None` when the slice is longer than [`MAX_ARRAY_LEN`],
331    /// the same fallible shape [`from_string`](Self::from_string) has for the
332    /// same reason: the value lives in a `heapless::Vec` inside the server's
333    /// fixed slot and there is no allocator to grow it.
334    ///
335    /// These three exist so a caller outside `nros-params` can build an array
336    /// value without naming `heapless` or the capacity constant. The C++ FFI
337    /// shim is such a caller: `nros_cpp_node_declare_param_*_array` forwards
338    /// `nros::ComponentNode`'s `std::vector<T>` facade into the executor's
339    /// store, and the capacity belongs where the storage is.
340    pub fn from_bool_array(values: &[bool]) -> Option<Self> {
341        Some(Self::BoolArray(Vec::from_slice(values).ok()?))
342    }
343
344    /// Create an integer-array value from a slice. See
345    /// [`from_bool_array`](Self::from_bool_array).
346    pub fn from_integer_array(values: &[i64]) -> Option<Self> {
347        Some(Self::IntegerArray(Vec::from_slice(values).ok()?))
348    }
349
350    /// Create a double-array value from a slice. See
351    /// [`from_bool_array`](Self::from_bool_array).
352    pub fn from_double_array(values: &[f64]) -> Option<Self> {
353        Some(Self::DoubleArray(Vec::from_slice(values).ok()?))
354    }
355
356    /// Create a byte-array value from a slice; `None` past
357    /// [`MAX_BYTE_ARRAY_LEN`]. See [`from_bool_array`](Self::from_bool_array).
358    pub fn from_byte_array(values: &[u8]) -> Option<Self> {
359        Some(Self::ByteArray(Vec::from_slice(values).ok()?))
360    }
361
362    /// Set `self` to a string, IN PLACE: the `from_*`
363    /// constructors' in-place twins, for a caller filling a slot it already
364    /// holds. `from_string(v)` returns an `Option<Self>`, and binding it puts
365    /// one or two ~8 KiB values on the caller's stack; this writes into
366    /// `self`. `false`, with `self` left as an empty value of the variant, when
367    /// `value` exceeds [`MAX_STRING_VALUE_LEN`].
368    pub fn assign_string(&mut self, value: &str) -> bool {
369        if !matches!(self, Self::String(_)) {
370            *self = Self::String(String::new());
371        }
372        match self {
373            Self::String(s) => {
374                s.clear();
375                s.push_str(value).is_ok()
376            }
377            _ => false,
378        }
379    }
380
381    /// Set `self` to a bool array in place; `false` past [`MAX_ARRAY_LEN`].
382    /// See [`assign_string`](Self::assign_string).
383    pub fn assign_bool_array(&mut self, values: &[bool]) -> bool {
384        assign_slice!(self, BoolArray, values)
385    }
386
387    /// Set `self` to an integer array in place; `false` past
388    /// [`MAX_ARRAY_LEN`]. See [`assign_string`](Self::assign_string).
389    pub fn assign_integer_array(&mut self, values: &[i64]) -> bool {
390        assign_slice!(self, IntegerArray, values)
391    }
392
393    /// Set `self` to a double array in place; `false` past
394    /// [`MAX_ARRAY_LEN`]. See [`assign_string`](Self::assign_string).
395    pub fn assign_double_array(&mut self, values: &[f64]) -> bool {
396        assign_slice!(self, DoubleArray, values)
397    }
398
399    /// Set `self` to a byte array in place; `false` past
400    /// [`MAX_BYTE_ARRAY_LEN`]. See [`assign_string`](Self::assign_string).
401    pub fn assign_byte_array(&mut self, values: &[u8]) -> bool {
402        assign_slice!(self, ByteArray, values)
403    }
404}
405
406/// The body of the `assign_*_array` family: switch `$v` to `$variant` with an
407/// empty payload when it is another variant, then copy `$values` in.
408macro_rules! assign_slice {
409    ($v:expr, $variant:ident, $values:expr) => {{
410        if !matches!($v, Self::$variant(_)) {
411            *$v = Self::$variant(Vec::new());
412        }
413        match $v {
414            Self::$variant(d) => {
415                d.clear();
416                d.extend_from_slice($values).is_ok()
417            }
418            _ => false,
419        }
420    }};
421}
422use assign_slice;
423
424/// Floating point range constraints for parameters
425#[derive(Debug, Clone, Copy, Default)]
426pub struct FloatingPointRange {
427    /// Minimum allowed value (inclusive)
428    pub min: f64,
429    /// Maximum allowed value (inclusive)
430    pub max: f64,
431    /// Step size for value changes (0 = any step allowed)
432    pub step: f64,
433}
434
435impl FloatingPointRange {
436    /// Create a new floating point range
437    pub const fn new(min: f64, max: f64, step: f64) -> Self {
438        Self { min, max, step }
439    }
440
441    /// A range is well-formed when `min <= max` and `step >= 0` (0 = no step).
442    ///
443    /// Upstream refuses to DECLARE with an ill-formed range
444    /// (`DeclarationError::InvalidRange`); a negative step here would also go
445    /// on the wire as a huge `u64` in `DescribeParameters`.
446    pub fn is_valid(&self) -> bool {
447        self.min <= self.max && self.step >= 0.0 && !self.step.is_nan()
448    }
449
450    /// Check if a value is within this range.
451    ///
452    /// `step` is ENFORCED, mirroring rclrs `range.rs`. A value is
453    /// in range iff `min <= v <= max` and, when `step != 0`, `v` lies on the
454    /// lattice `min + k*step` within floating tolerance. Either endpoint is
455    /// always accepted, exactly as upstream (the upper bound need not be on
456    /// the lattice). The tolerance is upstream's: 100 ULP, relative to the
457    /// magnitude of the two operands.
458    pub fn contains(&self, value: f64) -> bool {
459        if are_close(value, self.min) || are_close(value, self.max) {
460            return true;
461        }
462        if !(value >= self.min && value <= self.max) {
463            return false;
464        }
465        if self.step == 0.0 {
466            return true;
467        }
468        let nearest = round_to_nearest((value - self.min) / self.step) * self.step + self.min;
469        are_close(nearest, value)
470    }
471}
472
473/// rclrs `ParameterRange<f64>::are_close`: equal within 100 ULP of the
474/// operands' magnitude. One spelling, shared by the endpoint and lattice
475/// checks so they cannot drift apart.
476#[inline]
477fn are_close(a: f64, b: f64) -> bool {
478    const ULP_TOL: f64 = 100.0;
479    (a - b).abs() <= f64::EPSILON * (a + b).abs() * ULP_TOL
480}
481
482/// Round half away from zero without `std` (`f64::round` is not in `core`
483/// on every toolchain this crate targets). Saturates through the `i64` cast
484/// for a quotient beyond `2^63`, where the lattice is not representable
485/// anyway.
486#[inline]
487fn round_to_nearest(q: f64) -> f64 {
488    if !q.is_finite() {
489        return q;
490    }
491    let shifted = if q < 0.0 { q - 0.5 } else { q + 0.5 };
492    (shifted as i64) as f64
493}
494
495/// Integer range constraints for parameters
496#[derive(Debug, Clone, Copy, Default)]
497pub struct IntegerRange {
498    /// Minimum allowed value (inclusive)
499    pub min: i64,
500    /// Maximum allowed value (inclusive)
501    pub max: i64,
502    /// Step size for value changes (0 = any step allowed)
503    pub step: i64,
504}
505
506impl IntegerRange {
507    /// Create a new integer range
508    pub const fn new(min: i64, max: i64, step: i64) -> Self {
509        Self { min, max, step }
510    }
511
512    /// A range is well-formed when `min <= max` and `step >= 0` (0 = no step).
513    /// See [`FloatingPointRange::is_valid`].
514    pub fn is_valid(&self) -> bool {
515        self.min <= self.max && self.step >= 0
516    }
517
518    /// Check if a value is within this range.
519    ///
520    /// `step` is ENFORCED, mirroring rclrs `range.rs`: in range
521    /// iff `min <= v <= max` and, when `step != 0`, `(v - min)` is a multiple
522    /// of `step`. The upper bound is always accepted even when off-lattice,
523    /// exactly as upstream. Arithmetic is checked so an extreme `min` cannot
524    /// overflow into a panic.
525    pub fn contains(&self, value: i64) -> bool {
526        if !(value >= self.min && value <= self.max) {
527            return false;
528        }
529        if value == self.max || self.step == 0 {
530            return true;
531        }
532        match value
533            .checked_sub(self.min)
534            .and_then(|d| d.checked_rem(self.step))
535        {
536            Some(rem) => rem == 0,
537            // `value - min` does not fit an `i64`, so it is not `k * step`
538            // for any representable `k` the caller could have meant.
539            None => false,
540        }
541    }
542}
543
544/// Range constraints for a parameter
545#[derive(Debug, Clone, Copy, Default)]
546pub enum ParameterRange {
547    /// No range constraints
548    #[default]
549    None,
550    /// Floating point range
551    FloatingPoint(FloatingPointRange),
552    /// Integer range
553    Integer(IntegerRange),
554}
555
556impl ParameterRange {
557    /// Well-formed: `None`, or an arm whose `min <= max` and `step >= 0`.
558    pub fn is_valid(&self) -> bool {
559        match self {
560            Self::None => true,
561            Self::FloatingPoint(r) => r.is_valid(),
562            Self::Integer(r) => r.is_valid(),
563        }
564    }
565
566    /// THE range predicate. Every set — `ParameterServer::set`, the six
567    /// service handlers, the typed API — and every declare-time default check
568    /// reaches this one function, so an integer and a floating-point value
569    /// cannot be judged by two different rules.
570    ///
571    /// A value whose type does not match the arm (a string against an
572    /// integer range, a `NotSet`) is not the range's business and passes; the
573    /// type check is a separate, earlier verdict.
574    pub fn contains(&self, value: &ParameterValue) -> bool {
575        match (self, value) {
576            (Self::None, _) => true,
577            (Self::Integer(range), ParameterValue::Integer(v)) => range.contains(*v),
578            (Self::FloatingPoint(range), ParameterValue::Double(v)) => range.contains(*v),
579            _ => true,
580        }
581    }
582}
583
584/// Parameter descriptor containing metadata
585///
586/// Describes a parameter including its type, constraints, and documentation.
587#[derive(Debug, Clone)]
588pub struct ParameterDescriptor {
589    /// Parameter type
590    pub param_type: ParameterType,
591    /// Human-readable description.
592    ///
593    /// Its own capacity, `NROS_PARAMS_MAX_DESCRIPTION_BYTES`. It
594    /// used to share `MAX_STRING_VALUE_LEN`, which the contract derives to 0
595    /// for an image with no string parameter, so such an image could carry no
596    /// description at all. Write it with [`Self::set_description`], which
597    /// truncates and records the truncation instead of dropping the text.
598    pub description: String<MAX_PARAM_DESCRIPTION_LEN>,
599    /// Free-text extra constraints — `rcl_interfaces/msg/ParameterDescriptor`'s
600    /// `additional_constraints`, which `ros2 param describe` prints.
601    ///
602    /// Its own capacity, `NROS_PARAMS_MAX_CONSTRAINTS_BYTES`,
603    /// **default 0**. Sharing the description's knob was the first shape and
604    /// the derived service buffer measured it wrong: the describe reply's
605    /// bound is a worst case over CAPACITY, not over use, so every image would
606    /// have paid 256 bytes per parameter for a field it never sets — 2,048
607    /// bytes on the eight-parameter island, taking its reply past the 4,096
608    /// fallback. An image that wants constraint text states the knob. Write it
609    /// with [`Self::set_additional_constraints`], which truncates at a
610    /// character boundary and records the truncation under its own flag, so a
611    /// value that does not fit is reported, naming this field and
612    /// `NROS_PARAMS_MAX_CONSTRAINTS_BYTES`, rather than dropped in silence.
613    pub additional_constraints: String<MAX_PARAM_CONSTRAINTS_LEN>,
614    /// Whether the parameter is read-only
615    pub read_only: bool,
616    /// Whether the parameter type can change dynamically
617    pub dynamic_typing: bool,
618    /// Range constraints
619    pub range: ParameterRange,
620    /// phase-446 F2 -- the description given was longer than
621    /// `NROS_PARAMS_MAX_DESCRIPTION_BYTES` and `description` holds a prefix of it.
622    /// Read by [`ParameterServer::take_truncated_descriptions`](crate::ParameterServerOps::take_truncated_descriptions), which reports
623    /// each one once and clears it.
624    ///
625    /// [`ParameterServer::take_truncated_descriptions`]: crate::ParameterServerOps::take_truncated_descriptions
626    description_truncated: bool,
627    /// Issue 2686 -- the same for `additional_constraints`, which has its own
628    /// knob (`NROS_PARAMS_MAX_CONSTRAINTS_BYTES`). A separate flag, so the
629    /// report names the field that was cut and the knob that sizes it.
630    constraints_truncated: bool,
631}
632
633// Issue 2686 -- a truncation report names the field and its knob.
634/// One of a descriptor's two prose fields. Each has its own capacity and its
635/// own knob, and a truncation report names both.
636#[derive(Debug, Clone, Copy, PartialEq, Eq)]
637pub enum DescriptorText {
638    /// `description`, sized by `NROS_PARAMS_MAX_DESCRIPTION_BYTES`.
639    Description,
640    /// `additional_constraints`, sized by `NROS_PARAMS_MAX_CONSTRAINTS_BYTES`.
641    Constraints,
642}
643
644impl DescriptorText {
645    /// The `rcl_interfaces/msg/ParameterDescriptor` field this text is.
646    pub const fn field(self) -> &'static str {
647        match self {
648            Self::Description => "description",
649            Self::Constraints => "additional_constraints",
650        }
651    }
652
653    /// The knob that sizes this field.
654    pub const fn knob(self) -> &'static str {
655        match self {
656            Self::Description => "NROS_PARAMS_MAX_DESCRIPTION_BYTES",
657            Self::Constraints => "NROS_PARAMS_MAX_CONSTRAINTS_BYTES",
658        }
659    }
660
661    /// This image's capacity for the field, in bytes.
662    pub const fn capacity(self) -> usize {
663        match self {
664            Self::Description => MAX_PARAM_DESCRIPTION_LEN,
665            Self::Constraints => MAX_PARAM_CONSTRAINTS_LEN,
666        }
667    }
668}
669
670/// Store as much of `text` as `dst` holds, cut at a UTF-8
671/// character boundary. Returns whether anything was cut.
672///
673/// `heapless::String::push_str` is all-or-nothing, so the old
674/// `let _ = push_str(..)` stored NOTHING for a description one byte too long.
675/// A prefix is what a reader of `ros2 param describe` can still use, and the
676/// `true` return is what lets the caller say it happened.
677pub fn fit_description<const N: usize>(dst: &mut String<N>, text: &str) -> bool {
678    dst.clear();
679    let mut cut = text.len().min(N);
680    while !text.is_char_boundary(cut) {
681        cut -= 1;
682    }
683    // Cannot fail: `cut <= N` bytes into an empty `String<N>`.
684    let stored = dst.push_str(&text[..cut]).is_ok();
685    debug_assert!(stored, "a prefix of at most N bytes fits String<N>");
686    cut < text.len()
687}
688
689impl ParameterDescriptor {
690    /// Create a new parameter descriptor
691    pub fn new(name: &str, param_type: ParameterType) -> Option<Self> {
692        if name.len() > MAX_PARAM_NAME_LEN {
693            return None;
694        }
695        Some(Self {
696            param_type,
697            description: String::new(),
698            additional_constraints: String::new(),
699            read_only: false,
700            dynamic_typing: false,
701            range: ParameterRange::None,
702            description_truncated: false,
703            constraints_truncated: false,
704        })
705    }
706
707    /// Set the description. A description longer than
708    /// `NROS_PARAMS_MAX_DESCRIPTION_BYTES` is truncated at a character boundary
709    /// and recorded (see [`Self::set_description`]).
710    pub fn with_description(mut self, desc: &str) -> Self {
711        self.set_description(desc);
712        self
713    }
714
715    /// Set the description, truncating at a character
716    /// boundary when it is longer than `NROS_PARAMS_MAX_DESCRIPTION_BYTES`.
717    /// Returns whether it was truncated; the descriptor also remembers it, so
718    /// the executor can report it once the parameter is declared.
719    pub fn set_description(&mut self, desc: &str) -> bool {
720        #[cfg(feature = "descriptor-text-observer")]
721        crate::descriptor_text_observer::observe_descriptor_text(
722            crate::descriptor_text_observer::DescriptorText::Description,
723            desc.len(),
724        );
725        self.description_truncated = fit_description(&mut self.description, desc);
726        self.description_truncated
727    }
728
729    /// Whether the last description set was truncated and not yet reported.
730    pub fn description_truncated(&self) -> bool {
731        self.description_truncated
732    }
733
734    // Issue 2686.
735    /// Whether the last constraints text set was truncated and not yet
736    /// reported.
737    pub fn constraints_truncated(&self) -> bool {
738        self.constraints_truncated
739    }
740
741    /// Whether either prose field was truncated and not yet reported.
742    pub fn any_text_truncated(&self) -> bool {
743        self.description_truncated || self.constraints_truncated
744    }
745
746    /// The prose fields truncated and not yet reported, description first.
747    pub fn truncated_texts(&self) -> impl Iterator<Item = DescriptorText> + use<> {
748        let d = self
749            .description_truncated
750            .then_some(DescriptorText::Description);
751        let c = self
752            .constraints_truncated
753            .then_some(DescriptorText::Constraints);
754        d.into_iter().chain(c)
755    }
756
757    /// rclc's `additional_constraints`, the fourth argument of
758    /// `rclc_add_parameter_description`. Truncated and recorded like the
759    /// description; returns whether anything was cut.
760    pub fn set_additional_constraints(&mut self, text: &str) -> bool {
761        #[cfg(feature = "descriptor-text-observer")]
762        crate::descriptor_text_observer::observe_descriptor_text(
763            crate::descriptor_text_observer::DescriptorText::Constraints,
764            text.len(),
765        );
766        // Its own flag (issue 2686): the constraints text has its own knob,
767        // so a cut here is reported as the constraints field's, naming
768        // `NROS_PARAMS_MAX_CONSTRAINTS_BYTES`, and leaves an intact description
769        // unreported.
770        self.constraints_truncated = fit_description(&mut self.additional_constraints, text);
771        self.constraints_truncated
772    }
773
774    /// Builder form of [`Self::set_additional_constraints`].
775    pub fn with_additional_constraints(mut self, text: &str) -> Self {
776        self.set_additional_constraints(text);
777        self
778    }
779
780    /// Mark every truncation as reported (phase-446 F2 -- once per parameter).
781    pub(crate) fn clear_truncated_texts(&mut self) {
782        self.description_truncated = false;
783        self.constraints_truncated = false;
784    }
785
786    /// Set read-only flag
787    pub fn with_read_only(mut self, read_only: bool) -> Self {
788        self.read_only = read_only;
789        self
790    }
791
792    /// Set dynamic typing flag
793    pub fn with_dynamic_typing(mut self, dynamic: bool) -> Self {
794        self.dynamic_typing = dynamic;
795        self
796    }
797
798    /// Set integer range constraints
799    pub fn with_integer_range(mut self, min: i64, max: i64, step: i64) -> Self {
800        self.range = ParameterRange::Integer(IntegerRange::new(min, max, step));
801        self
802    }
803
804    /// Set floating point range constraints
805    pub fn with_float_range(mut self, min: f64, max: f64, step: f64) -> Self {
806        self.range = ParameterRange::FloatingPoint(FloatingPointRange::new(min, max, step));
807        self
808    }
809
810    /// Check if a value satisfies the range constraints — min, max AND step.
811    ///
812    /// Forwards to [`ParameterRange::contains`], the single predicate.
813    pub fn validate_range(&self, value: &ParameterValue) -> bool {
814        self.range.contains(value)
815    }
816}
817
818/// A named parameter with value and optional descriptor
819#[derive(Debug, Clone)]
820pub struct Parameter {
821    /// Parameter name
822    pub name: String<MAX_PARAM_NAME_LEN>,
823    /// Parameter value
824    pub value: ParameterValue,
825}
826
827impl Parameter {
828    /// Create a new parameter with a value
829    pub fn new(name: &str, value: ParameterValue) -> Option<Self> {
830        let mut n = String::new();
831        n.push_str(name).ok()?;
832        Some(Self { name: n, value })
833    }
834
835    /// Create a new boolean parameter
836    pub fn bool(name: &str, value: bool) -> Option<Self> {
837        Self::new(name, ParameterValue::Bool(value))
838    }
839
840    /// Create a new integer parameter
841    pub fn integer(name: &str, value: i64) -> Option<Self> {
842        Self::new(name, ParameterValue::Integer(value))
843    }
844
845    /// Create a new double parameter
846    pub fn double(name: &str, value: f64) -> Option<Self> {
847        Self::new(name, ParameterValue::Double(value))
848    }
849
850    /// Create a new string parameter
851    pub fn string(name: &str, value: &str) -> Option<Self> {
852        Self::new(name, ParameterValue::from_string(value)?)
853    }
854
855    /// Get the parameter type
856    pub fn param_type(&self) -> ParameterType {
857        self.value.param_type()
858    }
859
860    /// Get the parameter name
861    pub fn name(&self) -> &str {
862        &self.name
863    }
864}
865
866/// Result of setting a parameter
867///
868/// DEPRECATED: the store answers `Result<(), ParameterError>`,
869/// rclrs's one spelling -- `Success` is `Ok(())` and each other verdict is the
870/// [`ParameterError`](crate::ParameterError) variant of the same name. Kept one
871/// release so out-of-tree code naming it keeps compiling.
872#[deprecated(
873    since = "0.6.0",
874    note = "the parameter store returns `Result<(), ParameterError>`; `Success` is `Ok(())`"
875)]
876#[derive(Debug, Clone, Copy, PartialEq, Eq)]
877pub enum SetParameterResult {
878    /// Parameter was set successfully
879    Success,
880    /// Parameter is read-only
881    ReadOnly,
882    /// Parameter type mismatch (and dynamic typing disabled)
883    TypeMismatch,
884    /// Value is outside allowed range
885    OutOfRange,
886    /// Parameter not found
887    NotFound,
888    /// Storage is full
889    StorageFull,
890    /// A set on a name that was never declared, and the server does not
891    /// allow undeclared parameters (issue 1151; rclrs `parameter.rs`).
892    ///
893    /// Distinct from [`NotFound`](Self::NotFound): that is what a DIRECT
894    /// `ParameterServer::set` says about a missing name; this is what the
895    /// wire-facing [`ParameterServer::apply`](crate::ParameterServerOps::apply)
896    /// says when the only remaining option — declaring it — is switched off.
897    Undeclared,
898    /// A declaration whose range is ill-formed (`min > max` or `step < 0`),
899    /// or whose default does not satisfy its own range (issue 1150; rclrs
900    /// `DeclarationError::InvalidRange` / `InitialValueOutOfRange`).
901    InvalidRange,
902    /// A registered on-set-parameters callback refused the write — rclcpp's
903    /// `SetParametersResult { successful: false }` from
904    /// `add_on_set_parameters_callback` (phase-417 W4.a).
905    ///
906    /// Distinct from every verdict above it: those are the STORE's rules, and
907    /// a caller can predict them from the descriptor. This one is the
908    /// APPLICATION's rule, and only the application knows why.
909    Rejected,
910}
911
912#[allow(deprecated)]
913impl SetParameterResult {
914    /// Check if the result indicates success
915    pub fn is_success(&self) -> bool {
916        matches!(self, Self::Success)
917    }
918}
919
920/// A value does not fit the compile-time parameter capacity.
921///
922/// Returned by [`ParameterVariant::try_to_parameter_value`]. A named type
923/// rather than `()` so the failure reads at the call site and clippy's
924/// `result_unit_err` stays satisfied.
925#[derive(Debug, Clone, Copy, PartialEq, Eq)]
926pub struct CapacityExceeded;
927
928/// Trait for types that can be used as typed parameters
929///
930/// This trait provides conversions between Rust types and ParameterValue,
931/// enabling type-safe parameter access.
932pub trait ParameterVariant: Clone {
933    /// Convert this type to a ParameterValue
934    fn to_parameter_value(&self) -> ParameterValue;
935
936    /// Fallible conversion — `Err(())` when `self` does not fit the
937    /// compile-time capacity (issue 0323).
938    ///
939    /// [`Self::to_parameter_value`] cannot report that: the hosted `std`
940    /// impls used `unwrap_or_default()`, so an over-long `String` became
941    /// `ParameterValue::NotSet` (a TYPE change) and an oversized `Vec`
942    /// became an EMPTY array, both indistinguishable from a caller who
943    /// meant it. Callers at the declare/set boundary should prefer this.
944    ///
945    /// Defaults to infallible for impls whose values cannot overflow (the
946    /// scalars); the `std` collection impls override it.
947    fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
948        Ok(self.to_parameter_value())
949    }
950
951    /// Try to extract this type from a ParameterValue
952    fn from_parameter_value(value: &ParameterValue) -> Option<Self>;
953
954    /// Get the expected parameter type
955    fn parameter_type() -> ParameterType;
956}
957
958// Implement ParameterVariant for basic types
959
960impl ParameterVariant for bool {
961    fn to_parameter_value(&self) -> ParameterValue {
962        ParameterValue::Bool(*self)
963    }
964
965    fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
966        value.as_bool()
967    }
968
969    fn parameter_type() -> ParameterType {
970        ParameterType::Bool
971    }
972}
973
974impl ParameterVariant for i64 {
975    fn to_parameter_value(&self) -> ParameterValue {
976        ParameterValue::Integer(*self)
977    }
978
979    fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
980        value.as_integer()
981    }
982
983    fn parameter_type() -> ParameterType {
984        ParameterType::Integer
985    }
986}
987
988impl ParameterVariant for f64 {
989    fn to_parameter_value(&self) -> ParameterValue {
990        ParameterValue::Double(*self)
991    }
992
993    fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
994        value.as_double()
995    }
996
997    fn parameter_type() -> ParameterType {
998        ParameterType::Double
999    }
1000}
1001
1002// `ParameterVariant` for `heapless::String` — the fixed-capacity parameter type.
1003//
1004// phase-359 W10 — this was `#[cfg(not(feature = "std"))]`, which said a hosted
1005// build may not use a fixed-capacity string parameter. Nothing enforced that:
1006// the `alloc` impl below is on a DIFFERENT type, so an `alloc`-without-`std`
1007// build has always had both, and only the hosted flavour was singled out. A
1008// consumer that wants bounded parameter storage on a host — the usual reason
1009// being that the same node also builds for a target — was told no by a gate
1010// that was expressing a preference, not a constraint.
1011impl ParameterVariant for String<MAX_STRING_VALUE_LEN> {
1012    fn to_parameter_value(&self) -> ParameterValue {
1013        ParameterValue::String(self.clone())
1014    }
1015
1016    fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1017        if let ParameterValue::String(s) = value {
1018            Some(s.clone())
1019        } else {
1020            None
1021        }
1022    }
1023
1024    fn parameter_type() -> ParameterType {
1025        ParameterType::String
1026    }
1027}
1028
1029// Implement ParameterVariant for std::string::String (std)
1030#[cfg(feature = "alloc")]
1031impl ParameterVariant for alloc::string::String {
1032    fn to_parameter_value(&self) -> ParameterValue {
1033        ParameterValue::from_string(self.as_str()).unwrap_or_default()
1034    }
1035
1036    fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
1037        ParameterValue::from_string(self.as_str()).ok_or(CapacityExceeded)
1038    }
1039
1040    fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1041        value.as_string().map(|s| s.to_string())
1042    }
1043
1044    fn parameter_type() -> ParameterType {
1045        ParameterType::String
1046    }
1047}
1048
1049// Implement ParameterVariant for std::vec::Vec<i64> (std)
1050#[cfg(feature = "alloc")]
1051impl ParameterVariant for alloc::vec::Vec<i64> {
1052    fn to_parameter_value(&self) -> ParameterValue {
1053        ParameterValue::IntegerArray(Vec::from_slice(self.as_slice()).unwrap_or_default())
1054    }
1055
1056    fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
1057        Vec::from_slice(self.as_slice())
1058            .map(ParameterValue::IntegerArray)
1059            .map_err(|_| CapacityExceeded)
1060    }
1061
1062    fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1063        value.as_integer_array().map(|v| v.to_vec())
1064    }
1065
1066    fn parameter_type() -> ParameterType {
1067        ParameterType::IntegerArray
1068    }
1069}
1070
1071// Implement ParameterVariant for std::vec::Vec<f64> (std)
1072#[cfg(feature = "alloc")]
1073impl ParameterVariant for alloc::vec::Vec<f64> {
1074    fn to_parameter_value(&self) -> ParameterValue {
1075        ParameterValue::DoubleArray(Vec::from_slice(self.as_slice()).unwrap_or_default())
1076    }
1077
1078    fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
1079        Vec::from_slice(self.as_slice())
1080            .map(ParameterValue::DoubleArray)
1081            .map_err(|_| CapacityExceeded)
1082    }
1083
1084    fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1085        value.as_double_array().map(|v| v.to_vec())
1086    }
1087
1088    fn parameter_type() -> ParameterType {
1089        ParameterType::DoubleArray
1090    }
1091}
1092
1093// Implement ParameterVariant for std::vec::Vec<bool> (std)
1094#[cfg(feature = "alloc")]
1095impl ParameterVariant for alloc::vec::Vec<bool> {
1096    fn to_parameter_value(&self) -> ParameterValue {
1097        ParameterValue::BoolArray(Vec::from_slice(self.as_slice()).unwrap_or_default())
1098    }
1099
1100    fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
1101        Vec::from_slice(self.as_slice())
1102            .map(ParameterValue::BoolArray)
1103            .map_err(|_| CapacityExceeded)
1104    }
1105
1106    fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1107        value.as_bool_array().map(|v| v.to_vec())
1108    }
1109
1110    fn parameter_type() -> ParameterType {
1111        ParameterType::BoolArray
1112    }
1113}
1114
1115// Implement ParameterVariant for std::vec::Vec<std::string::String> (std)
1116#[cfg(feature = "alloc")]
1117impl ParameterVariant for alloc::vec::Vec<alloc::string::String> {
1118    fn to_parameter_value(&self) -> ParameterValue {
1119        let mut vec = Vec::new();
1120        for s in self {
1121            let mut h_string = String::new();
1122            if h_string.push_str(s.as_str()).is_ok() {
1123                let _ = vec.push(h_string);
1124            }
1125        }
1126        ParameterValue::StringArray(vec)
1127    }
1128
1129    fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
1130        // The infallible form above SKIPS any element that does not fit,
1131        // so a 3-element vec could arrive as 2 with no signal (issue 0323).
1132        let mut vec = Vec::new();
1133        for s in self {
1134            let mut h_string = String::new();
1135            h_string
1136                .push_str(s.as_str())
1137                .map_err(|_| CapacityExceeded)?;
1138            vec.push(h_string).map_err(|_| CapacityExceeded)?;
1139        }
1140        Ok(ParameterValue::StringArray(vec))
1141    }
1142
1143    fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1144        if let ParameterValue::StringArray(v) = value {
1145            Some(v.iter().map(|s| s.as_str().to_string()).collect())
1146        } else {
1147            None
1148        }
1149    }
1150
1151    fn parameter_type() -> ParameterType {
1152        ParameterType::StringArray
1153    }
1154}
1155
1156#[cfg(test)]
1157#[allow(deprecated)] // the retired SetParameterResult keeps its own tests one release
1158mod tests {
1159    use super::*;
1160
1161    // ── issue 1150: step is ENFORCED, min/max/step as rclrs `range.rs` ──
1162
1163    #[test]
1164    fn integer_step_accepts_lattice_points_and_rejects_the_rest() {
1165        let r = IntegerRange::new(10, 20, 5);
1166        assert!(r.contains(10));
1167        assert!(r.contains(15));
1168        assert!(r.contains(20));
1169        // Inside min..max but off the lattice: this is the case the old
1170        // `min <= v <= max` accepted and upstream rejects.
1171        assert!(!r.contains(11));
1172        assert!(!r.contains(14));
1173        assert!(!r.contains(19));
1174        // Bounds still apply.
1175        assert!(!r.contains(5));
1176        assert!(!r.contains(25));
1177    }
1178
1179    #[test]
1180    fn integer_upper_bound_is_accepted_even_off_lattice() {
1181        // rclrs: `if upper == value { return true }` before the step test.
1182        let r = IntegerRange::new(0, 7, 3);
1183        assert!(r.contains(6));
1184        assert!(!r.contains(5));
1185        assert!(r.contains(7));
1186    }
1187
1188    #[test]
1189    fn integer_step_zero_means_unconstrained() {
1190        let r = IntegerRange::new(0, 100, 0);
1191        for v in [0, 1, 37, 99, 100] {
1192            assert!(r.contains(v), "{v}");
1193        }
1194        assert!(!r.contains(101));
1195    }
1196
1197    #[test]
1198    fn integer_step_does_not_overflow_at_the_extremes() {
1199        let r = IntegerRange::new(i64::MIN, i64::MAX, 2);
1200        // `v - min` overflows for every positive v; that must be a verdict,
1201        // not a panic.
1202        let _ = r.contains(1);
1203        let _ = r.contains(i64::MAX - 1);
1204        assert!(r.contains(i64::MIN));
1205        assert!(r.contains(i64::MAX));
1206    }
1207
1208    #[test]
1209    fn float_step_accepts_lattice_points_within_tolerance() {
1210        let r = FloatingPointRange::new(0.0, 1.0, 0.1);
1211        // 0.3 is not exactly representable and 0.1 * 3 != 0.3 in binary;
1212        // upstream's 100-ULP tolerance is what makes this pass.
1213        for v in [0.0, 0.1, 0.3, 0.7, 1.0] {
1214            assert!(r.contains(v), "{v}");
1215        }
1216        assert!(r.contains(0.1 + 0.2));
1217        // Off the lattice by more than the tolerance.
1218        assert!(!r.contains(0.05));
1219        assert!(!r.contains(0.35));
1220        assert!(!r.contains(0.999));
1221        // Bounds.
1222        assert!(!r.contains(-0.1));
1223        assert!(!r.contains(1.1));
1224    }
1225
1226    #[test]
1227    fn float_endpoints_are_accepted_even_off_lattice() {
1228        let r = FloatingPointRange::new(0.0, 1.0, 0.3);
1229        assert!(r.contains(0.9));
1230        assert!(!r.contains(0.95));
1231        assert!(r.contains(1.0));
1232    }
1233
1234    #[test]
1235    fn float_step_zero_means_unconstrained() {
1236        let r = FloatingPointRange::new(0.0, 10.0, 0.0);
1237        for v in [0.0, 0.001, 3.25, 9.999, 10.0] {
1238            assert!(r.contains(v), "{v}");
1239        }
1240        assert!(!r.contains(10.001));
1241    }
1242
1243    #[test]
1244    fn float_step_with_a_nonzero_min_is_relative_to_min() {
1245        let r = FloatingPointRange::new(0.5, 2.5, 0.5);
1246        assert!(r.contains(1.5));
1247        assert!(!r.contains(1.25));
1248        assert!(r.contains(0.5));
1249    }
1250
1251    #[test]
1252    fn range_validity_is_min_le_max_and_step_ge_zero() {
1253        assert!(IntegerRange::new(0, 10, 0).is_valid());
1254        assert!(IntegerRange::new(0, 10, 3).is_valid());
1255        assert!(IntegerRange::new(5, 5, 1).is_valid());
1256        assert!(!IntegerRange::new(10, 0, 1).is_valid());
1257        assert!(!IntegerRange::new(0, 10, -1).is_valid());
1258        assert!(FloatingPointRange::new(0.0, 1.0, 0.0).is_valid());
1259        assert!(!FloatingPointRange::new(1.0, 0.0, 0.1).is_valid());
1260        assert!(!FloatingPointRange::new(0.0, 1.0, -0.1).is_valid());
1261        assert!(!FloatingPointRange::new(0.0, 1.0, f64::NAN).is_valid());
1262        assert!(ParameterRange::None.is_valid());
1263    }
1264
1265    #[test]
1266    fn descriptor_validate_range_enforces_step_on_both_arms() {
1267        let int_desc = ParameterDescriptor::new("i", ParameterType::Integer)
1268            .unwrap()
1269            .with_integer_range(0, 100, 10);
1270        assert!(int_desc.validate_range(&ParameterValue::Integer(30)));
1271        assert!(!int_desc.validate_range(&ParameterValue::Integer(31)));
1272        // A value of the other type is not the range's business.
1273        assert!(int_desc.validate_range(&ParameterValue::Double(31.0)));
1274
1275        let f_desc = ParameterDescriptor::new("f", ParameterType::Double)
1276            .unwrap()
1277            .with_float_range(0.0, 10.0, 0.5);
1278        assert!(f_desc.validate_range(&ParameterValue::Double(2.5)));
1279        assert!(!f_desc.validate_range(&ParameterValue::Double(2.7)));
1280        assert!(f_desc.validate_range(&ParameterValue::Integer(3)));
1281    }
1282
1283    #[test]
1284    #[allow(clippy::approx_constant)]
1285    fn test_parameter_value_types() {
1286        let bool_val = ParameterValue::Bool(true);
1287        assert_eq!(bool_val.param_type(), ParameterType::Bool);
1288        assert_eq!(bool_val.as_bool(), Some(true));
1289
1290        let int_val = ParameterValue::Integer(42);
1291        assert_eq!(int_val.param_type(), ParameterType::Integer);
1292        assert_eq!(int_val.as_integer(), Some(42));
1293
1294        let double_val = ParameterValue::Double(3.14);
1295        assert_eq!(double_val.param_type(), ParameterType::Double);
1296        assert_eq!(double_val.as_double(), Some(3.14));
1297    }
1298
1299    #[test]
1300    fn test_parameter_value_string() {
1301        let string_val = ParameterValue::from_string("hello").unwrap();
1302        assert_eq!(string_val.param_type(), ParameterType::String);
1303        assert_eq!(string_val.as_string(), Some("hello"));
1304    }
1305
1306    #[test]
1307    fn test_parameter_creation() {
1308        let param = Parameter::bool("my_param", true).unwrap();
1309        assert_eq!(param.name(), "my_param");
1310        assert_eq!(param.param_type(), ParameterType::Bool);
1311        assert_eq!(param.value.as_bool(), Some(true));
1312    }
1313
1314    #[test]
1315    fn test_parameter_descriptor() {
1316        let desc = ParameterDescriptor::new("speed", ParameterType::Double)
1317            .unwrap()
1318            .with_description("Maximum speed in m/s")
1319            .with_float_range(0.0, 10.0, 0.1);
1320
1321        assert_eq!(desc.param_type, ParameterType::Double);
1322        assert!(!desc.read_only);
1323
1324        // Test range validation
1325        assert!(desc.validate_range(&ParameterValue::Double(5.0)));
1326        assert!(!desc.validate_range(&ParameterValue::Double(15.0)));
1327    }
1328
1329    #[test]
1330    fn test_integer_range() {
1331        let range = IntegerRange::new(0, 100, 1);
1332        assert!(range.contains(50));
1333        assert!(range.contains(0));
1334        assert!(range.contains(100));
1335        assert!(!range.contains(-1));
1336        assert!(!range.contains(101));
1337    }
1338
1339    #[test]
1340    fn test_set_result() {
1341        assert!(SetParameterResult::Success.is_success());
1342        assert!(!SetParameterResult::ReadOnly.is_success());
1343    }
1344}
1345
1346// =============================================================================
1347// Ghost model validation
1348// =============================================================================
1349
1350#[cfg(test)]
1351mod ghost_checks {
1352    use super::*;
1353    use nros_ghost_types::ParameterValueGhost;
1354
1355    /// Structural check: exhaustive match maps all 10 variants.
1356    /// If a variant is added or removed, this fails to compile.
1357    fn ghost_from_value(v: &ParameterValue) -> ParameterValueGhost {
1358        match v {
1359            ParameterValue::NotSet => ParameterValueGhost::NotSet,
1360            ParameterValue::Bool(b) => ParameterValueGhost::Bool(*b),
1361            ParameterValue::Integer(i) => ParameterValueGhost::Integer(*i),
1362            ParameterValue::Double(_) => ParameterValueGhost::Double,
1363            ParameterValue::String(_) => ParameterValueGhost::String,
1364            ParameterValue::ByteArray(_) => ParameterValueGhost::ByteArray,
1365            ParameterValue::BoolArray(_) => ParameterValueGhost::BoolArray,
1366            ParameterValue::IntegerArray(_) => ParameterValueGhost::IntegerArray,
1367            ParameterValue::DoubleArray(_) => ParameterValueGhost::DoubleArray,
1368            ParameterValue::StringArray(_) => ParameterValueGhost::StringArray,
1369        }
1370    }
1371
1372    #[test]
1373    fn ghost_variant_coverage() {
1374        // Exhaustive match compiles — all 10 variants exist in both types
1375        let _ = ghost_from_value(&ParameterValue::NotSet);
1376        let _ = ghost_from_value(&ParameterValue::Bool(true));
1377        let _ = ghost_from_value(&ParameterValue::Integer(0));
1378        let _ = ghost_from_value(&ParameterValue::Double(0.0));
1379        let _ = ghost_from_value(&ParameterValue::String(String::new()));
1380        let _ = ghost_from_value(&ParameterValue::ByteArray(Vec::new()));
1381        let _ = ghost_from_value(&ParameterValue::BoolArray(Vec::new()));
1382        let _ = ghost_from_value(&ParameterValue::IntegerArray(Vec::new()));
1383        let _ = ghost_from_value(&ParameterValue::DoubleArray(Vec::new()));
1384        let _ = ghost_from_value(&ParameterValue::StringArray(Vec::new()));
1385    }
1386
1387    #[test]
1388    fn ghost_bool_preserves() {
1389        let ghost = ghost_from_value(&ParameterValue::Bool(true));
1390        assert!(matches!(ghost, ParameterValueGhost::Bool(true)));
1391    }
1392
1393    #[test]
1394    fn ghost_integer_preserves() {
1395        let ghost = ghost_from_value(&ParameterValue::Integer(42));
1396        assert!(matches!(ghost, ParameterValueGhost::Integer(42)));
1397    }
1398}
1399
1400// =============================================================================
1401// Kani bounded model checking proofs
1402// =============================================================================
1403
1404#[cfg(kani)]
1405mod verification {
1406    use super::*;
1407
1408    // ---- ParameterValue type conversions ----
1409
1410    #[kani::proof]
1411    fn parameter_i64_roundtrip() {
1412        let val: i64 = kani::any();
1413        let pv = ParameterValue::from_integer(val);
1414        assert_eq!(pv.as_integer(), Some(val));
1415        assert_eq!(pv.param_type(), ParameterType::Integer);
1416        assert!(pv.is_set());
1417    }
1418
1419    #[kani::proof]
1420    fn parameter_bool_roundtrip() {
1421        let val: bool = kani::any();
1422        let pv = ParameterValue::from_bool(val);
1423        assert_eq!(pv.as_bool(), Some(val));
1424        assert_eq!(pv.param_type(), ParameterType::Bool);
1425        assert!(pv.is_set());
1426    }
1427
1428    #[kani::proof]
1429    fn parameter_double_roundtrip() {
1430        let val: f64 = kani::any();
1431        let pv = ParameterValue::from_double(val);
1432        let result = pv.as_double();
1433        assert!(result.is_some());
1434        assert_eq!(result.unwrap().to_bits(), val.to_bits());
1435        assert_eq!(pv.param_type(), ParameterType::Double);
1436    }
1437
1438    #[kani::proof]
1439    fn parameter_not_set_default() {
1440        let pv = ParameterValue::default();
1441        assert!(!pv.is_set());
1442        assert_eq!(pv.param_type(), ParameterType::NotSet);
1443        assert!(pv.as_bool().is_none());
1444        assert!(pv.as_integer().is_none());
1445        assert!(pv.as_double().is_none());
1446        assert!(pv.as_string().is_none());
1447    }
1448
1449    // ---- Type mismatch returns None ----
1450
1451    #[kani::proof]
1452    fn parameter_type_mismatch_bool() {
1453        let val: i64 = kani::any();
1454        let pv = ParameterValue::from_integer(val);
1455        assert!(pv.as_bool().is_none());
1456        assert!(pv.as_double().is_none());
1457        assert!(pv.as_string().is_none());
1458    }
1459
1460    #[kani::proof]
1461    fn parameter_type_mismatch_integer() {
1462        let val: bool = kani::any();
1463        let pv = ParameterValue::from_bool(val);
1464        assert!(pv.as_integer().is_none());
1465        assert!(pv.as_double().is_none());
1466        assert!(pv.as_string().is_none());
1467    }
1468
1469    // ---- IntegerRange ----
1470
1471    #[kani::proof]
1472    fn integer_range_contains_bounds() {
1473        let min: i64 = kani::any();
1474        let max: i64 = kani::any();
1475        // Constrain to bounded range to avoid subtraction overflow
1476        kani::assume(min >= -1_000_000 && min <= 1_000_000);
1477        kani::assume(max >= -1_000_000 && max <= 1_000_000);
1478        kani::assume(min <= max);
1479        let range = IntegerRange::new(min, max, 1);
1480        // Endpoints must be contained
1481        assert!(range.contains(min));
1482        assert!(range.contains(max));
1483    }
1484
1485    #[kani::proof]
1486    fn integer_range_outside_bounds() {
1487        let min: i64 = kani::any();
1488        let max: i64 = kani::any();
1489        kani::assume(min <= max);
1490        kani::assume(min > i64::MIN); // So min-1 doesn't overflow
1491        kani::assume(max < i64::MAX); // So max+1 doesn't overflow
1492        let range = IntegerRange::new(min, max, 1);
1493        assert!(!range.contains(min - 1));
1494        assert!(!range.contains(max + 1));
1495    }
1496
1497    // ---- FloatingPointRange ----
1498
1499    #[kani::proof]
1500    fn float_range_contains_bounds() {
1501        let min: f64 = kani::any();
1502        let max: f64 = kani::any();
1503        kani::assume(!min.is_nan() && !max.is_nan());
1504        kani::assume(min <= max);
1505        let range = FloatingPointRange::new(min, max, 0.0);
1506        assert!(range.contains(min));
1507        assert!(range.contains(max));
1508    }
1509
1510    // ---- SetParameterResult ----
1511
1512    #[kani::proof]
1513    fn set_result_success_only() {
1514        // Only Success should return true from is_success()
1515        assert!(SetParameterResult::Success.is_success());
1516        assert!(!SetParameterResult::ReadOnly.is_success());
1517        assert!(!SetParameterResult::TypeMismatch.is_success());
1518        assert!(!SetParameterResult::OutOfRange.is_success());
1519        assert!(!SetParameterResult::NotFound.is_success());
1520        assert!(!SetParameterResult::StorageFull.is_success());
1521    }
1522}
1523
1524// The heap is what these need — the over-long values they build are a `Vec` and
1525// a `String`, which `alloc` has.
1526#[cfg(all(test, feature = "alloc"))]
1527mod issue_0323_tests {
1528    use super::*;
1529
1530    /// issue 0323 — an over-long hosted `String` used to become
1531    /// `ParameterValue::NotSet` via `unwrap_or_default()`: a TYPE change the
1532    /// caller could not distinguish from deliberately clearing the parameter.
1533    #[test]
1534    fn oversize_string_is_rejected_not_silently_notset() {
1535        let long = "x".repeat(MAX_STRING_VALUE_LEN + 1);
1536        assert!(
1537            matches!(long.to_parameter_value(), ParameterValue::NotSet),
1538            "documenting the legacy infallible behaviour"
1539        );
1540        assert!(
1541            long.try_to_parameter_value().is_err(),
1542            "the fallible path must reject it"
1543        );
1544    }
1545
1546    /// Issue 2647 -- a value is as large as its largest variant, and the
1547    /// string array is the product of two bounds. Its element count is
1548    /// `MAX_STRING_ARRAY_LEN`, never `MAX_ARRAY_LEN`, so an image with a
1549    /// `string` and a `double_array` but no `string_array` (which derives
1550    /// `MAX_STRING_ARRAY_LEN = 0`) does not pay their product in every slot.
1551    #[test]
1552    fn a_value_is_sized_by_the_string_array_bound_not_the_array_bound() {
1553        use core::mem::size_of;
1554        let string_array = size_of::<Vec<String<MAX_STRING_VALUE_LEN>, MAX_STRING_ARRAY_LEN>>();
1555        let largest_other = [
1556            size_of::<String<MAX_STRING_VALUE_LEN>>(),
1557            size_of::<Vec<bool, MAX_ARRAY_LEN>>(),
1558            size_of::<Vec<i64, MAX_ARRAY_LEN>>(),
1559            size_of::<Vec<f64, MAX_ARRAY_LEN>>(),
1560            size_of::<Vec<u8, MAX_BYTE_ARRAY_LEN>>(),
1561        ]
1562        .into_iter()
1563        .max()
1564        .unwrap();
1565        // The enum adds at most a tag and its alignment to its largest variant.
1566        let bound = string_array.max(largest_other) + 16;
1567        assert!(
1568            size_of::<ParameterValue>() <= bound,
1569            "ParameterValue is {} B, more than its largest variant ({} B) plus a tag",
1570            size_of::<ParameterValue>(),
1571            string_array.max(largest_other)
1572        );
1573        // And the string-array variant uses ITS bound: no element count but
1574        // `MAX_STRING_ARRAY_LEN` fits, whatever `MAX_ARRAY_LEN` is.
1575        let strings: alloc::vec::Vec<alloc::string::String> =
1576            (0..MAX_STRING_ARRAY_LEN).map(|_| "w".into()).collect();
1577        assert!(strings.clone().try_to_parameter_value().is_ok());
1578        let mut over = strings;
1579        over.push("w".into());
1580        assert!(over.try_to_parameter_value().is_err());
1581    }
1582
1583    /// The array case: `unwrap_or_default()` yielded an EMPTY array.
1584    #[test]
1585    fn oversize_integer_array_is_rejected_not_silently_empty() {
1586        let big: alloc::vec::Vec<i64> = (0..(MAX_ARRAY_LEN as i64 + 1)).collect();
1587        match big.to_parameter_value() {
1588            ParameterValue::IntegerArray(v) => {
1589                assert!(v.is_empty(), "documenting the legacy empty-array behaviour")
1590            }
1591            other => panic!("unexpected {other:?}"),
1592        }
1593        assert!(big.try_to_parameter_value().is_err());
1594    }
1595
1596    /// `Vec<String>` silently SKIPPED elements that did not fit.
1597    #[test]
1598    fn oversize_string_array_element_is_rejected_not_skipped() {
1599        let big: alloc::vec::Vec<alloc::string::String> = (0..(MAX_STRING_ARRAY_LEN + 1))
1600            .map(|i| i.to_string())
1601            .collect();
1602        assert!(big.try_to_parameter_value().is_err());
1603    }
1604
1605    // -- phase-446 F2: a description has its own capacity and never vanishes --
1606
1607    /// A description that fits is stored whole and reports nothing.
1608    #[test]
1609    fn a_description_that_fits_is_stored_whole() {
1610        let mut s: String<16> = String::new();
1611        assert!(!fit_description(&mut s, "wheel speed"));
1612        assert_eq!(s.as_str(), "wheel speed");
1613        // Exactly the capacity is still a fit.
1614        assert!(!fit_description(&mut s, "0123456789abcdef"));
1615        assert_eq!(s.len(), 16);
1616    }
1617
1618    /// One byte too long used to store NOTHING (`let _ = push_str`, which is
1619    /// all-or-nothing). Now it keeps the prefix and says it cut.
1620    #[test]
1621    fn a_long_description_keeps_its_prefix_and_reports_the_cut() {
1622        let mut s: String<8> = String::new();
1623        assert!(fit_description(&mut s, "0123456789"));
1624        assert_eq!(s.as_str(), "01234567");
1625    }
1626
1627    /// The cut never splits a character: `e-acute` is two bytes and `ruler`
1628    /// (U+1F4CF) four, so a cut inside either backs off to the boundary before
1629    /// it rather than producing invalid UTF-8.
1630    #[test]
1631    fn truncation_backs_off_to_a_character_boundary() {
1632        let mut s: String<5> = String::new();
1633        // "abcd" + e-acute (bytes 4..6): byte 5 is mid-character.
1634        assert!(fit_description(&mut s, "abcd\u{e9}f"));
1635        assert_eq!(s.as_str(), "abcd");
1636        let mut s: String<6> = String::new();
1637        // "ab" + a 4-byte character (bytes 2..6) fits exactly at 6.
1638        assert!(fit_description(&mut s, "ab\u{1f4cf}z"));
1639        assert_eq!(s.as_str(), "ab\u{1f4cf}");
1640        let mut s: String<5> = String::new();
1641        assert!(fit_description(&mut s, "ab\u{1f4cf}z"));
1642        assert_eq!(s.as_str(), "ab");
1643    }
1644
1645    /// Capacity 0 is a stated "no descriptions": nothing is stored, and any
1646    /// non-empty description still reports, so the choice is visible.
1647    #[test]
1648    fn zero_capacity_stores_no_description_and_reports_it() {
1649        let mut s: String<0> = String::new();
1650        assert!(fit_description(&mut s, "anything"));
1651        assert!(s.is_empty());
1652        assert!(
1653            !fit_description(&mut s, ""),
1654            "an empty description loses nothing, so there is nothing to report"
1655        );
1656    }
1657
1658    /// The descriptor records the cut, and a fitting description clears it.
1659    #[test]
1660    fn the_descriptor_remembers_a_truncated_description() {
1661        let long = "d".repeat(MAX_PARAM_DESCRIPTION_LEN + 3);
1662        let d = ParameterDescriptor::new("p", ParameterType::Bool)
1663            .unwrap()
1664            .with_description(&long);
1665        assert_eq!(d.description.len(), MAX_PARAM_DESCRIPTION_LEN);
1666        assert!(d.description_truncated());
1667        let mut d = d;
1668        assert!(!d.set_description(""));
1669        assert!(!d.description_truncated());
1670    }
1671
1672    /// Issue 2686 -- a constraints text that does not fit is the
1673    /// constraints field's truncation, sized by its own knob, not a
1674    /// description that did not fit. The description here is intact.
1675    #[test]
1676    fn a_truncated_constraints_text_is_not_a_truncated_description() {
1677        let long = "c".repeat(MAX_PARAM_CONSTRAINTS_LEN + 1);
1678        let mut d = ParameterDescriptor::new("p", ParameterType::Bool)
1679            .unwrap()
1680            .with_description("fits");
1681        assert!(d.set_additional_constraints(&long));
1682        assert!(
1683            !d.description_truncated(),
1684            "the description is whole; only the constraints were cut"
1685        );
1686        assert!(d.constraints_truncated());
1687        let cut: heapless::Vec<DescriptorText, 2> = d.truncated_texts().collect();
1688        assert_eq!(cut.as_slice(), &[DescriptorText::Constraints]);
1689        assert_eq!(cut[0].knob(), "NROS_PARAMS_MAX_CONSTRAINTS_BYTES");
1690        assert_eq!(cut[0].field(), "additional_constraints");
1691        assert_eq!(cut[0].capacity(), MAX_PARAM_CONSTRAINTS_LEN);
1692        // Both cut: both reported, each under its own knob.
1693        d.set_description(&"d".repeat(MAX_PARAM_DESCRIPTION_LEN + 1));
1694        let both: heapless::Vec<DescriptorText, 2> = d.truncated_texts().collect();
1695        assert_eq!(
1696            both.as_slice(),
1697            &[DescriptorText::Description, DescriptorText::Constraints]
1698        );
1699        assert_eq!(both[0].knob(), "NROS_PARAMS_MAX_DESCRIPTION_BYTES");
1700    }
1701}