Skip to main content

charon_lib/ast/bodies/
values.rs

1//! Contains definitions for variables and constant values.
2use core::hash::Hash;
3use derive_generic_visitor::{Drive, DriveMut, DriveTwo};
4use enum_as_inner::EnumAsInner;
5use serde::{Deserialize, Serialize};
6use serde_state::{DeserializeState, SerializeState};
7use std::vec::Vec;
8
9use crate::ast::*;
10
11/// A constant expression.
12#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
13#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
14#[serde_state(state_implements = DedupSerializerState)] // Avoid corecursive impls due to perfect derive
15pub struct ConstantExpr(pub HashConsed<WithCachedTypeInfo<(ConstantExprKind, Ty)>>);
16
17#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
18#[derive(EnumAsInner)]
19#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
20#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("C"))]
21pub enum ConstantExprKind {
22    /// Boolean value.
23    Bool(bool),
24    /// Integer value.
25    #[serde_state(stateless)]
26    Integer(IntegerValue),
27    /// Char value.
28    Char(char),
29    /// Float value.
30    #[serde_state(stateless)]
31    Float(FloatValue),
32    /// Value of an ADT (struct or enum).
33    ///
34    /// This is eliminated inside functions if `--raw-consts` is off.
35    Adt(Option<VariantId>, IndexVec<FieldId, ConstantExpr>),
36    /// Array value.
37    ///
38    /// This is eliminated inside functions if `--raw-consts` is off.
39    Array(Vec<ConstantExpr>),
40    /// A shared reference to a constant place.
41    ///
42    /// This is eliminated inside functions if `--raw-consts` is off.
43    Ref(GlobalPlace, Option<UnsizingMetadata>),
44    /// A raw pointer to a constant place.
45    ///
46    /// This is eliminated inside functions if `--raw-consts` is off.
47    Ptr(RefKind, GlobalPlace, Option<UnsizingMetadata>),
48    /// `str` value. This represents an unsized value of type `str` (and not `&str`).
49    Str(String),
50    /// Byte string value.
51    ByteStr(Vec<u8>),
52    /// ZST constant corresponding to the unique value of the type of a function item.
53    FnDef(FnPtr),
54    /// A function pointer value; this is a pointer (i.e. an address).
55    ///
56    /// This is eliminated inside functions if `--raw-consts` is off.
57    FnPtr(FnPtr),
58    /// Cast a constant value to another type (e.g. erase a vtable method pointer to `*const ()`).
59    Cast(ConstantExpr, CastKind),
60    /// A pointer with no provenance (e.g. 0 for the null pointer)
61    ///
62    /// This is eliminated inside functions if `--raw-consts` is off.
63    PtrNoProvenance(#[serde(with = "scalar_value_ser_de")] u128),
64    /// The address of a linker symbol, as a `*const ()`. The address may be null, if the
65    /// symbol wasn't defined at link time.
66    ExternSymbol(String),
67    /// The `TypeId` value for a type.
68    TypeId(Ty),
69    /// Raw memory value obtained from constant evaluation. Used when a more structured
70    /// representation isn't possible (e.g. for unions) or just isn't implemented yet.
71    RawMemory(Vec<Byte>),
72
73    /// A const generic var
74    Var(ConstGenericDbVar),
75    /// The value of a constant/static.
76    ///
77    /// This is eliminated inside functions if `--raw-consts` is off.
78    Global(GlobalDeclRef),
79    /// A call to a `const fn`.
80    Call(FnPtr, Vec<ConstantExpr>),
81    /// A trait associated constant.
82    ///
83    /// E.g.:
84    /// ```text
85    /// impl Foo for Bar {
86    ///   const C : usize = 32; // <-
87    /// }
88    /// ```
89    TraitConst(TraitRef, AssocConstId),
90    /// A reference to the vtable `static` item for this trait ref. This can be normalized if we
91    /// emitted a vtable item.
92    ///
93    /// This is eliminated if `--raw-consts` is off.
94    VTableRef(PolyTraitRef),
95    /// The integer discriminant value corresponding to this enum variant.
96    Discriminant(TypeDeclRef, VariantId),
97    /// Make an array of `count` copies of `value`. `value` does not need to be `Copy` or `Clone`.
98    Repeat {
99        value: ConstantExpr,
100        count: ConstantExpr,
101        /// Proof that the element type is `Sized`; absent with `--hide-marker-traits`.
102        value_is_sized: Option<TraitRef>,
103    },
104    /// The size of the given type.
105    SizeOf(Ty),
106    /// The alignment of the given type.
107    AlignOf(Ty),
108    /// The offset of the given field.
109    OffsetOf(TypeDeclRef, Option<VariantId>, FieldId),
110
111    /// A constant expression that Charon doesn't handle, along with the reason why.
112    Opaque(String),
113}
114
115/// The place a `Ref`/`Ptr` constant points to, e.g. `GLOBAL.0[1]`. This is a constant version of
116/// [`Place`].
117#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
118#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
119#[serde_state(state_implements = DedupSerializerState)] // Avoid corecursive impls due to perfect derive
120pub struct GlobalPlace {
121    #[cfg_attr(feature = "charon_on_charon", charon::rename("global_place_kind"))]
122    pub kind: GlobalPlaceKind,
123    /// The type of the place.
124    #[cfg_attr(feature = "charon_on_charon", charon::rename("global_place_ty"))]
125    pub ty: Ty,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
129#[derive(EnumAsInner)]
130#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
131#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("GlobalPlace"))]
132pub enum GlobalPlaceKind {
133    /// The allocation behind this provenance.
134    Global(GlobalProvenance),
135    /// A constant value that isn't stored in a global, e.g. the pointee of a reference in a const
136    /// generic argument. It has no projections.
137    // TODO: put these values in globals, to preserve sharing
138    Value(ConstantExpr),
139    /// A subplace of a place.
140    Projection(Box<GlobalPlace>, ConstProjectionElem),
141}
142
143impl GlobalPlace {
144    pub fn new_global(global: GlobalDeclRef, ty: Ty) -> Self {
145        GlobalPlace {
146            kind: GlobalPlaceKind::Global(GlobalProvenance::Global(global)),
147            ty,
148        }
149    }
150
151    pub fn new_value(value: ConstantExpr) -> Self {
152        GlobalPlace {
153            ty: value.ty().clone(),
154            kind: GlobalPlaceKind::Value(value),
155        }
156    }
157
158    pub fn project(self, elem: ConstProjectionElem, ty: Ty) -> Self {
159        GlobalPlace {
160            kind: GlobalPlaceKind::Projection(Box::new(self), elem),
161            ty,
162        }
163    }
164}
165
166/// A projection inside the pointee of a `Ref`/`Ptr` constant. This is a constant version of
167/// [`ProjectionElem`].
168#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
169#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
170#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("CProj"))]
171pub enum ConstProjectionElem {
172    /// Project to the field of an ADT.
173    Field(Option<VariantId>, FieldId),
174    /// Project to the element of an array at the given index.
175    #[serde_state(stateless)]
176    Index(IntegerValue),
177    /// Project to the subarray `array[from..to]`.
178    #[serde_state(stateless)]
179    Subslice {
180        from: IntegerValue,
181        to: IntegerValue,
182    },
183    /// Like `ProjectionElem::Offset`: the place located `count * size_of::<ty>()` bytes after the
184    /// current place (or `count` bytes if `ty` is `None`). `pointee_is_sized` is the proof that the
185    /// pointee type is sized.
186    Offset {
187        count: IntegerValue,
188        ty: Option<Ty>,
189        in_bounds: bool,
190        pointee_is_sized: Option<TraitRef>,
191    },
192}
193
194/// A scalar value.
195#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
196#[derive(EnumAsInner)]
197#[derive(
198    Serialize,
199    Deserialize,
200    SerializeState,
201    DeserializeState,
202    Drive,
203    DriveMut,
204    DriveTwo
205)]
206#[cfg_attr(feature = "charon_on_charon", charon::variants_suffix("Integer"))]
207#[serde_state(stateless)]
208pub enum IntegerValue {
209    Unsigned(UIntTy, #[serde(with = "scalar_value_ser_de")] u128),
210    Signed(IntTy, #[serde(with = "scalar_value_ser_de")] i128),
211}
212
213/// This is simlar to the Scalar value above. However, instead of storing
214/// the float value itself, we store its String representation. This allows
215/// to derive the Eq and Ord traits, which are not implemented for floats
216#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
217#[derive(Serialize, Deserialize, Drive, DriveMut, DriveTwo)]
218pub struct FloatValue {
219    #[cfg_attr(feature = "charon_on_charon", charon::rename("float_value"))]
220    pub value: String,
221    #[cfg_attr(feature = "charon_on_charon", charon::rename("float_bits"))]
222    #[serde(with = "scalar_value_ser_de")]
223    pub bits: u128,
224    #[cfg_attr(feature = "charon_on_charon", charon::rename("float_ty"))]
225    pub ty: FloatTy,
226}
227
228/// Provenance is the location in memory a pointer (or the byte of a pointer, see [`Byte`])
229/// points to. `GlobalProvenance` represents a compile-time provenance.
230/// See <https://doc.rust-lang.org/std/ptr/index.html#provenance>
231#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
232#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
233#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("Prov"))]
234pub enum GlobalProvenance {
235    Global(GlobalDeclRef),
236    /// A function, with the type of function pointers to it.
237    Function(FnPtr, Ty),
238    /// The allocation backing the `TypeId` of this type. Note that `TypeId`s always have 16 bytes
239    /// worth of provenance, regardless of the platform's pointer size, so [`Byte::Provenance`]'s byte index can
240    /// go up to 16! In other words, the bytes of a full `TypeId` are `Provenance(TypeId(ty), 0, 0..16)`.
241    TypeId(Ty),
242}
243
244/// A byte, in the MiniRust sense: it can either be uninitialized, a concrete u8 value,
245/// or part of a pointer with provenance (e.g. to a global or a function)
246#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
247#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
248pub enum Byte {
249    /// An uninitialized byte
250    Uninit,
251    /// A concrete byte value
252    Value(u8),
253    /// A byte that is part of a pointer with provenance, at the given offset into the pointee.
254    /// The u8 is the index of this byte within the pointer. Note that we do not have an actual
255    /// value for this pointer byte, unlike MiniRust, as that is non-deterministic.
256    Provenance(GlobalProvenance, IntegerValue, u8),
257}
258
259macro_rules! static_constant {
260    ($e:expr) => {{
261        use std::sync::LazyLock;
262        static CONSTANT: LazyLock<ConstantExpr> = LazyLock::new(|| $e);
263        CONSTANT.clone()
264    }};
265}
266
267impl ConstantExpr {
268    pub fn new(kind: ConstantExprKind, ty: Ty) -> Self {
269        Self(HashConsed::new(WithCachedTypeInfo::new((kind, ty))))
270    }
271
272    pub fn kind(&self) -> &ConstantExprKind {
273        &self.0.inner().0
274    }
275
276    pub fn ty(&self) -> &Ty {
277        &self.0.inner().1
278    }
279
280    pub fn with_contents_mut<R>(
281        &mut self,
282        f: impl FnOnce(&mut ConstantExprKind, &mut Ty) -> R,
283    ) -> R {
284        self.0
285            .with_inner_mut(|contents| contents.with_value_mut(|(kind, ty)| f(kind, ty)))
286    }
287
288    pub fn mk_unit() -> Self {
289        static_constant!(ConstantExpr::new(
290            ConstantExprKind::Adt(None, IndexVec::new()),
291            Ty::mk_unit(),
292        ))
293    }
294
295    pub fn mk_usize(value: u128) -> Self {
296        if value == 0 {
297            static_constant!(IntegerValue::mk_usize(0).to_constant())
298        } else {
299            IntegerValue::mk_usize(value).to_constant()
300        }
301    }
302
303    pub fn mk_bool(value: bool) -> Self {
304        match value {
305            true => static_constant!(ConstantExpr::new(
306                ConstantExprKind::Bool(true),
307                Ty::mk_bool()
308            )),
309            false => static_constant!(ConstantExpr::new(
310                ConstantExprKind::Bool(false),
311                Ty::mk_bool()
312            )),
313        }
314    }
315
316    pub fn as_usize_literal(&self) -> Option<u128> {
317        match self.kind() {
318            ConstantExprKind::Integer(IntegerValue::Unsigned(UIntTy::Usize, value)) => Some(*value),
319            _ => None,
320        }
321    }
322}
323
324impl ConstantExprKind {
325    pub fn from_bits(scalar_ty: &ScalarTy, bits: u128) -> Option<Self> {
326        match *scalar_ty {
327            ScalarTy::Integer(int_ty) => Some(Self::Integer(IntegerValue::from_bits(int_ty, bits))),
328            ScalarTy::Bool => match bits {
329                0 => Some(Self::Bool(false)),
330                1 => Some(Self::Bool(true)),
331                _ => None,
332            },
333            ScalarTy::Char => {
334                let bytes: [u8; 4] = bits.to_le_bytes()[0..4].try_into().unwrap();
335                Some(Self::Char(
336                    std::char::from_u32(u32::from_le_bytes(bytes)).unwrap(),
337                ))
338            }
339            ScalarTy::Float(_) => None,
340        }
341    }
342}
343
344impl std::ops::Deref for ConstantExpr {
345    type Target = WithCachedTypeInfo<(ConstantExprKind, Ty)>;
346    fn deref(&self) -> &Self::Target {
347        &self.0
348    }
349}
350
351impl IntegerValue {
352    fn ptr_size_max(ptr_size: ByteCount, signed: bool) -> u128 {
353        match ptr_size {
354            2 => {
355                if signed {
356                    i16::MAX as u128
357                } else {
358                    u16::MAX as u128
359                }
360            }
361            4 => {
362                if signed {
363                    i32::MAX as u128
364                } else {
365                    u32::MAX as u128
366                }
367            }
368            8 => {
369                if signed {
370                    i64::MAX as u128
371                } else {
372                    u64::MAX as u128
373                }
374            }
375            _ => panic!("`ptr_size_max`: unsupported ptr size {ptr_size}"),
376        }
377    }
378
379    fn ptr_size_min(ptr_size: ByteCount, signed: bool) -> i128 {
380        match ptr_size {
381            2 => {
382                if signed {
383                    i16::MIN as i128
384                } else {
385                    u16::MIN as i128
386                }
387            }
388            4 => {
389                if signed {
390                    i32::MIN as i128
391                } else {
392                    u32::MIN as i128
393                }
394            }
395            8 => {
396                if signed {
397                    i64::MIN as i128
398                } else {
399                    u64::MIN as i128
400                }
401            }
402            _ => panic!("`ptr_size_min`: unsupported ptr size {ptr_size}"),
403        }
404    }
405
406    pub fn ty(&self) -> IntegerTy {
407        match self {
408            IntegerValue::Signed(ty, _) => IntegerTy::Signed(*ty),
409            IntegerValue::Unsigned(ty, _) => IntegerTy::Unsigned(*ty),
410        }
411    }
412
413    pub fn is_int(&self) -> bool {
414        matches!(self, IntegerValue::Signed(_, _))
415    }
416
417    pub fn is_uint(&self) -> bool {
418        matches!(self, IntegerValue::Unsigned(_, _))
419    }
420
421    /// When computing the result of binary operations, we convert the values
422    /// to u128 then back to the target type (while performing dynamic checks
423    /// of course).
424    pub fn as_uint(&self) -> Option<u128> {
425        match self {
426            IntegerValue::Unsigned(_, v) => Some(*v),
427            _ => None,
428        }
429    }
430
431    pub fn uint_is_in_bounds(ptr_size: ByteCount, ty: UIntTy, v: u128) -> bool {
432        match ty {
433            UIntTy::Usize => v <= Self::ptr_size_max(ptr_size, false),
434            UIntTy::U8 => v <= (u8::MAX as u128),
435            UIntTy::U16 => v <= (u16::MAX as u128),
436            UIntTy::U32 => v <= (u32::MAX as u128),
437            UIntTy::U64 => v <= (u64::MAX as u128),
438            UIntTy::U128 => true,
439        }
440    }
441
442    pub fn from_unchecked_uint(ty: UIntTy, v: u128) -> IntegerValue {
443        IntegerValue::Unsigned(ty, v)
444    }
445
446    pub fn from_uint(ptr_size: ByteCount, ty: UIntTy, v: u128) -> Option<Self> {
447        if !IntegerValue::uint_is_in_bounds(ptr_size, ty, v) {
448            None
449        } else {
450            Some(IntegerValue::from_unchecked_uint(ty, v))
451        }
452    }
453
454    pub fn mk_usize(value: u128) -> Self {
455        IntegerValue::Unsigned(UIntTy::Usize, value)
456    }
457
458    /// When computing the result of binary operations, we convert the values
459    /// to i128 then back to the target type (while performing dynamic checks
460    /// of course).
461    pub fn as_int(&self) -> Option<i128> {
462        match self {
463            IntegerValue::Signed(_, v) => Some(*v),
464            _ => None,
465        }
466    }
467
468    pub fn int_is_in_bounds(ptr_size: ByteCount, ty: IntTy, v: i128) -> bool {
469        match ty {
470            IntTy::Isize => {
471                v >= Self::ptr_size_min(ptr_size, true)
472                    && v <= Self::ptr_size_max(ptr_size, true) as i128
473            }
474            IntTy::I8 => v >= (i8::MIN as i128) && v <= (i8::MAX as i128),
475            IntTy::I16 => v >= (i16::MIN as i128) && v <= (i16::MAX as i128),
476            IntTy::I32 => v >= (i32::MIN as i128) && v <= (i32::MAX as i128),
477            IntTy::I64 => v >= (i64::MIN as i128) && v <= (i64::MAX as i128),
478            IntTy::I128 => true,
479        }
480    }
481
482    pub fn from_unchecked_int(ty: IntTy, v: i128) -> IntegerValue {
483        IntegerValue::Signed(ty, v)
484    }
485
486    /// Most integers are represented as `u128` by rustc. We must be careful not to sign-extend.
487    pub fn to_bits(&self) -> u128 {
488        match *self {
489            IntegerValue::Unsigned(_, v) => v,
490            IntegerValue::Signed(_, v) => u128::from_le_bytes(v.to_le_bytes()),
491        }
492    }
493
494    /// Translates little endian bytes into a corresponding `IntegerValue`.
495    /// This needs to do the round-trip to the correct integer type to guarantee
496    /// that the values are correctly sign-extended (e.g. if the bytes encode -1i8, taking all 16 bytes
497    /// would lead to the value 255i128 instead of -1i128).
498    pub fn from_le_bytes(ty: IntegerTy, bytes: [u8; 16]) -> Self {
499        macro_rules! from_le_bytes {
500            ($m:ident, $b:ident, [$(($i_ty: ty, $i:ident, $s:ident, $n_ty:ty, $t:ty)),*]) => {
501                match $m {
502                    $(
503                        IntegerTy::$s(<$i_ty>::$i) => {
504                            let n = size_of::<$n_ty>();
505                            let b: [u8; _] = $b[0..n].try_into().unwrap();
506                            IntegerValue::$s(<$i_ty>::$i, <$n_ty>::from_le_bytes(b) as $t)
507                        }
508                    )*
509                }
510            }
511        }
512
513        from_le_bytes!(
514            ty,
515            bytes,
516            [
517                (IntTy, Isize, Signed, isize, i128),
518                (IntTy, I8, Signed, i8, i128),
519                (IntTy, I16, Signed, i16, i128),
520                (IntTy, I32, Signed, i32, i128),
521                (IntTy, I64, Signed, i64, i128),
522                (IntTy, I128, Signed, i128, i128),
523                (UIntTy, Usize, Unsigned, usize, u128),
524                (UIntTy, U8, Unsigned, u8, u128),
525                (UIntTy, U16, Unsigned, u16, u128),
526                (UIntTy, U32, Unsigned, u32, u128),
527                (UIntTy, U64, Unsigned, u64, u128),
528                (UIntTy, U128, Unsigned, u128, u128)
529            ]
530        )
531    }
532
533    pub fn from_bits(ty: IntegerTy, bits: u128) -> Self {
534        let bytes = bits.to_le_bytes();
535        Self::from_le_bytes(ty, bytes)
536    }
537
538    /// **Warning**: most constants are stored as u128 by rustc. When converting
539    /// to i128, it is not correct to do `v as i128`, we must reinterpret the
540    /// bits (see [IntegerValue::from_le_bytes]).
541    pub fn from_int(ptr_size: ByteCount, ty: IntTy, v: i128) -> Option<IntegerValue> {
542        if !IntegerValue::int_is_in_bounds(ptr_size, ty, v) {
543            None
544        } else {
545            Some(IntegerValue::from_unchecked_int(ty, v))
546        }
547    }
548
549    /// Increment the value, staying within the same integer type. Returns `None` on overflow.
550    pub fn add(self, n: u128) -> Option<Self> {
551        Some(match self {
552            IntegerValue::Unsigned(ty, v) => IntegerValue::Unsigned(ty, v.checked_add(n)?),
553            IntegerValue::Signed(ty, v) => {
554                IntegerValue::Signed(ty, v.checked_add(n.try_into().unwrap())?)
555            }
556        })
557    }
558
559    pub fn to_constant(self) -> ConstantExpr {
560        let scalar_ty = ScalarTy::Integer(self.ty());
561        ConstantExpr::new(
562            ConstantExprKind::Integer(self),
563            TyKind::Scalar(scalar_ty).into_ty(),
564        )
565    }
566}
567
568/// Custom serializer that stores 128 bit integers as strings to avoid overflow.
569pub(crate) mod scalar_value_ser_de {
570    use std::{marker::PhantomData, str::FromStr};
571
572    use serde::de::{Deserializer, Error};
573
574    pub fn serialize<S, V>(val: &V, serializer: S) -> Result<S::Ok, S::Error>
575    where
576        S: serde::ser::Serializer,
577        V: ToString,
578    {
579        serializer.serialize_str(&val.to_string())
580    }
581
582    /// Stateful variant for types that derive `SerializeState`: the state is irrelevant for a
583    /// scalar, so we delegate to the stateless [`serialize`].
584    pub fn serialize_state<S, State: ?Sized, V>(
585        val: &V,
586        _state: &State,
587        serializer: S,
588    ) -> Result<S::Ok, S::Error>
589    where
590        S: serde::ser::Serializer,
591        V: ToString,
592    {
593        serialize(val, serializer)
594    }
595
596    pub fn deserialize<'de, D, V>(deserializer: D) -> Result<V, D::Error>
597    where
598        D: Deserializer<'de>,
599        V: FromStr,
600    {
601        struct Visitor<V> {
602            _val: PhantomData<V>,
603        }
604        impl<'de, V> serde::de::Visitor<'de> for Visitor<V>
605        where
606            V: FromStr,
607        {
608            type Value = V;
609            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
610                write!(f, "IntegerValue value")
611            }
612            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
613            where
614                E: Error,
615            {
616                v.parse()
617                    .map_err(|_| E::custom("Could not parse 128 bit integer!"))
618            }
619        }
620        deserializer.deserialize_str(Visitor { _val: PhantomData })
621    }
622
623    /// Stateful variant for types that derive `DeserializeState`: the state is irrelevant for a
624    /// scalar, so we delegate to the stateless [`deserialize`].
625    pub fn deserialize_state<'de, D, State: ?Sized, V>(
626        _state: &State,
627        deserializer: D,
628    ) -> Result<V, D::Error>
629    where
630        D: Deserializer<'de>,
631        V: FromStr,
632    {
633        deserialize(deserializer)
634    }
635}
636
637#[cfg(test)]
638mod test {
639    use super::*;
640
641    #[test]
642    fn test_big_endian_scalars() {
643        let u128 = 0x12345678901234567890123456789012u128;
644        let le_bytes = u128.to_le_bytes();
645
646        let le_scalar = IntegerValue::from_le_bytes(IntegerTy::Unsigned(UIntTy::U128), le_bytes);
647        assert_eq!(le_scalar, IntegerValue::Unsigned(UIntTy::U128, u128));
648
649        let i64 = 0x1234567890123456i64;
650        let le_bytes = (i64 as i128).to_le_bytes();
651        let le_scalar = IntegerValue::from_le_bytes(IntegerTy::Signed(IntTy::I64), le_bytes);
652        assert_eq!(le_scalar, IntegerValue::Signed(IntTy::I64, i64 as i128));
653    }
654}