Skip to main content

nros_params/
typed.rs

1//! Typed parameter API
2//!
3//! This module provides a fluent builder pattern for declaring typed parameters
4//! in a ROS 2 node, aligning with the rclrs API.
5
6#[cfg(test)]
7use crate::ParameterStorage;
8use crate::{
9    DeclarationError, NodeKey, ParameterDescriptor, ParameterRange, ParameterServer, ParameterType,
10};
11use heapless::String;
12
13/// Trait for types that can be used as typed parameters
14pub use crate::ParameterVariant;
15
16/// Error type for typed parameter operations
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ParameterError {
19    /// Parameter already declared with a different type
20    TypeMismatch,
21    /// Value is outside allowed range
22    OutOfRange,
23    /// Parameter is read-only
24    ReadOnly,
25    /// Parameter not found
26    NotFound,
27    /// Internal storage is full
28    StorageFull,
29    /// String conversion failed
30    StringConversion,
31    /// Invalid range for type
32    InvalidRange,
33    /// An on-set-parameters callback refused the write (phase-417 W4.a).
34    Rejected,
35    /// A set on a name that was never declared, and the server does not
36    /// allow undeclared parameters (issue 1151; rclrs `parameter.rs`).
37    ///
38    /// Distinct from [`NotFound`](Self::NotFound): that is what a DIRECT
39    /// `ParameterServer::set` says about a missing name; this is what the
40    /// wire-facing [`ParameterServer::apply`](crate::ParameterServerOps::apply)
41    /// says when the only remaining option — declaring it — is switched off.
42    /// Moved here from the retired `SetParameterResult` (phase-515).
43    Undeclared,
44}
45
46#[allow(deprecated)]
47impl From<crate::SetParameterResult> for ParameterError {
48    /// The retired verdict enum's error half, kept for one release beside the
49    /// deprecated type (phase-515).
50    fn from(result: crate::SetParameterResult) -> Self {
51        use crate::SetParameterResult as R;
52        match result {
53            R::TypeMismatch => ParameterError::TypeMismatch,
54            R::OutOfRange => ParameterError::OutOfRange,
55            R::ReadOnly => ParameterError::ReadOnly,
56            R::NotFound => ParameterError::NotFound,
57            R::StorageFull => ParameterError::StorageFull,
58            R::InvalidRange => ParameterError::InvalidRange,
59            R::Rejected => ParameterError::Rejected,
60            R::Undeclared => ParameterError::Undeclared,
61            R::Success => panic!("SetParameterResult::Success is not an error"),
62        }
63    }
64}
65
66/// Trait for types that can be converted to a parameter range from `RangeInclusive`
67pub trait RangeConvertible: ParameterVariant + Clone {
68    /// Convert a `RangeInclusive<Self>` to a `ParameterRange`
69    fn to_parameter_range(
70        range: core::ops::RangeInclusive<Self>,
71    ) -> Result<ParameterRange, ParameterError>;
72}
73
74impl RangeConvertible for i64 {
75    fn to_parameter_range(
76        range: core::ops::RangeInclusive<Self>,
77    ) -> Result<ParameterRange, ParameterError> {
78        Ok(ParameterRange::Integer(crate::IntegerRange::new(
79            *range.start(),
80            *range.end(),
81            1, // Default step of 1
82        )))
83    }
84}
85
86impl RangeConvertible for f64 {
87    fn to_parameter_range(
88        range: core::ops::RangeInclusive<Self>,
89    ) -> Result<ParameterRange, ParameterError> {
90        Ok(ParameterRange::FloatingPoint(
91            crate::FloatingPointRange::new(
92                *range.start(),
93                *range.end(),
94                0.0, // No step constraint (any value in range is valid)
95            ),
96        ))
97    }
98}
99
100/// Builder for declaring a typed parameter
101pub struct ParameterBuilder<'a, 's, T: ParameterVariant> {
102    /// Borrow of the parameter server. phase-382 W2' — the server itself
103    /// borrows its table, so every handle onto it carries BOTH lifetimes:
104    /// `'a` is this borrow, `'s` is the caller-owned storage underneath.
105    server: &'a mut ParameterServer<'s>,
106    /// phase-426 W1 — the node this parameter belongs to. Fixed when the
107    /// builder is made, so a chained call cannot lose it and land the
108    /// declaration on a sibling.
109    node: NodeKey,
110    /// Parameter name
111    name: &'a str,
112    /// Default value
113    default: Option<T>,
114    /// Human-readable description
115    description: Option<&'a str>,
116    /// phase-417 W4.a — the descriptor's other free text,
117    /// `rcl_interfaces/msg/ParameterDescriptor::additional_constraints`, which
118    /// `ros2 param describe` prints.
119    constraints: Option<&'a str>,
120    /// Range constraints
121    range: Option<ParameterRange>,
122    /// Whether the parameter is read-only
123    read_only: bool,
124    /// Phantom data to hold the type parameter
125    _phantom: core::marker::PhantomData<T>,
126}
127
128impl<'a, 's, T: ParameterVariant> ParameterBuilder<'a, 's, T> {
129    /// Create a new parameter builder
130    pub fn new(server: &'a mut ParameterServer<'s>, node: NodeKey, name: &'a str) -> Self {
131        Self {
132            server,
133            node,
134            name,
135            default: None,
136            description: None,
137            constraints: None,
138            range: None,
139            read_only: false,
140            _phantom: core::marker::PhantomData,
141        }
142    }
143
144    /// Set a default value for the parameter
145    ///
146    /// The ONE default setter. rclrs also has `default_from_iter(impl IntoIterator)`
147    /// and `default_string_array(&[&str])`; neither exists here, so pass the array
148    /// value itself. An array is a `heapless::Vec` bounded by `MAX_ARRAY_LEN` (a
149    /// string array is `Vec<String<MAX_STRING_VALUE_LEN>, MAX_STRING_ARRAY_LEN>`, two
150    /// compile-time bounds), and an over-capacity value is refused by
151    /// [`ParameterVariant::try_to_parameter_value`], never truncated. No allocator.
152    pub fn default(mut self, value: T) -> Self {
153        self.default = Some(value);
154        self
155    }
156
157    /// Set a human-readable description for the parameter
158    pub fn description(mut self, desc: &'a str) -> Self {
159        self.description = Some(desc);
160        self
161    }
162
163    /// Set the free-text `additional_constraints` — rclrs's
164    /// `ParameterBuilder::constraints`, and rclc's fourth argument to
165    /// `rclc_add_parameter_description`.
166    ///
167    /// Text longer than `NROS_PARAMS_MAX_CONSTRAINTS_BYTES` — whose default is
168    /// **0**, so an image pays for this field only when it asks for it — is
169    /// truncated at a character boundary and REPORTED once through
170    /// [`ParameterServer::take_truncated_descriptions`](crate::ParameterServerOps::take_truncated_descriptions), never dropped in
171    /// silence.
172    ///
173    /// [`ParameterServer::take_truncated_descriptions`]: crate::ParameterServerOps::take_truncated_descriptions
174    pub fn constraints(mut self, text: &'a str) -> Self {
175        self.constraints = Some(text);
176        self
177    }
178
179    /// Set integer range constraints for the parameter
180    pub fn integer_range(mut self, min: i64, max: i64, step: i64) -> Result<Self, ParameterError> {
181        if T::parameter_type() != ParameterType::Integer {
182            return Err(ParameterError::InvalidRange);
183        }
184        let range = crate::IntegerRange::new(min, max, step);
185        // Issue 1150 — `min > max` or a negative step is refused here, where
186        // the caller can see it, not silently stored and published.
187        if !range.is_valid() {
188            return Err(ParameterError::InvalidRange);
189        }
190        self.range = Some(ParameterRange::Integer(range));
191        Ok(self)
192    }
193
194    /// Set floating point range constraints for the parameter
195    pub fn float_range(mut self, min: f64, max: f64, step: f64) -> Result<Self, ParameterError> {
196        if T::parameter_type() != ParameterType::Double {
197            return Err(ParameterError::InvalidRange);
198        }
199        let range = crate::FloatingPointRange::new(min, max, step);
200        if !range.is_valid() {
201            return Err(ParameterError::InvalidRange);
202        }
203        self.range = Some(ParameterRange::FloatingPoint(range));
204        Ok(self)
205    }
206
207    /// Set range constraints using an inclusive range
208    ///
209    /// This is a convenience method that works with `RangeInclusive`:
210    /// - For `i64` parameters: `range(0..=100)` sets an integer range with step 1
211    /// - For `f64` parameters: `range(0.0..=1.0)` sets a floating point range with step 0.0
212    ///
213    /// For more control (e.g., custom step), use `integer_range()` or `float_range()`.
214    pub fn range(mut self, range: core::ops::RangeInclusive<T>) -> Result<Self, ParameterError>
215    where
216        T: RangeConvertible,
217    {
218        self.range = Some(T::to_parameter_range(range)?);
219        Ok(self)
220    }
221
222    /// The descriptor the three terminal verbs declare with — ONE
223    /// construction (phase-417 W4.a).
224    ///
225    /// It was written out three times, identically but for the `read_only`
226    /// line, which is why `additional_constraints` would otherwise have needed
227    /// adding in three places and reached whichever two somebody remembered.
228    /// `read_only` stays at the call site because that is the one line the
229    /// three genuinely disagree about.
230    ///
231    /// phase-446 F2 -- a too-long description is truncated and reported, never
232    /// a reason to refuse the declaration: the contract derives the string
233    /// capacity to 0 for a scalar-only image, and this used to fail every
234    /// `.description(..)` there with `StringConversion`. The same holds for
235    /// the constraints text, whose capacity DEFAULTS to 0.
236    fn build_descriptor(&self) -> Result<ParameterDescriptor, DeclarationError> {
237        let mut descriptor = ParameterDescriptor::new(self.name, T::parameter_type())
238            .ok_or(DeclarationError::NameTooLong)?;
239        if let Some(desc) = self.description {
240            descriptor.set_description(desc);
241        }
242        if let Some(text) = self.constraints {
243            descriptor.set_additional_constraints(text);
244        }
245        descriptor.range = self.range.unwrap_or_default();
246        Ok(descriptor)
247    }
248
249    /// Declare a read-only parameter
250    ///
251    /// Read-only parameters cannot be changed after declaration.
252    /// A default value must be provided.
253    pub fn read_only(self) -> Result<ReadOnlyParameter<'a, 's, T>, DeclarationError> {
254        // Must have a default value for read-only parameters
255        let default_value = self
256            .default
257            .as_ref()
258            .ok_or(DeclarationError::NoValueAvailable)?
259            .clone();
260
261        let mut descriptor = self.build_descriptor()?;
262        descriptor.read_only = true;
263
264        let param_value = default_value.to_parameter_value();
265
266        declare(
267            self.server,
268            self.node,
269            self.name,
270            descriptor,
271            Some(&param_value),
272        )?;
273
274        Ok(ReadOnlyParameter::new(self.server, self.node, self.name))
275    }
276
277    /// Declare a mandatory parameter
278    ///
279    /// If no default value is provided, it must be set externally before use.
280    pub fn mandatory(self) -> Result<MandatoryParameter<'a, 's, T>, DeclarationError> {
281        let mut descriptor = self.build_descriptor()?;
282        descriptor.read_only = self.read_only;
283
284        let default_value = self.default.map(|v| v.to_parameter_value());
285
286        declare(
287            self.server,
288            self.node,
289            self.name,
290            descriptor,
291            default_value.as_ref(),
292        )?;
293
294        Ok(MandatoryParameter::new(self.server, self.node, self.name))
295    }
296
297    /// Declare an optional parameter
298    pub fn optional(self) -> Result<OptionalParameter<'a, 's, T>, DeclarationError> {
299        let mut descriptor = self.build_descriptor()?;
300        descriptor.read_only = self.read_only;
301
302        let default_value = self.default.map(|v| v.to_parameter_value());
303
304        declare(
305            self.server,
306            self.node,
307            self.name,
308            descriptor,
309            default_value.as_ref(),
310        )?;
311
312        Ok(OptionalParameter::new(self.server, self.node, self.name))
313    }
314}
315
316/// The typed terminals' declaration, reporting rclrs's [`DeclarationError`].
317///
318/// `ParameterServer::declare_parameter` answers in `ParameterError`, where
319/// `TypeMismatch` means "already declared" and `InvalidRange` covers both an
320/// ill-formed range and a default outside it; this names each case. It keeps
321/// that call (rather than `try_declare_with_descriptor`) because the typed
322/// path emits no parameter event on declaration, and changing that is not
323/// part of a rename (phase-515 R8).
324fn declare(
325    server: &mut ParameterServer<'_>,
326    node: NodeKey,
327    name: &str,
328    descriptor: ParameterDescriptor,
329    value: Option<&crate::ParameterValue>,
330) -> Result<(), DeclarationError> {
331    // Issue 2969 -- a name the launch seeded is adopted, not refused: the
332    // launch value wins over `value` (the builder's default), as rclrs applies
333    // an override at declaration, and must have the declared type.
334    if let Some(adopted) =
335        server.adopt_launch_seed(node, name, descriptor.param_type, Some(&descriptor))
336    {
337        return adopted;
338    }
339    let consistency = ParameterServer::declaration_consistency(
340        Some(&descriptor),
341        &value.cloned().unwrap_or_default(),
342    );
343    server
344        .declare_parameter(node, name, descriptor, value)
345        .map_err(|result| match result {
346            ParameterError::TypeMismatch => DeclarationError::AlreadyDeclared,
347            ParameterError::InvalidRange => {
348                consistency.err().unwrap_or(DeclarationError::InvalidRange)
349            }
350            _ => DeclarationError::StorageFull,
351        })
352}
353
354/// A parameter that must always have a value
355pub struct MandatoryParameter<'a, 's, T: ParameterVariant> {
356    server: &'a mut ParameterServer<'s>,
357    /// phase-426 W1 — the node whose table this handle reads and writes.
358    node: NodeKey,
359    name: String<{ crate::MAX_PARAM_NAME_LEN }>,
360    _phantom: core::marker::PhantomData<T>,
361}
362
363impl<'a, 's, T: ParameterVariant> MandatoryParameter<'a, 's, T> {
364    pub(crate) fn new(server: &'a mut ParameterServer<'s>, node: NodeKey, name: &'a str) -> Self {
365        let mut n = String::new();
366        n.push_str(name).unwrap();
367        Self {
368            server,
369            node,
370            name: n,
371            _phantom: core::marker::PhantomData,
372        }
373    }
374
375    /// Get the current value of the parameter
376    pub fn get(&self) -> T {
377        self.server
378            .get_parameter_value(self.node, self.name.as_str())
379            .and_then(|val| T::from_parameter_value(&val))
380            .expect("Mandatory parameter must have a value")
381    }
382
383    /// Set the value of the parameter
384    pub fn set(&mut self, value: T) -> Result<(), ParameterError> {
385        // issue 0323 — reject an over-capacity value here rather than letting
386        // `to_parameter_value`'s `unwrap_or_default()` turn it into `NotSet`
387        // (a TYPE change) or an EMPTY array and then reporting success.
388        let converted = value
389            .try_to_parameter_value()
390            .map_err(|_| ParameterError::StringConversion)?;
391        let result = self
392            .server
393            .set_parameter_value(self.node, self.name.as_str(), converted);
394        // The typed API never auto-declares, so an undeclared name is simply
395        // not there.
396        result.map_err(|e| match e {
397            ParameterError::Undeclared => ParameterError::NotFound,
398            e => e,
399        })
400    }
401}
402
403/// A parameter that may or may not have a value
404pub struct OptionalParameter<'a, 's, T: ParameterVariant> {
405    server: &'a mut ParameterServer<'s>,
406    /// phase-426 W1 — the node whose table this handle reads and writes.
407    node: NodeKey,
408    name: String<{ crate::MAX_PARAM_NAME_LEN }>,
409    _phantom: core::marker::PhantomData<T>,
410}
411
412impl<'a, 's, T: ParameterVariant> OptionalParameter<'a, 's, T> {
413    pub(crate) fn new(server: &'a mut ParameterServer<'s>, node: NodeKey, name: &'a str) -> Self {
414        let mut n = String::new();
415        n.push_str(name).unwrap();
416        Self {
417            server,
418            node,
419            name: n,
420            _phantom: core::marker::PhantomData,
421        }
422    }
423
424    /// Get the current value of the parameter, if set
425    pub fn get(&self) -> Option<T> {
426        self.server
427            .get_parameter_value(self.node, self.name.as_str())
428            .and_then(|val| T::from_parameter_value(&val))
429    }
430
431    /// Set the value of the parameter
432    pub fn set(&mut self, value: Option<T>) -> Result<(), ParameterError> {
433        let param_value = value.map(|v| v.to_parameter_value());
434        let result = self.server.set_parameter_value(
435            self.node,
436            self.name.as_str(),
437            param_value.unwrap_or_default(),
438        );
439        // The typed API never auto-declares, so an undeclared name is simply
440        // not there.
441        result.map_err(|e| match e {
442            ParameterError::Undeclared => ParameterError::NotFound,
443            e => e,
444        })
445    }
446}
447
448/// A parameter whose value cannot be changed after declaration
449pub struct ReadOnlyParameter<'a, 's, T: ParameterVariant> {
450    server: &'a mut ParameterServer<'s>,
451    /// phase-426 W1 — the node whose table this handle reads and writes.
452    node: NodeKey,
453    name: String<{ crate::MAX_PARAM_NAME_LEN }>,
454    _phantom: core::marker::PhantomData<T>,
455}
456
457impl<'a, 's, T: ParameterVariant> ReadOnlyParameter<'a, 's, T> {
458    pub(crate) fn new(server: &'a mut ParameterServer<'s>, node: NodeKey, name: &'a str) -> Self {
459        let mut n = String::new();
460        n.push_str(name).unwrap();
461        Self {
462            server,
463            node,
464            name: n,
465            _phantom: core::marker::PhantomData,
466        }
467    }
468
469    /// Get the current value of the parameter
470    pub fn get(&self) -> T {
471        self.server
472            .get_parameter_value(self.node, self.name.as_str())
473            .and_then(|val| T::from_parameter_value(&val))
474            .expect("Read-only parameter must have a value")
475    }
476}
477
478/// Provides access to undeclared parameters in a ParameterServer
479///
480/// This struct is returned by `Node::use_undeclared_parameters()` and allows
481/// for dynamic retrieval of parameter values by name without explicit declaration.
482///
483/// rclrs's `Parameters`: read AND write, by name. It was
484/// `UndeclaredParameters`, which survives one release as a deprecated alias.
485pub struct Parameters<'a, 's> {
486    server: &'a mut ParameterServer<'s>,
487    /// phase-426 W1 — whose undeclared parameters. Without this the accessor
488    /// reads whatever node happened to declare the name first.
489    node: NodeKey,
490}
491
492/// The former name of [`Parameters`].
493// phase-515 R8 took rclrs's name.
494#[deprecated(
495    since = "0.6.0",
496    note = "renamed to `Parameters`, rclrs's name; use `Parameters`"
497)]
498pub type UndeclaredParameters<'a, 's> = Parameters<'a, 's>;
499
500impl<'a, 's> Parameters<'a, 's> {
501    pub fn new(server: &'a mut ParameterServer<'s>, node: NodeKey) -> Self {
502        Self { server, node }
503    }
504
505    /// rclrs's `Parameters::get::<T>(name)`: the value of
506    /// `name` as `T`, or `None` when it is unset or holds another type.
507    pub fn get<T: crate::ParameterVariant>(&self, name: &str) -> Option<T> {
508        self.server
509            .get(self.node, name)
510            .and_then(|value| T::from_parameter_value(value))
511    }
512
513    /// rclrs's `Parameters::set(name, value)`, declaring
514    /// `name` if absent. ADOPT-BOUNDED: it takes `&mut self` where rclrs's
515    /// takes `&self` (this store has no interior mutability; the handle
516    /// borrows the server mutably), and a value past this node's compile-time
517    /// capacity is `ParameterError::StringConversion` rather than rclrs's
518    /// `ParameterValueError`.
519    pub fn set<T: crate::ParameterVariant>(
520        &mut self,
521        name: &str,
522        value: T,
523    ) -> Result<(), ParameterError> {
524        let value = value
525            .try_to_parameter_value()
526            .map_err(|_| ParameterError::StringConversion)?;
527        self.set_value(name, value)
528    }
529
530    /// Try to get the value of an undeclared boolean parameter
531    pub fn get_bool(&self, name: &str) -> Option<bool> {
532        self.server.get_bool(self.node, name)
533    }
534
535    /// Try to get the value of an undeclared integer parameter
536    pub fn get_integer(&self, name: &str) -> Option<i64> {
537        self.server.get_integer(self.node, name)
538    }
539
540    /// Try to get the value of an undeclared double parameter
541    pub fn get_double(&self, name: &str) -> Option<f64> {
542        self.server.get_double(self.node, name)
543    }
544
545    /// Try to get the value of an undeclared string parameter
546    pub fn get_string(&self, name: &str) -> Option<&str> {
547        self.server.get_string(self.node, name)
548    }
549
550    // ---- writes (phase-417 W4.a) -------------------------------------------
551    //
552    // rclrs's `Parameters` handle reads AND writes; ours only read, which made
553    // `use_undeclared_parameters` half a handle. The writes go through
554    // `ParameterServer::set_or_declare` rather than `apply`, and that is the
555    // whole point of the type: `apply` refuses a name the node never declared
556    // unless the node opted in, and this handle IS the opt-in — a caller
557    // reaches it by naming it, exactly as the store's own doc comment for
558    // `set_or_declare` describes.
559
560    /// Set (declaring if absent) an undeclared boolean parameter.
561    pub fn set_bool(&mut self, name: &str, value: bool) -> Result<(), ParameterError> {
562        self.set_value(name, crate::ParameterValue::Bool(value))
563    }
564
565    /// Set (declaring if absent) an undeclared integer parameter.
566    pub fn set_integer(&mut self, name: &str, value: i64) -> Result<(), ParameterError> {
567        self.set_value(name, crate::ParameterValue::Integer(value))
568    }
569
570    /// Set (declaring if absent) an undeclared double parameter.
571    pub fn set_double(&mut self, name: &str, value: f64) -> Result<(), ParameterError> {
572        self.set_value(name, crate::ParameterValue::Double(value))
573    }
574
575    /// Set (declaring if absent) an undeclared string parameter.
576    pub fn set_string(&mut self, name: &str, value: &str) -> Result<(), ParameterError> {
577        let value =
578            crate::ParameterValue::from_string(value).ok_or(ParameterError::StringConversion)?;
579        self.set_value(name, value)
580    }
581
582    fn set_value(
583        &mut self,
584        name: &str,
585        value: crate::ParameterValue,
586    ) -> Result<(), ParameterError> {
587        self.server
588            .set_or_declare(self.node, name, value)
589            .map_err(|e| match e {
590                ParameterError::Undeclared => ParameterError::NotFound,
591                e => e,
592            })
593    }
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    /// phase-426 W1 — the node these single-node tests are about.
601    const NODE: NodeKey = NodeKey::PRIMARY;
602
603    #[test]
604    fn test_mandatory_parameter_with_default() {
605        let mut storage: ParameterStorage = ParameterStorage::new();
606        let mut server = ParameterServer::new_in(storage.as_table());
607        let param = ParameterBuilder::<i64>::new(&mut server, NODE, "test_param")
608            .default(42)
609            .description("A test parameter")
610            .mandatory()
611            .expect("Failed to declare parameter");
612
613        assert_eq!(param.get(), 42);
614    }
615
616    #[test]
617    fn test_mandatory_parameter_set() {
618        let mut storage: ParameterStorage = ParameterStorage::new();
619        let mut server = ParameterServer::new_in(storage.as_table());
620        let mut param = ParameterBuilder::<i64>::new(&mut server, NODE, "test_param")
621            .default(0)
622            .mandatory()
623            .expect("Failed to declare parameter");
624
625        param.set(100).expect("Failed to set parameter");
626        assert_eq!(param.get(), 100);
627    }
628
629    #[test]
630    fn test_optional_parameter_none() {
631        let mut storage: ParameterStorage = ParameterStorage::new();
632        let mut server = ParameterServer::new_in(storage.as_table());
633        let param = ParameterBuilder::<i64>::new(&mut server, NODE, "test_param")
634            .optional()
635            .expect("Failed to declare parameter");
636
637        assert_eq!(param.get(), None);
638    }
639
640    #[test]
641    fn test_optional_parameter_with_default() {
642        let mut storage: ParameterStorage = ParameterStorage::new();
643        let mut server = ParameterServer::new_in(storage.as_table());
644        let param = ParameterBuilder::<i64>::new(&mut server, NODE, "test_param")
645            .default(42)
646            .optional()
647            .expect("Failed to declare parameter");
648
649        assert_eq!(param.get(), Some(42));
650    }
651
652    #[test]
653    fn test_optional_parameter_set() {
654        let mut storage: ParameterStorage = ParameterStorage::new();
655        let mut server = ParameterServer::new_in(storage.as_table());
656        let mut param = ParameterBuilder::<i64>::new(&mut server, NODE, "test_param")
657            .optional()
658            .expect("Failed to declare parameter");
659
660        param.set(Some(100)).expect("Failed to set parameter");
661        assert_eq!(param.get(), Some(100));
662    }
663
664    #[test]
665    fn test_read_only_parameter() {
666        let mut storage: ParameterStorage = ParameterStorage::new();
667        let mut server = ParameterServer::new_in(storage.as_table());
668        let param = ParameterBuilder::<i64>::new(&mut server, NODE, "readonly_param")
669            .default(42)
670            .description("A read-only parameter")
671            .read_only()
672            .expect("Failed to declare parameter");
673
674        assert_eq!(param.get(), 42);
675    }
676
677    #[test]
678    fn test_read_only_parameter_requires_default() {
679        let mut storage: ParameterStorage = ParameterStorage::new();
680        let mut server = ParameterServer::new_in(storage.as_table());
681        let result = ParameterBuilder::<i64>::new(&mut server, NODE, "readonly_param").read_only();
682
683        assert_eq!(result.err(), Some(DeclarationError::NoValueAvailable));
684    }
685
686    /// phase-515 R8 -- the terminals report rclrs's `DeclarationError`, and
687    /// each case the old `ParameterError` conflated is named.
688    #[test]
689    fn builder_terminals_report_declaration_errors() {
690        let mut storage: ParameterStorage = ParameterStorage::new();
691        let mut server = ParameterServer::new_in(storage.as_table());
692        ParameterBuilder::<i64>::new(&mut server, NODE, "dup")
693            .default(1)
694            .mandatory()
695            .expect("first declaration");
696        let again = ParameterBuilder::<i64>::new(&mut server, NODE, "dup")
697            .default(1)
698            .mandatory();
699        assert_eq!(again.err(), Some(DeclarationError::AlreadyDeclared));
700
701        let outside = ParameterBuilder::<i64>::new(&mut server, NODE, "ranged")
702            .default(500)
703            .integer_range(0, 100, 1)
704            .expect("well-formed range")
705            .optional();
706        assert_eq!(
707            outside.err(),
708            Some(DeclarationError::InitialValueOutOfRange)
709        );
710
711        // `?` into a `ParameterError` caller still compiles, and reads as before.
712        let as_param_error: ParameterError = DeclarationError::AlreadyDeclared.into();
713        assert_eq!(as_param_error, ParameterError::TypeMismatch);
714    }
715
716    // Issue 2969.
717    /// A typed declaration of a name the launch seeded ADOPTS the seed: its
718    /// value over the builder's default, checked against the declared type and
719    /// range. Only the first declaration adopts; a second one is the code's
720    /// own duplicate, refused as before. An unmarked name (no launch seed) is
721    /// refused as before too.
722    #[test]
723    fn a_typed_declaration_adopts_its_launch_seed_once() {
724        let mut storage: ParameterStorage = ParameterStorage::new();
725        let mut server = ParameterServer::new_in(storage.as_table());
726        assert!(server.declare_ref(NODE, "period", &crate::ParameterValue::Integer(20)));
727        assert!(server.mark_launch_seed(NODE, "period"));
728        let period = ParameterBuilder::<i64>::new(&mut server, NODE, "period")
729            .default(5)
730            .mandatory()
731            .expect("the launch seed is adopted");
732        assert_eq!(period.get(), 20, "the launch value wins over the default");
733        let again = ParameterBuilder::<i64>::new(&mut server, NODE, "period").optional();
734        assert_eq!(again.err(), Some(DeclarationError::AlreadyDeclared));
735
736        // Another type: refused naming the cause, never stored over.
737        assert!(server.declare_ref(NODE, "gain", &crate::ParameterValue::Integer(3)));
738        assert!(server.mark_launch_seed(NODE, "gain"));
739        let gain = ParameterBuilder::<f64>::new(&mut server, NODE, "gain").optional();
740        assert_eq!(gain.err(), Some(DeclarationError::LaunchValueTypeMismatch));
741
742        // Outside the declared range: refused like an out-of-range default.
743        assert!(server.declare_ref(NODE, "rate", &crate::ParameterValue::Integer(500)));
744        assert!(server.mark_launch_seed(NODE, "rate"));
745        let rate = ParameterBuilder::<i64>::new(&mut server, NODE, "rate")
746            .integer_range(0, 100, 1)
747            .expect("well-formed range")
748            .optional();
749        assert_eq!(rate.err(), Some(DeclarationError::InitialValueOutOfRange));
750
751        // No mark: a name already there is a duplicate, as before 2969.
752        assert!(server.declare_ref(NODE, "plain", &crate::ParameterValue::Integer(1)));
753        let plain = ParameterBuilder::<i64>::new(&mut server, NODE, "plain").optional();
754        assert_eq!(plain.err(), Some(DeclarationError::AlreadyDeclared));
755    }
756
757    #[test]
758    fn test_integer_range_constraint() {
759        let mut storage: ParameterStorage = ParameterStorage::new();
760        let mut server = ParameterServer::new_in(storage.as_table());
761        let mut param = ParameterBuilder::<i64>::new(&mut server, NODE, "ranged_param")
762            .default(50)
763            .integer_range(0, 100, 1)
764            .expect("Failed to set range")
765            .mandatory()
766            .expect("Failed to declare parameter");
767
768        // Valid value within range
769        param.set(75).expect("Failed to set valid value");
770        assert_eq!(param.get(), 75);
771    }
772
773    #[test]
774    fn test_float_range_constraint() {
775        let mut storage: ParameterStorage = ParameterStorage::new();
776        let mut server = ParameterServer::new_in(storage.as_table());
777        let mut param = ParameterBuilder::<f64>::new(&mut server, NODE, "float_param")
778            .default(0.5)
779            .float_range(0.0, 1.0, 0.0)
780            .expect("Failed to set range")
781            .mandatory()
782            .expect("Failed to declare parameter");
783
784        // Valid value within range
785        param.set(0.75).expect("Failed to set valid value");
786        assert_eq!(param.get(), 0.75);
787    }
788
789    #[test]
790    fn test_range_convenience_integer() {
791        let mut storage: ParameterStorage = ParameterStorage::new();
792        let mut server = ParameterServer::new_in(storage.as_table());
793        let param = ParameterBuilder::<i64>::new(&mut server, NODE, "ranged_param")
794            .default(50)
795            .range(0..=100)
796            .expect("Failed to set range")
797            .mandatory()
798            .expect("Failed to declare parameter");
799
800        assert_eq!(param.get(), 50);
801    }
802
803    #[test]
804    fn test_range_convenience_float() {
805        let mut storage: ParameterStorage = ParameterStorage::new();
806        let mut server = ParameterServer::new_in(storage.as_table());
807        let param = ParameterBuilder::<f64>::new(&mut server, NODE, "float_param")
808            .default(0.5)
809            .range(0.0..=1.0)
810            .expect("Failed to set range")
811            .mandatory()
812            .expect("Failed to declare parameter");
813
814        assert_eq!(param.get(), 0.5);
815    }
816
817    /// phase-417 W4.a -- the builder's `constraints` reaches the stored
818    /// descriptor through the ONE `build_descriptor`, from every terminal
819    /// verb, and a text that does not fit the (default 0) capacity is
820    /// REPORTED rather than dropped in silence.
821    // The comparison and the `min` below read as "always true" to clippy on a
822    // build that leaves `NROS_PARAMS_MAX_CONSTRAINTS_BYTES` at its default of 0 --
823    // and that is the point: the constant is a KNOB, the test is written
824    // against it so it holds at 0, at 64 and at 256, and a version specialised
825    // to whichever value this build resolved would read as coverage on the
826    // other two.
827    #[allow(clippy::absurd_extreme_comparisons, clippy::unnecessary_min_or_max)]
828    #[test]
829    fn builder_constraints_reach_the_descriptor_from_every_terminal() {
830        let text = "positive, hz";
831        let fits = text.len() <= crate::MAX_PARAM_CONSTRAINTS_LEN;
832        let stored = &text[..crate::MAX_PARAM_CONSTRAINTS_LEN.min(text.len())];
833
834        for which in 0..3u8 {
835            let mut storage: ParameterStorage = ParameterStorage::new();
836            let mut server = ParameterServer::new_in(storage.as_table());
837            {
838                let b = ParameterBuilder::<f64>::new(&mut server, NODE, "rate")
839                    .default(1.0)
840                    .description("publish rate")
841                    .constraints(text);
842                match which {
843                    0 => {
844                        b.read_only().expect("read_only");
845                    }
846                    1 => {
847                        b.mandatory().expect("mandatory");
848                    }
849                    _ => {
850                        b.optional().expect("optional");
851                    }
852                }
853            }
854            let desc = server.get_descriptor(NODE, "rate").expect("descriptor");
855            assert_eq!(desc.description.as_str(), "publish rate");
856            assert_eq!(
857                desc.additional_constraints.as_str(),
858                stored,
859                "terminal {which} lost the constraints text"
860            );
861            let mut reported = 0usize;
862            server.take_truncated_descriptions(|_, _, text| {
863                // Issue 2686: the constraints field, not the description.
864                assert_eq!(text, crate::DescriptorText::Constraints);
865                reported += 1;
866            });
867            assert_eq!(
868                reported,
869                usize::from(!fits),
870                "terminal {which}: a constraints string that did not fit went unreported"
871            );
872        }
873    }
874
875    #[test]
876    fn test_parameter_description() {
877        let mut storage: ParameterStorage = ParameterStorage::new();
878        let mut server = ParameterServer::new_in(storage.as_table());
879        let _param = ParameterBuilder::<i64>::new(&mut server, NODE, "described_param")
880            .default(42)
881            .description("This is a test description")
882            .mandatory()
883            .expect("Failed to declare parameter");
884
885        // Verify description was set in the server
886        let desc = server.get_descriptor(NODE, "described_param");
887        assert!(desc.is_some());
888        assert_eq!(
889            desc.unwrap().description.as_str(),
890            "This is a test description"
891        );
892    }
893
894    #[test]
895    fn test_bool_parameter() {
896        let mut storage: ParameterStorage = ParameterStorage::new();
897        let mut server = ParameterServer::new_in(storage.as_table());
898        let mut param = ParameterBuilder::<bool>::new(&mut server, NODE, "bool_param")
899            .default(false)
900            .mandatory()
901            .expect("Failed to declare parameter");
902
903        assert!(!param.get());
904        param.set(true).expect("Failed to set parameter");
905        assert!(param.get());
906    }
907
908    #[test]
909    fn test_undeclared_parameters() {
910        use crate::ParameterValue;
911
912        let mut storage: ParameterStorage = ParameterStorage::new();
913        let mut server = ParameterServer::new_in(storage.as_table());
914
915        // Set some values using set_or_declare (simulating external parameter loading)
916        server
917            .set_or_declare(NODE, "flag", ParameterValue::Bool(true))
918            .unwrap();
919        server
920            .set_or_declare(NODE, "count", ParameterValue::Integer(42))
921            .unwrap();
922        server
923            .set_or_declare(NODE, "ratio", ParameterValue::Double(0.5))
924            .unwrap();
925
926        let undeclared = Parameters::new(&mut server, NODE);
927
928        assert_eq!(undeclared.get_bool("flag"), Some(true));
929        assert_eq!(undeclared.get_integer("count"), Some(42));
930        assert_eq!(undeclared.get_double("ratio"), Some(0.5));
931        assert_eq!(undeclared.get_string("nonexistent"), None);
932    }
933
934    /// phase-515 R8 -- rclrs's generic `Parameters::get::<T>` / `set`.
935    #[test]
936    fn parameters_generic_get_and_set() {
937        let mut storage: ParameterStorage = ParameterStorage::new();
938        let mut server = ParameterServer::new_in(storage.as_table());
939        let mut params = Parameters::new(&mut server, NODE);
940
941        params
942            .set("rate", 10i64)
943            .expect("set declares an absent name");
944        params.set("enabled", true).expect("set a bool");
945        assert_eq!(params.get::<i64>("rate"), Some(10));
946        assert_eq!(params.get::<bool>("enabled"), Some(true));
947        // Another type than the one stored reads as absent, as in rclrs.
948        assert_eq!(params.get::<bool>("rate"), None);
949        assert_eq!(params.get::<i64>("missing"), None);
950        params.set("rate", 20i64).expect("overwrite");
951        assert_eq!(params.get::<i64>("rate"), Some(20));
952    }
953}