Skip to main content

nros_params/
server.rs

1//! Parameter server implementation
2//!
3//! Provides a static storage parameter server for embedded systems.
4//! Parameters are stored in a fixed-size array with compile-time capacity.
5
6use crate::{
7    ParameterError,
8    types::{
9        FloatingPointRange, IntegerRange, MAX_PARAM_NAME_LEN, NodeFlags, NodeKey, Parameter,
10        ParameterDescriptor, ParameterRange, ParameterType, ParameterValue,
11    },
12};
13use heapless::String;
14
15// MAX_PARAMETERS is generated by build.rs and included via types.rs.
16use crate::types::MAX_PARAMETERS;
17
18/// What a pending `/parameter_events` entry
19/// reports. The value is read from the store when the event is published, so
20/// an event says what the parameter IS, not what it was when it moved.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum ParameterEventKind {
23    /// Declared (locally, or by a remote set on an undeclared-allowing node).
24    New,
25    /// Its value changed.
26    Changed,
27    /// Undeclared.
28    Deleted,
29    /// Issue 2023 — the node's start-up event when it holds no parameter at
30    /// the moment events go on: the node's name and three EMPTY lists. A
31    /// node that does hold parameters announces itself with one `New` per
32    /// parameter instead (see [`ParameterServer::pop_initial_parameter_event`](crate::ParameterServerOps::pop_initial_parameter_event)).
33    Announce,
34}
35
36/// One change waiting to be published on `/parameter_events`.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct PendingParameterEvent {
39    /// The node whose parameter moved.
40    pub node: NodeKey,
41    /// What happened to it.
42    pub kind: ParameterEventKind,
43    /// Its name.
44    pub name: String<MAX_PARAM_NAME_LEN>,
45}
46
47/// How many changes the store holds between two flushes of
48/// `/parameter_events`.
49///
50/// A flush runs after every C or C++ parameter call and on every spin, so this only
51/// has to cover the changes ONE spin's parameter services make; a burst past
52/// it is counted ([`ParameterServer::take_parameter_events_dropped`](crate::ParameterServerOps::take_parameter_events_dropped)) and
53/// reported, never blocked on. A second change to a name already pending
54/// merges into its entry, since the event carries the value at publish time.
55pub const PARAMETER_EVENT_LOG_LEN: usize = 8;
56
57/// Entry in the parameter storage.
58///
59/// phase-382 W2' — crate-private ON PURPOSE. The storage is caller-owned now,
60/// but the SLOT layout is not part of the deal: consumers name
61/// [`ParameterTable`] / [`ParameterStorage`], never this.
62#[derive(Debug, Clone)]
63pub(crate) struct ParameterEntry {
64    /// phase-426 W1 — which node declared it. The slot arena is shared (one
65    /// fixed table per executor, no per-node allocation); this is what keeps
66    /// two nodes' identically-named parameters apart inside it.
67    node: NodeKey,
68    /// The parameter (name + value)
69    param: Parameter,
70    /// Optional descriptor with constraints
71    descriptor: Option<ParameterDescriptor>,
72    // Issue 2969.
73    /// The entry holds a launch value the code has not declared yet. The first
74    /// declaration of the name ADOPTS it ([`ParameterServer::adopt_launch_seed`])
75    /// and clears this, so a second declaration is the code's own duplicate.
76    launch_seed: bool,
77}
78
79/// Why a declaration was refused.
80///
81/// rclrs separates DECLARE-time failures from set-time ones, and this is that
82/// separation: a write's `Result<(), ParameterError>` answers "may this WRITE happen", this
83/// answers "may this parameter EXIST". Ours is a subset of rclrs's, and the
84/// difference is structural rather than an omission: rclrs's
85/// `NoValueAvailable`, `OverrideValueTypeMismatch` and `PriorValueTypeMismatch`
86/// are about a launch OVERRIDE arriving before the declaration and disagreeing
87/// with it, and nano-ros seeds overrides through the same
88/// [`ParameterServer::apply`](crate::ParameterServerOps::apply) path a remote set uses — so a disagreeing
89/// override is a `ParameterError`, on the write that carried it, and
90/// cannot reach a declaration.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum DeclarationError {
93    /// This node already declared this name (rclrs `AlreadyDeclared`).
94    AlreadyDeclared,
95    /// The descriptor's range is ill-formed — `min > max`, or a negative step
96    /// (rclrs `InvalidRange`).
97    InvalidRange,
98    /// The default value is outside the descriptor's range (rclrs
99    /// `InitialValueOutOfRange`).
100    InitialValueOutOfRange,
101    /// Every slot of the caller-owned table is taken. No rclrs correspondent:
102    /// rclrs's store grows, ours is the storage the caller placed.
103    StorageFull,
104    /// The name is longer than `NROS_PARAMS_MAX_NAME_BYTES`. No rclrs
105    /// correspondent, same reason.
106    NameTooLong,
107    /// A read-only parameter was declared with no default (rclrs
108    /// `NoValueAvailable`; phase-515 R8). A read-only value can never be set
109    /// later, so it must arrive with the declaration.
110    NoValueAvailable,
111    // Issue 2969.
112    /// The launch value seeded for this name has another type than the code
113    /// declares it with (rclrs `OverrideValueTypeMismatch`).
114    LaunchValueTypeMismatch,
115}
116
117/// What each refusal means, for a caller that prints the `Err` it got back. A
118/// full store names the knob that sizes it ([`crate::STORE_SIZE_REMEDY`]).
119// GitHub #4018 -- `StorageFull` was the one refusal whose fix is a build
120// knob, and a bare `{:?}` named nothing.
121impl core::fmt::Display for DeclarationError {
122    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
123        match self {
124            DeclarationError::AlreadyDeclared => f.write_str("the parameter is already declared"),
125            DeclarationError::InvalidRange => f.write_str("the parameter's range is ill-formed"),
126            DeclarationError::InitialValueOutOfRange => {
127                f.write_str("the parameter's default is outside its range")
128            }
129            DeclarationError::StorageFull => write!(
130                f,
131                "the parameter store is full, so the parameter was not declared and a launch \
132                 or YAML value for it is not applied. {}",
133                crate::STORE_SIZE_REMEDY
134            ),
135            DeclarationError::NameTooLong => f.write_str(
136                "the parameter's name is longer than NROS_PARAMS_MAX_NAME_BYTES \
137                 (`max_param_name_len` under `[knobs.params]`)",
138            ),
139            DeclarationError::NoValueAvailable => {
140                f.write_str("a read-only parameter was declared with no default")
141            }
142            DeclarationError::LaunchValueTypeMismatch => f.write_str(
143                "the parameter's launch value has another type than the code declares it with; \
144                 write the launch value in the declared type",
145            ),
146        }
147    }
148}
149
150/// phase-515 R8 -- the typed builder's terminals return [`DeclarationError`]
151/// now, as rclrs's do. This keeps `?` into a [`ParameterError`]-returning
152/// caller compiling, and maps each case to the `ParameterError` such a caller
153/// saw before the change.
154impl From<DeclarationError> for crate::ParameterError {
155    fn from(e: DeclarationError) -> Self {
156        match e {
157            DeclarationError::AlreadyDeclared => crate::ParameterError::TypeMismatch,
158            DeclarationError::InvalidRange => crate::ParameterError::InvalidRange,
159            DeclarationError::InitialValueOutOfRange => crate::ParameterError::OutOfRange,
160            DeclarationError::StorageFull | DeclarationError::NameTooLong => {
161                crate::ParameterError::StorageFull
162            }
163            DeclarationError::NoValueAvailable => crate::ParameterError::NotFound,
164            DeclarationError::LaunchValueTypeMismatch => crate::ParameterError::TypeMismatch,
165        }
166    }
167}
168
169/// An on-set-parameters callback.
170///
171/// `false` REFUSES the write, which is rclcpp's
172/// `add_on_set_parameters_callback` contract (a `SetParametersResult` whose
173/// `successful` is false) and the contract C's rclc parameter server carries
174/// too (with the old value).
175///
176/// A `fn` pointer plus an [`OnSetContext`], not a closure: this crate is
177/// `no_std` with no allocator, so there is nothing to box a `FnMut` into.
178///
179/// The hook sees BOTH sides of the change,
180/// rclc's `rclc_parameter_callback_t` contract: `old` is `None` when the write
181/// would CREATE the parameter (an undeclared remote set), `new` is `None` when
182/// it would DELETE it (a remote `NOT_SET` on a node that asked for
183/// [`set_delete_on_not_set`](crate::ParameterServerOps::set_delete_on_not_set)).
184/// rclcpp's `add_on_set_parameters_callback` reads only `new`, so the C++ and
185/// Rust facades ignore `old`.
186pub type OnSetParameterFn = fn(
187    node: NodeKey,
188    name: &str,
189    old: Option<&ParameterValue>,
190    new: Option<&ParameterValue>,
191    ctx: OnSetContext,
192) -> bool;
193
194/// Two machine words of caller context, carried verbatim to an
195/// [`OnSetParameterFn`].
196///
197/// TWO, not one, because of the consumer that drives this API: a C or C++
198/// registration is a FUNCTION POINTER plus a user `void*`, and the shim needs
199/// both to reach the caller's code. One word would force each wrapper to keep
200/// a static side table mapping an index back to the pair — a second, smaller
201/// registry with its own bound and its own exhaustion story.
202///
203/// `usize`, not `*mut c_void`: a raw pointer in this struct would strip
204/// [`ParameterServer`]'s auto traits, and the store lives inside the executor.
205/// The C and C++ shims cast through it and say so.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
207pub struct OnSetContext {
208    /// First word. The wrappers put the user's `void* context` here, so a
209    /// Rust caller with one pointer to carry uses this one and ignores `b`.
210    pub a: usize,
211    /// Second word. The wrappers put the C function pointer here.
212    pub b: usize,
213}
214
215impl OnSetContext {
216    /// One word of context; `b` is zero.
217    pub const fn new(a: usize) -> Self {
218        Self { a, b: 0 }
219    }
220
221    /// Both words.
222    pub const fn pair(a: usize, b: usize) -> Self {
223        Self { a, b }
224    }
225}
226
227/// A registered [`OnSetParameterFn`], returned by
228/// [`ParameterServer::add_on_set_parameters_callback`](crate::ParameterServerOps::add_on_set_parameters_callback) and consumed by
229/// [`ParameterServer::remove_on_set_parameters_callback`](crate::ParameterServerOps::remove_on_set_parameters_callback).
230///
231/// rclcpp hands back an owning `OnSetParametersCallbackHandle` shared_ptr whose
232/// destruction unregisters. With no allocator there is nothing to own, so this
233/// is a plain index token and unregistering is explicit.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub struct OnSetParameterHandle(u16);
236
237impl OnSetParameterHandle {
238    /// The token as a plain integer, for an FFI that must hand it to C.
239    ///
240    /// An opaque `u16` rather than a pointer: it indexes the bounded registry
241    /// and nothing else, so a wrong value is a `false` from
242    /// [`ParameterServer::remove_on_set_parameters_callback`](crate::ParameterServerOps::remove_on_set_parameters_callback) rather than a
243    /// wild write.
244    pub const fn raw(self) -> u16 {
245        self.0
246    }
247
248    /// Rebuild a handle a C caller kept. See [`Self::raw`].
249    pub const fn from_raw(raw: u16) -> Self {
250        Self(raw)
251    }
252}
253
254#[derive(Clone, Copy)]
255struct OnSetCallbackSlot {
256    node: NodeKey,
257    callback: OnSetParameterFn,
258    ctx: OnSetContext,
259}
260
261/// How many on-set-parameters callbacks ONE store holds, across every node.
262///
263/// A BOUNDED registry with a stated capacity, because the
264/// unbounded upstream shape needs an allocator this crate does not have. Four,
265/// and the number is chosen rather than inherited: a slot costs
266/// `size_of::<Option<OnSetCallbackSlot>>()` — 32 bytes on a 64-bit host, 16 on
267/// a 32-bit target — so the whole registry is 128 bytes next to a 285,184-byte
268/// default table, and four is one hook for each node of a four-node composed
269/// image with none left to spare by accident. Registering a
270/// fifth REFUSES with `None` rather than dropping one silently.
271///
272/// It is deliberately NOT a build knob. Every other parameter capacity sizes
273/// the table a user's data lands in; this one sizes a table of code the image
274/// itself registers, which is known at build time by reading the source. A
275/// knob here would be a number nobody can derive and everybody has to state.
276pub const MAX_ON_SET_CALLBACKS: usize = 4;
277
278/// The slot table a [`ParameterServer`] borrows.
279///
280/// The server's storage is CALLER-OWNED, and this newtype is
281/// what makes that expressible without publishing the slot type. A slot is a
282/// `ParameterEntry`, which stays PRIVATE (it is the store's internal slot
283/// layout, not an API); a consumer that only needs to *name* the storage —
284/// `nros-node`, which carves it out of the executor backing in W3' — names a
285/// `ParameterTable` instead.
286///
287/// **The table's LENGTH is the server's capacity.** [`MAX_PARAMETERS`] is the
288/// DEFAULT capacity (see [`ParameterStorage`]), not a bound the borrow
289/// re-imposes: a caller who hands over a longer or shorter table gets exactly
290/// that many slots, and every capacity question the server answers
291/// ([`is_full`](crate::ParameterServerOps::is_full), the declare path) reads it from
292/// here.
293pub struct ParameterTable<'s> {
294    entries: &'s mut [Option<ParameterEntry>],
295}
296
297impl<'s> ParameterTable<'s> {
298    /// Wrap a caller-owned slice of slots.
299    pub(crate) fn new(entries: &'s mut [Option<ParameterEntry>]) -> Self {
300        Self { entries }
301    }
302
303    /// Number of slots — the capacity of a server built on this table.
304    pub fn capacity(&self) -> usize {
305        self.entries.len()
306    }
307
308    /// Number of slots currently holding a parameter.
309    pub fn occupied(&self) -> usize {
310        self.entries.iter().filter(|slot| slot.is_some()).count()
311    }
312}
313
314/// One slot of a [`ParameterTable`], opaque.
315///
316/// What a caller CARVES when it places a table in memory it
317/// already owns (the executor's backing). The slot layout is
318/// `Option<ParameterEntry>` and stays private; this wrapper publishes only its
319/// size and alignment (`size_of::<ParameterSlot>()`), which is exactly what a
320/// region placement needs, and [`ParameterTable::init_in`] is the one way to
321/// turn carved, uninitialised slots into a table.
322///
323/// `repr(transparent)`, so a `[ParameterSlot]` IS a `[Option<ParameterEntry>]`
324/// and the table borrows it without a copy.
325#[repr(transparent)]
326pub struct ParameterSlot(Option<ParameterEntry>);
327
328impl<'s> ParameterTable<'s> {
329    /// Initialise `slots` to empty IN PLACE and borrow them as a table.
330    ///
331    /// The home the executor carves for its store. Each slot is written
332    /// through its own pointer, so the largest stack temporary is one slot,
333    /// never the table (the stack-overrun hazard [`ParameterStorage`]
334    /// describes, which a carved region avoids by construction as long as
335    /// nothing builds the table by value).
336    /// Any length works; the length is the capacity, as for every table.
337    pub fn init_in(slots: &'s mut [core::mem::MaybeUninit<ParameterSlot>]) -> Self {
338        for slot in slots.iter_mut() {
339            slot.write(ParameterSlot(None));
340        }
341        let len = slots.len();
342        let base = slots.as_mut_ptr().cast::<Option<ParameterEntry>>();
343        // SAFETY: every element was written above, so the slice is initialised;
344        // `ParameterSlot` is `repr(transparent)` over `Option<ParameterEntry>`,
345        // so the element layouts are identical; the borrow is `slots`' own,
346        // for `'s`, and `slots` is not reachable again while it lives.
347        let entries = unsafe { core::slice::from_raw_parts_mut(base, len) };
348        Self::new(entries)
349    }
350}
351
352impl core::fmt::Debug for ParameterTable<'_> {
353    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
354        f.debug_struct("ParameterTable")
355            .field("capacity", &self.capacity())
356            .finish_non_exhaustive()
357    }
358}
359
360/// Backing storage a caller places, then lends to a [`ParameterServer`].
361///
362/// `N` defaults to [`MAX_PARAMETERS`], the build-time knob
363/// (`NROS_PARAMS_MAX_PARAMETERS` / `CONFIG_NROS_PARAMS_MAX_PARAMETERS`). It is a DEFAULT,
364/// not a cap — `ParameterStorage::<8>::new()` and `ParameterStorage::<256>`
365/// are equally valid, and the server takes its capacity from whatever table it
366/// is handed.
367///
368/// The intended shapes are a `static`, a caller-owned struct field, or (with
369/// `alloc`) one allocation made once at start-up:
370///
371/// ```
372/// use nros_params::{
373///     NodeKey, ParameterServer, ParameterServerOps as _, ParameterStorage, ParameterValue,
374/// };
375///
376/// let mut storage: ParameterStorage<8> = ParameterStorage::new();
377/// let mut server = ParameterServer::new_in(storage.as_table());
378/// assert!(server.declare(NodeKey::PRIMARY, "max_speed", ParameterValue::Double(1.0)));
379/// ```
380///
381/// # Why this type exists at all
382///
383/// This is where the size lives, and it is enormous: `ParameterValue` is sized
384/// by its largest variant
385/// (`StringArray(Vec<String<MAX_STRING_VALUE_LEN>, MAX_STRING_ARRAY_LEN>)`), so every
386/// slot costs ~8.5 KiB whatever it actually holds. Measured: **285,184 bytes**
387/// at the default 32 slots, **2,281,472** at 256. (An earlier figure of
388/// 285,192 included the eight-byte `count` that stayed behind on
389/// [`ParameterServer`], which is 24 bytes total now.)
390///
391/// Before storage became caller-owned, that bulk was INSIDE `ParameterServer`,
392/// so `Box::new(ParameterServer::new())` built a multi-hundred-KiB value on the
393/// STACK before copying it into the allocation — Rust has no placement-new —
394/// which silently overran a thread stack sized for anything smaller. On the
395/// Zephyr lane an image built with 256 slots booted to `dds_create_participant`
396/// and hung with no fault and no output, while 32 — which fits the 512 KiB main
397/// stack the cyclonedds snippet asks for — ran clean. The mitigation then was
398/// `ParameterServer::init_in_place`, a placement initialiser that bounded the
399/// largest temporary at one `Option<ParameterEntry>`.
400///
401/// W2' dissolves the *server* half of that: `ParameterServer` is now a table
402/// borrow plus a count (tens of bytes), so nothing about constructing a server
403/// depends on the knob. The bulk did not vanish, it MOVED here — and so did
404/// the hazard, verbatim: `Box::new(ParameterStorage::new())` is the same
405/// stack-first copy the issue was about. [`init_in_place`] is therefore kept,
406/// on the type that is actually big, and any heap-placed storage must go
407/// through it. A caller who places the storage as a `static` or lets W3' carve
408/// it out of the executor backing never materialises it by value and does not
409/// need it.
410///
411/// [`init_in_place`]: ParameterStorage::init_in_place
412pub struct ParameterStorage<const N: usize = MAX_PARAMETERS> {
413    entries: [Option<ParameterEntry>; N],
414}
415
416impl<const N: usize> ParameterStorage<N> {
417    /// Create empty storage.
418    ///
419    /// `const`, so a `static NROS_PARAMS: ParameterStorage = ParameterStorage::new();`
420    /// lands in `.bss` with no initialiser and no stack temporary.
421    // No `Default`: it would spell this same construction as a by-value
422    // expression, which is exactly the `Box::new(Default::default())` shape
423    // issue 0756 is about (see the type docs). Callers name `new()` — or
424    // `init_in_place` when the home is a heap allocation.
425    #[allow(clippy::new_without_default)]
426    #[allow(clippy::large_stack_arrays)] // Intentional: this IS the storage.
427    pub const fn new() -> Self {
428        Self {
429            entries: [const { None }; N],
430        }
431    }
432
433    /// Slots in this storage.
434    pub const fn capacity(&self) -> usize {
435        N
436    }
437
438    /// Lend the storage to a [`ParameterServer`].
439    pub fn as_table(&mut self) -> ParameterTable<'_> {
440        ParameterTable::new(&mut self.entries)
441    }
442
443    /// Initialise storage directly into `dst`, without ever materialising one
444    /// by value.
445    ///
446    /// See this type's documentation for why that matters. The
447    /// short version: this type is 285,184 bytes at the default 32 slots and
448    /// 2,281,472 at 256, and Rust has no placement-new, so
449    /// `Box::new(ParameterStorage::new())` builds all of it on the caller's
450    /// stack first. Initialising through the allocation bounds the largest
451    /// stack temporary at one `Option<ParameterEntry>`, so the
452    /// `NROS_PARAMS_MAX_PARAMETERS` knob no longer decides whether boot survives.
453    ///
454    /// # Safety
455    ///
456    /// `dst` must be non-null, correctly aligned, and valid for writes of
457    /// `size_of::<Self>()` bytes. The pointee may be uninitialised on entry;
458    /// it is fully initialised on return.
459    pub unsafe fn init_in_place(dst: *mut Self) {
460        // addr_of_mut! throughout: `(*dst).entries` as a place expression
461        // would require the pointee to already be initialised.
462        // Safety: delegated to this function's own contract on `dst`.
463        unsafe {
464            let entries = core::ptr::addr_of_mut!((*dst).entries).cast::<Option<ParameterEntry>>();
465            for i in 0..N {
466                entries.add(i).write(None);
467            }
468        }
469    }
470}
471
472/// Parameter server over caller-owned storage
473///
474/// Stores parameters in a [`ParameterTable`] the caller lends it; the table's
475/// length is the capacity. [`ParameterStorage`] is the usual way to produce
476/// one, defaulting to the build-time `MAX_PARAMETERS` slots.
477///
478/// # Keyed by node
479///
480/// Every per-parameter method takes a [`NodeKey`] first. The slot arena is
481/// shared (one table per executor), but a name is only ever looked up within
482/// one node, so two nodes composed onto one executor hold
483/// independent values for the same name — which is what upstream does, where
484/// each node owns a table and a set of six services.
485///
486/// # Example
487///
488/// ```
489/// use nros_params::{
490///     NodeKey, ParameterServer, ParameterServerOps as _, ParameterStorage, ParameterValue,
491/// };
492///
493/// let mut storage = ParameterStorage::<8>::new();
494/// let mut server = ParameterServer::new_in(storage.as_table());
495/// let talker = NodeKey::new(0);
496/// let listener = NodeKey::new(1);
497///
498/// // Declare a parameter with initial value
499/// server.declare(talker, "rate", ParameterValue::Double(1.0));
500/// server.declare(listener, "rate", ParameterValue::Double(2.0));
501///
502/// // Get parameter value
503/// assert_eq!(
504///     server.get(talker, "rate").and_then(|v| v.as_double()),
505///     Some(1.0)
506/// );
507/// assert_eq!(
508///     server.get(listener, "rate").and_then(|v| v.as_double()),
509///     Some(2.0)
510/// );
511///
512/// // Set parameter value
513/// server.set(talker, "rate", ParameterValue::Double(3.0));
514/// ```
515pub struct ParameterServer<'s> {
516    /// Borrowed parameter storage
517    table: ParameterTable<'s>,
518    /// Number of parameters currently stored, across every node.
519    count: usize,
520    /// May a wire-facing set ([`apply`](Self::apply)) DECLARE a name the node
521    /// does not hold? Off by default, as upstream
522    /// (`allow_undeclared_parameters` in rclcpp's `NodeOptions`,
523    /// `allow_undeclared` in rclrs) — issue 1151.
524    ///
525    /// phase-426 W1 — PER NODE, because upstream's is a node option. One node
526    /// opting in must not decide what a remote set may do to its sibling.
527    allow_undeclared: NodeFlags,
528    /// phase-491 W2 — nodes whose remote `NOT_SET` DELETES the parameter
529    /// (rclc's set-service behaviour) instead of being refused as a type
530    /// change (rclcpp's, for a statically typed parameter). Set by the C
531    /// `rclc_parameter_server_t`; per node because the two client libraries
532    /// disagree and both live in one store.
533    delete_on_not_set: NodeFlags,
534    /// phase-446 F2 -- a declared descriptor holds a truncated description
535    /// nobody has reported yet. Lets [`Self::take_truncated_descriptions`]
536    /// answer "nothing" without walking the table, which is what lets the
537    /// executor ask on every spin.
538    truncation_pending: bool,
539    /// phase-491 W3 — nodes whose changes are logged for `/parameter_events`.
540    events_enabled: NodeFlags,
541    /// phase-491 W3 — changes not yet published, oldest first.
542    event_log: heapless::Deque<PendingParameterEvent, PARAMETER_EVENT_LOG_LEN>,
543    /// phase-491 W3 — changes that found the log full since the last read.
544    events_dropped: u32,
545    /// Issue 2023 — nodes whose events just went ON and whose start-up
546    /// event (every parameter they already hold, as `New`) is not yet
547    /// drained. rclcpp's publisher exists before the first declaration, so
548    /// a subscriber sees every parameter arrive; ours goes on later (the
549    /// node table is built after the store), and this is what keeps the two
550    /// equal without a log entry per parameter.
551    events_initial: NodeFlags,
552    /// Issue 2023 — how far the start-up drain of [`Self::events_initial`]'s
553    /// lowest node has got, as an index into that node's parameters.
554    initial_cursor: usize,
555    /// phase-417 W4.a — the bounded on-set-parameters registry. See
556    /// [`MAX_ON_SET_CALLBACKS`] for why it is bounded and why 4.
557    on_set: [Option<OnSetCallbackSlot>; MAX_ON_SET_CALLBACKS],
558}
559
560impl<'s> ParameterServer<'s> {
561    /// phase-446 F2 -- report each declared parameter whose description was
562    /// truncated to `NROS_PARAMS_MAX_DESCRIPTION_BYTES`, ONCE, and forget it.
563    /// Issue 2686: `report` is called once per truncated FIELD, with the
564    /// [`DescriptorText`](crate::DescriptorText) that names the field and the
565    /// knob that sizes it, so a cut constraints text is never reported as a
566    /// description.
567    ///
568    /// This crate has no logger, so it records the truncation on the
569    /// descriptor and the executor, which has one, drains it here and logs.
570    /// The truncation itself happens where the text is given
571    /// ([`ParameterDescriptor::set_description`]), and a declaration can come
572    /// through several builders; the store is where every one of them lands.
573    /// Returns how many truncated fields were reported.
574    pub(crate) fn take_truncated_descriptions(
575        &mut self,
576        mut report: impl FnMut(NodeKey, &str, crate::DescriptorText),
577    ) -> usize {
578        if !self.truncation_pending {
579            return 0;
580        }
581        self.truncation_pending = false;
582        let mut n = 0;
583        for entry in self.table.entries.iter_mut().flatten() {
584            if let Some(d) = entry.descriptor.as_mut()
585                && d.any_text_truncated()
586            {
587                for text in d.truncated_texts() {
588                    report(entry.node, entry.param.name.as_str(), text);
589                    n += 1;
590                }
591                d.clear_truncated_texts();
592            }
593        }
594        n
595    }
596
597    /// Note a descriptor entering the store (phase-446 F2).
598    #[inline]
599    fn note_descriptor(&mut self, descriptor: Option<&ParameterDescriptor>) {
600        if descriptor.is_some_and(ParameterDescriptor::any_text_truncated) {
601            self.truncation_pending = true;
602        }
603    }
604
605    /// Create a parameter server over `table`.
606    ///
607    /// The server ADOPTS whatever the table already holds: `count` is
608    /// recovered from the occupied slots rather than assumed zero. That is
609    /// what makes a table safe to hand to a second server after the first is
610    /// dropped (and what lets storage arrive pre-seeded), where assuming empty
611    /// would desynchronise the count from the slots — `is_full` wrong in one
612    /// direction, `remove` underflowing in the other. Fresh
613    /// [`ParameterStorage`] is all-`None`, so the usual path costs one scan
614    /// and starts at zero.
615    pub(crate) fn new_in(table: ParameterTable<'s>) -> Self {
616        let count = table.occupied();
617        Self {
618            table,
619            count,
620            allow_undeclared: NodeFlags::new(),
621            delete_on_not_set: NodeFlags::new(),
622            on_set: [None; MAX_ON_SET_CALLBACKS],
623            // An adopted table may already hold a truncated description, so
624            // the first drain looks rather than assuming none.
625            truncation_pending: true,
626            events_enabled: NodeFlags::new(),
627            event_log: heapless::Deque::new(),
628            events_dropped: 0,
629            events_initial: NodeFlags::new(),
630            initial_cursor: 0,
631        }
632    }
633
634    /// Let a wire-facing set ([`apply`](Self::apply)) create a parameter
635    /// `node` never declared. Default `false`: a remote set on a misspelled
636    /// name used to report success and create the misspelling (issue 1151);
637    /// now it is refused with a reason unless this is switched on, as
638    /// upstream.
639    ///
640    /// phase-426 W1 — scoped to `node`. Switching it on for `/talker` leaves
641    /// `/listener` refusing undeclared names.
642    pub(crate) fn set_allow_undeclared(&mut self, node: NodeKey, allow: bool) {
643        self.allow_undeclared.set(node, allow);
644    }
645
646    /// Whether [`apply`](Self::apply) may declare an unknown name on `node`.
647    pub(crate) fn allows_undeclared(&self, node: NodeKey) -> bool {
648        self.allow_undeclared.get(node)
649    }
650
651    /// phase-491 W3 — log `node`'s changes for `/parameter_events`
652    /// (rclc's `notify_changed_over_dds`). Off by default, so a node nobody
653    /// asked events for pays nothing.
654    ///
655    /// Issue 2023 — switching it ON (from off) also queues the node's
656    /// START-UP event: every parameter the node already holds is reported as
657    /// `New` by [`pop_initial_parameter_event`](Self::pop_initial_parameter_event),
658    /// or one [`ParameterEventKind::Announce`] when it holds none, so a
659    /// subscriber sees what rclcpp's would although our publisher comes up
660    /// after the first declarations.
661    pub(crate) fn set_parameter_events(&mut self, node: NodeKey, on: bool) {
662        if on && !self.events_enabled.get(node) {
663            self.events_initial.set(node, true);
664        }
665        if !on {
666            self.events_initial.set(node, false);
667            if self.events_initial.first().is_none() {
668                self.initial_cursor = 0;
669            }
670        }
671        self.events_enabled.set(node, on);
672    }
673
674    /// Whether `node`'s changes are logged for `/parameter_events`.
675    pub(crate) fn parameter_events_enabled(&self, node: NodeKey) -> bool {
676        self.events_enabled.get(node)
677    }
678
679    /// Issue 2023 — the next entry of a node's START-UP event, queued when its
680    /// events went on: one `New` per parameter it held then (read at drain
681    /// time, so it reports the current value), or one `Announce` for a node
682    /// that holds none. Drain this BEFORE [`pop_parameter_event`](Self::pop_parameter_event);
683    /// while a node's start-up event is pending its changes are not logged
684    /// separately, because the drain reports them.
685    ///
686    /// Bounded and allocation-free: a cursor into the fixed table, no copy of
687    /// the node's parameter list.
688    pub(crate) fn pop_initial_parameter_event(&mut self) -> Option<PendingParameterEvent> {
689        loop {
690            let node = self.events_initial.first()?;
691            let k = self.initial_cursor;
692            let next = self.iter(node).nth(k).map(|p| p.name.clone());
693            match next {
694                Some(name) => {
695                    self.initial_cursor = k + 1;
696                    return Some(PendingParameterEvent {
697                        node,
698                        kind: ParameterEventKind::New,
699                        name,
700                    });
701                }
702                None => {
703                    self.events_initial.set(node, false);
704                    self.initial_cursor = 0;
705                    if k == 0 {
706                        return Some(PendingParameterEvent {
707                            node,
708                            kind: ParameterEventKind::Announce,
709                            name: String::new(),
710                        });
711                    }
712                }
713            }
714        }
715    }
716
717    /// phase-491 W3 — the oldest change waiting for `/parameter_events`.
718    pub(crate) fn pop_parameter_event(&mut self) -> Option<PendingParameterEvent> {
719        self.event_log.pop_front()
720    }
721
722    /// phase-491 W3 — how many changes found the log full since the last
723    /// call, and reset the count.
724    pub(crate) fn take_parameter_events_dropped(&mut self) -> u32 {
725        core::mem::take(&mut self.events_dropped)
726    }
727
728    /// Record a change for `/parameter_events`, merging into an entry already
729    /// pending for the same name.
730    fn note_event(&mut self, node: NodeKey, kind: ParameterEventKind, name: &str) {
731        // Issue 2023 — a node whose start-up event is still pending is
732        // reported by that drain, which reads the table as it stands.
733        if !self.events_enabled.get(node) || self.events_initial.get(node) {
734            return;
735        }
736        if let Some(e) = self
737            .event_log
738            .iter_mut()
739            .find(|e| e.node == node && e.name.as_str() == name)
740        {
741            // New-then-changed is still new; anything then deleted is deleted;
742            // deleted-then-declared is new again.
743            e.kind = match (e.kind, kind) {
744                (ParameterEventKind::New, ParameterEventKind::Changed) => ParameterEventKind::New,
745                (_, k) => k,
746            };
747            return;
748        }
749        let mut stored = String::new();
750        if stored.push_str(name).is_err()
751            || self
752                .event_log
753                .push_back(PendingParameterEvent {
754                    node,
755                    kind,
756                    name: stored,
757                })
758                .is_err()
759        {
760            self.events_dropped = self.events_dropped.saturating_add(1);
761        }
762    }
763
764    /// phase-491 W2 — make a wire-facing `NOT_SET` on `node` DELETE the
765    /// parameter, after the on-set hooks accept `(old, None)`. This is rclc's
766    /// parameter server (`rclc_parameter_server_set_service_callback`); the
767    /// default, off, keeps rclcpp's refusal.
768    pub(crate) fn set_delete_on_not_set(&mut self, node: NodeKey, on: bool) {
769        self.delete_on_not_set.set(node, on);
770    }
771
772    /// Get the number of parameters `node` has stored.
773    pub(crate) fn len(&self, node: NodeKey) -> usize {
774        self.entries_of(node).count()
775    }
776
777    /// Check if `node` has no parameters
778    pub(crate) fn is_empty(&self, node: NodeKey) -> bool {
779        self.len(node) == 0
780    }
781
782    /// Parameters held across EVERY node — how much of the shared arena is in
783    /// use. [`len`](Self::len) is the per-node question; this one is the
784    /// capacity question's other half.
785    pub(crate) fn total_len(&self) -> usize {
786        self.count
787    }
788
789    /// Capacity of the borrowed table.
790    ///
791    /// phase-382 W2' — this is the TABLE's length, not `MAX_PARAMETERS`. The
792    /// build-time knob only picks the default size of a [`ParameterStorage`].
793    ///
794    /// phase-426 W1 — the arena is SHARED across nodes, so this is not a
795    /// per-node budget: `MAX_PARAMETERS` bounds the image, not each node.
796    pub(crate) fn capacity(&self) -> usize {
797        self.table.capacity()
798    }
799
800    /// Check if the server is at capacity (across every node)
801    pub(crate) fn is_full(&self) -> bool {
802        self.count >= self.table.capacity()
803    }
804
805    /// Occupied slots belonging to `node`.
806    fn entries_of(&self, node: NodeKey) -> impl Iterator<Item = &ParameterEntry> {
807        self.table
808            .entries
809            .iter()
810            .filter_map(|slot| slot.as_ref())
811            .filter(move |e| e.node == node)
812    }
813
814    /// Find the index of `node`'s parameter by name.
815    ///
816    /// phase-426 W1 — the node is part of the key, so a sibling's identically
817    /// named parameter is simply not found here.
818    fn find_index(&self, node: NodeKey, name: &str) -> Option<usize> {
819        self.table.entries.iter().position(|entry| {
820            entry
821                .as_ref()
822                .map(|e| e.node == node && e.param.name.as_str() == name)
823                .unwrap_or(false)
824        })
825    }
826
827    /// Find an empty slot
828    fn find_empty_slot(&self) -> Option<usize> {
829        self.table.entries.iter().position(|entry| entry.is_none())
830    }
831
832    /// Declare a new parameter with a value on `node`
833    ///
834    /// If the parameter already exists, this does nothing and returns false.
835    /// Returns true if the parameter was declared successfully.
836    ///
837    /// phase-428 W6 remainder: this is the method `Executor::declare_parameter`
838    /// delegates to, so marking only the wrapper would leave the class half
839    /// fixed one crate down.
840    #[must_use]
841    pub(crate) fn declare(&mut self, node: NodeKey, name: &str, value: ParameterValue) -> bool {
842        self.declare_with_descriptor(node, name, value, None)
843    }
844
845    /// [`declare`](Self::declare), borrowing the value (issue 2070): the
846    /// spelling a large value should take, since it is copied into its slot
847    /// once instead of through every frame.
848    #[must_use]
849    pub(crate) fn declare_ref(
850        &mut self,
851        node: NodeKey,
852        name: &str,
853        value: &ParameterValue,
854    ) -> bool {
855        self.try_declare_ref(node, name, value, None).is_ok()
856    }
857
858    // Issue 2969.
859    /// Mark `name` on `node`, just declared from a launch file, as a launch
860    /// seed: the first declaration the code makes of it adopts the value
861    /// ([`adopt_launch_seed`](Self::adopt_launch_seed)). `false` when the name
862    /// is not in the store.
863    pub(crate) fn mark_launch_seed(&mut self, node: NodeKey, name: &str) -> bool {
864        match self.find_index(node, name) {
865            Some(i) => {
866                if let Some(entry) = self.table.entries[i].as_mut() {
867                    entry.launch_seed = true;
868                }
869                true
870            }
871            None => false,
872        }
873    }
874
875    // Issue 2969.
876    /// The code declares `name` on `node` as `param_type`. When the store
877    /// holds a launch seed for it, the declaration ADOPTS the seed, as rclcpp
878    /// and rclrs apply a launch override at declaration: `Some(Ok(()))`, the
879    /// seed's value kept, `descriptor` (if any) attached and checked against
880    /// it, and the mark cleared so a later declaration is a duplicate.
881    /// `Some(Err(LaunchValueTypeMismatch))` when the seed has another type,
882    /// `Some(Err(InitialValueOutOfRange))` when the descriptor's range
883    /// refuses it. `None` when there is no seed to adopt: the caller declares
884    /// as it always did.
885    ///
886    /// The ONE rule for every language's declaration (the Rust typed and
887    /// declarative routes, C's rclc server, C++'s node), so a launch value
888    /// is adopted or refused the same way whichever code declares it.
889    pub(crate) fn adopt_launch_seed(
890        &mut self,
891        node: NodeKey,
892        name: &str,
893        param_type: crate::ParameterType,
894        descriptor: Option<&ParameterDescriptor>,
895    ) -> Option<Result<(), DeclarationError>> {
896        let i = self.find_index(node, name)?;
897        let entry = self.table.entries[i].as_mut()?;
898        if !entry.launch_seed {
899            return None;
900        }
901        if entry.param.value.param_type() != param_type {
902            return Some(Err(DeclarationError::LaunchValueTypeMismatch));
903        }
904        if let Some(d) = descriptor {
905            if let Err(e) = Self::declaration_consistency(Some(d), &entry.param.value) {
906                return Some(Err(e));
907            }
908        }
909        let entry = self.table.entries[i].as_mut()?;
910        entry.launch_seed = false;
911        if let Some(d) = descriptor {
912            entry.descriptor = Some(d.clone());
913            self.note_descriptor(Some(d));
914        }
915        Some(Ok(()))
916    }
917
918    /// Declare a new parameter with value and descriptor on `node`
919    ///
920    /// The descriptor provides metadata like description, constraints, and read-only flag.
921    ///
922    /// phase-428 W6 remainder: see [`Self::declare`]. Every `false` arm below
923    /// is a REFUSAL (name taken, table full, value rejected), never a question.
924    #[must_use]
925    pub(crate) fn declare_with_descriptor(
926        &mut self,
927        node: NodeKey,
928        name: &str,
929        value: ParameterValue,
930        descriptor: Option<ParameterDescriptor>,
931    ) -> bool {
932        self.try_declare_with_descriptor(node, name, value, descriptor)
933            .is_ok()
934    }
935
936    /// [`declare`](Self::declare), saying WHY it refused — phase-417 W4.a.
937    ///
938    /// rclrs separates declare-time failures from set-time ones
939    /// ([`DeclarationError`] against [`ParameterError`]); ours returned a
940    /// bare `bool` for "the name was taken", "the table was full" and "the
941    /// default is outside the range" alike, so a caller could not tell a
942    /// programming error from a capacity one. The `bool` spellings above
943    /// forward to this, so there is exactly one declare path.
944    pub(crate) fn try_declare(
945        &mut self,
946        node: NodeKey,
947        name: &str,
948        value: ParameterValue,
949    ) -> Result<(), DeclarationError> {
950        self.try_declare_with_descriptor(node, name, value, None)
951    }
952
953    /// [`declare_with_descriptor`](Self::declare_with_descriptor), saying WHY
954    /// it refused. See [`try_declare`](Self::try_declare).
955    pub(crate) fn try_declare_with_descriptor(
956        &mut self,
957        node: NodeKey,
958        name: &str,
959        value: ParameterValue,
960        descriptor: Option<ParameterDescriptor>,
961    ) -> Result<(), DeclarationError> {
962        self.try_declare_ref(node, name, &value, descriptor)
963    }
964
965    /// [`try_declare_with_descriptor`](Self::try_declare_with_descriptor),
966    /// borrowing the value — issue 2070. THE declare path; the by-value
967    /// spellings forward here.
968    ///
969    /// A [`ParameterValue`] is as large as its largest variant (`StringArray`:
970    /// `MAX_STRING_ARRAY_LEN` x `MAX_STRING_VALUE_LEN`, ~8 KiB at the defaults), and
971    /// the by-value path moved it through every frame and built it again in
972    /// [`Parameter::new`] and in the slot's `Some(..)`: ~57 KiB of stack for
973    /// one `declare_parameter<double>` on aarch64, ~67 KiB on Cortex-M3,
974    /// which overflowed a 64 KiB RTOS app stack into the kernel's globals.
975    /// Here the slot is filled with an empty value and the caller's is copied
976    /// into it once, in place ([`ParameterValue::assign_from`]).
977    pub(crate) fn try_declare_ref(
978        &mut self,
979        node: NodeKey,
980        name: &str,
981        value: &ParameterValue,
982        descriptor: Option<ParameterDescriptor>,
983    ) -> Result<(), DeclarationError> {
984        // Check if already exists
985        if self.find_index(node, name).is_some() {
986            return Err(DeclarationError::AlreadyDeclared);
987        }
988
989        // Issue 1150 — an ill-formed range, or a default the range rejects,
990        // is refused at declaration, as upstream. Same predicate as every set.
991        Self::declaration_consistency(descriptor.as_ref(), value)?;
992        self.declare_into(node, name, descriptor, &mut |slot| slot.assign_from(value))
993    }
994
995    /// Declare a parameter whose value `fill` writes straight into its slot,
996    /// with no descriptor -- issue 2815.
997    ///
998    /// For a SCALAR default (`use_sim_time = false`): even
999    /// [`declare_ref`](Self::declare_ref) needs a `ParameterValue` in the
1000    /// caller's frame to borrow, and that value is ~8 KiB whatever variant it
1001    /// holds. Writing `*slot = ParameterValue::Bool(false)` through the slot
1002    /// builds nothing that size on the stack.
1003    pub(crate) fn declare_with(
1004        &mut self,
1005        node: NodeKey,
1006        name: &str,
1007        fill: &mut dyn FnMut(&mut ParameterValue),
1008    ) -> bool {
1009        if self.find_index(node, name).is_some() {
1010            return false;
1011        }
1012        self.declare_into(node, name, None, fill).is_ok()
1013    }
1014
1015    /// The slot write shared by every declare: an empty slot, the name, then
1016    /// the value written in place by `fill`. The caller has checked that the
1017    /// name is free and the value consistent with `descriptor`.
1018    fn declare_into(
1019        &mut self,
1020        node: NodeKey,
1021        name: &str,
1022        descriptor: Option<ParameterDescriptor>,
1023        fill: &mut dyn FnMut(&mut ParameterValue),
1024    ) -> Result<(), DeclarationError> {
1025        // Find an empty slot
1026        let slot = match self.find_empty_slot() {
1027            Some(idx) => idx,
1028            None => return Err(DeclarationError::StorageFull),
1029        };
1030
1031        // The name is checked before the slot is touched, so a refusal
1032        // leaves the table as it was.
1033        let mut stored_name = String::new();
1034        if stored_name.push_str(name).is_err() {
1035            return Err(DeclarationError::NameTooLong);
1036        }
1037
1038        self.note_descriptor(descriptor.as_ref());
1039        // Issue 2070 -- the slot is written in place and the value copied in
1040        // once: an entry built on the stack and moved in is a second ~8 KiB
1041        // `ParameterValue` in this frame.
1042        let cell = &mut self.table.entries[slot];
1043        *cell = Some(ParameterEntry {
1044            node,
1045            param: Parameter {
1046                name: stored_name,
1047                value: ParameterValue::NotSet,
1048            },
1049            descriptor,
1050            launch_seed: false,
1051        });
1052        if let Some(entry) = cell {
1053            fill(&mut entry.param.value);
1054        }
1055        self.count += 1;
1056        self.note_event(node, ParameterEventKind::New, name);
1057        Ok(())
1058    }
1059
1060    /// The declare-time half of issue 1150: the range must be well-formed
1061    /// and the initial value must satisfy it. ONE spelling for both declare
1062    /// paths.
1063    ///
1064    /// phase-417 W4.a — it returns rclrs's two distinct names rather than a
1065    /// `bool`, because the remedies differ: `InvalidRange` means fix the
1066    /// range, `InitialValueOutOfRange` means fix the default. The `bool`
1067    /// spelling below is kept for the caller that only has a
1068    /// `ParameterError` channel, so there is still one predicate.
1069    pub(crate) fn declaration_consistency(
1070        descriptor: Option<&ParameterDescriptor>,
1071        value: &ParameterValue,
1072    ) -> Result<(), DeclarationError> {
1073        match descriptor {
1074            Some(desc) if !desc.range.is_valid() => Err(DeclarationError::InvalidRange),
1075            Some(desc) if !desc.validate_range(value) => {
1076                Err(DeclarationError::InitialValueOutOfRange)
1077            }
1078            _ => Ok(()),
1079        }
1080    }
1081
1082    fn declaration_is_consistent(
1083        descriptor: Option<&ParameterDescriptor>,
1084        value: &ParameterValue,
1085    ) -> bool {
1086        Self::declaration_consistency(descriptor, value).is_ok()
1087    }
1088
1089    /// Would `set(name, value)` succeed on an EXISTING entry? Read-only,
1090    /// then type, then range — the one ordering every set path uses.
1091    fn check_set_existing(
1092        entry: &ParameterEntry,
1093        value: &ParameterValue,
1094    ) -> Result<(), ParameterError> {
1095        if let Some(ref desc) = entry.descriptor {
1096            if desc.read_only {
1097                return Err(ParameterError::ReadOnly);
1098            }
1099            if !desc.dynamic_typing && desc.param_type != value.param_type() {
1100                return Err(ParameterError::TypeMismatch);
1101            }
1102            if !desc.validate_range(value) {
1103                return Err(ParameterError::OutOfRange);
1104            }
1105        }
1106        Ok(())
1107    }
1108
1109    /// Dry-run of [`apply`](Self::apply): the verdict a wire-facing set would
1110    /// get, without changing anything. `SetParametersAtomically` runs this
1111    /// over the whole batch before applying any of it.
1112    pub(crate) fn check_apply(
1113        &self,
1114        node: NodeKey,
1115        name: &str,
1116        value: &ParameterValue,
1117    ) -> Result<(), ParameterError> {
1118        match self
1119            .find_index(node, name)
1120            .and_then(|idx| self.table.entries[idx].as_ref())
1121        {
1122            Some(entry) => Self::check_set_existing(entry, value),
1123            None if !self.allows_undeclared(node) => Err(ParameterError::Undeclared),
1124            None if self.is_full() => Err(ParameterError::StorageFull),
1125            None if name.len() > MAX_PARAM_NAME_LEN => Err(ParameterError::StorageFull),
1126            None => Ok(()),
1127        }
1128    }
1129
1130    /// THE wire-facing set — what one element of `SetParameters` /
1131    /// `SetParametersAtomically` does (issue 1151).
1132    ///
1133    /// An existing parameter is set through [`set`](Self::set). An unknown
1134    /// name is [`Undeclared`](ParameterError::Undeclared) unless
1135    /// [`set_allow_undeclared`](Self::set_allow_undeclared) was switched on
1136    /// FOR THAT NODE, in which case it is declared (or `StorageFull`). Every
1137    /// service handler and every facade writer goes through here so the
1138    /// by-value oracle, the streaming path, the atomic pre-check and the C
1139    /// setters cannot disagree about what "undeclared" means.
1140    pub(crate) fn apply(
1141        &mut self,
1142        node: NodeKey,
1143        name: &str,
1144        value: ParameterValue,
1145    ) -> Result<(), ParameterError> {
1146        self.apply_ref(node, name, &value)
1147    }
1148
1149    /// [`apply`](Self::apply), borrowing the value -- issue 2104, and THE
1150    /// apply the by-value spelling forwards to. The value is copied once, into
1151    /// its slot (`ParameterValue::assign_from`); moved in, a ~8 KiB value is a
1152    /// copy in every frame it passes, which is what put a C++ array set at
1153    /// 16.6 KiB of Cortex-M3 stack.
1154    pub(crate) fn apply_ref(
1155        &mut self,
1156        node: NodeKey,
1157        name: &str,
1158        value: &ParameterValue,
1159    ) -> Result<(), ParameterError> {
1160        if matches!(value, ParameterValue::NotSet) && self.delete_on_not_set.get(node) {
1161            return self.apply_delete(node, name);
1162        }
1163        self.check_apply(node, name, value)?;
1164        // phase-417 W4.a — the accept/reject hook, AFTER the store's own rules
1165        // and BEFORE the write, which is rclcpp's ordering: a callback never
1166        // sees a write the type, range or read-only rules already refused, and
1167        // a callback that refuses leaves the value untouched. `apply` is the
1168        // one seam every writer funnels through (the six services, the C and
1169        // C++ facades, `Executor::set_parameter`), so hooking it here is what
1170        // makes one registration reach all of them.
1171        if !self.run_on_set_callbacks(node, name, self.get(node, name), Some(value)) {
1172            return Err(ParameterError::Rejected);
1173        }
1174        if self.find_index(node, name).is_some() {
1175            self.set_ref(node, name, value)
1176        } else if self.declare_ref(node, name, value) {
1177            Ok(())
1178        } else {
1179            Err(ParameterError::StorageFull)
1180        }
1181    }
1182
1183    /// [`apply`](Self::apply), taking the value from a caller-owned STAGING
1184    /// slot instead of by value — RFC-0105 D10.2 / issue 1812.
1185    ///
1186    /// A `ParameterValue` is sized by its largest variant (~8.5 KiB at the
1187    /// default bounds), so `apply(value)` puts one on the caller's stack, and
1188    /// the wire handler that decoded it put another there before that. A
1189    /// remote set decodes into a slot carved from the executor backing and
1190    /// hands it here: the same rules, hooks and order as `apply`, and the
1191    /// write is a SWAP between the slot and the stored value, so no
1192    /// value-sized temporary exists on any path that sets an existing
1193    /// parameter. On return `staged` holds the previous value (or whatever it
1194    /// held, when the set was refused); its content is scratch.
1195    ///
1196    /// The one path that still builds an entry is the undeclared add
1197    /// (`allow_undeclared`), which places an EMPTY entry first and then swaps
1198    /// the value into it; see `declare_placeholder`.
1199    pub(crate) fn apply_staged(
1200        &mut self,
1201        node: NodeKey,
1202        name: &str,
1203        staged: &mut ParameterValue,
1204    ) -> Result<(), ParameterError> {
1205        if matches!(staged, ParameterValue::NotSet) && self.delete_on_not_set.get(node) {
1206            return self.apply_delete(node, name);
1207        }
1208        self.check_apply(node, name, staged)?;
1209        if !self.run_on_set_callbacks(node, name, self.get(node, name), Some(staged)) {
1210            return Err(ParameterError::Rejected);
1211        }
1212        let (idx, kind) = match self.find_index(node, name) {
1213            Some(idx) => (idx, ParameterEventKind::Changed),
1214            None => match self.declare_placeholder(node, name) {
1215                Some(idx) => (idx, ParameterEventKind::New),
1216                None => return Err(ParameterError::StorageFull),
1217            },
1218        };
1219        match self.table.entries[idx].as_mut() {
1220            Some(entry) => {
1221                core::mem::swap(&mut entry.param.value, staged);
1222                self.note_event(node, kind, name);
1223                Ok(())
1224            }
1225            None => Err(ParameterError::NotFound),
1226        }
1227    }
1228
1229    /// Place a `NotSet` entry named `name` on `node` and return its index —
1230    /// the undeclared-add half of [`apply_staged`](Self::apply_staged).
1231    ///
1232    /// Out of line on purpose: an unoptimised build materialises the entry it
1233    /// writes, and that frame belongs on the rare path only, never on the
1234    /// frame every remote set runs in.
1235    #[inline(never)]
1236    fn declare_placeholder(&mut self, node: NodeKey, name: &str) -> Option<usize> {
1237        let slot = self.find_empty_slot()?;
1238        let mut stored = String::new();
1239        stored.push_str(name).ok()?;
1240        self.table.entries[slot] = Some(ParameterEntry {
1241            node,
1242            param: Parameter {
1243                name: stored,
1244                value: ParameterValue::NotSet,
1245            },
1246            descriptor: None,
1247            launch_seed: false,
1248        });
1249        self.count += 1;
1250        Some(slot)
1251    }
1252
1253    /// The delete half of [`apply`](Self::apply) for a node that asked for
1254    /// [`set_delete_on_not_set`](Self::set_delete_on_not_set): read-only
1255    /// refuses, the hooks see `(old, None)`, then the parameter is removed.
1256    fn apply_delete(&mut self, node: NodeKey, name: &str) -> Result<(), ParameterError> {
1257        let Some(entry) = self
1258            .find_index(node, name)
1259            .and_then(|idx| self.table.entries[idx].as_ref())
1260        else {
1261            return Err(ParameterError::NotFound);
1262        };
1263        if entry.descriptor.as_ref().is_some_and(|d| d.read_only) {
1264            return Err(ParameterError::ReadOnly);
1265        }
1266        if !self.run_on_set_callbacks(node, name, self.get(node, name), None) {
1267            return Err(ParameterError::Rejected);
1268        }
1269        self.remove(node, name);
1270        Ok(())
1271    }
1272
1273    /// phase-491 W2 (RFC-0105 D6/D7) — rclc's LOCAL typed set,
1274    /// `rclc_parameter_set_{bool,int,double}`.
1275    ///
1276    /// rclc's owner of a parameter is not bound by its own read-only flag or
1277    /// range: read-only is "read-only to the OUTSIDE", and rclc never checks a
1278    /// range at all. So this is type, then the hooks with `(old, new)`, then
1279    /// the write — and nothing else. Remote writes keep going through
1280    /// [`apply`](Self::apply), which enforces both.
1281    ///
1282    /// The type check compares against the STORED value's type unless the
1283    /// descriptor allows dynamic typing, because rclc refuses a typed set of
1284    /// the wrong type (`RCLC_PARAMETER_TYPE_MISMATCH`) whether or not a
1285    /// descriptor was ever attached.
1286    pub(crate) fn set_local(
1287        &mut self,
1288        node: NodeKey,
1289        name: &str,
1290        value: ParameterValue,
1291    ) -> Result<(), ParameterError> {
1292        let Some(idx) = self.find_index(node, name) else {
1293            return Err(ParameterError::NotFound);
1294        };
1295        let Some(entry) = self.table.entries[idx].as_ref() else {
1296            return Err(ParameterError::NotFound);
1297        };
1298        let dynamic = entry.descriptor.as_ref().is_some_and(|d| d.dynamic_typing);
1299        if !dynamic && entry.param.value.param_type() != value.param_type() {
1300            return Err(ParameterError::TypeMismatch);
1301        }
1302        if !self.run_on_set_callbacks(node, name, Some(&entry.param.value), Some(&value)) {
1303            return Err(ParameterError::Rejected);
1304        }
1305        if let Some(entry) = self.table.entries[idx].as_mut() {
1306            entry.param.value = value;
1307        }
1308        self.note_event(node, ParameterEventKind::Changed, name);
1309        Ok(())
1310    }
1311
1312    /// Run every registered hook for `node`. `false` from any one of them
1313    /// refuses the write; the rest are not consulted, as rclcpp stops at the
1314    /// first unsuccessful result.
1315    fn run_on_set_callbacks(
1316        &self,
1317        node: NodeKey,
1318        name: &str,
1319        old: Option<&ParameterValue>,
1320        new: Option<&ParameterValue>,
1321    ) -> bool {
1322        for slot in self.on_set.iter().flatten() {
1323            if slot.node == node && !(slot.callback)(node, name, old, new, slot.ctx) {
1324                return false;
1325            }
1326        }
1327        true
1328    }
1329
1330    /// Register an accept/reject hook for writes to `node` — rclcpp's
1331    /// `add_on_set_parameters_callback` (phase-417 W4.a).
1332    ///
1333    /// The callback runs on every [`apply`](Self::apply): a remote
1334    /// `ros2 param set`, a C++
1335    /// `Node::set_parameter`, a Rust `Executor::set_parameter`. Returning
1336    /// `false` refuses the write with [`ParameterError::Rejected`] and
1337    /// leaves the stored value alone.
1338    ///
1339    /// `None` when all [`MAX_ON_SET_CALLBACKS`] slots are taken — a refusal,
1340    /// never a silent eviction.
1341    pub(crate) fn add_on_set_parameters_callback(
1342        &mut self,
1343        node: NodeKey,
1344        callback: OnSetParameterFn,
1345        ctx: OnSetContext,
1346    ) -> Option<OnSetParameterHandle> {
1347        let idx = self.on_set.iter().position(Option::is_none)?;
1348        self.on_set[idx] = Some(OnSetCallbackSlot {
1349            node,
1350            callback,
1351            ctx,
1352        });
1353        Some(OnSetParameterHandle(idx as u16))
1354    }
1355
1356    /// Unregister a hook — rclcpp's `remove_on_set_parameters_callback`.
1357    /// `false` if the slot was already empty.
1358    pub(crate) fn remove_on_set_parameters_callback(
1359        &mut self,
1360        handle: OnSetParameterHandle,
1361    ) -> bool {
1362        let idx = handle.0 as usize;
1363        if idx >= MAX_ON_SET_CALLBACKS || self.on_set[idx].is_none() {
1364            return false;
1365        }
1366        self.on_set[idx] = None;
1367        true
1368    }
1369
1370    /// How many hook slots are free. Lets a caller ask before registering
1371    /// rather than discovering the bound as a `None`.
1372    pub(crate) fn on_set_callbacks_free(&self) -> usize {
1373        self.on_set.iter().filter(|s| s.is_none()).count()
1374    }
1375
1376    // ---- descriptor mutation on a DECLARED parameter (phase-417 W4.a) ------
1377    //
1378    // rclc's shape: `rclc_add_parameter_description`,
1379    // `rclc_add_parameter_constraint_double` / `_integer` and
1380    // `rclc_set_parameter_read_only` all attach metadata AFTER the declaration,
1381    // so a C caller that cannot build a descriptor value still gets one. Ours
1382    // are the same verbs against the one store, and they are what the C and C++
1383    // descriptor surfaces forward to — a wrapper that built its own descriptor
1384    // table would be the second store phase-426 removed.
1385    //
1386    // Each creates the descriptor on demand: a parameter declared without one
1387    // has `None` in its slot, and refusing to describe it would make "declare
1388    // then describe" work only in the order rclc does not use.
1389
1390    /// The descriptor of `node`'s `name`, creating an empty one typed from the
1391    /// stored value if the declaration carried none.
1392    fn descriptor_mut(&mut self, node: NodeKey, name: &str) -> Option<&mut ParameterDescriptor> {
1393        let idx = self.find_index(node, name)?;
1394        let entry = self.table.entries[idx].as_mut()?;
1395        if entry.descriptor.is_none() {
1396            entry.descriptor = Some(ParameterDescriptor::new(
1397                name,
1398                entry.param.value.param_type(),
1399            )?);
1400        }
1401        entry.descriptor.as_mut()
1402    }
1403
1404    /// Attach a description and free-text constraints to a declared parameter
1405    /// — rclc's `rclc_add_parameter_description`. Either text may be empty.
1406    /// `false` if the parameter is not declared on `node`.
1407    pub(crate) fn set_parameter_description(
1408        &mut self,
1409        node: NodeKey,
1410        name: &str,
1411        description: &str,
1412        additional_constraints: &str,
1413    ) -> bool {
1414        let mut truncated = false;
1415        let found = match self.descriptor_mut(node, name) {
1416            Some(desc) => {
1417                truncated |= desc.set_description(description);
1418                truncated |= desc.set_additional_constraints(additional_constraints);
1419                true
1420            }
1421            None => false,
1422        };
1423        // Same report path a declared-with-descriptor truncation takes, so the
1424        // executor logs it once whichever verb supplied the text.
1425        self.truncation_pending |= truncated;
1426        found
1427    }
1428
1429    /// Mark a declared parameter read-only, so every later write is
1430    /// [`ParameterError::ReadOnly`] — rclc's
1431    /// `rclc_set_parameter_read_only`. `false` if not declared on `node`.
1432    pub(crate) fn set_parameter_read_only(
1433        &mut self,
1434        node: NodeKey,
1435        name: &str,
1436        read_only: bool,
1437    ) -> bool {
1438        match self.descriptor_mut(node, name) {
1439            Some(desc) => {
1440                desc.read_only = read_only;
1441                true
1442            }
1443            None => false,
1444        }
1445    }
1446
1447    /// Attach an integer range to a declared parameter — rclc's
1448    /// `rclc_add_parameter_constraint_integer`.
1449    ///
1450    /// Refuses an ill-formed range, and refuses one the CURRENT value does not
1451    /// satisfy: attaching a constraint that the stored value already violates
1452    /// would leave the store in a state no `set` could have produced, and
1453    /// `ros2 param describe` would then advertise a bound the value breaks.
1454    pub(crate) fn set_parameter_integer_range(
1455        &mut self,
1456        node: NodeKey,
1457        name: &str,
1458        min: i64,
1459        max: i64,
1460        step: i64,
1461    ) -> bool {
1462        self.set_parameter_range(
1463            node,
1464            name,
1465            ParameterRange::Integer(IntegerRange::new(min, max, step)),
1466        )
1467    }
1468
1469    /// Attach a floating-point range to a declared parameter — rclc's
1470    /// `rclc_add_parameter_constraint_double`. See
1471    /// [`set_parameter_integer_range`](Self::set_parameter_integer_range).
1472    pub(crate) fn set_parameter_float_range(
1473        &mut self,
1474        node: NodeKey,
1475        name: &str,
1476        min: f64,
1477        max: f64,
1478        step: f64,
1479    ) -> bool {
1480        self.set_parameter_range(
1481            node,
1482            name,
1483            ParameterRange::FloatingPoint(FloatingPointRange::new(min, max, step)),
1484        )
1485    }
1486
1487    /// The one range-attaching path both spellings above use.
1488    fn set_parameter_range(&mut self, node: NodeKey, name: &str, range: ParameterRange) -> bool {
1489        if !range.is_valid() {
1490            return false;
1491        }
1492        let idx = match self.find_index(node, name) {
1493            Some(idx) => idx,
1494            None => return false,
1495        };
1496        // The stored value has to satisfy the range BEFORE it is attached, and
1497        // reading it needs the entry, so the check happens here rather than
1498        // inside `descriptor_mut`. Borrowed, not cloned (issue 2104): the clone
1499        // was a 16.9 KiB frame on Cortex-M3 for a range check.
1500        match self.table.entries[idx].as_ref() {
1501            Some(entry) if range.contains(&entry.param.value) => {}
1502            _ => return false,
1503        }
1504        match self.descriptor_mut(node, name) {
1505            Some(desc) => {
1506                desc.range = range;
1507                true
1508            }
1509            None => false,
1510        }
1511    }
1512
1513    /// All-or-nothing multi-set — `~/set_parameters_atomically`'s local twin
1514    /// (phase-417 W4.a).
1515    ///
1516    /// We SERVED this and offered it in no language, so the only way to reach
1517    /// our own atomic set was over the wire. This is the same two passes the
1518    /// service handler makes: every item is checked against the CURRENT state,
1519    /// and only if all pass is any applied.
1520    ///
1521    /// `items` yields `None` for an element that could not even be turned into
1522    /// a value — which is how the service handler reports a wire value that
1523    /// does not fit the store's capacity (issue 0323) — and a `None` refuses
1524    /// the batch like any other failing check.
1525    ///
1526    /// It is `Clone` because the two passes walk it twice; a slice iterator is.
1527    ///
1528    /// Returns `Ok(())`, or the FIRST verdict that
1529    /// refused. Nothing is written on a refusal.
1530    ///
1531    /// The per-item check is against the state BEFORE the batch, not against
1532    /// the state each earlier item would leave. That is the service handler's
1533    /// contract verbatim, and it matters in one case: a batch that declares
1534    /// more undeclared names than there are free slots passes the check and
1535    /// fills what it can. Making the pre-check cumulative would need a
1536    /// speculative copy of the table, which is the allocation this store does
1537    /// not have.
1538    pub(crate) fn apply_atomically<'x, I>(
1539        &mut self,
1540        node: NodeKey,
1541        items: I,
1542    ) -> Result<(), ParameterError>
1543    where
1544        I: Iterator<Item = Option<(&'x str, ParameterValue)>> + Clone,
1545    {
1546        // Issue 2104 -- ONE implementation of the two passes, in
1547        // `apply_atomically_with`; this adapts an iterator to its fill
1548        // callback, restarting the iterator at each pass's first element.
1549        let count = items.clone().count();
1550        let mut it = items.clone();
1551        self.apply_atomically_with(node, count, |i, slot| {
1552            if i == 0 {
1553                it = items.clone();
1554            }
1555            let (name, value) = it.next()??;
1556            slot.assign_from(&value);
1557            Some(name)
1558        })
1559    }
1560
1561    /// [`apply_atomically`](Self::apply_atomically), with element `i` FILLED
1562    /// into one scratch value by `fill(i, slot)` -- issue 2104.
1563    ///
1564    /// `fill` returns the element's name, or `None` for an element that could
1565    /// not be turned into a value (which refuses the batch, as a `None` item
1566    /// does). It is called for `0..count` in order, once per pass, so it must
1567    /// fill the same value for the same `i` both times.
1568    ///
1569    /// The iterator form hands each ~8 KiB value out by value, so a C++
1570    /// `set_parameters_atomically` held one in its closure's frame and more in
1571    /// its own (25 KiB on Cortex-M3). Here the only value is `slot`, which a
1572    /// caller fills in place (`ParameterValue::assign_string`, …).
1573    pub(crate) fn apply_atomically_with<'x>(
1574        &mut self,
1575        node: NodeKey,
1576        count: usize,
1577        mut fill: impl FnMut(usize, &mut ParameterValue) -> Option<&'x str>,
1578    ) -> Result<(), ParameterError> {
1579        let mut slot = ParameterValue::NotSet;
1580        for i in 0..count {
1581            let Some(name) = fill(i, &mut slot) else {
1582                return Err(ParameterError::TypeMismatch);
1583            };
1584            self.check_apply(node, name, &slot)?;
1585            // The hook is consulted in the CHECK pass, so a callback that
1586            // refuses one element refuses the batch before anything is
1587            // written. `apply` will consult it again on the write pass; a hook
1588            // that answers differently to the same value twice is the caller's
1589            // own inconsistency, and the second answer is the one that stands.
1590            if !self.run_on_set_callbacks(node, name, self.get(node, name), Some(&slot)) {
1591                return Err(ParameterError::Rejected);
1592            }
1593        }
1594        for i in 0..count {
1595            let Some(name) = fill(i, &mut slot) else {
1596                continue;
1597            };
1598            let _ = self.apply_ref(node, name, &slot);
1599        }
1600        Ok(())
1601    }
1602
1603    /// Get a parameter value by name
1604    pub(crate) fn get(&self, node: NodeKey, name: &str) -> Option<&ParameterValue> {
1605        self.find_index(node, name)
1606            .and_then(|idx| self.table.entries[idx].as_ref())
1607            .map(|entry| &entry.param.value)
1608    }
1609
1610    /// Get a parameter by name
1611    pub(crate) fn get_parameter(&self, node: NodeKey, name: &str) -> Option<&Parameter> {
1612        self.find_index(node, name)
1613            .and_then(|idx| self.table.entries[idx].as_ref())
1614            .map(|entry| &entry.param)
1615    }
1616
1617    /// Get a parameter descriptor by name
1618    pub(crate) fn get_descriptor(&self, node: NodeKey, name: &str) -> Option<&ParameterDescriptor> {
1619        self.find_index(node, name)
1620            .and_then(|idx| self.table.entries[idx].as_ref())
1621            .and_then(|entry| entry.descriptor.as_ref())
1622    }
1623
1624    /// Set a parameter value
1625    ///
1626    /// Returns the result of the set operation.
1627    pub(crate) fn set(
1628        &mut self,
1629        node: NodeKey,
1630        name: &str,
1631        value: ParameterValue,
1632    ) -> Result<(), ParameterError> {
1633        self.set_ref(node, name, &value)
1634    }
1635
1636    /// [`set`](Self::set), borrowing the value (issue 2104): it is copied
1637    /// once, into the stored value.
1638    pub(crate) fn set_ref(
1639        &mut self,
1640        node: NodeKey,
1641        name: &str,
1642        value: &ParameterValue,
1643    ) -> Result<(), ParameterError> {
1644        let idx = match self.find_index(node, name) {
1645            Some(idx) => idx,
1646            None => return Err(ParameterError::NotFound),
1647        };
1648
1649        let entry = match self.table.entries[idx].as_mut() {
1650            Some(e) => e,
1651            None => return Err(ParameterError::NotFound),
1652        };
1653
1654        // Read-only, type, range (min/max/step) — one predicate, shared with
1655        // the atomic pre-check.
1656        Self::check_set_existing(entry, value)?;
1657
1658        entry.param.value.assign_from(value);
1659        self.note_event(node, ParameterEventKind::Changed, name);
1660        Ok(())
1661    }
1662
1663    /// Unset an optional parameter (set to NotSet)
1664    ///
1665    /// This bypasses the type check to allow optional parameters to be unset.
1666    /// Returns an error if the parameter is read-only.
1667    pub(crate) fn unset(&mut self, node: NodeKey, name: &str) -> Result<(), ParameterError> {
1668        let idx = match self.find_index(node, name) {
1669            Some(idx) => idx,
1670            None => return Err(ParameterError::NotFound),
1671        };
1672
1673        let entry = match self.table.entries[idx].as_mut() {
1674            Some(e) => e,
1675            None => return Err(ParameterError::NotFound),
1676        };
1677
1678        // Check if read-only
1679        if let Some(ref desc) = entry.descriptor
1680            && desc.read_only
1681        {
1682            return Err(ParameterError::ReadOnly);
1683        }
1684
1685        entry.param.value = ParameterValue::NotSet;
1686        self.note_event(node, ParameterEventKind::Changed, name);
1687        Ok(())
1688    }
1689
1690    /// Set or declare a parameter — an EXPLICIT auto-declare for in-image
1691    /// callers.
1692    ///
1693    /// If the parameter exists, sets its value. Otherwise, declares it. This
1694    /// ignores `allow_undeclared` on purpose: the flag governs what a REMOTE
1695    /// set may do; a Rust caller naming this method has opted in by naming
1696    /// it. Nothing on the wire path — and, since phase-426 W2, nothing on the
1697    /// C or C++ facade path either — reaches here (issue 1151).
1698    pub(crate) fn set_or_declare(
1699        &mut self,
1700        node: NodeKey,
1701        name: &str,
1702        value: ParameterValue,
1703    ) -> Result<(), ParameterError> {
1704        if self.find_index(node, name).is_some() {
1705            self.set(node, name, value)
1706        } else if self.declare(node, name, value) {
1707            Ok(())
1708        } else {
1709            Err(ParameterError::StorageFull)
1710        }
1711    }
1712
1713    /// Check if a parameter exists
1714    pub(crate) fn has(&self, node: NodeKey, name: &str) -> bool {
1715        self.find_index(node, name).is_some()
1716    }
1717
1718    /// Remove a parameter
1719    ///
1720    /// Returns true if the parameter was removed.
1721    pub(crate) fn remove(&mut self, node: NodeKey, name: &str) -> bool {
1722        if let Some(idx) = self.find_index(node, name) {
1723            self.table.entries[idx] = None;
1724            self.count -= 1;
1725            self.note_event(node, ParameterEventKind::Deleted, name);
1726            true
1727        } else {
1728            false
1729        }
1730    }
1731
1732    /// Get the type of a parameter
1733    pub(crate) fn get_type(&self, node: NodeKey, name: &str) -> Option<ParameterType> {
1734        self.get(node, name).map(|v| v.param_type())
1735    }
1736
1737    /// Iterate over `node`'s parameters
1738    pub(crate) fn iter(&self, node: NodeKey) -> impl Iterator<Item = &Parameter> {
1739        self.entries_of(node).map(|e| &e.param)
1740    }
1741
1742    /// List `node`'s parameter names
1743    pub(crate) fn list_names(&self, node: NodeKey) -> impl Iterator<Item = &str> {
1744        self.iter(node).map(|p| p.name.as_str())
1745    }
1746
1747    /// List `node`'s parameter names with a given prefix
1748    pub(crate) fn list_with_prefix<'a>(
1749        &'a self,
1750        node: NodeKey,
1751        prefix: &'a str,
1752    ) -> impl Iterator<Item = &'a str> {
1753        self.list_names(node)
1754            .filter(move |name| name.starts_with(prefix))
1755    }
1756
1757    /// Get a bool parameter value
1758    pub(crate) fn get_bool(&self, node: NodeKey, name: &str) -> Option<bool> {
1759        self.get(node, name).and_then(|v| v.as_bool())
1760    }
1761
1762    /// Get an integer parameter value
1763    pub(crate) fn get_integer(&self, node: NodeKey, name: &str) -> Option<i64> {
1764        self.get(node, name).and_then(|v| v.as_integer())
1765    }
1766
1767    /// Get a double parameter value
1768    pub(crate) fn get_double(&self, node: NodeKey, name: &str) -> Option<f64> {
1769        self.get(node, name).and_then(|v| v.as_double())
1770    }
1771
1772    /// Get a string parameter value
1773    pub(crate) fn get_string(&self, node: NodeKey, name: &str) -> Option<&str> {
1774        self.get(node, name).and_then(|v| v.as_string())
1775    }
1776
1777    /// Set a bool parameter value
1778    pub(crate) fn set_bool(
1779        &mut self,
1780        node: NodeKey,
1781        name: &str,
1782        value: bool,
1783    ) -> Result<(), ParameterError> {
1784        self.set(node, name, ParameterValue::Bool(value))
1785    }
1786
1787    /// Set an integer parameter value
1788    pub(crate) fn set_integer(
1789        &mut self,
1790        node: NodeKey,
1791        name: &str,
1792        value: i64,
1793    ) -> Result<(), ParameterError> {
1794        self.set(node, name, ParameterValue::Integer(value))
1795    }
1796
1797    /// Set a double parameter value
1798    pub(crate) fn set_double(
1799        &mut self,
1800        node: NodeKey,
1801        name: &str,
1802        value: f64,
1803    ) -> Result<(), ParameterError> {
1804        self.set(node, name, ParameterValue::Double(value))
1805    }
1806
1807    /// Set a string parameter value
1808    pub(crate) fn set_string(
1809        &mut self,
1810        node: NodeKey,
1811        name: &str,
1812        value: &str,
1813    ) -> Result<(), ParameterError> {
1814        match ParameterValue::from_string(value) {
1815            Some(v) => self.set(node, name, v),
1816            None => Err(ParameterError::StorageFull), // String too long
1817        }
1818    }
1819
1820    /// Declare a parameter with a descriptor and optional initial value.
1821    ///
1822    /// This is a more comprehensive declaration method used by the typed parameter API.
1823    ///
1824    /// # Arguments
1825    /// - `node`: The node the parameter belongs to.
1826    /// - `name`: The parameter's name. The entry's `Parameter` holds it; the
1827    ///   descriptor does not carry a second copy.
1828    /// - `descriptor`: The metadata for the parameter.
1829    /// - `initial_value`: An optional initial value for the parameter. If `None`,
1830    ///   the parameter will be initialized to `ParameterValue::NotSet`.
1831    pub(crate) fn declare_parameter(
1832        &mut self,
1833        node: NodeKey,
1834        name: &str,
1835        descriptor: ParameterDescriptor,
1836        initial_value: Option<&ParameterValue>,
1837    ) -> Result<(), ParameterError> {
1838        // Check if already exists
1839        if self.find_index(node, name).is_some() {
1840            return Err(ParameterError::TypeMismatch); // Indicates already declared
1841        }
1842
1843        let param_value = initial_value.cloned().unwrap_or_default();
1844
1845        // Issue 1150 — same declare-time check as `declare_with_descriptor`.
1846        if !Self::declaration_is_consistent(Some(&descriptor), &param_value) {
1847            return Err(ParameterError::InvalidRange);
1848        }
1849
1850        // Find an empty slot
1851        let slot = match self.find_empty_slot() {
1852            Some(idx) => idx,
1853            None => return Err(ParameterError::StorageFull),
1854        };
1855
1856        let param = Parameter::new(name, param_value).ok_or(ParameterError::StorageFull)?; // name too long
1857
1858        self.note_descriptor(Some(&descriptor));
1859        self.table.entries[slot] = Some(ParameterEntry {
1860            node,
1861            param,
1862            descriptor: Some(descriptor),
1863            launch_seed: false,
1864        });
1865        self.count += 1;
1866        Ok(())
1867    }
1868
1869    /// Get the current value of a parameter.
1870    ///
1871    /// Returns `Some(ParameterValue)` if the parameter exists, `None` otherwise.
1872    /// The `ParameterValue` is cloned to avoid lifetime issues with `&mut self`.
1873    pub(crate) fn get_parameter_value(&self, node: NodeKey, name: &str) -> Option<ParameterValue> {
1874        self.get(node, name).cloned()
1875    }
1876
1877    /// Set the value of a parameter.
1878    ///
1879    /// Returns `Ok(())` on success, or an error if the parameter
1880    /// is read-only, type mismatches, or is out of range.
1881    pub(crate) fn set_parameter_value(
1882        &mut self,
1883        node: NodeKey,
1884        name: &str,
1885        value: ParameterValue,
1886    ) -> Result<(), ParameterError> {
1887        self.set(node, name, value)
1888    }
1889}
1890
1891/// Builder for declaring parameters with a fluent API
1892pub struct LegacyParameterBuilder<'a, 's> {
1893    server: &'a mut ParameterServer<'s>,
1894    /// phase-426 W1 — the node this declaration belongs to, fixed when the
1895    /// builder is made so no chained call can lose it.
1896    node: NodeKey,
1897    name: String<MAX_PARAM_NAME_LEN>,
1898    value: ParameterValue,
1899    descriptor: Option<ParameterDescriptor>,
1900}
1901
1902impl<'a, 's> LegacyParameterBuilder<'a, 's> {
1903    /// Create a new parameter builder
1904    pub fn new(
1905        server: &'a mut ParameterServer<'s>,
1906        node: NodeKey,
1907        name: &str,
1908        value: ParameterValue,
1909    ) -> Option<Self> {
1910        let mut n = String::new();
1911        n.push_str(name).ok()?;
1912        Some(Self {
1913            server,
1914            node,
1915            name: n,
1916            value,
1917            descriptor: None,
1918        })
1919    }
1920
1921    /// Set the parameter description
1922    pub fn description(mut self, desc: &str) -> Self {
1923        let param_type = self.value.param_type();
1924        if self.descriptor.is_none() {
1925            self.descriptor = ParameterDescriptor::new(self.name.as_str(), param_type);
1926        }
1927        // phase-446 F2 -- truncated at a character boundary and recorded,
1928        // where `let _ = push_str` stored nothing for a too-long description.
1929        if let Some(ref mut d) = self.descriptor {
1930            d.set_description(desc);
1931        }
1932        self
1933    }
1934
1935    /// Set the parameter as read-only
1936    pub fn read_only(mut self) -> Self {
1937        let param_type = self.value.param_type();
1938        if self.descriptor.is_none() {
1939            self.descriptor = ParameterDescriptor::new(self.name.as_str(), param_type);
1940        }
1941        if let Some(ref mut d) = self.descriptor {
1942            d.read_only = true;
1943        }
1944        self
1945    }
1946
1947    /// Set integer range constraints
1948    pub fn integer_range(mut self, min: i64, max: i64, step: i64) -> Self {
1949        let param_type = self.value.param_type();
1950        if self.descriptor.is_none() {
1951            self.descriptor = ParameterDescriptor::new(self.name.as_str(), param_type);
1952        }
1953        if let Some(ref mut d) = self.descriptor {
1954            d.range = crate::types::ParameterRange::Integer(crate::types::IntegerRange::new(
1955                min, max, step,
1956            ));
1957        }
1958        self
1959    }
1960
1961    /// Set float range constraints
1962    pub fn float_range(mut self, min: f64, max: f64, step: f64) -> Self {
1963        let param_type = self.value.param_type();
1964        if self.descriptor.is_none() {
1965            self.descriptor = ParameterDescriptor::new(self.name.as_str(), param_type);
1966        }
1967        if let Some(ref mut d) = self.descriptor {
1968            d.range = crate::types::ParameterRange::FloatingPoint(
1969                crate::types::FloatingPointRange::new(min, max, step),
1970            );
1971        }
1972        self
1973    }
1974
1975    /// Declare the parameter
1976    ///
1977    /// The terminal of a builder chain, so a dropped
1978    /// answer is a parameter that was configured in full and then not declared.
1979    #[must_use]
1980    pub fn declare(self) -> bool {
1981        self.server.declare_with_descriptor(
1982            self.node,
1983            self.name.as_str(),
1984            self.value,
1985            self.descriptor,
1986        )
1987    }
1988}
1989
1990#[cfg(test)]
1991mod tests {
1992    use super::*;
1993
1994    /// phase-426 W1 — the node these single-node tests are about.
1995    const NODE: NodeKey = NodeKey::PRIMARY;
1996    use crate::types::{ParameterDescriptor, ParameterType};
1997
1998    // ── issue 2070: a borrowed declaration stores exactly what it was lent ──
1999
2000    fn every_variant() -> std::vec::Vec<ParameterValue> {
2001        let mut strings = ParameterValue::StringArray(Default::default());
2002        if let ParameterValue::StringArray(v) = &mut strings {
2003            for e in ["a", "", "frame_id"] {
2004                let mut s = heapless::String::new();
2005                s.push_str(e).unwrap();
2006                v.push(s).unwrap();
2007            }
2008        }
2009        std::vec![
2010            ParameterValue::Bool(true),
2011            ParameterValue::Integer(-7),
2012            ParameterValue::Double(2.5),
2013            ParameterValue::from_string("base_link").unwrap(),
2014            ParameterValue::from_byte_array(&[1, 2, 3]).unwrap(),
2015            ParameterValue::from_bool_array(&[true, false]).unwrap(),
2016            ParameterValue::from_integer_array(&[4, 5, 6]).unwrap(),
2017            ParameterValue::from_double_array(&[0.5, -1.0]).unwrap(),
2018            strings,
2019        ]
2020    }
2021
2022    /// `declare_ref` copies the value into its slot once, and what the slot
2023    /// then holds is the value it was lent, for every variant.
2024    #[test]
2025    fn a_borrowed_declaration_stores_the_value_it_was_lent() {
2026        let values = every_variant();
2027        let mut storage = ParameterStorage::<16>::new();
2028        let mut server = ParameterServer::new_in(storage.as_table());
2029        for (i, v) in values.iter().enumerate() {
2030            let name = std::format!("p{i}");
2031            assert!(server.declare_ref(NODE, &name, v));
2032            assert_eq!(
2033                std::format!("{:?}", server.get(NODE, &name).unwrap()),
2034                std::format!("{v:?}")
2035            );
2036        }
2037        assert_eq!(server.len(NODE), values.len());
2038        // A second declaration of a name is refused and leaves the first.
2039        assert!(!server.declare_ref(NODE, "p0", &ParameterValue::Integer(1)));
2040        assert!(matches!(
2041            server.get(NODE, "p0"),
2042            Some(ParameterValue::Bool(true))
2043        ));
2044    }
2045
2046    /// `assign_from` replaces whatever the destination held, including a
2047    /// different variant and a longer value of the same one.
2048    #[test]
2049    fn assign_from_replaces_any_previous_value() {
2050        let values = every_variant();
2051        for dst_init in &values {
2052            for src in &values {
2053                let mut dst = dst_init.clone();
2054                dst.assign_from(src);
2055                assert_eq!(std::format!("{dst:?}"), std::format!("{src:?}"));
2056            }
2057        }
2058        let mut long = ParameterValue::from_integer_array(&[1, 2, 3, 4]).unwrap();
2059        long.assign_from(&ParameterValue::from_integer_array(&[9]).unwrap());
2060        assert_eq!(
2061            std::format!("{long:?}"),
2062            std::format!("{:?}", ParameterValue::from_integer_array(&[9]).unwrap())
2063        );
2064    }
2065
2066    // ── phase-446 F2: a truncated description is reported once ──
2067
2068    /// Every declare path records a truncated description on the stored
2069    /// descriptor -- the plain descriptor, the typed builder and the legacy
2070    /// builder -- and `take_truncated_descriptions` hands each one over
2071    /// exactly once, with its node and name. A description that fits is
2072    /// never reported.
2073    #[test]
2074    fn each_truncated_description_is_handed_over_once() {
2075        let long = "y".repeat(crate::MAX_PARAM_DESCRIPTION_LEN + 1);
2076        let other = NodeKey::new(1);
2077        let mut storage = ParameterStorage::<8>::new();
2078        let mut server = ParameterServer::new_in(storage.as_table());
2079        assert_eq!(server.take_truncated_descriptions(|_, _, _| ()), 0);
2080
2081        let d = ParameterDescriptor::new("plain", ParameterType::Integer)
2082            .unwrap()
2083            .with_description(&long);
2084        assert!(server.declare_with_descriptor(NODE, "plain", ParameterValue::Integer(1), Some(d)));
2085        let fits = ParameterDescriptor::new("short", ParameterType::Integer)
2086            .unwrap()
2087            .with_description("");
2088        assert!(server.declare_with_descriptor(
2089            NODE,
2090            "short",
2091            ParameterValue::Integer(1),
2092            Some(fits)
2093        ));
2094        crate::ParameterBuilder::<i64>::new(&mut server, other, "typed")
2095            .default(3)
2096            .description(&long)
2097            .optional()
2098            .expect("a long description no longer refuses the declaration");
2099        assert!(
2100            LegacyParameterBuilder::new(&mut server, NODE, "legacy", ParameterValue::Bool(true))
2101                .unwrap()
2102                .description(&long)
2103                .declare()
2104        );
2105
2106        let mut seen: heapless::Vec<(usize, heapless::String<16>), 8> = heapless::Vec::new();
2107        let n = server.take_truncated_descriptions(|node, name, _| {
2108            let mut s = heapless::String::new();
2109            s.push_str(name).unwrap();
2110            seen.push((node.index(), s)).unwrap();
2111        });
2112        assert_eq!(n, 3, "{seen:?}");
2113        for (node, name) in [(0, "plain"), (1, "typed"), (0, "legacy")] {
2114            assert!(
2115                seen.iter().any(|(k, s)| *k == node && s.as_str() == name),
2116                "{name} on node {node} not reported: {seen:?}"
2117            );
2118        }
2119        assert!(!seen.iter().any(|(_, s)| s.as_str() == "short"));
2120        assert_eq!(
2121            server.take_truncated_descriptions(|_, _, _| ()),
2122            0,
2123            "once per parameter"
2124        );
2125        let kept = server.get_descriptor(other, "typed").unwrap();
2126        assert_eq!(kept.description.len(), crate::MAX_PARAM_DESCRIPTION_LEN);
2127    }
2128
2129    // ── phase-426 W1: the store is keyed by NODE ──
2130
2131    /// Two nodes composed onto one executor (RFC-0047) declaring the same
2132    /// name. Before W1 the table was flat, so the second `declare` returned
2133    /// `false` (already exists) and both nodes read ONE value: `/talker`'s
2134    /// `rate` and `/listener`'s `rate` were the same parameter.
2135    #[test]
2136    fn two_nodes_hold_independent_values_for_one_name() {
2137        let talker = NodeKey::new(0);
2138        let listener = NodeKey::new(1);
2139        let mut storage: ParameterStorage = ParameterStorage::new();
2140        let mut server = ParameterServer::new_in(storage.as_table());
2141
2142        assert!(server.declare(talker, "rate", ParameterValue::Integer(10)));
2143        // The pre-W1 collision: a flat table refuses this as a duplicate.
2144        assert!(
2145            server.declare(listener, "rate", ParameterValue::Integer(20)),
2146            "a sibling node's identical name is a DIFFERENT parameter"
2147        );
2148
2149        assert_eq!(server.get_integer(talker, "rate"), Some(10));
2150        assert_eq!(server.get_integer(listener, "rate"), Some(20));
2151
2152        // A set on one is invisible to the other.
2153        assert_eq!(
2154            server.set(talker, "rate", ParameterValue::Integer(11)),
2155            Ok(())
2156        );
2157        assert_eq!(server.get_integer(talker, "rate"), Some(11));
2158        assert_eq!(server.get_integer(listener, "rate"), Some(20));
2159
2160        // And each node enumerates only its own.
2161        assert_eq!(server.len(talker), 1);
2162        assert_eq!(server.len(listener), 1);
2163        assert_eq!(server.total_len(), 2, "one shared arena, two entries");
2164    }
2165
2166    /// A name one node declared is not a name its sibling has.
2167    #[test]
2168    fn a_sibling_cannot_read_or_write_a_name_it_never_declared() {
2169        let a = NodeKey::new(0);
2170        let b = NodeKey::new(3);
2171        let mut storage: ParameterStorage = ParameterStorage::new();
2172        let mut server = ParameterServer::new_in(storage.as_table());
2173        assert!(server.declare(a, "gain", ParameterValue::Double(1.0)));
2174
2175        assert!(!server.has(b, "gain"));
2176        assert!(server.get(b, "gain").is_none());
2177        assert_eq!(
2178            server.set(b, "gain", ParameterValue::Double(2.0)),
2179            Err(ParameterError::NotFound)
2180        );
2181        assert_eq!(
2182            server.check_apply(b, "gain", &ParameterValue::Double(2.0)),
2183            Err(ParameterError::Undeclared)
2184        );
2185        // Untouched.
2186        assert_eq!(server.get_double(a, "gain"), Some(1.0));
2187    }
2188
2189    /// `allow_undeclared` is a NODE option upstream, so one node opting in
2190    /// must not decide what a remote set may do to its sibling (issue 1151 +
2191    /// phase-426 W1).
2192    #[test]
2193    fn allow_undeclared_does_not_leak_to_a_sibling_node() {
2194        let permissive = NodeKey::new(1);
2195        let strict = NodeKey::new(2);
2196        let mut storage: ParameterStorage = ParameterStorage::new();
2197        let mut server = ParameterServer::new_in(storage.as_table());
2198        server.set_allow_undeclared(permissive, true);
2199
2200        assert!(server.allows_undeclared(permissive));
2201        assert!(!server.allows_undeclared(strict));
2202
2203        assert_eq!(
2204            server.apply(permissive, "fresh", ParameterValue::Integer(7)),
2205            Ok(())
2206        );
2207        assert_eq!(
2208            server.apply(strict, "fresh", ParameterValue::Integer(7)),
2209            Err(ParameterError::Undeclared),
2210            "the sibling still refuses a name IT never declared"
2211        );
2212        assert_eq!(server.get_integer(permissive, "fresh"), Some(7));
2213        assert!(!server.has(strict, "fresh"));
2214    }
2215
2216    /// The flag reaches every key in a `u8`'s range, not just the low ones —
2217    /// the bitmask is `[u64; 4]` precisely so there is no ceiling to find at
2218    /// runtime.
2219    #[test]
2220    fn the_allow_undeclared_flag_covers_the_whole_key_space() {
2221        let mut storage: ParameterStorage = ParameterStorage::new();
2222        let mut server = ParameterServer::new_in(storage.as_table());
2223        for raw in [0u8, 63, 64, 127, 128, 191, 192, 255] {
2224            let node = NodeKey::new(raw);
2225            assert!(!server.allows_undeclared(node), "raw {raw}");
2226            server.set_allow_undeclared(node, true);
2227            assert!(server.allows_undeclared(node), "raw {raw}");
2228            server.set_allow_undeclared(node, false);
2229            assert!(!server.allows_undeclared(node), "raw {raw}");
2230        }
2231    }
2232
2233    /// The arena is shared, so capacity is an IMAGE bound, and the node that
2234    /// runs into it is told `StorageFull` rather than being silently given a
2235    /// sibling's slot.
2236    #[test]
2237    fn the_slot_arena_is_shared_across_nodes() {
2238        let a = NodeKey::new(0);
2239        let b = NodeKey::new(1);
2240        let mut storage = ParameterStorage::<2>::new();
2241        let mut server = ParameterServer::new_in(storage.as_table());
2242        assert!(server.declare(a, "one", ParameterValue::Integer(1)));
2243        assert!(server.declare(b, "one", ParameterValue::Integer(2)));
2244        assert!(server.is_full());
2245        assert!(!server.declare(a, "two", ParameterValue::Integer(3)));
2246        assert_eq!(server.total_len(), 2);
2247        assert_eq!(server.len(a), 1);
2248        assert_eq!(server.len(b), 1);
2249    }
2250
2251    /// `remove` takes the right node's slot.
2252    #[test]
2253    fn remove_is_keyed_by_node() {
2254        let a = NodeKey::new(0);
2255        let b = NodeKey::new(1);
2256        let mut storage: ParameterStorage = ParameterStorage::new();
2257        let mut server = ParameterServer::new_in(storage.as_table());
2258        assert!(server.declare(a, "x", ParameterValue::Integer(1)));
2259        assert!(server.declare(b, "x", ParameterValue::Integer(2)));
2260
2261        assert!(server.remove(a, "x"));
2262        assert!(!server.has(a, "x"));
2263        assert_eq!(server.get_integer(b, "x"), Some(2));
2264        assert_eq!(server.total_len(), 1);
2265    }
2266
2267    // ── issue 1150: step reaches `set`, and declare validates its range ──
2268
2269    #[test]
2270    fn set_rejects_a_value_off_the_integer_step() {
2271        let mut storage: ParameterStorage = ParameterStorage::new();
2272        let mut server = ParameterServer::new_in(storage.as_table());
2273        let desc = ParameterDescriptor::new("rate", ParameterType::Integer)
2274            .unwrap()
2275            .with_integer_range(0, 100, 10);
2276        assert!(server.declare_with_descriptor(
2277            NODE,
2278            "rate",
2279            ParameterValue::Integer(20),
2280            Some(desc)
2281        ));
2282
2283        assert_eq!(
2284            server.set(NODE, "rate", ParameterValue::Integer(30)),
2285            Ok(())
2286        );
2287        // In range by min/max, off the lattice: the old `contains` said yes.
2288        assert_eq!(
2289            server.set(NODE, "rate", ParameterValue::Integer(35)),
2290            Err(ParameterError::OutOfRange)
2291        );
2292        assert_eq!(server.get_integer(NODE, "rate"), Some(30));
2293    }
2294
2295    #[test]
2296    fn set_rejects_a_value_off_the_float_step() {
2297        let mut storage: ParameterStorage = ParameterStorage::new();
2298        let mut server = ParameterServer::new_in(storage.as_table());
2299        let desc = ParameterDescriptor::new("gain", ParameterType::Double)
2300            .unwrap()
2301            .with_float_range(0.0, 1.0, 0.25);
2302        assert!(server.declare_with_descriptor(
2303            NODE,
2304            "gain",
2305            ParameterValue::Double(0.5),
2306            Some(desc)
2307        ));
2308
2309        assert_eq!(server.set_double(NODE, "gain", 0.75), Ok(()));
2310        assert_eq!(
2311            server.set_double(NODE, "gain", 0.6),
2312            Err(ParameterError::OutOfRange)
2313        );
2314        assert_eq!(server.get_double(NODE, "gain"), Some(0.75));
2315    }
2316
2317    #[test]
2318    fn declare_refuses_an_ill_formed_range() {
2319        let mut storage: ParameterStorage = ParameterStorage::new();
2320        let mut server = ParameterServer::new_in(storage.as_table());
2321        let desc = ParameterDescriptor::new("bad", ParameterType::Integer)
2322            .unwrap()
2323            .with_integer_range(0, 100, -1);
2324        assert!(!server.declare_with_descriptor(
2325            NODE,
2326            "bad",
2327            ParameterValue::Integer(0),
2328            Some(desc.clone())
2329        ));
2330        assert!(!server.has(NODE, "bad"));
2331        assert_eq!(
2332            server.declare_parameter(NODE, "bad", desc, Some(&ParameterValue::Integer(0))),
2333            Err(ParameterError::InvalidRange)
2334        );
2335        assert!(!server.has(NODE, "bad"));
2336    }
2337
2338    #[test]
2339    fn declare_refuses_a_default_its_own_range_rejects() {
2340        let mut storage: ParameterStorage = ParameterStorage::new();
2341        let mut server = ParameterServer::new_in(storage.as_table());
2342        let desc = ParameterDescriptor::new("odd", ParameterType::Integer)
2343            .unwrap()
2344            .with_integer_range(0, 100, 2);
2345        assert!(!server.declare_with_descriptor(
2346            NODE,
2347            "odd",
2348            ParameterValue::Integer(3),
2349            Some(desc.clone())
2350        ));
2351        assert!(server.declare_with_descriptor(
2352            NODE,
2353            "odd",
2354            ParameterValue::Integer(4),
2355            Some(desc)
2356        ));
2357    }
2358
2359    // ── issue 1151: a wire-facing set on an undeclared name is refused ──
2360
2361    #[test]
2362    fn apply_rejects_an_undeclared_name_by_default() {
2363        let mut storage: ParameterStorage = ParameterStorage::new();
2364        let mut server = ParameterServer::new_in(storage.as_table());
2365        assert!(server.declare(NODE, "max_speed", ParameterValue::Double(1.0)));
2366        assert!(!server.allows_undeclared(NODE));
2367
2368        // The typo from the issue: reported success and created a parameter
2369        // nobody reads.
2370        assert_eq!(
2371            server.check_apply(NODE, "max_speeed", &ParameterValue::Double(5.0)),
2372            Err(ParameterError::Undeclared)
2373        );
2374        assert_eq!(
2375            server.apply(NODE, "max_speeed", ParameterValue::Double(5.0)),
2376            Err(ParameterError::Undeclared)
2377        );
2378        assert!(!server.has(NODE, "max_speeed"));
2379        assert_eq!(server.len(NODE), 1);
2380        assert_eq!(server.get_double(NODE, "max_speed"), Some(1.0));
2381
2382        // A declared name still sets.
2383        assert_eq!(
2384            server.apply(NODE, "max_speed", ParameterValue::Double(5.0)),
2385            Ok(())
2386        );
2387        assert_eq!(server.get_double(NODE, "max_speed"), Some(5.0));
2388    }
2389
2390    #[test]
2391    fn apply_declares_an_unknown_name_under_allow_undeclared() {
2392        let mut storage: ParameterStorage = ParameterStorage::new();
2393        let mut server = ParameterServer::new_in(storage.as_table());
2394        server.set_allow_undeclared(NODE, true);
2395        assert!(server.allows_undeclared(NODE));
2396
2397        assert_eq!(
2398            server.check_apply(NODE, "fresh", &ParameterValue::Integer(7)),
2399            Ok(())
2400        );
2401        assert_eq!(
2402            server.apply(NODE, "fresh", ParameterValue::Integer(7)),
2403            Ok(())
2404        );
2405        assert_eq!(server.get_integer(NODE, "fresh"), Some(7));
2406    }
2407
2408    #[test]
2409    fn apply_under_allow_undeclared_still_reports_a_full_store() {
2410        let mut storage: ParameterStorage<1> = ParameterStorage::new();
2411        let mut server = ParameterServer::new_in(storage.as_table());
2412        server.set_allow_undeclared(NODE, true);
2413        assert!(server.declare(NODE, "only", ParameterValue::Bool(true)));
2414        assert_eq!(
2415            server.check_apply(NODE, "second", &ParameterValue::Bool(true)),
2416            Err(ParameterError::StorageFull)
2417        );
2418        assert_eq!(
2419            server.apply(NODE, "second", ParameterValue::Bool(true)),
2420            Err(ParameterError::StorageFull)
2421        );
2422    }
2423
2424    #[test]
2425    fn apply_enforces_the_existing_entry_rules_through_the_same_predicate() {
2426        let mut storage: ParameterStorage = ParameterStorage::new();
2427        let mut server = ParameterServer::new_in(storage.as_table());
2428        let desc = ParameterDescriptor::new("rate", ParameterType::Integer)
2429            .unwrap()
2430            .with_integer_range(0, 100, 10);
2431        assert!(server.declare_with_descriptor(
2432            NODE,
2433            "rate",
2434            ParameterValue::Integer(20),
2435            Some(desc)
2436        ));
2437        assert_eq!(
2438            server.check_apply(NODE, "rate", &ParameterValue::Integer(35)),
2439            Err(ParameterError::OutOfRange)
2440        );
2441        assert_eq!(
2442            server.apply(NODE, "rate", ParameterValue::Integer(35)),
2443            Err(ParameterError::OutOfRange)
2444        );
2445        assert_eq!(
2446            server.apply(NODE, "rate", ParameterValue::Double(30.0)),
2447            Err(ParameterError::TypeMismatch)
2448        );
2449        assert_eq!(server.get_integer(NODE, "rate"), Some(20));
2450    }
2451
2452    #[test]
2453    fn test_new_server() {
2454        let mut storage: ParameterStorage = ParameterStorage::new();
2455        let server = ParameterServer::new_in(storage.as_table());
2456        assert_eq!(server.len(NODE), 0);
2457        assert!(server.is_empty(NODE));
2458    }
2459
2460    #[test]
2461    #[allow(clippy::approx_constant)]
2462    fn test_declare_and_get() {
2463        let mut storage: ParameterStorage = ParameterStorage::new();
2464        let mut server = ParameterServer::new_in(storage.as_table());
2465
2466        assert!(server.declare(NODE, "my_bool", ParameterValue::Bool(true)));
2467        assert!(server.declare(NODE, "my_int", ParameterValue::Integer(42)));
2468        assert!(server.declare(NODE, "my_double", ParameterValue::Double(3.14)));
2469
2470        assert_eq!(server.len(NODE), 3);
2471        assert!(!server.is_empty(NODE));
2472
2473        assert_eq!(server.get_bool(NODE, "my_bool"), Some(true));
2474        assert_eq!(server.get_integer(NODE, "my_int"), Some(42));
2475        assert_eq!(server.get_double(NODE, "my_double"), Some(3.14));
2476    }
2477
2478    #[test]
2479    fn test_unset_clears_the_value_and_reports_success() {
2480        // phase-359 W10 / issue 0080 — what survives of
2481        // ~~`test_dirty_tracks_value_changes_not_declarations`~~. That test existed
2482        // for the persistence flush's dirty flag, which is deleted with the
2483        // seam; but it carried the crate's ONLY coverage of `unset`, so the
2484        // assertion moves here rather than going out with the flag.
2485        let mut storage: ParameterStorage = ParameterStorage::new();
2486        let mut server = ParameterServer::new_in(storage.as_table());
2487        assert!(server.declare(NODE, "count", ParameterValue::Integer(0)));
2488        assert_eq!(server.set_integer(NODE, "count", 10), Ok(()));
2489        assert_eq!(server.get_integer(NODE, "count"), Some(10));
2490
2491        assert_eq!(server.unset(NODE, "count"), Ok(()));
2492        assert_eq!(server.get_integer(NODE, "count"), None);
2493    }
2494
2495    #[test]
2496    fn test_set_parameter() {
2497        let mut storage: ParameterStorage = ParameterStorage::new();
2498        let mut server = ParameterServer::new_in(storage.as_table());
2499        assert!(server.declare(NODE, "count", ParameterValue::Integer(0)));
2500
2501        assert_eq!(server.set_integer(NODE, "count", 10), Ok(()));
2502        assert_eq!(server.get_integer(NODE, "count"), Some(10));
2503    }
2504
2505    #[test]
2506    fn test_set_nonexistent() {
2507        let mut storage: ParameterStorage = ParameterStorage::new();
2508        let mut server = ParameterServer::new_in(storage.as_table());
2509        assert_eq!(
2510            server.set(NODE, "nonexistent", ParameterValue::Integer(1)),
2511            Err(ParameterError::NotFound)
2512        );
2513    }
2514
2515    #[test]
2516    fn test_read_only_parameter() {
2517        let mut storage: ParameterStorage = ParameterStorage::new();
2518        let mut server = ParameterServer::new_in(storage.as_table());
2519
2520        let desc = ParameterDescriptor::new("version", ParameterType::String)
2521            .unwrap()
2522            .with_read_only(true);
2523
2524        assert!(server.declare_with_descriptor(
2525            NODE,
2526            "version",
2527            ParameterValue::from_string("1.0.0").unwrap(),
2528            Some(desc),
2529        ));
2530
2531        assert_eq!(
2532            server.set_string(NODE, "version", "2.0.0"),
2533            Err(ParameterError::ReadOnly)
2534        );
2535        assert_eq!(server.get_string(NODE, "version"), Some("1.0.0"));
2536    }
2537
2538    #[test]
2539    fn test_range_constraints() {
2540        let mut storage: ParameterStorage = ParameterStorage::new();
2541        let mut server = ParameterServer::new_in(storage.as_table());
2542
2543        let desc = ParameterDescriptor::new("speed", ParameterType::Double)
2544            .unwrap()
2545            .with_float_range(0.0, 10.0, 0.0);
2546
2547        assert!(server.declare_with_descriptor(
2548            NODE,
2549            "speed",
2550            ParameterValue::Double(5.0),
2551            Some(desc)
2552        ));
2553
2554        // Valid value
2555        assert_eq!(server.set_double(NODE, "speed", 8.0), Ok(()));
2556
2557        // Out of range
2558        assert_eq!(
2559            server.set_double(NODE, "speed", 15.0),
2560            Err(ParameterError::OutOfRange)
2561        );
2562        assert_eq!(server.get_double(NODE, "speed"), Some(8.0)); // Unchanged
2563    }
2564
2565    #[test]
2566    fn test_remove_parameter() {
2567        let mut storage: ParameterStorage = ParameterStorage::new();
2568        let mut server = ParameterServer::new_in(storage.as_table());
2569        assert!(server.declare(NODE, "temp", ParameterValue::Double(25.0)));
2570
2571        assert!(server.has(NODE, "temp"));
2572        assert!(server.remove(NODE, "temp"));
2573        assert!(!server.has(NODE, "temp"));
2574        assert!(!server.remove(NODE, "temp")); // Already removed
2575    }
2576
2577    #[test]
2578    fn test_list_parameters() {
2579        let mut storage: ParameterStorage = ParameterStorage::new();
2580        let mut server = ParameterServer::new_in(storage.as_table());
2581        assert!(server.declare(NODE, "robot.speed", ParameterValue::Double(1.0)));
2582        assert!(server.declare(
2583            NODE,
2584            "robot.name",
2585            ParameterValue::from_string("bot1").unwrap(),
2586        ));
2587        assert!(server.declare(NODE, "sensor.range", ParameterValue::Double(10.0)));
2588
2589        let robot_params: heapless::Vec<&str, 8> =
2590            server.list_with_prefix(NODE, "robot.").collect();
2591        assert_eq!(robot_params.len(), 2);
2592    }
2593
2594    #[test]
2595    fn test_set_or_declare() {
2596        let mut storage: ParameterStorage = ParameterStorage::new();
2597        let mut server = ParameterServer::new_in(storage.as_table());
2598
2599        // First call declares
2600        assert_eq!(
2601            server.set_or_declare(NODE, "new_param", ParameterValue::Integer(1)),
2602            Ok(())
2603        );
2604        assert_eq!(server.get_integer(NODE, "new_param"), Some(1));
2605
2606        // Second call sets
2607        assert_eq!(
2608            server.set_or_declare(NODE, "new_param", ParameterValue::Integer(2)),
2609            Ok(())
2610        );
2611        assert_eq!(server.get_integer(NODE, "new_param"), Some(2));
2612    }
2613
2614    #[test]
2615    fn test_duplicate_declare() {
2616        let mut storage: ParameterStorage = ParameterStorage::new();
2617        let mut server = ParameterServer::new_in(storage.as_table());
2618        assert!(server.declare(NODE, "param", ParameterValue::Integer(1)));
2619        assert!(!server.declare(NODE, "param", ParameterValue::Integer(2))); // Already exists
2620        assert_eq!(server.get_integer(NODE, "param"), Some(1)); // Unchanged
2621    }
2622
2623    // ── phase-417 W4.a: descriptors, undeclare, and the on-set hook ──
2624
2625    /// The four rclc descriptor verbs land on the ONE store and are visible
2626    /// through the ordinary descriptor read — a C or C++ wrapper forwarding to
2627    /// these adds no table of its own.
2628    #[test]
2629    // The comparison and the `min` below read as "always true" to clippy on a
2630    // build that leaves `NROS_PARAMS_MAX_CONSTRAINTS_BYTES` at its default of 0 --
2631    // and that is the point: the constant is a KNOB, the test is written
2632    // against it so it holds at 0, at 64 and at 256, and a version specialised
2633    // to whichever value this build resolved would read as coverage on the
2634    // other two.
2635    #[allow(clippy::absurd_extreme_comparisons, clippy::unnecessary_min_or_max)]
2636    fn descriptor_verbs_attach_to_a_declared_parameter() {
2637        let mut storage: ParameterStorage = ParameterStorage::new();
2638        let mut server = ParameterServer::new_in(storage.as_table());
2639        assert!(server.declare(NODE, "rate", ParameterValue::Double(2.0)));
2640
2641        // A parameter declared with no descriptor still gets one on demand:
2642        // rclc's order is declare-then-describe.
2643        assert!(server.get_descriptor(NODE, "rate").is_none());
2644        assert!(server.set_parameter_description(NODE, "rate", "publish rate", "hz, positive"));
2645        assert!(server.set_parameter_float_range(NODE, "rate", 0.0, 10.0, 0.0));
2646
2647        let desc = server.get_descriptor(NODE, "rate").expect("descriptor");
2648        assert_eq!(desc.description.as_str(), "publish rate");
2649        // Written against the CAPACITY, not a literal: `additional_constraints`
2650        // has its own knob (`NROS_PARAMS_MAX_CONSTRAINTS_BYTES`) whose default is
2651        // 0, so the default build stores a zero-length prefix. A test that
2652        // asserted the whole string would pass only on a build that states the
2653        // knob, and would read as coverage everywhere else.
2654        let constraints_fit = "hz, positive".len() <= crate::MAX_PARAM_CONSTRAINTS_LEN;
2655        assert_eq!(
2656            desc.additional_constraints.as_str(),
2657            &"hz, positive"[..crate::MAX_PARAM_CONSTRAINTS_LEN.min("hz, positive".len())]
2658        );
2659        assert_eq!(desc.param_type, ParameterType::Double);
2660
2661        // And the range is ENFORCED by the same predicate every set uses.
2662        assert_eq!(
2663            server.apply(NODE, "rate", ParameterValue::Double(50.0)),
2664            Err(ParameterError::OutOfRange)
2665        );
2666        assert_eq!(
2667            server.apply(NODE, "rate", ParameterValue::Double(5.0)),
2668            Ok(())
2669        );
2670
2671        // read-only is the same shape.
2672        assert!(server.set_parameter_read_only(NODE, "rate", true));
2673        assert_eq!(
2674            server.apply(NODE, "rate", ParameterValue::Double(6.0)),
2675            Err(ParameterError::ReadOnly)
2676        );
2677
2678        // Text that did not fit is REPORTED, never dropped in silence — which
2679        // is what makes a capacity of 0 an honest default rather than a
2680        // trap. At a capacity that fits, nothing is reported.
2681        let mut reported = 0usize;
2682        server.take_truncated_descriptions(|_, _, text| {
2683            // Issue 2686: the constraints field, not the description.
2684            assert_eq!(text, crate::DescriptorText::Constraints);
2685            reported += 1;
2686        });
2687        assert_eq!(
2688            reported,
2689            usize::from(!constraints_fit),
2690            "a constraints string that did not fit the capacity went unreported"
2691        );
2692
2693        // An undeclared name is refused rather than silently creating a
2694        // descriptor for a parameter that is not there.
2695        assert!(!server.set_parameter_description(NODE, "absent", "d", "c"));
2696        assert!(!server.set_parameter_read_only(NODE, "absent", true));
2697        assert!(!server.set_parameter_integer_range(NODE, "absent", 0, 1, 1));
2698    }
2699
2700    /// A range the stored value already violates is REFUSED, and so is an
2701    /// ill-formed one. Attaching either would advertise a bound over a value
2702    /// no `set` could have produced.
2703    #[test]
2704    fn a_range_must_fit_the_value_it_is_attached_to() {
2705        let mut storage: ParameterStorage = ParameterStorage::new();
2706        let mut server = ParameterServer::new_in(storage.as_table());
2707        assert!(server.declare(NODE, "depth", ParameterValue::Integer(100)));
2708
2709        assert!(!server.set_parameter_integer_range(NODE, "depth", 0, 10, 1));
2710        assert!(server.get_descriptor(NODE, "depth").is_none());
2711
2712        // min > max
2713        assert!(!server.set_parameter_integer_range(NODE, "depth", 10, 0, 1));
2714        // negative step
2715        assert!(!server.set_parameter_integer_range(NODE, "depth", 0, 1000, -1));
2716
2717        assert!(server.set_parameter_integer_range(NODE, "depth", 0, 1000, 1));
2718    }
2719
2720    /// `remove` is the undeclare every language forwards to: the slot frees,
2721    /// the count drops, and a later declare of the same name succeeds.
2722    #[test]
2723    fn undeclare_frees_the_slot_for_that_node_only() {
2724        let mut storage: ParameterStorage = ParameterStorage::new();
2725        let mut server = ParameterServer::new_in(storage.as_table());
2726        let other = NodeKey::new(1);
2727        assert!(server.declare(NODE, "rate", ParameterValue::Integer(1)));
2728        assert!(server.declare(other, "rate", ParameterValue::Integer(2)));
2729        assert_eq!(server.total_len(), 2);
2730
2731        assert!(server.remove(NODE, "rate"));
2732        assert!(!server.has(NODE, "rate"));
2733        assert!(server.has(other, "rate"));
2734        assert_eq!(server.total_len(), 1);
2735        assert!(!server.remove(NODE, "rate"));
2736
2737        assert!(server.declare(NODE, "rate", ParameterValue::Integer(3)));
2738        assert_eq!(server.get_integer(NODE, "rate"), Some(3));
2739    }
2740
2741    fn refuse_everything(
2742        _n: NodeKey,
2743        _name: &str,
2744        _old: Option<&ParameterValue>,
2745        _new: Option<&ParameterValue>,
2746        _ctx: OnSetContext,
2747    ) -> bool {
2748        false
2749    }
2750
2751    fn refuse_if_ctx_matches(
2752        _n: NodeKey,
2753        _name: &str,
2754        _old: Option<&ParameterValue>,
2755        new: Option<&ParameterValue>,
2756        ctx: OnSetContext,
2757    ) -> bool {
2758        new.and_then(ParameterValue::as_integer) != Some(ctx.a as i64)
2759    }
2760
2761    /// The hook runs on `apply` — the seam every facade and the six services
2762    /// funnel through — refuses with `Rejected`, leaves the value alone, and
2763    /// only for the node it was registered on.
2764    #[test]
2765    fn an_on_set_callback_vetoes_the_write_it_refuses() {
2766        let mut storage: ParameterStorage = ParameterStorage::new();
2767        let mut server = ParameterServer::new_in(storage.as_table());
2768        let other = NodeKey::new(1);
2769        assert!(server.declare(NODE, "rate", ParameterValue::Integer(1)));
2770        assert!(server.declare(other, "rate", ParameterValue::Integer(1)));
2771
2772        let h = server
2773            .add_on_set_parameters_callback(NODE, refuse_everything, OnSetContext::default())
2774            .expect("a free slot");
2775
2776        assert_eq!(
2777            server.apply(NODE, "rate", ParameterValue::Integer(9)),
2778            Err(ParameterError::Rejected)
2779        );
2780        assert_eq!(server.get_integer(NODE, "rate"), Some(1));
2781        // A sibling node's writes are untouched: the registration names a node.
2782        assert_eq!(
2783            server.apply(other, "rate", ParameterValue::Integer(9)),
2784            Ok(())
2785        );
2786
2787        assert!(server.remove_on_set_parameters_callback(h));
2788        assert!(!server.remove_on_set_parameters_callback(h));
2789        assert_eq!(
2790            server.apply(NODE, "rate", ParameterValue::Integer(9)),
2791            Ok(())
2792        );
2793    }
2794
2795    /// What the recording hook saw, reached through `OnSetContext::a`.
2796    #[derive(Default)]
2797    struct Seen {
2798        calls: u32,
2799        old: Option<i64>,
2800        new: Option<i64>,
2801        old_present: bool,
2802        new_present: bool,
2803    }
2804
2805    fn record(
2806        _n: NodeKey,
2807        _name: &str,
2808        old: Option<&ParameterValue>,
2809        new: Option<&ParameterValue>,
2810        ctx: OnSetContext,
2811    ) -> bool {
2812        // SAFETY: every test passes a `&mut Seen` that outlives the server.
2813        let seen = unsafe { &mut *(ctx.a as *mut Seen) };
2814        seen.calls += 1;
2815        seen.old_present = old.is_some();
2816        seen.new_present = new.is_some();
2817        seen.old = old.and_then(ParameterValue::as_integer);
2818        seen.new = new.and_then(ParameterValue::as_integer);
2819        true
2820    }
2821
2822    /// phase-491 W3 — the `/parameter_events` log: off by default, one entry
2823    /// per name (merged), and a burst past its bound is COUNTED, never blocked.
2824    #[test]
2825    fn the_event_log_merges_by_name_and_counts_overflow() {
2826        let mut storage: ParameterStorage = ParameterStorage::new();
2827        let mut server = ParameterServer::new_in(storage.as_table());
2828        assert!(server.declare(NODE, "quiet", ParameterValue::Integer(0)));
2829        assert!(server.pop_parameter_event().is_none(), "off by default");
2830
2831        server.set_parameter_events(NODE, true);
2832        // Issue 2023 — the start-up event names what the node already holds.
2833        let e = server
2834            .pop_initial_parameter_event()
2835            .expect("the start-up event");
2836        assert_eq!(
2837            (e.name.as_str(), e.kind),
2838            ("quiet", ParameterEventKind::New)
2839        );
2840        assert!(server.pop_initial_parameter_event().is_none());
2841        assert!(server.declare(NODE, "a", ParameterValue::Integer(1)));
2842        assert_eq!(server.set(NODE, "a", ParameterValue::Integer(2)), Ok(()));
2843        assert!(server.remove(NODE, "a"));
2844        let e = server.pop_parameter_event().expect("one merged entry");
2845        assert_eq!(
2846            (e.name.as_str(), e.kind),
2847            ("a", ParameterEventKind::Deleted)
2848        );
2849        assert!(server.pop_parameter_event().is_none());
2850
2851        for i in 0..PARAMETER_EVENT_LOG_LEN + 2 {
2852            let mut name = heapless::String::<8>::new();
2853            core::fmt::Write::write_fmt(&mut name, format_args!("p{i}")).unwrap();
2854            assert!(server.declare(NODE, &name, ParameterValue::Integer(0)));
2855        }
2856        assert_eq!(server.take_parameter_events_dropped(), 2);
2857        assert_eq!(
2858            server.take_parameter_events_dropped(),
2859            0,
2860            "the count resets"
2861        );
2862    }
2863
2864    /// Issue 2023 — the start-up event: one `New` per parameter the node held
2865    /// when events went on, at its CURRENT value; an `Announce` for a node
2866    /// holding none; changes made while it is pending fold into it rather
2867    /// than doubling up in the log; and re-enabling is not a second start-up.
2868    #[test]
2869    fn the_start_up_event_reports_what_the_node_holds() {
2870        let mut storage: ParameterStorage = ParameterStorage::new();
2871        let mut server = ParameterServer::new_in(storage.as_table());
2872        let other = NodeKey::new(1);
2873        assert!(server.declare(NODE, "a", ParameterValue::Integer(1)));
2874        assert!(server.declare(NODE, "b", ParameterValue::Integer(2)));
2875        assert!(server.declare(other, "x", ParameterValue::Integer(9)));
2876
2877        server.set_parameter_events(NODE, true);
2878        server.set_parameter_events(NodeKey::new(2), true);
2879        // Pending: a declaration and a removal fold into the drain.
2880        assert!(server.declare(NODE, "c", ParameterValue::Integer(3)));
2881        assert!(server.remove(NODE, "b"));
2882        assert!(server.pop_parameter_event().is_none(), "not logged twice");
2883
2884        let mut seen = heapless::Vec::<(u8, ParameterEventKind, String<8>), 8>::new();
2885        while let Some(e) = server.pop_initial_parameter_event() {
2886            let mut n = String::new();
2887            n.push_str(e.name.as_str()).unwrap();
2888            seen.push((e.node.raw(), e.kind, n)).unwrap();
2889        }
2890        let names: heapless::Vec<(u8, ParameterEventKind, &str), 8> =
2891            seen.iter().map(|(n, k, s)| (*n, *k, s.as_str())).collect();
2892        assert_eq!(
2893            names.as_slice(),
2894            &[
2895                (0, ParameterEventKind::New, "a"),
2896                (0, ParameterEventKind::New, "c"),
2897                (2, ParameterEventKind::Announce, ""),
2898            ],
2899            "node 1 never enabled events; node 2 holds nothing"
2900        );
2901
2902        // Already on: a second enable is not a second start-up.
2903        server.set_parameter_events(NODE, true);
2904        assert!(server.pop_initial_parameter_event().is_none());
2905        // After it drained, changes are logged as before.
2906        assert!(server.remove(NODE, "a"));
2907        let e = server.pop_parameter_event().expect("a logged deletion");
2908        assert_eq!(
2909            (e.name.as_str(), e.kind),
2910            ("a", ParameterEventKind::Deleted)
2911        );
2912    }
2913
2914    /// phase-491 W2 — the hook sees BOTH sides: `(old, new)` on a write to an
2915    /// existing parameter, `(None, new)` on a remote create.
2916    #[test]
2917    fn the_on_set_hook_sees_old_and_new() {
2918        let mut storage: ParameterStorage = ParameterStorage::new();
2919        let mut server = ParameterServer::new_in(storage.as_table());
2920        let mut seen = Seen::default();
2921        assert!(server.declare(NODE, "rate", ParameterValue::Integer(1)));
2922        server
2923            .add_on_set_parameters_callback(NODE, record, OnSetContext::new(&raw mut seen as usize))
2924            .expect("a free slot");
2925
2926        assert_eq!(
2927            server.apply(NODE, "rate", ParameterValue::Integer(2)),
2928            Ok(())
2929        );
2930        assert_eq!((seen.old, seen.new), (Some(1), Some(2)));
2931
2932        server.set_allow_undeclared(NODE, true);
2933        assert_eq!(
2934            server.apply(NODE, "fresh", ParameterValue::Integer(7)),
2935            Ok(())
2936        );
2937        assert!(!seen.old_present, "a create has no old value");
2938        assert_eq!(seen.new, Some(7));
2939    }
2940
2941    /// phase-491 W2 — rclc's LOCAL set: type, hook, write. Read-only and range
2942    /// do not bind the owner; a different type does.
2943    #[test]
2944    fn a_local_set_skips_read_only_and_range_but_not_type() {
2945        let mut storage: ParameterStorage = ParameterStorage::new();
2946        let mut server = ParameterServer::new_in(storage.as_table());
2947        let mut seen = Seen::default();
2948        assert!(server.declare(NODE, "rate", ParameterValue::Integer(1)));
2949        assert!(server.set_parameter_integer_range(NODE, "rate", 0, 10, 1));
2950        assert!(server.set_parameter_read_only(NODE, "rate", true));
2951        server
2952            .add_on_set_parameters_callback(NODE, record, OnSetContext::new(&raw mut seen as usize))
2953            .expect("a free slot");
2954
2955        // The remote path refuses both.
2956        assert_eq!(
2957            server.apply(NODE, "rate", ParameterValue::Integer(50)),
2958            Err(ParameterError::ReadOnly)
2959        );
2960        assert_eq!(seen.calls, 0, "a refused remote write reached the hook");
2961
2962        // The local path does not, and the hook sees (old, new).
2963        assert_eq!(
2964            server.set_local(NODE, "rate", ParameterValue::Integer(50)),
2965            Ok(())
2966        );
2967        assert_eq!((seen.old, seen.new), (Some(1), Some(50)));
2968        assert_eq!(server.get_integer(NODE, "rate"), Some(50));
2969
2970        assert_eq!(
2971            server.set_local(NODE, "rate", ParameterValue::Double(1.0)),
2972            Err(ParameterError::TypeMismatch)
2973        );
2974        assert_eq!(
2975            server.set_local(NODE, "nope", ParameterValue::Integer(1)),
2976            Err(ParameterError::NotFound)
2977        );
2978        assert!(
2979            server
2980                .add_on_set_parameters_callback(NODE, refuse_everything, OnSetContext::default())
2981                .is_some()
2982        );
2983        assert_eq!(
2984            server.set_local(NODE, "rate", ParameterValue::Integer(3)),
2985            Err(ParameterError::Rejected)
2986        );
2987        assert_eq!(server.get_integer(NODE, "rate"), Some(50));
2988    }
2989
2990    /// phase-491 W2 — rclc's set service DELETES on `NOT_SET`, after the hook
2991    /// accepts `(old, None)`; rclcpp's refuses. Per node.
2992    #[test]
2993    fn not_set_deletes_only_on_a_node_that_asked() {
2994        let mut storage: ParameterStorage = ParameterStorage::new();
2995        let mut server = ParameterServer::new_in(storage.as_table());
2996        let other = NodeKey::new(1);
2997        let mut seen = Seen::default();
2998        assert!(server.declare(NODE, "rate", ParameterValue::Integer(4)));
2999        assert!(server.declare(other, "rate", ParameterValue::Integer(4)));
3000        server.set_delete_on_not_set(NODE, true);
3001        server
3002            .add_on_set_parameters_callback(NODE, record, OnSetContext::new(&raw mut seen as usize))
3003            .expect("a free slot");
3004
3005        assert_eq!(server.apply(NODE, "rate", ParameterValue::NotSet), Ok(()));
3006        assert!(!server.has(NODE, "rate"));
3007        assert_eq!((seen.old, seen.new_present), (Some(4), false));
3008
3009        // The other node keeps rclcpp's semantics: no delete (with no descriptor
3010        // the store just records NOT_SET, as it always has).
3011        let _ = server.apply(other, "rate", ParameterValue::NotSet);
3012        assert!(
3013            server.has(other, "rate"),
3014            "the rclcpp node's parameter was deleted"
3015        );
3016
3017        assert!(server.declare(NODE, "ro", ParameterValue::Integer(1)));
3018        assert!(server.set_parameter_read_only(NODE, "ro", true));
3019        assert_eq!(
3020            server.apply(NODE, "ro", ParameterValue::NotSet),
3021            Err(ParameterError::ReadOnly)
3022        );
3023        assert!(server.has(NODE, "ro"));
3024    }
3025
3026    /// Issue 1812 / RFC-0105 D10.2 — `apply_staged` is `apply` with the value
3027    /// taken from a slot: the same verdict for every row `apply` decides, and
3028    /// the same store afterwards. Each row runs on two fresh, identically
3029    /// prepared servers, one per entry point.
3030    #[test]
3031    fn apply_staged_is_apply_from_a_slot() {
3032        fn reject(
3033            _: NodeKey,
3034            name: &str,
3035            _: Option<&ParameterValue>,
3036            _: Option<&ParameterValue>,
3037            _: OnSetContext,
3038        ) -> bool {
3039            name != "vetoed"
3040        }
3041        fn prepared(storage: &mut ParameterStorage<4>) -> ParameterServer<'_> {
3042            let mut server = ParameterServer::new_in(storage.as_table());
3043            assert!(server.declare(NODE, "rate", ParameterValue::Integer(1)));
3044            assert!(
3045                server.declare_with_descriptor(
3046                    NODE,
3047                    "ro",
3048                    ParameterValue::Integer(1),
3049                    Some(
3050                        ParameterDescriptor::new("ro", ParameterType::Integer)
3051                            .unwrap()
3052                            .with_read_only(true)
3053                    ),
3054                )
3055            );
3056            assert!(server.declare_with_descriptor(
3057                NODE,
3058                "typed",
3059                ParameterValue::Integer(1),
3060                Some(ParameterDescriptor::new("typed", ParameterType::Integer).unwrap()),
3061            ));
3062            assert!(server.declare(NODE, "vetoed", ParameterValue::Integer(1)));
3063            server
3064                .add_on_set_parameters_callback(NODE, reject, OnSetContext::new(0))
3065                .expect("a free slot");
3066            server
3067        }
3068        // The value is built per row (a `fn`), not held in the table: a
3069        // `ParameterValue` is ~8.5 KiB, which is the point of the slot.
3070        type Row = (&'static str, fn() -> ParameterValue, bool, bool);
3071        let rows: [Row; 7] = [
3072            ("rate", || ParameterValue::Integer(7), false, false),
3073            ("ro", || ParameterValue::Integer(7), false, false),
3074            ("typed", || ParameterValue::Bool(true), false, false),
3075            ("vetoed", || ParameterValue::Integer(7), false, false),
3076            ("fresh", || ParameterValue::Integer(7), false, false),
3077            // allow_undeclared: declares, but the 4-slot table is full.
3078            ("fresh", || ParameterValue::Integer(7), true, false),
3079            // delete_on_not_set: the rclc remote delete.
3080            ("rate", || ParameterValue::NotSet, false, true),
3081        ];
3082        for (name, value, allow, delete) in rows {
3083            let mut a_storage: ParameterStorage<4> = ParameterStorage::new();
3084            let mut b_storage: ParameterStorage<4> = ParameterStorage::new();
3085            let mut by_value = prepared(&mut a_storage);
3086            let mut by_slot = prepared(&mut b_storage);
3087            for s in [&mut by_value, &mut by_slot] {
3088                s.set_allow_undeclared(NODE, allow);
3089                s.set_delete_on_not_set(NODE, delete);
3090            }
3091            let want = by_value.apply(NODE, name, value());
3092            let mut slot = value();
3093            let got = by_slot.apply_staged(NODE, name, &mut slot);
3094            assert_eq!(got, want, "verdict for `{name}`");
3095            for probe in ["rate", "ro", "typed", "vetoed", "fresh"] {
3096                assert_eq!(
3097                    by_slot.get(NODE, probe).map(ParameterValue::param_type),
3098                    by_value.get(NODE, probe).map(ParameterValue::param_type),
3099                    "`{probe}` after setting `{name}`"
3100                );
3101                assert_eq!(
3102                    by_slot.get_integer(NODE, probe),
3103                    by_value.get_integer(NODE, probe),
3104                    "`{probe}` after setting `{name}`"
3105                );
3106            }
3107        }
3108
3109        // The undeclared add, with room: declared, value swapped in.
3110        let mut storage: ParameterStorage<4> = ParameterStorage::new();
3111        let mut server = ParameterServer::new_in(storage.as_table());
3112        server.set_allow_undeclared(NODE, true);
3113        let mut slot = ParameterValue::Double(2.5);
3114        assert_eq!(server.apply_staged(NODE, "fresh", &mut slot), Ok(()));
3115        assert_eq!(server.get_double(NODE, "fresh"), Some(2.5));
3116        assert_eq!(server.len(NODE), 1);
3117
3118        // A SWAP: the slot comes back holding the value it displaced.
3119        let mut slot = ParameterValue::Double(4.0);
3120        assert!(server.apply_staged(NODE, "fresh", &mut slot).is_ok());
3121        assert_eq!(slot.as_double(), Some(2.5));
3122        assert_eq!(server.get_double(NODE, "fresh"), Some(4.0));
3123    }
3124
3125    /// The registry is BOUNDED and says so: the (N+1)th registration is `None`,
3126    /// never a silent eviction of somebody else's hook. The context reaches
3127    /// the callback.
3128    #[test]
3129    fn the_on_set_registry_refuses_past_its_stated_capacity() {
3130        let mut storage: ParameterStorage = ParameterStorage::new();
3131        let mut server = ParameterServer::new_in(storage.as_table());
3132        assert!(server.declare(NODE, "rate", ParameterValue::Integer(1)));
3133
3134        assert_eq!(server.on_set_callbacks_free(), MAX_ON_SET_CALLBACKS);
3135        let mut handles = heapless::Vec::<_, MAX_ON_SET_CALLBACKS>::new();
3136        for i in 0..MAX_ON_SET_CALLBACKS {
3137            let h = server
3138                .add_on_set_parameters_callback(
3139                    NODE,
3140                    refuse_if_ctx_matches,
3141                    OnSetContext::new(40 + i),
3142                )
3143                .expect("within capacity");
3144            handles.push(h).expect("bounded by the same constant");
3145        }
3146        assert_eq!(server.on_set_callbacks_free(), 0);
3147        assert!(
3148            server
3149                .add_on_set_parameters_callback(NODE, refuse_everything, OnSetContext::default())
3150                .is_none()
3151        );
3152
3153        // Every registered hook is consulted, and each got its own context.
3154        for i in 0..MAX_ON_SET_CALLBACKS {
3155            assert_eq!(
3156                server.apply(NODE, "rate", ParameterValue::Integer(40 + i as i64)),
3157                Err(ParameterError::Rejected)
3158            );
3159        }
3160        assert_eq!(
3161            server.apply(NODE, "rate", ParameterValue::Integer(7)),
3162            Ok(())
3163        );
3164
3165        assert!(server.remove_on_set_parameters_callback(handles[0]));
3166        assert_eq!(server.on_set_callbacks_free(), 1);
3167    }
3168
3169    /// The hook runs AFTER the store's own rules, so a callback never sees a
3170    /// write the descriptor already refused.
3171    #[test]
3172    fn the_store_rules_run_before_the_hook() {
3173        let mut storage: ParameterStorage = ParameterStorage::new();
3174        let mut server = ParameterServer::new_in(storage.as_table());
3175        let desc = ParameterDescriptor::new("rate", ParameterType::Integer)
3176            .expect("name fits")
3177            .with_read_only(true);
3178        assert!(server.declare_with_descriptor(
3179            NODE,
3180            "rate",
3181            ParameterValue::Integer(1),
3182            Some(desc)
3183        ));
3184        let _ = server
3185            .add_on_set_parameters_callback(NODE, refuse_everything, OnSetContext::default())
3186            .expect("a free slot");
3187        // ReadOnly, not Rejected: the callback was never consulted.
3188        assert_eq!(
3189            server.apply(NODE, "rate", ParameterValue::Integer(2)),
3190            Err(ParameterError::ReadOnly)
3191        );
3192    }
3193
3194    /// The registry's cost is MEASURED, not asserted in prose: the doc on
3195    /// [`MAX_ON_SET_CALLBACKS`] names a byte count, and a slot that grows
3196    /// silently is how that number goes stale (the issue-1022 class).
3197    #[test]
3198    fn the_on_set_registry_costs_what_its_doc_says() {
3199        let slot = core::mem::size_of::<Option<OnSetCallbackSlot>>();
3200        let word = core::mem::size_of::<usize>();
3201        // node (1 byte, padded) + fn pointer + two context words, and the
3202        // `Option` rides in the padding or the null fn pointer.
3203        assert!(
3204            slot <= 4 * word,
3205            "an on-set slot is {slot} bytes, more than the four words its doc claims"
3206        );
3207        assert_eq!(
3208            core::mem::size_of::<[Option<OnSetCallbackSlot>; MAX_ON_SET_CALLBACKS]>(),
3209            MAX_ON_SET_CALLBACKS * slot
3210        );
3211    }
3212
3213    /// `try_declare` says WHY, where `declare` said only `false`.
3214    #[test]
3215    fn try_declare_names_the_refusal() {
3216        let mut storage: ParameterStorage<2> = ParameterStorage::new();
3217        let mut server = ParameterServer::new_in(storage.as_table());
3218
3219        assert_eq!(
3220            server.try_declare(NODE, "a", ParameterValue::Integer(1)),
3221            Ok(())
3222        );
3223        assert_eq!(
3224            server.try_declare(NODE, "a", ParameterValue::Integer(1)),
3225            Err(DeclarationError::AlreadyDeclared)
3226        );
3227
3228        let bad_range = ParameterDescriptor::new("b", ParameterType::Integer)
3229            .expect("name fits")
3230            .with_integer_range(10, 0, 1);
3231        assert_eq!(
3232            server.try_declare_with_descriptor(
3233                NODE,
3234                "b",
3235                ParameterValue::Integer(1),
3236                Some(bad_range)
3237            ),
3238            Err(DeclarationError::InvalidRange)
3239        );
3240
3241        let out_of_range = ParameterDescriptor::new("b", ParameterType::Integer)
3242            .expect("name fits")
3243            .with_integer_range(0, 10, 1);
3244        assert_eq!(
3245            server.try_declare_with_descriptor(
3246                NODE,
3247                "b",
3248                ParameterValue::Integer(99),
3249                Some(out_of_range)
3250            ),
3251            Err(DeclarationError::InitialValueOutOfRange)
3252        );
3253
3254        assert_eq!(
3255            server.try_declare(NODE, "b", ParameterValue::Integer(1)),
3256            Ok(())
3257        );
3258        assert_eq!(
3259            server.try_declare(NODE, "c", ParameterValue::Integer(1)),
3260            Err(DeclarationError::StorageFull)
3261        );
3262
3263        let long = "n".repeat(MAX_PARAM_NAME_LEN + 1);
3264        let mut roomy: ParameterStorage<2> = ParameterStorage::new();
3265        let mut server = ParameterServer::new_in(roomy.as_table());
3266        assert_eq!(
3267            server.try_declare(NODE, &long, ParameterValue::Integer(1)),
3268            Err(DeclarationError::NameTooLong)
3269        );
3270    }
3271}
3272
3273// =============================================================================
3274// Ghost model validation
3275// =============================================================================
3276
3277#[cfg(test)]
3278mod ghost_checks {
3279    use super::*;
3280    use nros_ghost_types::ParamServerGhost;
3281
3282    /// phase-426 W1 — the node these single-node tests are about.
3283    const NODE: NodeKey = NodeKey::PRIMARY;
3284
3285    /// Structural check: construct ParamServerGhost from ParameterServer private fields.
3286    /// If a field is renamed or retyped, this fails to compile.
3287    fn ghost_from_server(s: &ParameterServer<'_>) -> ParamServerGhost {
3288        ParamServerGhost {
3289            count: s.count,
3290            // phase-382 W2' — capacity is the borrowed TABLE's length. It used
3291            // to read `MAX_PARAMETERS`, which was the same number only because
3292            // the storage was the knob-sized array inside the server.
3293            max: s.table.capacity(),
3294        }
3295    }
3296
3297    #[test]
3298    fn ghost_new_count() {
3299        let mut storage: ParameterStorage = ParameterStorage::new();
3300        let capacity = storage.capacity();
3301        let server = ParameterServer::new_in(storage.as_table());
3302        let ghost = ghost_from_server(&server);
3303        assert_eq!(ghost.count, 0);
3304        // phase-382 W2' — the ghost's `max` is the TABLE's length, and the
3305        // default-parameter `ParameterStorage` is `MAX_PARAMETERS` long. This
3306        // used to be a literal `32`, which held only while the knob was at its
3307        // default.
3308        assert_eq!(ghost.max, capacity);
3309        assert_eq!(ghost.max, MAX_PARAMETERS);
3310    }
3311
3312    /// phase-382 W2' — capacity follows the TABLE, not `MAX_PARAMETERS`: a
3313    /// server built on a short table is full at that table's length.
3314    #[test]
3315    fn ghost_max_follows_a_shorter_table() {
3316        let mut storage = ParameterStorage::<2>::new();
3317        let mut server = ParameterServer::new_in(storage.as_table());
3318        assert_eq!(ghost_from_server(&server).max, 2);
3319        assert!(server.declare(NODE, "a", ParameterValue::Integer(1)));
3320        assert!(server.declare(NODE, "b", ParameterValue::Integer(2)));
3321        assert!(server.is_full());
3322        assert!(!server.declare(NODE, "c", ParameterValue::Integer(3)));
3323        let ghost = ghost_from_server(&server);
3324        assert!(ghost.count <= ghost.max);
3325    }
3326
3327    /// phase-382 W2' — `new_in` ADOPTS the table it is handed, so a second
3328    /// server over the same storage sees the parameters the first declared
3329    /// and keeps its count in step with the slots.
3330    #[test]
3331    fn ghost_count_recovers_from_a_reused_table() {
3332        let mut storage = ParameterStorage::<4>::new();
3333        {
3334            let mut first = ParameterServer::new_in(storage.as_table());
3335            assert!(first.declare(NODE, "kept", ParameterValue::Integer(7)));
3336        }
3337        let second = ParameterServer::new_in(storage.as_table());
3338        assert_eq!(ghost_from_server(&second).count, 1);
3339        assert_eq!(second.get_integer(NODE, "kept"), Some(7));
3340    }
3341
3342    #[test]
3343    fn ghost_declare_increments() {
3344        let mut storage: ParameterStorage = ParameterStorage::new();
3345        let mut server = ParameterServer::new_in(storage.as_table());
3346        let before = ghost_from_server(&server).count;
3347        assert!(server.declare(NODE, "test", ParameterValue::Integer(1)));
3348        let after = ghost_from_server(&server).count;
3349        assert_eq!(after, before + 1);
3350    }
3351
3352    #[test]
3353    fn ghost_remove_decrements() {
3354        let mut storage: ParameterStorage = ParameterStorage::new();
3355        let mut server = ParameterServer::new_in(storage.as_table());
3356        assert!(server.declare(NODE, "test", ParameterValue::Integer(1)));
3357        let before = ghost_from_server(&server).count;
3358        assert!(server.remove(NODE, "test"));
3359        let after = ghost_from_server(&server).count;
3360        assert_eq!(after, before - 1);
3361    }
3362
3363    #[test]
3364    fn ghost_count_bounded() {
3365        let mut storage: ParameterStorage = ParameterStorage::new();
3366        let mut server = ParameterServer::new_in(storage.as_table());
3367        for i in 0..MAX_PARAMETERS {
3368            let mut name = heapless::String::<64>::new();
3369            let _ = core::fmt::write(&mut name, format_args!("p{}", i));
3370            assert!(server.declare(NODE, name.as_str(), ParameterValue::Integer(i as i64)));
3371        }
3372        let ghost = ghost_from_server(&server);
3373        assert!(ghost.count <= ghost.max);
3374        assert_eq!(ghost.count, MAX_PARAMETERS);
3375        // Next declare should fail — count stays bounded
3376        assert!(!server.declare(NODE, "overflow", ParameterValue::Integer(0)));
3377        let ghost2 = ghost_from_server(&server);
3378        assert!(ghost2.count <= ghost2.max);
3379    }
3380}
3381
3382// =============================================================================
3383// Kani bounded model checking proofs
3384// =============================================================================
3385
3386#[cfg(kani)]
3387mod verification {
3388    use super::*;
3389
3390    /// phase-426 W1 — the node these single-node tests are about.
3391    const NODE: NodeKey = NodeKey::PRIMARY;
3392
3393    // phase-382 W2' — each proof used to build the whole store on the proof
3394    // stack (`ParameterServer::new()`); it now places a `ParameterStorage` and
3395    // lends it, which is the only shape a caller-owned store has. Kani still
3396    // sees the same `MAX_PARAMETERS` slots, so the bounds are unchanged.
3397
3398    #[kani::proof]
3399    fn server_new_is_empty() {
3400        let mut storage: ParameterStorage = ParameterStorage::new();
3401        let server = ParameterServer::new_in(storage.as_table());
3402        assert!(server.is_empty(NODE));
3403        assert_eq!(server.len(NODE), 0);
3404        assert!(!server.is_full());
3405    }
3406
3407    #[kani::proof]
3408    fn server_declare_get_roundtrip_integer() {
3409        let mut storage: ParameterStorage = ParameterStorage::new();
3410        let mut server = ParameterServer::new_in(storage.as_table());
3411        let val: i64 = kani::any();
3412        assert!(server.declare(NODE, "test", ParameterValue::Integer(val)));
3413        assert_eq!(server.get_integer(NODE, "test"), Some(val));
3414        assert!(server.has(NODE, "test"));
3415        assert_eq!(server.len(NODE), 1);
3416    }
3417
3418    #[kani::proof]
3419    fn server_declare_get_roundtrip_bool() {
3420        let mut storage: ParameterStorage = ParameterStorage::new();
3421        let mut server = ParameterServer::new_in(storage.as_table());
3422        let val: bool = kani::any();
3423        assert!(server.declare(NODE, "test", ParameterValue::Bool(val)));
3424        assert_eq!(server.get_bool(NODE, "test"), Some(val));
3425    }
3426
3427    #[kani::proof]
3428    fn server_set_requires_declare() {
3429        let mut storage: ParameterStorage = ParameterStorage::new();
3430        let mut server = ParameterServer::new_in(storage.as_table());
3431        let val: i64 = kani::any();
3432        // Set without declare should fail
3433        let result = server.set(NODE, "test", ParameterValue::Integer(val));
3434        assert_eq!(result, Err(ParameterError::NotFound));
3435    }
3436
3437    #[kani::proof]
3438    fn server_duplicate_declare_fails() {
3439        let mut storage: ParameterStorage = ParameterStorage::new();
3440        let mut server = ParameterServer::new_in(storage.as_table());
3441        assert!(server.declare(NODE, "test", ParameterValue::Integer(1)));
3442        assert!(!server.declare(NODE, "test", ParameterValue::Integer(2)));
3443        // Original value preserved
3444        assert_eq!(server.get_integer(NODE, "test"), Some(1));
3445    }
3446
3447    #[kani::proof]
3448    fn server_remove_clears() {
3449        let mut storage: ParameterStorage = ParameterStorage::new();
3450        let mut server = ParameterServer::new_in(storage.as_table());
3451        assert!(server.declare(NODE, "test", ParameterValue::Integer(42)));
3452        assert!(server.has(NODE, "test"));
3453        assert!(server.remove(NODE, "test"));
3454        assert!(!server.has(NODE, "test"));
3455        assert_eq!(server.len(NODE), 0);
3456    }
3457
3458    #[kani::proof]
3459    fn server_get_nonexistent_returns_none() {
3460        let mut storage: ParameterStorage = ParameterStorage::new();
3461        let server = ParameterServer::new_in(storage.as_table());
3462        assert!(server.get(NODE, "nonexistent").is_none());
3463        assert!(server.get_bool(NODE, "nonexistent").is_none());
3464        assert!(server.get_integer(NODE, "nonexistent").is_none());
3465        assert!(server.get_double(NODE, "nonexistent").is_none());
3466        assert!(server.get_string(NODE, "nonexistent").is_none());
3467    }
3468}