1
#![cfg_attr(not(feature = "std"), no_std)]
2

            
3
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
4

            
5
pub const MAGIC_NOMI: u32 = 0x4E4F_4D49;
6
pub const MAGIC_OUTP: u32 = 0x4F55_5450;
7
pub const BASE_OFFSET: u32 = 0x1000;
8
pub 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`).
14
pub const MAX_WIRE_LIST_DEPTH: usize = 62;
15

            
16
macro_rules! impl_try_from_u8 {
17
    ($name:ident { $($variant:ident = $val:expr),* $(,)? }) => {
18
        impl TryFrom<u8> for $name {
19
            type Error = ();
20
10870090
            fn try_from(v: u8) -> Result<Self, ()> {
21
10870090
                match v {
22
3241172
                    $($val => Ok(Self::$variant),)*
23
418
                    _ => Err(()),
24
                }
25
10870090
            }
26
        }
27
    };
28
}
29

            
30
#[repr(u8)]
31
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32
pub enum ContextType {
33
    EntityCreate = 0,
34
    EntityUpdate = 1,
35
    EntityDelete = 2,
36
    BatchProcess = 3,
37
}
38

            
39
impl_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)]
48
pub 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

            
60
impl_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)]
74
pub 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

            
98
impl_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)]
115
pub enum Operation {
116
    Nop = 0,
117
    Create = 1,
118
    Update = 2,
119
    Delete = 3,
120
    Link = 4,
121
    Unlink = 5,
122
}
123

            
124
impl_try_from_u8!(Operation {
125
    Nop = 0,
126
    Create = 1,
127
    Update = 2,
128
    Delete = 3,
129
    Link = 4,
130
    Unlink = 5,
131
});
132

            
133
pub struct EntityFlags;
134

            
135
impl EntityFlags {
136
    #[must_use]
137
209
    pub fn is_primary(flags: u8) -> bool {
138
209
        flags & 0x01 != 0
139
209
    }
140

            
141
    #[must_use]
142
209
    pub fn is_context(flags: u8) -> bool {
143
209
        flags & 0x02 != 0
144
209
    }
145

            
146
    #[must_use]
147
4115419
    pub fn make(is_primary: bool, is_context: bool) -> u8 {
148
4115419
        u8::from(is_primary) | (u8::from(is_context) << 1)
149
4115419
    }
150
}
151

            
152
// Include generated struct definitions from org document
153
include!("generated.rs");
154

            
155
impl GlobalHeader {
156
    #[must_use]
157
1801581
    pub fn new(
158
1801581
        context_type: ContextType,
159
1801581
        primary_entity_type: EntityType,
160
1801581
        input_entity_count: u32,
161
1801581
        primary_entity_idx: u32,
162
1801581
    ) -> Self {
163
1801581
        Self {
164
1801581
            magic: MAGIC_NOMI,
165
1801581
            version: FORMAT_VERSION,
166
1801581
            context_type: context_type as u8,
167
1801581
            primary_entity_type: primary_entity_type as u8,
168
1801581
            input_entity_count,
169
1801581
            entities_offset: 0,
170
1801581
            strings_pool_offset: 0,
171
1801581
            strings_pool_size: 0,
172
1801581
            output_offset: 0,
173
1801581
            output_size: 0,
174
1801581
            primary_entity_idx,
175
1801581
            reserved: [0; 28],
176
1801581
        }
177
1801581
    }
178

            
179
    #[must_use]
180
1801581
    pub fn as_bytes(&self) -> &[u8] {
181
1801581
        <Self as IntoBytes>::as_bytes(self)
182
1801581
    }
183
}
184

            
185
impl EntityHeader {
186
    #[must_use]
187
4143217
    pub fn new(
188
4143217
        entity_type: EntityType,
189
4143217
        operation: Operation,
190
4143217
        flags: u8,
191
4143217
        id: [u8; 16],
192
4143217
        parent_idx: i32,
193
4143217
        data_offset: u32,
194
4143217
        data_size: u32,
195
4143217
    ) -> Self {
196
4143217
        Self {
197
4143217
            entity_type: entity_type as u8,
198
4143217
            operation: operation as u8,
199
4143217
            flags,
200
4143217
            reserved: [0],
201
4143217
            id,
202
4143217
            parent_idx,
203
4143217
            data_offset,
204
4143217
            data_size,
205
4143217
        }
206
4143217
    }
207
}
208

            
209
impl OutputHeader {
210
    #[must_use]
211
3612357
    pub fn new(output_start_idx: u32) -> Self {
212
3612357
        Self {
213
3612357
            magic: MAGIC_OUTP,
214
3612357
            output_entity_count: 0,
215
3612357
            output_start_idx,
216
3612357
            strings_offset: 0,
217
3612357
            next_write_pos: 0,
218
3612357
            reserved: [0; 4],
219
3612357
        }
220
3612357
    }
221
}
222

            
223
#[cfg(test)]
224
mod tests {
225
    use super::*;
226

            
227
    #[test]
228
1
    fn test_size_constants() {
229
1
        assert_eq!(GLOBAL_HEADER_SIZE, 64);
230
1
        assert_eq!(ENTITY_HEADER_SIZE, 32);
231
1
        assert_eq!(OUTPUT_HEADER_SIZE, 24);
232
1
        assert_eq!(TRANSACTION_DATA_SIZE, 48);
233
1
        assert_eq!(SPLIT_DATA_SIZE, 72);
234
1
        assert_eq!(TAG_DATA_SIZE, 16);
235
1
        assert_eq!(ACCOUNT_DATA_SIZE, 48);
236
1
        assert_eq!(COMMODITY_DATA_SIZE, 32);
237
1
    }
238

            
239
    #[test]
240
1
    fn test_global_header_roundtrip() {
241
1
        let header = GlobalHeader::new(ContextType::EntityCreate, EntityType::Transaction, 5, 0);
242
1
        let bytes = header.as_bytes();
243
1
        let parsed = GlobalHeader::from_bytes(bytes).unwrap();
244
1
        assert_eq!(parsed.magic, MAGIC_NOMI);
245
1
        assert_eq!(parsed.input_entity_count, 5);
246
1
    }
247

            
248
    #[test]
249
1
    fn test_entity_header_roundtrip() {
250
1
        let id = [1u8; 16];
251
1
        let header = EntityHeader::new(EntityType::Split, Operation::Create, 0, id, -1, 100, 64);
252
1
        let bytes = header.to_bytes();
253
1
        let parsed = EntityHeader::from_bytes(&bytes).unwrap();
254
1
        assert_eq!(parsed.entity_type, EntityType::Split as u8);
255
1
        assert_eq!(parsed.parent_idx, -1);
256
1
        assert_eq!(parsed.data_offset, 100);
257
1
    }
258

            
259
    #[test]
260
1
    fn test_output_header_roundtrip() {
261
1
        let header = OutputHeader::new(10);
262
1
        let bytes = header.to_bytes();
263
1
        let parsed = OutputHeader::from_bytes(&bytes).unwrap();
264
1
        assert_eq!(parsed.magic, MAGIC_OUTP);
265
1
        assert_eq!(parsed.output_start_idx, 10);
266
1
    }
267

            
268
    #[test]
269
1
    fn test_tag_data_roundtrip() {
270
1
        let tag = TagData {
271
1
            name_offset: 100,
272
1
            value_offset: 105,
273
1
            name_len: 5,
274
1
            value_len: 10,
275
1
            reserved: [0; 4],
276
1
        };
277
1
        let bytes = tag.to_bytes();
278
1
        let parsed = TagData::from_bytes(&bytes).unwrap();
279
1
        assert_eq!(parsed.name_offset, 100);
280
1
        assert_eq!(parsed.value_offset, 105);
281
1
        assert_eq!(parsed.name_len, 5);
282
1
        assert_eq!(parsed.value_len, 10);
283
1
    }
284

            
285
    #[test]
286
1
    fn test_debug_value_data_roundtrip() {
287
1
        let value = DebugValueData {
288
1
            value_type: ValueType::Number as u8,
289
1
            reserved: [0; 7],
290
1
            data1: 3,
291
1
            data2: 4,
292
1
        };
293
1
        let bytes = value.to_bytes();
294
1
        let parsed = DebugValueData::from_bytes(&bytes).unwrap();
295
1
        assert_eq!(parsed.value_type, ValueType::Number as u8);
296
1
        assert_eq!(parsed.data1, 3);
297
1
        assert_eq!(parsed.data2, 4);
298
1
    }
299
}