1use heapless::{String, Vec};
7
8#[cfg(feature = "alloc")]
12use alloc::string::ToString;
13
14pub use crate::config::*;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
34pub struct NodeKey(u8);
35
36impl NodeKey {
37 pub const PRIMARY: NodeKey = NodeKey(0);
39
40 pub const fn new(index: u8) -> Self {
42 NodeKey(index)
43 }
44
45 pub const fn index(self) -> usize {
47 self.0 as usize
48 }
49
50 pub const fn raw(self) -> u8 {
52 self.0
53 }
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
65pub struct NodeFlags {
66 bits: [u64; 4],
67}
68
69impl NodeFlags {
70 pub const fn new() -> Self {
72 Self { bits: [0; 4] }
73 }
74
75 pub const fn get(&self, node: NodeKey) -> bool {
77 let raw = node.raw() as usize;
78 self.bits[raw >> 6] & (1u64 << (raw & 63)) != 0
79 }
80
81 pub fn first(&self) -> Option<NodeKey> {
83 for (word, bits) in self.bits.iter().enumerate() {
84 if *bits != 0 {
85 return Some(NodeKey::new(
86 (word * 64 + bits.trailing_zeros() as usize) as u8,
87 ));
88 }
89 }
90 None
91 }
92
93 pub fn set(&mut self, node: NodeKey, on: bool) {
95 let raw = node.raw() as usize;
96 let mask = 1u64 << (raw & 63);
97 if on {
98 self.bits[raw >> 6] |= mask;
99 } else {
100 self.bits[raw >> 6] &= !mask;
101 }
102 }
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
109#[repr(u8)]
110pub enum ParameterType {
111 #[default]
113 NotSet = 0,
114 Bool = 1,
116 Integer = 2,
118 Double = 3,
120 String = 4,
122 ByteArray = 5,
124 BoolArray = 6,
126 IntegerArray = 7,
128 DoubleArray = 8,
130 StringArray = 9,
132}
133
134#[derive(Debug, Clone, Default)]
140#[allow(clippy::large_enum_variant)]
141pub enum ParameterValue {
142 #[default]
144 NotSet,
145 Bool(bool),
147 Integer(i64),
149 Double(f64),
151 String(String<MAX_STRING_VALUE_LEN>),
153 ByteArray(Vec<u8, MAX_BYTE_ARRAY_LEN>),
155 BoolArray(Vec<bool, MAX_ARRAY_LEN>),
157 IntegerArray(Vec<i64, MAX_ARRAY_LEN>),
159 DoubleArray(Vec<f64, MAX_ARRAY_LEN>),
161 StringArray(Vec<String<MAX_STRING_VALUE_LEN>, MAX_STRING_ARRAY_LEN>),
168}
169
170impl ParameterValue {
171 pub fn assign_from(&mut self, src: &ParameterValue) {
180 macro_rules! fill {
181 ($variant:ident, $dst:ident, $body:expr) => {{
182 if !matches!(self, Self::$variant(_)) {
183 *self = Self::$variant(Default::default());
184 }
185 if let Self::$variant($dst) = self {
186 $dst.clear();
187 $body;
188 }
189 }};
190 }
191 match src {
192 Self::NotSet => *self = Self::NotSet,
193 Self::Bool(v) => *self = Self::Bool(*v),
194 Self::Integer(v) => *self = Self::Integer(*v),
195 Self::Double(v) => *self = Self::Double(*v),
196 Self::String(v) => fill!(String, d, {
197 let _ = d.push_str(v);
198 }),
199 Self::ByteArray(v) => fill!(ByteArray, d, {
200 let _ = d.extend_from_slice(v);
201 }),
202 Self::BoolArray(v) => fill!(BoolArray, d, {
203 let _ = d.extend_from_slice(v);
204 }),
205 Self::IntegerArray(v) => fill!(IntegerArray, d, {
206 let _ = d.extend_from_slice(v);
207 }),
208 Self::DoubleArray(v) => fill!(DoubleArray, d, {
209 let _ = d.extend_from_slice(v);
210 }),
211 Self::StringArray(v) => fill!(StringArray, d, {
212 for e in v {
213 let mut s = String::new();
214 let _ = s.push_str(e);
215 let _ = d.push(s);
216 }
217 }),
218 }
219 }
220
221 pub fn param_type(&self) -> ParameterType {
223 match self {
224 Self::NotSet => ParameterType::NotSet,
225 Self::Bool(_) => ParameterType::Bool,
226 Self::Integer(_) => ParameterType::Integer,
227 Self::Double(_) => ParameterType::Double,
228 Self::String(_) => ParameterType::String,
229 Self::ByteArray(_) => ParameterType::ByteArray,
230 Self::BoolArray(_) => ParameterType::BoolArray,
231 Self::IntegerArray(_) => ParameterType::IntegerArray,
232 Self::DoubleArray(_) => ParameterType::DoubleArray,
233 Self::StringArray(_) => ParameterType::StringArray,
234 }
235 }
236
237 pub fn is_set(&self) -> bool {
239 !matches!(self, Self::NotSet)
240 }
241
242 pub fn as_bool(&self) -> Option<bool> {
244 match self {
245 Self::Bool(v) => Some(*v),
246 _ => None,
247 }
248 }
249
250 pub fn as_integer(&self) -> Option<i64> {
252 match self {
253 Self::Integer(v) => Some(*v),
254 _ => None,
255 }
256 }
257
258 pub fn as_double(&self) -> Option<f64> {
260 match self {
261 Self::Double(v) => Some(*v),
262 _ => None,
263 }
264 }
265
266 pub fn as_string(&self) -> Option<&str> {
268 match self {
269 Self::String(v) => Some(v.as_str()),
270 _ => None,
271 }
272 }
273
274 pub fn as_byte_array(&self) -> Option<&[u8]> {
276 match self {
277 Self::ByteArray(v) => Some(v.as_slice()),
278 _ => None,
279 }
280 }
281
282 pub fn as_bool_array(&self) -> Option<&[bool]> {
284 match self {
285 Self::BoolArray(v) => Some(v.as_slice()),
286 _ => None,
287 }
288 }
289
290 pub fn as_integer_array(&self) -> Option<&[i64]> {
292 match self {
293 Self::IntegerArray(v) => Some(v.as_slice()),
294 _ => None,
295 }
296 }
297
298 pub fn as_double_array(&self) -> Option<&[f64]> {
300 match self {
301 Self::DoubleArray(v) => Some(v.as_slice()),
302 _ => None,
303 }
304 }
305
306 pub fn from_bool(value: bool) -> Self {
308 Self::Bool(value)
309 }
310
311 pub fn from_integer(value: i64) -> Self {
313 Self::Integer(value)
314 }
315
316 pub fn from_double(value: f64) -> Self {
318 Self::Double(value)
319 }
320
321 pub fn from_string(value: &str) -> Option<Self> {
323 let mut s = String::new();
324 s.push_str(value).ok()?;
325 Some(Self::String(s))
326 }
327
328 pub fn from_bool_array(values: &[bool]) -> Option<Self> {
341 Some(Self::BoolArray(Vec::from_slice(values).ok()?))
342 }
343
344 pub fn from_integer_array(values: &[i64]) -> Option<Self> {
347 Some(Self::IntegerArray(Vec::from_slice(values).ok()?))
348 }
349
350 pub fn from_double_array(values: &[f64]) -> Option<Self> {
353 Some(Self::DoubleArray(Vec::from_slice(values).ok()?))
354 }
355
356 pub fn from_byte_array(values: &[u8]) -> Option<Self> {
359 Some(Self::ByteArray(Vec::from_slice(values).ok()?))
360 }
361
362 pub fn assign_string(&mut self, value: &str) -> bool {
369 if !matches!(self, Self::String(_)) {
370 *self = Self::String(String::new());
371 }
372 match self {
373 Self::String(s) => {
374 s.clear();
375 s.push_str(value).is_ok()
376 }
377 _ => false,
378 }
379 }
380
381 pub fn assign_bool_array(&mut self, values: &[bool]) -> bool {
384 assign_slice!(self, BoolArray, values)
385 }
386
387 pub fn assign_integer_array(&mut self, values: &[i64]) -> bool {
390 assign_slice!(self, IntegerArray, values)
391 }
392
393 pub fn assign_double_array(&mut self, values: &[f64]) -> bool {
396 assign_slice!(self, DoubleArray, values)
397 }
398
399 pub fn assign_byte_array(&mut self, values: &[u8]) -> bool {
402 assign_slice!(self, ByteArray, values)
403 }
404}
405
406macro_rules! assign_slice {
409 ($v:expr, $variant:ident, $values:expr) => {{
410 if !matches!($v, Self::$variant(_)) {
411 *$v = Self::$variant(Vec::new());
412 }
413 match $v {
414 Self::$variant(d) => {
415 d.clear();
416 d.extend_from_slice($values).is_ok()
417 }
418 _ => false,
419 }
420 }};
421}
422use assign_slice;
423
424#[derive(Debug, Clone, Copy, Default)]
426pub struct FloatingPointRange {
427 pub min: f64,
429 pub max: f64,
431 pub step: f64,
433}
434
435impl FloatingPointRange {
436 pub const fn new(min: f64, max: f64, step: f64) -> Self {
438 Self { min, max, step }
439 }
440
441 pub fn is_valid(&self) -> bool {
447 self.min <= self.max && self.step >= 0.0 && !self.step.is_nan()
448 }
449
450 pub fn contains(&self, value: f64) -> bool {
459 if are_close(value, self.min) || are_close(value, self.max) {
460 return true;
461 }
462 if !(value >= self.min && value <= self.max) {
463 return false;
464 }
465 if self.step == 0.0 {
466 return true;
467 }
468 let nearest = round_to_nearest((value - self.min) / self.step) * self.step + self.min;
469 are_close(nearest, value)
470 }
471}
472
473#[inline]
477fn are_close(a: f64, b: f64) -> bool {
478 const ULP_TOL: f64 = 100.0;
479 (a - b).abs() <= f64::EPSILON * (a + b).abs() * ULP_TOL
480}
481
482#[inline]
487fn round_to_nearest(q: f64) -> f64 {
488 if !q.is_finite() {
489 return q;
490 }
491 let shifted = if q < 0.0 { q - 0.5 } else { q + 0.5 };
492 (shifted as i64) as f64
493}
494
495#[derive(Debug, Clone, Copy, Default)]
497pub struct IntegerRange {
498 pub min: i64,
500 pub max: i64,
502 pub step: i64,
504}
505
506impl IntegerRange {
507 pub const fn new(min: i64, max: i64, step: i64) -> Self {
509 Self { min, max, step }
510 }
511
512 pub fn is_valid(&self) -> bool {
515 self.min <= self.max && self.step >= 0
516 }
517
518 pub fn contains(&self, value: i64) -> bool {
526 if !(value >= self.min && value <= self.max) {
527 return false;
528 }
529 if value == self.max || self.step == 0 {
530 return true;
531 }
532 match value
533 .checked_sub(self.min)
534 .and_then(|d| d.checked_rem(self.step))
535 {
536 Some(rem) => rem == 0,
537 None => false,
540 }
541 }
542}
543
544#[derive(Debug, Clone, Copy, Default)]
546pub enum ParameterRange {
547 #[default]
549 None,
550 FloatingPoint(FloatingPointRange),
552 Integer(IntegerRange),
554}
555
556impl ParameterRange {
557 pub fn is_valid(&self) -> bool {
559 match self {
560 Self::None => true,
561 Self::FloatingPoint(r) => r.is_valid(),
562 Self::Integer(r) => r.is_valid(),
563 }
564 }
565
566 pub fn contains(&self, value: &ParameterValue) -> bool {
575 match (self, value) {
576 (Self::None, _) => true,
577 (Self::Integer(range), ParameterValue::Integer(v)) => range.contains(*v),
578 (Self::FloatingPoint(range), ParameterValue::Double(v)) => range.contains(*v),
579 _ => true,
580 }
581 }
582}
583
584#[derive(Debug, Clone)]
588pub struct ParameterDescriptor {
589 pub param_type: ParameterType,
591 pub description: String<MAX_PARAM_DESCRIPTION_LEN>,
599 pub additional_constraints: String<MAX_PARAM_CONSTRAINTS_LEN>,
614 pub read_only: bool,
616 pub dynamic_typing: bool,
618 pub range: ParameterRange,
620 description_truncated: bool,
627 constraints_truncated: bool,
631}
632
633#[derive(Debug, Clone, Copy, PartialEq, Eq)]
637pub enum DescriptorText {
638 Description,
640 Constraints,
642}
643
644impl DescriptorText {
645 pub const fn field(self) -> &'static str {
647 match self {
648 Self::Description => "description",
649 Self::Constraints => "additional_constraints",
650 }
651 }
652
653 pub const fn knob(self) -> &'static str {
655 match self {
656 Self::Description => "NROS_PARAMS_MAX_DESCRIPTION_BYTES",
657 Self::Constraints => "NROS_PARAMS_MAX_CONSTRAINTS_BYTES",
658 }
659 }
660
661 pub const fn capacity(self) -> usize {
663 match self {
664 Self::Description => MAX_PARAM_DESCRIPTION_LEN,
665 Self::Constraints => MAX_PARAM_CONSTRAINTS_LEN,
666 }
667 }
668}
669
670pub fn fit_description<const N: usize>(dst: &mut String<N>, text: &str) -> bool {
678 dst.clear();
679 let mut cut = text.len().min(N);
680 while !text.is_char_boundary(cut) {
681 cut -= 1;
682 }
683 let stored = dst.push_str(&text[..cut]).is_ok();
685 debug_assert!(stored, "a prefix of at most N bytes fits String<N>");
686 cut < text.len()
687}
688
689impl ParameterDescriptor {
690 pub fn new(name: &str, param_type: ParameterType) -> Option<Self> {
692 if name.len() > MAX_PARAM_NAME_LEN {
693 return None;
694 }
695 Some(Self {
696 param_type,
697 description: String::new(),
698 additional_constraints: String::new(),
699 read_only: false,
700 dynamic_typing: false,
701 range: ParameterRange::None,
702 description_truncated: false,
703 constraints_truncated: false,
704 })
705 }
706
707 pub fn with_description(mut self, desc: &str) -> Self {
711 self.set_description(desc);
712 self
713 }
714
715 pub fn set_description(&mut self, desc: &str) -> bool {
720 #[cfg(feature = "descriptor-text-observer")]
721 crate::descriptor_text_observer::observe_descriptor_text(
722 crate::descriptor_text_observer::DescriptorText::Description,
723 desc.len(),
724 );
725 self.description_truncated = fit_description(&mut self.description, desc);
726 self.description_truncated
727 }
728
729 pub fn description_truncated(&self) -> bool {
731 self.description_truncated
732 }
733
734 pub fn constraints_truncated(&self) -> bool {
738 self.constraints_truncated
739 }
740
741 pub fn any_text_truncated(&self) -> bool {
743 self.description_truncated || self.constraints_truncated
744 }
745
746 pub fn truncated_texts(&self) -> impl Iterator<Item = DescriptorText> + use<> {
748 let d = self
749 .description_truncated
750 .then_some(DescriptorText::Description);
751 let c = self
752 .constraints_truncated
753 .then_some(DescriptorText::Constraints);
754 d.into_iter().chain(c)
755 }
756
757 pub fn set_additional_constraints(&mut self, text: &str) -> bool {
761 #[cfg(feature = "descriptor-text-observer")]
762 crate::descriptor_text_observer::observe_descriptor_text(
763 crate::descriptor_text_observer::DescriptorText::Constraints,
764 text.len(),
765 );
766 self.constraints_truncated = fit_description(&mut self.additional_constraints, text);
771 self.constraints_truncated
772 }
773
774 pub fn with_additional_constraints(mut self, text: &str) -> Self {
776 self.set_additional_constraints(text);
777 self
778 }
779
780 pub(crate) fn clear_truncated_texts(&mut self) {
782 self.description_truncated = false;
783 self.constraints_truncated = false;
784 }
785
786 pub fn with_read_only(mut self, read_only: bool) -> Self {
788 self.read_only = read_only;
789 self
790 }
791
792 pub fn with_dynamic_typing(mut self, dynamic: bool) -> Self {
794 self.dynamic_typing = dynamic;
795 self
796 }
797
798 pub fn with_integer_range(mut self, min: i64, max: i64, step: i64) -> Self {
800 self.range = ParameterRange::Integer(IntegerRange::new(min, max, step));
801 self
802 }
803
804 pub fn with_float_range(mut self, min: f64, max: f64, step: f64) -> Self {
806 self.range = ParameterRange::FloatingPoint(FloatingPointRange::new(min, max, step));
807 self
808 }
809
810 pub fn validate_range(&self, value: &ParameterValue) -> bool {
814 self.range.contains(value)
815 }
816}
817
818#[derive(Debug, Clone)]
820pub struct Parameter {
821 pub name: String<MAX_PARAM_NAME_LEN>,
823 pub value: ParameterValue,
825}
826
827impl Parameter {
828 pub fn new(name: &str, value: ParameterValue) -> Option<Self> {
830 let mut n = String::new();
831 n.push_str(name).ok()?;
832 Some(Self { name: n, value })
833 }
834
835 pub fn bool(name: &str, value: bool) -> Option<Self> {
837 Self::new(name, ParameterValue::Bool(value))
838 }
839
840 pub fn integer(name: &str, value: i64) -> Option<Self> {
842 Self::new(name, ParameterValue::Integer(value))
843 }
844
845 pub fn double(name: &str, value: f64) -> Option<Self> {
847 Self::new(name, ParameterValue::Double(value))
848 }
849
850 pub fn string(name: &str, value: &str) -> Option<Self> {
852 Self::new(name, ParameterValue::from_string(value)?)
853 }
854
855 pub fn param_type(&self) -> ParameterType {
857 self.value.param_type()
858 }
859
860 pub fn name(&self) -> &str {
862 &self.name
863 }
864}
865
866#[deprecated(
873 since = "0.6.0",
874 note = "the parameter store returns `Result<(), ParameterError>`; `Success` is `Ok(())`"
875)]
876#[derive(Debug, Clone, Copy, PartialEq, Eq)]
877pub enum SetParameterResult {
878 Success,
880 ReadOnly,
882 TypeMismatch,
884 OutOfRange,
886 NotFound,
888 StorageFull,
890 Undeclared,
898 InvalidRange,
902 Rejected,
910}
911
912#[allow(deprecated)]
913impl SetParameterResult {
914 pub fn is_success(&self) -> bool {
916 matches!(self, Self::Success)
917 }
918}
919
920#[derive(Debug, Clone, Copy, PartialEq, Eq)]
926pub struct CapacityExceeded;
927
928pub trait ParameterVariant: Clone {
933 fn to_parameter_value(&self) -> ParameterValue;
935
936 fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
948 Ok(self.to_parameter_value())
949 }
950
951 fn from_parameter_value(value: &ParameterValue) -> Option<Self>;
953
954 fn parameter_type() -> ParameterType;
956}
957
958impl ParameterVariant for bool {
961 fn to_parameter_value(&self) -> ParameterValue {
962 ParameterValue::Bool(*self)
963 }
964
965 fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
966 value.as_bool()
967 }
968
969 fn parameter_type() -> ParameterType {
970 ParameterType::Bool
971 }
972}
973
974impl ParameterVariant for i64 {
975 fn to_parameter_value(&self) -> ParameterValue {
976 ParameterValue::Integer(*self)
977 }
978
979 fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
980 value.as_integer()
981 }
982
983 fn parameter_type() -> ParameterType {
984 ParameterType::Integer
985 }
986}
987
988impl ParameterVariant for f64 {
989 fn to_parameter_value(&self) -> ParameterValue {
990 ParameterValue::Double(*self)
991 }
992
993 fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
994 value.as_double()
995 }
996
997 fn parameter_type() -> ParameterType {
998 ParameterType::Double
999 }
1000}
1001
1002impl ParameterVariant for String<MAX_STRING_VALUE_LEN> {
1012 fn to_parameter_value(&self) -> ParameterValue {
1013 ParameterValue::String(self.clone())
1014 }
1015
1016 fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1017 if let ParameterValue::String(s) = value {
1018 Some(s.clone())
1019 } else {
1020 None
1021 }
1022 }
1023
1024 fn parameter_type() -> ParameterType {
1025 ParameterType::String
1026 }
1027}
1028
1029#[cfg(feature = "alloc")]
1031impl ParameterVariant for alloc::string::String {
1032 fn to_parameter_value(&self) -> ParameterValue {
1033 ParameterValue::from_string(self.as_str()).unwrap_or_default()
1034 }
1035
1036 fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
1037 ParameterValue::from_string(self.as_str()).ok_or(CapacityExceeded)
1038 }
1039
1040 fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1041 value.as_string().map(|s| s.to_string())
1042 }
1043
1044 fn parameter_type() -> ParameterType {
1045 ParameterType::String
1046 }
1047}
1048
1049#[cfg(feature = "alloc")]
1051impl ParameterVariant for alloc::vec::Vec<i64> {
1052 fn to_parameter_value(&self) -> ParameterValue {
1053 ParameterValue::IntegerArray(Vec::from_slice(self.as_slice()).unwrap_or_default())
1054 }
1055
1056 fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
1057 Vec::from_slice(self.as_slice())
1058 .map(ParameterValue::IntegerArray)
1059 .map_err(|_| CapacityExceeded)
1060 }
1061
1062 fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1063 value.as_integer_array().map(|v| v.to_vec())
1064 }
1065
1066 fn parameter_type() -> ParameterType {
1067 ParameterType::IntegerArray
1068 }
1069}
1070
1071#[cfg(feature = "alloc")]
1073impl ParameterVariant for alloc::vec::Vec<f64> {
1074 fn to_parameter_value(&self) -> ParameterValue {
1075 ParameterValue::DoubleArray(Vec::from_slice(self.as_slice()).unwrap_or_default())
1076 }
1077
1078 fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
1079 Vec::from_slice(self.as_slice())
1080 .map(ParameterValue::DoubleArray)
1081 .map_err(|_| CapacityExceeded)
1082 }
1083
1084 fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1085 value.as_double_array().map(|v| v.to_vec())
1086 }
1087
1088 fn parameter_type() -> ParameterType {
1089 ParameterType::DoubleArray
1090 }
1091}
1092
1093#[cfg(feature = "alloc")]
1095impl ParameterVariant for alloc::vec::Vec<bool> {
1096 fn to_parameter_value(&self) -> ParameterValue {
1097 ParameterValue::BoolArray(Vec::from_slice(self.as_slice()).unwrap_or_default())
1098 }
1099
1100 fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
1101 Vec::from_slice(self.as_slice())
1102 .map(ParameterValue::BoolArray)
1103 .map_err(|_| CapacityExceeded)
1104 }
1105
1106 fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1107 value.as_bool_array().map(|v| v.to_vec())
1108 }
1109
1110 fn parameter_type() -> ParameterType {
1111 ParameterType::BoolArray
1112 }
1113}
1114
1115#[cfg(feature = "alloc")]
1117impl ParameterVariant for alloc::vec::Vec<alloc::string::String> {
1118 fn to_parameter_value(&self) -> ParameterValue {
1119 let mut vec = Vec::new();
1120 for s in self {
1121 let mut h_string = String::new();
1122 if h_string.push_str(s.as_str()).is_ok() {
1123 let _ = vec.push(h_string);
1124 }
1125 }
1126 ParameterValue::StringArray(vec)
1127 }
1128
1129 fn try_to_parameter_value(&self) -> Result<ParameterValue, CapacityExceeded> {
1130 let mut vec = Vec::new();
1133 for s in self {
1134 let mut h_string = String::new();
1135 h_string
1136 .push_str(s.as_str())
1137 .map_err(|_| CapacityExceeded)?;
1138 vec.push(h_string).map_err(|_| CapacityExceeded)?;
1139 }
1140 Ok(ParameterValue::StringArray(vec))
1141 }
1142
1143 fn from_parameter_value(value: &ParameterValue) -> Option<Self> {
1144 if let ParameterValue::StringArray(v) = value {
1145 Some(v.iter().map(|s| s.as_str().to_string()).collect())
1146 } else {
1147 None
1148 }
1149 }
1150
1151 fn parameter_type() -> ParameterType {
1152 ParameterType::StringArray
1153 }
1154}
1155
1156#[cfg(test)]
1157#[allow(deprecated)] mod tests {
1159 use super::*;
1160
1161 #[test]
1164 fn integer_step_accepts_lattice_points_and_rejects_the_rest() {
1165 let r = IntegerRange::new(10, 20, 5);
1166 assert!(r.contains(10));
1167 assert!(r.contains(15));
1168 assert!(r.contains(20));
1169 assert!(!r.contains(11));
1172 assert!(!r.contains(14));
1173 assert!(!r.contains(19));
1174 assert!(!r.contains(5));
1176 assert!(!r.contains(25));
1177 }
1178
1179 #[test]
1180 fn integer_upper_bound_is_accepted_even_off_lattice() {
1181 let r = IntegerRange::new(0, 7, 3);
1183 assert!(r.contains(6));
1184 assert!(!r.contains(5));
1185 assert!(r.contains(7));
1186 }
1187
1188 #[test]
1189 fn integer_step_zero_means_unconstrained() {
1190 let r = IntegerRange::new(0, 100, 0);
1191 for v in [0, 1, 37, 99, 100] {
1192 assert!(r.contains(v), "{v}");
1193 }
1194 assert!(!r.contains(101));
1195 }
1196
1197 #[test]
1198 fn integer_step_does_not_overflow_at_the_extremes() {
1199 let r = IntegerRange::new(i64::MIN, i64::MAX, 2);
1200 let _ = r.contains(1);
1203 let _ = r.contains(i64::MAX - 1);
1204 assert!(r.contains(i64::MIN));
1205 assert!(r.contains(i64::MAX));
1206 }
1207
1208 #[test]
1209 fn float_step_accepts_lattice_points_within_tolerance() {
1210 let r = FloatingPointRange::new(0.0, 1.0, 0.1);
1211 for v in [0.0, 0.1, 0.3, 0.7, 1.0] {
1214 assert!(r.contains(v), "{v}");
1215 }
1216 assert!(r.contains(0.1 + 0.2));
1217 assert!(!r.contains(0.05));
1219 assert!(!r.contains(0.35));
1220 assert!(!r.contains(0.999));
1221 assert!(!r.contains(-0.1));
1223 assert!(!r.contains(1.1));
1224 }
1225
1226 #[test]
1227 fn float_endpoints_are_accepted_even_off_lattice() {
1228 let r = FloatingPointRange::new(0.0, 1.0, 0.3);
1229 assert!(r.contains(0.9));
1230 assert!(!r.contains(0.95));
1231 assert!(r.contains(1.0));
1232 }
1233
1234 #[test]
1235 fn float_step_zero_means_unconstrained() {
1236 let r = FloatingPointRange::new(0.0, 10.0, 0.0);
1237 for v in [0.0, 0.001, 3.25, 9.999, 10.0] {
1238 assert!(r.contains(v), "{v}");
1239 }
1240 assert!(!r.contains(10.001));
1241 }
1242
1243 #[test]
1244 fn float_step_with_a_nonzero_min_is_relative_to_min() {
1245 let r = FloatingPointRange::new(0.5, 2.5, 0.5);
1246 assert!(r.contains(1.5));
1247 assert!(!r.contains(1.25));
1248 assert!(r.contains(0.5));
1249 }
1250
1251 #[test]
1252 fn range_validity_is_min_le_max_and_step_ge_zero() {
1253 assert!(IntegerRange::new(0, 10, 0).is_valid());
1254 assert!(IntegerRange::new(0, 10, 3).is_valid());
1255 assert!(IntegerRange::new(5, 5, 1).is_valid());
1256 assert!(!IntegerRange::new(10, 0, 1).is_valid());
1257 assert!(!IntegerRange::new(0, 10, -1).is_valid());
1258 assert!(FloatingPointRange::new(0.0, 1.0, 0.0).is_valid());
1259 assert!(!FloatingPointRange::new(1.0, 0.0, 0.1).is_valid());
1260 assert!(!FloatingPointRange::new(0.0, 1.0, -0.1).is_valid());
1261 assert!(!FloatingPointRange::new(0.0, 1.0, f64::NAN).is_valid());
1262 assert!(ParameterRange::None.is_valid());
1263 }
1264
1265 #[test]
1266 fn descriptor_validate_range_enforces_step_on_both_arms() {
1267 let int_desc = ParameterDescriptor::new("i", ParameterType::Integer)
1268 .unwrap()
1269 .with_integer_range(0, 100, 10);
1270 assert!(int_desc.validate_range(&ParameterValue::Integer(30)));
1271 assert!(!int_desc.validate_range(&ParameterValue::Integer(31)));
1272 assert!(int_desc.validate_range(&ParameterValue::Double(31.0)));
1274
1275 let f_desc = ParameterDescriptor::new("f", ParameterType::Double)
1276 .unwrap()
1277 .with_float_range(0.0, 10.0, 0.5);
1278 assert!(f_desc.validate_range(&ParameterValue::Double(2.5)));
1279 assert!(!f_desc.validate_range(&ParameterValue::Double(2.7)));
1280 assert!(f_desc.validate_range(&ParameterValue::Integer(3)));
1281 }
1282
1283 #[test]
1284 #[allow(clippy::approx_constant)]
1285 fn test_parameter_value_types() {
1286 let bool_val = ParameterValue::Bool(true);
1287 assert_eq!(bool_val.param_type(), ParameterType::Bool);
1288 assert_eq!(bool_val.as_bool(), Some(true));
1289
1290 let int_val = ParameterValue::Integer(42);
1291 assert_eq!(int_val.param_type(), ParameterType::Integer);
1292 assert_eq!(int_val.as_integer(), Some(42));
1293
1294 let double_val = ParameterValue::Double(3.14);
1295 assert_eq!(double_val.param_type(), ParameterType::Double);
1296 assert_eq!(double_val.as_double(), Some(3.14));
1297 }
1298
1299 #[test]
1300 fn test_parameter_value_string() {
1301 let string_val = ParameterValue::from_string("hello").unwrap();
1302 assert_eq!(string_val.param_type(), ParameterType::String);
1303 assert_eq!(string_val.as_string(), Some("hello"));
1304 }
1305
1306 #[test]
1307 fn test_parameter_creation() {
1308 let param = Parameter::bool("my_param", true).unwrap();
1309 assert_eq!(param.name(), "my_param");
1310 assert_eq!(param.param_type(), ParameterType::Bool);
1311 assert_eq!(param.value.as_bool(), Some(true));
1312 }
1313
1314 #[test]
1315 fn test_parameter_descriptor() {
1316 let desc = ParameterDescriptor::new("speed", ParameterType::Double)
1317 .unwrap()
1318 .with_description("Maximum speed in m/s")
1319 .with_float_range(0.0, 10.0, 0.1);
1320
1321 assert_eq!(desc.param_type, ParameterType::Double);
1322 assert!(!desc.read_only);
1323
1324 assert!(desc.validate_range(&ParameterValue::Double(5.0)));
1326 assert!(!desc.validate_range(&ParameterValue::Double(15.0)));
1327 }
1328
1329 #[test]
1330 fn test_integer_range() {
1331 let range = IntegerRange::new(0, 100, 1);
1332 assert!(range.contains(50));
1333 assert!(range.contains(0));
1334 assert!(range.contains(100));
1335 assert!(!range.contains(-1));
1336 assert!(!range.contains(101));
1337 }
1338
1339 #[test]
1340 fn test_set_result() {
1341 assert!(SetParameterResult::Success.is_success());
1342 assert!(!SetParameterResult::ReadOnly.is_success());
1343 }
1344}
1345
1346#[cfg(test)]
1351mod ghost_checks {
1352 use super::*;
1353 use nros_ghost_types::ParameterValueGhost;
1354
1355 fn ghost_from_value(v: &ParameterValue) -> ParameterValueGhost {
1358 match v {
1359 ParameterValue::NotSet => ParameterValueGhost::NotSet,
1360 ParameterValue::Bool(b) => ParameterValueGhost::Bool(*b),
1361 ParameterValue::Integer(i) => ParameterValueGhost::Integer(*i),
1362 ParameterValue::Double(_) => ParameterValueGhost::Double,
1363 ParameterValue::String(_) => ParameterValueGhost::String,
1364 ParameterValue::ByteArray(_) => ParameterValueGhost::ByteArray,
1365 ParameterValue::BoolArray(_) => ParameterValueGhost::BoolArray,
1366 ParameterValue::IntegerArray(_) => ParameterValueGhost::IntegerArray,
1367 ParameterValue::DoubleArray(_) => ParameterValueGhost::DoubleArray,
1368 ParameterValue::StringArray(_) => ParameterValueGhost::StringArray,
1369 }
1370 }
1371
1372 #[test]
1373 fn ghost_variant_coverage() {
1374 let _ = ghost_from_value(&ParameterValue::NotSet);
1376 let _ = ghost_from_value(&ParameterValue::Bool(true));
1377 let _ = ghost_from_value(&ParameterValue::Integer(0));
1378 let _ = ghost_from_value(&ParameterValue::Double(0.0));
1379 let _ = ghost_from_value(&ParameterValue::String(String::new()));
1380 let _ = ghost_from_value(&ParameterValue::ByteArray(Vec::new()));
1381 let _ = ghost_from_value(&ParameterValue::BoolArray(Vec::new()));
1382 let _ = ghost_from_value(&ParameterValue::IntegerArray(Vec::new()));
1383 let _ = ghost_from_value(&ParameterValue::DoubleArray(Vec::new()));
1384 let _ = ghost_from_value(&ParameterValue::StringArray(Vec::new()));
1385 }
1386
1387 #[test]
1388 fn ghost_bool_preserves() {
1389 let ghost = ghost_from_value(&ParameterValue::Bool(true));
1390 assert!(matches!(ghost, ParameterValueGhost::Bool(true)));
1391 }
1392
1393 #[test]
1394 fn ghost_integer_preserves() {
1395 let ghost = ghost_from_value(&ParameterValue::Integer(42));
1396 assert!(matches!(ghost, ParameterValueGhost::Integer(42)));
1397 }
1398}
1399
1400#[cfg(kani)]
1405mod verification {
1406 use super::*;
1407
1408 #[kani::proof]
1411 fn parameter_i64_roundtrip() {
1412 let val: i64 = kani::any();
1413 let pv = ParameterValue::from_integer(val);
1414 assert_eq!(pv.as_integer(), Some(val));
1415 assert_eq!(pv.param_type(), ParameterType::Integer);
1416 assert!(pv.is_set());
1417 }
1418
1419 #[kani::proof]
1420 fn parameter_bool_roundtrip() {
1421 let val: bool = kani::any();
1422 let pv = ParameterValue::from_bool(val);
1423 assert_eq!(pv.as_bool(), Some(val));
1424 assert_eq!(pv.param_type(), ParameterType::Bool);
1425 assert!(pv.is_set());
1426 }
1427
1428 #[kani::proof]
1429 fn parameter_double_roundtrip() {
1430 let val: f64 = kani::any();
1431 let pv = ParameterValue::from_double(val);
1432 let result = pv.as_double();
1433 assert!(result.is_some());
1434 assert_eq!(result.unwrap().to_bits(), val.to_bits());
1435 assert_eq!(pv.param_type(), ParameterType::Double);
1436 }
1437
1438 #[kani::proof]
1439 fn parameter_not_set_default() {
1440 let pv = ParameterValue::default();
1441 assert!(!pv.is_set());
1442 assert_eq!(pv.param_type(), ParameterType::NotSet);
1443 assert!(pv.as_bool().is_none());
1444 assert!(pv.as_integer().is_none());
1445 assert!(pv.as_double().is_none());
1446 assert!(pv.as_string().is_none());
1447 }
1448
1449 #[kani::proof]
1452 fn parameter_type_mismatch_bool() {
1453 let val: i64 = kani::any();
1454 let pv = ParameterValue::from_integer(val);
1455 assert!(pv.as_bool().is_none());
1456 assert!(pv.as_double().is_none());
1457 assert!(pv.as_string().is_none());
1458 }
1459
1460 #[kani::proof]
1461 fn parameter_type_mismatch_integer() {
1462 let val: bool = kani::any();
1463 let pv = ParameterValue::from_bool(val);
1464 assert!(pv.as_integer().is_none());
1465 assert!(pv.as_double().is_none());
1466 assert!(pv.as_string().is_none());
1467 }
1468
1469 #[kani::proof]
1472 fn integer_range_contains_bounds() {
1473 let min: i64 = kani::any();
1474 let max: i64 = kani::any();
1475 kani::assume(min >= -1_000_000 && min <= 1_000_000);
1477 kani::assume(max >= -1_000_000 && max <= 1_000_000);
1478 kani::assume(min <= max);
1479 let range = IntegerRange::new(min, max, 1);
1480 assert!(range.contains(min));
1482 assert!(range.contains(max));
1483 }
1484
1485 #[kani::proof]
1486 fn integer_range_outside_bounds() {
1487 let min: i64 = kani::any();
1488 let max: i64 = kani::any();
1489 kani::assume(min <= max);
1490 kani::assume(min > i64::MIN); kani::assume(max < i64::MAX); let range = IntegerRange::new(min, max, 1);
1493 assert!(!range.contains(min - 1));
1494 assert!(!range.contains(max + 1));
1495 }
1496
1497 #[kani::proof]
1500 fn float_range_contains_bounds() {
1501 let min: f64 = kani::any();
1502 let max: f64 = kani::any();
1503 kani::assume(!min.is_nan() && !max.is_nan());
1504 kani::assume(min <= max);
1505 let range = FloatingPointRange::new(min, max, 0.0);
1506 assert!(range.contains(min));
1507 assert!(range.contains(max));
1508 }
1509
1510 #[kani::proof]
1513 fn set_result_success_only() {
1514 assert!(SetParameterResult::Success.is_success());
1516 assert!(!SetParameterResult::ReadOnly.is_success());
1517 assert!(!SetParameterResult::TypeMismatch.is_success());
1518 assert!(!SetParameterResult::OutOfRange.is_success());
1519 assert!(!SetParameterResult::NotFound.is_success());
1520 assert!(!SetParameterResult::StorageFull.is_success());
1521 }
1522}
1523
1524#[cfg(all(test, feature = "alloc"))]
1527mod issue_0323_tests {
1528 use super::*;
1529
1530 #[test]
1534 fn oversize_string_is_rejected_not_silently_notset() {
1535 let long = "x".repeat(MAX_STRING_VALUE_LEN + 1);
1536 assert!(
1537 matches!(long.to_parameter_value(), ParameterValue::NotSet),
1538 "documenting the legacy infallible behaviour"
1539 );
1540 assert!(
1541 long.try_to_parameter_value().is_err(),
1542 "the fallible path must reject it"
1543 );
1544 }
1545
1546 #[test]
1552 fn a_value_is_sized_by_the_string_array_bound_not_the_array_bound() {
1553 use core::mem::size_of;
1554 let string_array = size_of::<Vec<String<MAX_STRING_VALUE_LEN>, MAX_STRING_ARRAY_LEN>>();
1555 let largest_other = [
1556 size_of::<String<MAX_STRING_VALUE_LEN>>(),
1557 size_of::<Vec<bool, MAX_ARRAY_LEN>>(),
1558 size_of::<Vec<i64, MAX_ARRAY_LEN>>(),
1559 size_of::<Vec<f64, MAX_ARRAY_LEN>>(),
1560 size_of::<Vec<u8, MAX_BYTE_ARRAY_LEN>>(),
1561 ]
1562 .into_iter()
1563 .max()
1564 .unwrap();
1565 let bound = string_array.max(largest_other) + 16;
1567 assert!(
1568 size_of::<ParameterValue>() <= bound,
1569 "ParameterValue is {} B, more than its largest variant ({} B) plus a tag",
1570 size_of::<ParameterValue>(),
1571 string_array.max(largest_other)
1572 );
1573 let strings: alloc::vec::Vec<alloc::string::String> =
1576 (0..MAX_STRING_ARRAY_LEN).map(|_| "w".into()).collect();
1577 assert!(strings.clone().try_to_parameter_value().is_ok());
1578 let mut over = strings;
1579 over.push("w".into());
1580 assert!(over.try_to_parameter_value().is_err());
1581 }
1582
1583 #[test]
1585 fn oversize_integer_array_is_rejected_not_silently_empty() {
1586 let big: alloc::vec::Vec<i64> = (0..(MAX_ARRAY_LEN as i64 + 1)).collect();
1587 match big.to_parameter_value() {
1588 ParameterValue::IntegerArray(v) => {
1589 assert!(v.is_empty(), "documenting the legacy empty-array behaviour")
1590 }
1591 other => panic!("unexpected {other:?}"),
1592 }
1593 assert!(big.try_to_parameter_value().is_err());
1594 }
1595
1596 #[test]
1598 fn oversize_string_array_element_is_rejected_not_skipped() {
1599 let big: alloc::vec::Vec<alloc::string::String> = (0..(MAX_STRING_ARRAY_LEN + 1))
1600 .map(|i| i.to_string())
1601 .collect();
1602 assert!(big.try_to_parameter_value().is_err());
1603 }
1604
1605 #[test]
1609 fn a_description_that_fits_is_stored_whole() {
1610 let mut s: String<16> = String::new();
1611 assert!(!fit_description(&mut s, "wheel speed"));
1612 assert_eq!(s.as_str(), "wheel speed");
1613 assert!(!fit_description(&mut s, "0123456789abcdef"));
1615 assert_eq!(s.len(), 16);
1616 }
1617
1618 #[test]
1621 fn a_long_description_keeps_its_prefix_and_reports_the_cut() {
1622 let mut s: String<8> = String::new();
1623 assert!(fit_description(&mut s, "0123456789"));
1624 assert_eq!(s.as_str(), "01234567");
1625 }
1626
1627 #[test]
1631 fn truncation_backs_off_to_a_character_boundary() {
1632 let mut s: String<5> = String::new();
1633 assert!(fit_description(&mut s, "abcd\u{e9}f"));
1635 assert_eq!(s.as_str(), "abcd");
1636 let mut s: String<6> = String::new();
1637 assert!(fit_description(&mut s, "ab\u{1f4cf}z"));
1639 assert_eq!(s.as_str(), "ab\u{1f4cf}");
1640 let mut s: String<5> = String::new();
1641 assert!(fit_description(&mut s, "ab\u{1f4cf}z"));
1642 assert_eq!(s.as_str(), "ab");
1643 }
1644
1645 #[test]
1648 fn zero_capacity_stores_no_description_and_reports_it() {
1649 let mut s: String<0> = String::new();
1650 assert!(fit_description(&mut s, "anything"));
1651 assert!(s.is_empty());
1652 assert!(
1653 !fit_description(&mut s, ""),
1654 "an empty description loses nothing, so there is nothing to report"
1655 );
1656 }
1657
1658 #[test]
1660 fn the_descriptor_remembers_a_truncated_description() {
1661 let long = "d".repeat(MAX_PARAM_DESCRIPTION_LEN + 3);
1662 let d = ParameterDescriptor::new("p", ParameterType::Bool)
1663 .unwrap()
1664 .with_description(&long);
1665 assert_eq!(d.description.len(), MAX_PARAM_DESCRIPTION_LEN);
1666 assert!(d.description_truncated());
1667 let mut d = d;
1668 assert!(!d.set_description(""));
1669 assert!(!d.description_truncated());
1670 }
1671
1672 #[test]
1676 fn a_truncated_constraints_text_is_not_a_truncated_description() {
1677 let long = "c".repeat(MAX_PARAM_CONSTRAINTS_LEN + 1);
1678 let mut d = ParameterDescriptor::new("p", ParameterType::Bool)
1679 .unwrap()
1680 .with_description("fits");
1681 assert!(d.set_additional_constraints(&long));
1682 assert!(
1683 !d.description_truncated(),
1684 "the description is whole; only the constraints were cut"
1685 );
1686 assert!(d.constraints_truncated());
1687 let cut: heapless::Vec<DescriptorText, 2> = d.truncated_texts().collect();
1688 assert_eq!(cut.as_slice(), &[DescriptorText::Constraints]);
1689 assert_eq!(cut[0].knob(), "NROS_PARAMS_MAX_CONSTRAINTS_BYTES");
1690 assert_eq!(cut[0].field(), "additional_constraints");
1691 assert_eq!(cut[0].capacity(), MAX_PARAM_CONSTRAINTS_LEN);
1692 d.set_description(&"d".repeat(MAX_PARAM_DESCRIPTION_LEN + 1));
1694 let both: heapless::Vec<DescriptorText, 2> = d.truncated_texts().collect();
1695 assert_eq!(
1696 both.as_slice(),
1697 &[DescriptorText::Description, DescriptorText::Constraints]
1698 );
1699 assert_eq!(both[0].knob(), "NROS_PARAMS_MAX_DESCRIPTION_BYTES");
1700 }
1701}