1
use super::*;
2
use scripting_format::OutputHeader;
3

            
4
/// An output buffer holding one entity per `(entity_type, value_type)`.
5
8
fn output(entities: &[(EntityType, ValueType)]) -> Vec<u8> {
6
8
    let mut header = OutputHeader::new(0);
7
8
    header.output_entity_count = u32::try_from(entities.len()).unwrap_or(u32::MAX);
8
8
    let mut bytes = header.to_bytes().to_vec();
9
8
    for (entity_type, value_type) in entities {
10
17
        let data_offset = u32::try_from(bytes.len() + ENTITY_HEADER_SIZE).unwrap_or(u32::MAX);
11
17
        let entity = EntityHeader {
12
17
            entity_type: *entity_type as u8,
13
17
            operation: 0,
14
17
            flags: 0,
15
17
            reserved: [0],
16
17
            id: [0; 16],
17
17
            parent_idx: -1,
18
17
            data_offset,
19
17
            data_size: u32::try_from(DEBUG_VALUE_DATA_SIZE).unwrap_or(u32::MAX),
20
17
        };
21
17
        bytes.extend_from_slice(&entity.to_bytes());
22
17
        let value = DebugValueData {
23
17
            value_type: *value_type as u8,
24
17
            reserved: [0; 7],
25
17
            data1: 1,
26
17
            data2: 1,
27
17
        };
28
17
        bytes.extend_from_slice(&value.to_bytes());
29
    }
30
8
    bytes
31
8
}
32

            
33
14
fn debug(value_type: ValueType) -> (EntityType, ValueType) {
34
14
    (EntityType::DebugValue, value_type)
35
14
}
36

            
37
/// One debug value as the guest writes it: its type, `data1` / `data2` and
38
/// the `inline` bytes after its fixed data.
39
type Item<'a> = (ValueType, i64, i64, &'a [u8]);
40

            
41
/// An output buffer holding one debug value of `value_type` with `data1` /
42
/// `data2` and `inline` bytes after its fixed data, as the guest writes it.
43
17
fn output_one(value_type: ValueType, data1: i64, data2: i64, inline: &[u8]) -> Vec<u8> {
44
17
    output_run(&[(value_type, data1, data2, inline)])
45
17
}
46

            
47
/// An output buffer holding each of `items` as one debug value entity.
48
28
fn output_run(items: &[Item]) -> Vec<u8> {
49
28
    let mut header = OutputHeader::new(0);
50
28
    header.output_entity_count = u32::try_from(items.len()).unwrap_or(u32::MAX);
51
28
    let mut bytes = header.to_bytes().to_vec();
52
28
    for (value_type, data1, data2, inline) in items {
53
58
        let data_size = u32::try_from(DEBUG_VALUE_DATA_SIZE + inline.len()).unwrap_or(u32::MAX);
54
58
        let entity = EntityHeader {
55
58
            entity_type: EntityType::DebugValue as u8,
56
58
            operation: 0,
57
58
            flags: 0,
58
58
            reserved: [0],
59
58
            id: [0; 16],
60
58
            parent_idx: -1,
61
58
            data_offset: u32::try_from(bytes.len() + ENTITY_HEADER_SIZE).unwrap_or(u32::MAX),
62
58
            data_size,
63
58
        };
64
58
        bytes.extend_from_slice(&entity.to_bytes());
65
58
        let value = DebugValueData {
66
58
            value_type: *value_type as u8,
67
58
            reserved: [0; 7],
68
58
            data1: *data1,
69
58
            data2: *data2,
70
58
        };
71
58
        bytes.extend_from_slice(&value.to_bytes());
72
58
        bytes.extend_from_slice(inline);
73
    }
74
28
    bytes
75
28
}
76

            
77
10
fn symbol(name: &str) -> Item<'_> {
78
10
    (
79
10
        ValueType::Symbol,
80
10
        0,
81
10
        i64::try_from(name.len()).unwrap_or(i64::MAX),
82
10
        name.as_bytes(),
83
10
    )
84
10
}
85

            
86
6
fn number(n: i64) -> Item<'static> {
87
6
    (ValueType::Number, n, 1, &[])
88
6
}
89

            
90
2
fn scalar(numer: i64, denom: i64) -> Item<'static> {
91
2
    (ValueType::Scalar, numer, denom, &[])
92
2
}
93

            
94
17
fn tag(value_type: ValueType) -> Item<'static> {
95
17
    (value_type, 0, 0, &[])
96
17
}
97

            
98
10
fn printed(items: &[Item]) -> Result<String> {
99
10
    decode_result(&output_run(items)).map(|value| nomiscript::format_value(&value))
100
10
}
101

            
102
/// The money tag (plan 0014 Stage 1, ISS-018): numerator and denominator in
103
/// the data fields, the commodity id's high and low i64 halves inline, each
104
/// little-endian as the guest's `i64.store` writes them.
105
#[test]
106
1
fn atomic_money_decodes_with_its_commodity_id() {
107
1
    let id = uuid::Uuid::from_u128(0x0123_4567_89ab_cdef_0f1e_2d3c_4b5a_6978);
108
1
    let (hi, lo) = id.as_u64_pair();
109
1
    let mut inline = hi.to_le_bytes().to_vec();
110
1
    inline.extend_from_slice(&lo.to_le_bytes());
111
1
    let data = output_one(ValueType::Commodity, 3, 2, &inline);
112
1
    assert_eq!(
113
1
        decode_result(&data),
114
1
        Ok(Value::Commodity {
115
1
            amount: Fraction::new(3, 2),
116
1
            commodity_id: id,
117
1
        })
118
    );
119
1
    let truncated = output_one(ValueType::Commodity, 3, 2, &inline[..8]);
120
1
    assert!(matches!(
121
1
        decode_result(&truncated),
122
        Err(DecodeError::Malformed(_))
123
    ));
124
1
}
125

            
126
#[test]
127
1
fn a_non_positive_denominator_is_malformed_not_a_panic() {
128
1
    for value_type in [ValueType::Number, ValueType::Scalar, ValueType::Commodity] {
129
3
        for (numer, denom) in [(1, 0), (1, i64::MIN), (i64::MIN, -1)] {
130
9
            let data = output_one(value_type, numer, denom, &[0; 16]);
131
9
            assert_eq!(
132
9
                decode_result(&data),
133
9
                Err(DecodeError::Malformed(
134
9
                    "non-positive denominator".to_string()
135
9
                ))
136
            );
137
        }
138
    }
139
1
}
140

            
141
/// The entity tag (plan 0014 Stage 1, ISS-058): the kind's wire code alone,
142
/// decoded as the struct the eval-path plist names.
143
#[test]
144
1
fn an_entity_tag_decodes_as_its_kind() {
145
1
    for (kind, name) in [
146
1
        (EntityKind::Account, "account"),
147
1
        (EntityKind::Transaction, "transaction"),
148
1
        (EntityKind::Commodity, "commodity"),
149
1
        (EntityKind::Tag, "tag"),
150
1
    ] {
151
4
        let data = output_one(ValueType::Entity, kind.wire_code(), 0, &[]);
152
4
        assert_eq!(
153
4
            decode_result(&data),
154
4
            Ok(Value::Struct {
155
4
                name: name.to_string(),
156
4
                fields: Vec::new(),
157
4
            }),
158
            "{kind}"
159
        );
160
    }
161
1
    let condition = output_one(ValueType::Entity, EntityKind::Condition.wire_code(), 0, &[]);
162
1
    assert_eq!(decode_result(&condition), Ok(Value::Condition));
163
1
    let unknown = output_one(ValueType::Entity, 99, 0, &[]);
164
1
    assert!(matches!(
165
1
        decode_result(&unknown),
166
        Err(DecodeError::Malformed(_))
167
    ));
168
1
}
169

            
170
#[test]
171
1
fn a_nested_list_decodes_in_pre_order() {
172
1
    let data = output(&[
173
1
        debug(ValueType::List),
174
1
        debug(ValueType::Number),
175
1
        debug(ValueType::List),
176
1
        debug(ValueType::T),
177
1
        debug(ValueType::ListEnd),
178
1
        debug(ValueType::ListEnd),
179
1
    ]);
180
1
    let value = decode_result(&data).map(|value| nomiscript::format_value(&value));
181
1
    assert_eq!(value.ok().as_deref(), Some("(1 (t))"));
182
1
}
183

            
184
#[test]
185
1
fn other_entities_between_list_items_are_skipped() {
186
1
    let data = output(&[
187
1
        debug(ValueType::List),
188
1
        (EntityType::Tag, ValueType::Nil),
189
1
        debug(ValueType::T),
190
1
        debug(ValueType::ListEnd),
191
1
    ]);
192
1
    let value = decode_result(&data).map(|value| nomiscript::format_value(&value));
193
1
    assert_eq!(value.ok().as_deref(), Some("(t)"));
194
1
}
195

            
196
#[test]
197
1
fn the_last_complete_value_is_the_result() {
198
1
    let data = output(&[debug(ValueType::T), debug(ValueType::Nil)]);
199
1
    assert!(matches!(decode_result(&data), Ok(Value::Nil)));
200
1
}
201

            
202
#[test]
203
1
fn a_malformed_list_run_is_an_error() {
204
1
    for entities in [
205
1
        vec![debug(ValueType::List), debug(ValueType::T)],
206
1
        vec![debug(ValueType::ListEnd)],
207
1
    ] {
208
2
        assert!(matches!(
209
2
            decode_result(&output(&entities)),
210
            Err(DecodeError::Malformed(_))
211
        ));
212
    }
213
1
}
214

            
215
#[test]
216
1
fn an_output_without_a_debug_value_is_absent_not_malformed() {
217
1
    assert_eq!(
218
1
        decode_result(&output(&[(EntityType::Tag, ValueType::Nil)])),
219
1
        Err(DecodeError::Absent("no debug value in output"))
220
    );
221
1
    assert_eq!(
222
1
        decode_result(&output(&[])),
223
1
        Err(DecodeError::Absent("no output entities"))
224
    );
225
1
}
226

            
227
#[test]
228
1
fn the_output_region_stops_at_the_buffer_capacity() {
229
1
    let memory: Vec<u8> = (0..=255).collect();
230
1
    assert_eq!(output_region(&memory, 16, 8).ok(), Some(&memory[16..24]));
231
1
}
232

            
233
#[test]
234
1
fn an_output_region_outside_memory_is_an_error() {
235
1
    let memory = [0u8; 32];
236
1
    assert!(output_region(&memory, 16, 17).is_err());
237
1
    assert!(output_region(&memory, usize::MAX, 1).is_err());
238
1
}
239

            
240
/// A decodable value just past the capacity is not part of the result.
241
#[test]
242
1
fn a_value_written_past_the_capacity_is_not_decoded() {
243
1
    let bytes = output(&[(EntityType::DebugValue, ValueType::Nil)]);
244
1
    let region = output_region(&bytes, 0, OUTPUT_HEADER_SIZE + ENTITY_HEADER_SIZE);
245
1
    assert!(region.and_then(decode_result).is_err());
246
1
    assert!(decode_result(&bytes).is_ok());
247
1
}
248

            
249
#[test]
250
1
fn a_struct_run_decodes_to_a_named_struct_printed_as_cl() {
251
1
    let run = [
252
1
        tag(ValueType::Struct),
253
1
        symbol("PT"),
254
1
        symbol(":X"),
255
1
        number(8),
256
1
        tag(ValueType::ListEnd),
257
1
    ];
258
1
    assert_eq!(printed(&run).as_deref(), Ok("#S(PT :X 8)"));
259
1
    let decoded = decode_result(&output_run(&run));
260
1
    assert_eq!(
261
1
        decoded,
262
1
        Ok(Value::Struct {
263
1
            name: "PT".to_string(),
264
1
            fields: vec![("X".to_string(), Value::Number(Number::Index(8)))],
265
1
        })
266
    );
267
1
}
268

            
269
#[test]
270
1
fn nested_structs_and_nil_fields_print_as_cl() {
271
1
    let run = [
272
1
        tag(ValueType::List),
273
1
        tag(ValueType::Struct),
274
1
        symbol("BOX2"),
275
1
        symbol(":INNER"),
276
1
        tag(ValueType::Struct),
277
1
        symbol("PT"),
278
1
        symbol(":X"),
279
1
        number(8),
280
1
        tag(ValueType::ListEnd),
281
1
        symbol(":TAIL"),
282
1
        tag(ValueType::Nil),
283
1
        tag(ValueType::ListEnd),
284
1
        tag(ValueType::ListEnd),
285
1
    ];
286
1
    assert_eq!(
287
1
        printed(&run).as_deref(),
288
1
        Ok("(#S(BOX2 :INNER #S(PT :X 8) :TAIL nil))")
289
    );
290
1
}
291

            
292
#[test]
293
1
fn a_struct_without_a_name_or_a_field_value_is_malformed() {
294
1
    for run in [
295
1
        vec![tag(ValueType::Struct), tag(ValueType::ListEnd)],
296
1
        vec![tag(ValueType::Struct), number(1), tag(ValueType::ListEnd)],
297
1
        vec![
298
1
            tag(ValueType::Struct),
299
1
            symbol("PT"),
300
1
            number(1),
301
1
            number(2),
302
1
            tag(ValueType::ListEnd),
303
1
        ],
304
1
        vec![
305
1
            tag(ValueType::Struct),
306
1
            symbol("PT"),
307
1
            symbol(":X"),
308
1
            tag(ValueType::ListEnd),
309
1
        ],
310
1
    ] {
311
4
        assert!(matches!(printed(&run), Err(DecodeError::Malformed(_))));
312
    }
313
1
}
314

            
315
#[test]
316
1
fn an_index_and_a_scalar_print_with_their_kind() {
317
1
    assert_eq!(printed(&[number(2)]), Ok("2".to_string()));
318
1
    assert_eq!(printed(&[scalar(2, 1)]), Ok("2/1".to_string()));
319
1
    assert_eq!(printed(&[scalar(1, 4)]), Ok("1/4".to_string()));
320
1
}
321

            
322
#[test]
323
1
fn an_index_with_a_denominator_is_malformed() {
324
1
    let run = [(ValueType::Number, 1, 2, &[][..])];
325
1
    assert_eq!(
326
1
        printed(&run),
327
1
        Err(DecodeError::Malformed(
328
1
            "index with a denominator".to_string()
329
1
        ))
330
    );
331
1
}