Skip to main content

predsync_core/
value.rs

1//! Value representations for alloc and bounded/no-alloc paths.
2
3use crate::Slot;
4
5#[cfg(feature = "alloc")]
6use alloc::{string::String, vec::Vec};
7
8/// Borrowed value view used by core encode/decode logic.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum ValueRef<'a> {
11    Scalar(Slot),
12    List(&'a [Slot]),
13    Str(&'a str),
14}
15
16/// A field value at the core alloc API boundary.
17#[cfg(feature = "alloc")]
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Value {
20    Scalar(Slot),
21    List(Vec<Slot>),
22    Str(String),
23}
24
25#[cfg(feature = "alloc")]
26impl Value {
27    pub fn as_ref(&self) -> ValueRef<'_> {
28        match self {
29            Self::Scalar(s) => ValueRef::Scalar(*s),
30            Self::List(v) => ValueRef::List(v),
31            Self::Str(s) => ValueRef::Str(s),
32        }
33    }
34}
35
36/// Bounded value for no-alloc encode/decode.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum BoundedValue<const MAX_LIST: usize, const MAX_STR: usize> {
39    Scalar(Slot),
40    List(heapless::Vec<Slot, MAX_LIST>),
41    Str(heapless::String<MAX_STR>),
42}
43
44impl<const MAX_LIST: usize, const MAX_STR: usize> BoundedValue<MAX_LIST, MAX_STR> {
45    pub fn try_str(s: &str) -> Option<Self> {
46        let mut hs = heapless::String::new();
47        hs.push_str(s).ok()?;
48        Some(Self::Str(hs))
49    }
50    pub fn as_ref(&self) -> ValueRef<'_> {
51        match self {
52            Self::Scalar(s) => ValueRef::Scalar(*s),
53            Self::List(v) => ValueRef::List(v),
54            Self::Str(s) => ValueRef::Str(s.as_str()),
55        }
56    }
57}