twine_data/
types.rs

1//! Base types.
2//!
3//! These types are used throughout the library.
4
5use std::fmt::{Debug, Display};
6
7/// An offset in a blob.
8pub type Offset = u64;
9
10/// A tag, similar to a CBOR tag.
11pub type Tag = u64;
12
13/// A constructor index, used to encode `enum`s (sum types, optional, etc.) by their index.
14#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
15pub struct VariantIdx(pub u32);
16
17/// Immediate value, without nesting.
18///
19/// An immediate value is one that can be _skipped_ over efficiently.
20/// Only immediate values can be stored in arrays and maps; more complex values have to be
21/// stored indirectly via a reference.
22#[derive(Debug, Clone, Copy, PartialEq)]
23pub enum Immediate<'a> {
24    /// CBOR/JSON null.
25    Null,
26    Bool(bool),
27    Int64(i64),
28    Float(f64),
29    /// Text, in UTF8
30    String(&'a str),
31    /// Binary blob.
32    Bytes(&'a [u8]),
33    /// A variant with 0 arguments.
34    Variant0(VariantIdx),
35    /// An explicit reference to a full value (which comes at an earlier offset).
36    Ref(Offset),
37    /// An automatically followed reference to a full value (which comes at an earlier offset).
38    Pointer(Offset),
39}
40
41impl<'a> Default for Immediate<'a> {
42    fn default() -> Self {
43        Immediate::Null
44    }
45}
46
47macro_rules! impl_from {
48    ($variant:path, $typ:ty, $typ_real:ty) => {
49        impl<'a> From<$typ_real> for Immediate<'a> {
50            fn from(v: $typ_real) -> Immediate<'a> {
51                $variant(v as $typ)
52            }
53        }
54    };
55}
56
57impl<'a> From<()> for Immediate<'a> {
58    fn from(_v: ()) -> Self {
59        Immediate::Null
60    }
61}
62
63impl_from!(Immediate::Bool, bool, bool);
64impl_from!(Immediate::Int64, i64, i64);
65impl_from!(Immediate::Int64, i64, i32);
66impl_from!(Immediate::Float, f64, f64);
67impl_from!(Immediate::Float, f64, f32);
68impl_from!(Immediate::String, &'a str, &'a str);
69impl_from!(Immediate::Bytes, &'a [u8], &'a [u8]);
70impl_from!(Immediate::Pointer, Offset, Offset);
71
72#[derive(Debug, Clone, Copy)]
73pub struct Error {
74    /// Error message.
75    pub msg: &'static str,
76    /// Offset at which error occurred in the twine blob.
77    pub off: Offset,
78}
79
80pub type Result<T> = core::result::Result<T, Error>;
81
82impl Display for Error {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        write!(
85            f,
86            "Twine error: {} at offset=0x{:x} ({})",
87            self.msg, self.off, self.off
88        )
89    }
90}
91
92impl std::error::Error for Error {}