Skip to main content

scripting_format/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2
3use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
4
5pub const MAGIC_NOMI: u32 = 0x4E4F_4D49;
6pub const MAGIC_OUTP: u32 = 0x4F55_5450;
7pub const BASE_OFFSET: u32 = 0x1000;
8pub const FORMAT_VERSION: u16 = 1;
9/// Deepest list and struct nesting a script's result may have: the guest
10/// writes a placeholder past it, so a struct holding itself ends, and the host
11/// decoder refuses it. A client reader counts every expression, so the
12/// `(:id N :value V)` envelope and the atom inside the innermost list take two
13/// of its levels (`nomiscript::MAX_READ_DEPTH`).
14pub const MAX_WIRE_LIST_DEPTH: usize = 62;
15
16macro_rules! impl_try_from_u8 {
17    ($name:ident { $($variant:ident = $val:expr),* $(,)? }) => {
18        impl TryFrom<u8> for $name {
19            type Error = ();
20            fn try_from(v: u8) -> Result<Self, ()> {
21                match v {
22                    $($val => Ok(Self::$variant),)*
23                    _ => Err(()),
24                }
25            }
26        }
27    };
28}
29
30#[repr(u8)]
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum ContextType {
33    EntityCreate = 0,
34    EntityUpdate = 1,
35    EntityDelete = 2,
36    BatchProcess = 3,
37}
38
39impl_try_from_u8!(ContextType {
40    EntityCreate = 0,
41    EntityUpdate = 1,
42    EntityDelete = 2,
43    BatchProcess = 3,
44});
45
46#[repr(u8)]
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum EntityType {
49    Transaction = 0,
50    Split = 1,
51    Tag = 2,
52    Account = 3,
53    Commodity = 4,
54    Price = 5,
55    Budget = 6,
56    Lot = 7,
57    DebugValue = 0xFF,
58}
59
60impl_try_from_u8!(EntityType {
61    Transaction = 0,
62    Split = 1,
63    Tag = 2,
64    Account = 3,
65    Commodity = 4,
66    Price = 5,
67    Budget = 6,
68    Lot = 7,
69    DebugValue = 0xFF,
70});
71
72#[repr(u8)]
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum ValueType {
75    Nil = 0,
76    T = 1,
77    /// An index: `data1` the integer, `data2` its denominator 1.
78    Number = 2,
79    String = 3,
80    Symbol = 4,
81    /// Opens a list: its elements follow as debug values, closed by `ListEnd`.
82    List = 5,
83    ListEnd = 6,
84    /// Atomic money: `data1` / `data2` the amount's numerator / denominator,
85    /// then the commodity id's 16 big-endian bytes inline.
86    Commodity = 7,
87    /// A server entity reference: `data1` is the kind's `EntityKind::wire_code`.
88    Entity = 8,
89    /// Opens a runtime struct instance, closed by `ListEnd`: the name symbol
90    /// follows, then each field's keyword symbol and its value.
91    Struct = 9,
92    /// A closure: `data1` is the site of its source.
93    Closure = 10,
94    /// A scalar, whole or not: `data1` / `data2` the numerator / denominator.
95    Scalar = 11,
96}
97
98impl_try_from_u8!(ValueType {
99    Nil = 0,
100    T = 1,
101    Number = 2,
102    String = 3,
103    Symbol = 4,
104    List = 5,
105    ListEnd = 6,
106    Commodity = 7,
107    Entity = 8,
108    Struct = 9,
109    Closure = 10,
110    Scalar = 11,
111});
112
113#[repr(u8)]
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub enum Operation {
116    Nop = 0,
117    Create = 1,
118    Update = 2,
119    Delete = 3,
120    Link = 4,
121    Unlink = 5,
122}
123
124impl_try_from_u8!(Operation {
125    Nop = 0,
126    Create = 1,
127    Update = 2,
128    Delete = 3,
129    Link = 4,
130    Unlink = 5,
131});
132
133pub struct EntityFlags;
134
135impl EntityFlags {
136    #[must_use]
137    pub fn is_primary(flags: u8) -> bool {
138        flags & 0x01 != 0
139    }
140
141    #[must_use]
142    pub fn is_context(flags: u8) -> bool {
143        flags & 0x02 != 0
144    }
145
146    #[must_use]
147    pub fn make(is_primary: bool, is_context: bool) -> u8 {
148        u8::from(is_primary) | (u8::from(is_context) << 1)
149    }
150}
151
152// Include generated struct definitions from org document
153include!("generated.rs");
154
155impl GlobalHeader {
156    #[must_use]
157    pub fn new(
158        context_type: ContextType,
159        primary_entity_type: EntityType,
160        input_entity_count: u32,
161        primary_entity_idx: u32,
162    ) -> Self {
163        Self {
164            magic: MAGIC_NOMI,
165            version: FORMAT_VERSION,
166            context_type: context_type as u8,
167            primary_entity_type: primary_entity_type as u8,
168            input_entity_count,
169            entities_offset: 0,
170            strings_pool_offset: 0,
171            strings_pool_size: 0,
172            output_offset: 0,
173            output_size: 0,
174            primary_entity_idx,
175            reserved: [0; 28],
176        }
177    }
178
179    #[must_use]
180    pub fn as_bytes(&self) -> &[u8] {
181        <Self as IntoBytes>::as_bytes(self)
182    }
183}
184
185impl EntityHeader {
186    #[must_use]
187    pub fn new(
188        entity_type: EntityType,
189        operation: Operation,
190        flags: u8,
191        id: [u8; 16],
192        parent_idx: i32,
193        data_offset: u32,
194        data_size: u32,
195    ) -> Self {
196        Self {
197            entity_type: entity_type as u8,
198            operation: operation as u8,
199            flags,
200            reserved: [0],
201            id,
202            parent_idx,
203            data_offset,
204            data_size,
205        }
206    }
207}
208
209impl OutputHeader {
210    #[must_use]
211    pub fn new(output_start_idx: u32) -> Self {
212        Self {
213            magic: MAGIC_OUTP,
214            output_entity_count: 0,
215            output_start_idx,
216            strings_offset: 0,
217            next_write_pos: 0,
218            reserved: [0; 4],
219        }
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn test_size_constants() {
229        assert_eq!(GLOBAL_HEADER_SIZE, 64);
230        assert_eq!(ENTITY_HEADER_SIZE, 32);
231        assert_eq!(OUTPUT_HEADER_SIZE, 24);
232        assert_eq!(TRANSACTION_DATA_SIZE, 48);
233        assert_eq!(SPLIT_DATA_SIZE, 72);
234        assert_eq!(TAG_DATA_SIZE, 16);
235        assert_eq!(ACCOUNT_DATA_SIZE, 48);
236        assert_eq!(COMMODITY_DATA_SIZE, 32);
237    }
238
239    #[test]
240    fn test_global_header_roundtrip() {
241        let header = GlobalHeader::new(ContextType::EntityCreate, EntityType::Transaction, 5, 0);
242        let bytes = header.as_bytes();
243        let parsed = GlobalHeader::from_bytes(bytes).unwrap();
244        assert_eq!(parsed.magic, MAGIC_NOMI);
245        assert_eq!(parsed.input_entity_count, 5);
246    }
247
248    #[test]
249    fn test_entity_header_roundtrip() {
250        let id = [1u8; 16];
251        let header = EntityHeader::new(EntityType::Split, Operation::Create, 0, id, -1, 100, 64);
252        let bytes = header.to_bytes();
253        let parsed = EntityHeader::from_bytes(&bytes).unwrap();
254        assert_eq!(parsed.entity_type, EntityType::Split as u8);
255        assert_eq!(parsed.parent_idx, -1);
256        assert_eq!(parsed.data_offset, 100);
257    }
258
259    #[test]
260    fn test_output_header_roundtrip() {
261        let header = OutputHeader::new(10);
262        let bytes = header.to_bytes();
263        let parsed = OutputHeader::from_bytes(&bytes).unwrap();
264        assert_eq!(parsed.magic, MAGIC_OUTP);
265        assert_eq!(parsed.output_start_idx, 10);
266    }
267
268    #[test]
269    fn test_tag_data_roundtrip() {
270        let tag = TagData {
271            name_offset: 100,
272            value_offset: 105,
273            name_len: 5,
274            value_len: 10,
275            reserved: [0; 4],
276        };
277        let bytes = tag.to_bytes();
278        let parsed = TagData::from_bytes(&bytes).unwrap();
279        assert_eq!(parsed.name_offset, 100);
280        assert_eq!(parsed.value_offset, 105);
281        assert_eq!(parsed.name_len, 5);
282        assert_eq!(parsed.value_len, 10);
283    }
284
285    #[test]
286    fn test_debug_value_data_roundtrip() {
287        let value = DebugValueData {
288            value_type: ValueType::Number as u8,
289            reserved: [0; 7],
290            data1: 3,
291            data2: 4,
292        };
293        let bytes = value.to_bytes();
294        let parsed = DebugValueData::from_bytes(&bytes).unwrap();
295        assert_eq!(parsed.value_type, ValueType::Number as u8);
296        assert_eq!(parsed.data1, 3);
297        assert_eq!(parsed.data2, 4);
298    }
299}