arora-buffers 2.1.0

Binary read/write buffers and type tags for the Arora module value ABI.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! `Value` ⇄ buffer bytes, **borrowing and zero-copy** — the counterpart of
//! [`crate::froto_value`] for callers that want to read without copying.
//!
//! Its `Value<'a>` is a *local, slimmer* mirror of `arora_types::Value`: ids stay
//! raw `Cow<[u8]>` (never parsed to `Uuid`), and numeric arrays / strings borrow
//! straight out of the buffer (`Cow<[f64]>` via the zero-copy bulk readers)
//! instead of copying. That borrowing read is the whole reason to reach for it —
//! e.g. handing an `f64[]` to a GPU consumer. It carries *less* than the
//! canonical `Value`: no option, map, uuid, error or mixed-type array.
//!
//! It also derives `serde`, so the same `Value<'a>` round-trips through YAML/JSON
//! — a separate hat from the buffer path, independent of it (that coverage also
//! lives on the canonical `arora_types::Value`). See the crate README for how it
//! sits next to `froto_value` / `froto_serde` / `froto_checked_value`.

use serde::{Deserialize, Serialize};
use std::borrow::Cow;

use crate::{
    reader::BufferReader, writer::BufferWriter, TYPE_ARRAY, TYPE_BOOLEAN, TYPE_ENUMERATION,
    TYPE_F32, TYPE_F64, TYPE_I16, TYPE_I32, TYPE_I64, TYPE_I8, TYPE_STRING, TYPE_STRUCTURE,
    TYPE_U16, TYPE_U32, TYPE_U64, TYPE_U8, TYPE_UNIT,
};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StructureField<'a> {
    pub id: Cow<'a, [u8]>,
    pub value: Value<'a>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Structure<'a> {
    pub id: Cow<'a, [u8]>,
    pub fields: Vec<StructureField<'a>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StructureRaw<'a> {
    pub fields: Vec<StructureField<'a>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Enumeration<'a> {
    pub id: Cow<'a, [u8]>,
    pub variant_id: Cow<'a, [u8]>,
    pub value: Box<Value<'a>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EnumerationRaw<'a> {
    pub variant_id: Cow<'a, [u8]>,
    pub value: Box<Value<'a>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Value<'a> {
    #[serde(rename = "unit")]
    Unit,
    #[serde(rename = "bool")]
    Boolean(bool),
    #[serde(rename = "u8")]
    U8(u8),
    #[serde(rename = "u16")]
    U16(u16),
    #[serde(rename = "u32")]
    U32(u32),
    #[serde(rename = "u64")]
    U64(u64),
    #[serde(rename = "i8")]
    I8(i8),
    #[serde(rename = "i16")]
    I16(i16),
    #[serde(rename = "i32")]
    I32(i32),
    #[serde(rename = "i64")]
    I64(i64),
    #[serde(rename = "f32")]
    F32(f32),
    #[serde(rename = "f64")]
    F64(f64),
    #[serde(rename = "str")]
    String(Cow<'a, str>),
    #[serde(rename = "struct")]
    Structure(Structure<'a>),
    #[serde(rename = "enum")]
    Enumeration(Enumeration<'a>),
    #[serde(rename = "bool[]")]
    ArrayBoolean(Cow<'a, [bool]>),
    #[serde(rename = "u8[]")]
    ArrayU8(Cow<'a, [u8]>),
    #[serde(rename = "u16[]")]
    ArrayU16(Cow<'a, [u16]>),
    #[serde(rename = "u32[]")]
    ArrayU32(Cow<'a, [u32]>),
    #[serde(rename = "u64[]")]
    ArrayU64(Cow<'a, [u64]>),
    #[serde(rename = "i8[]")]
    ArrayI8(Cow<'a, [i8]>),
    #[serde(rename = "i16[]")]
    ArrayI16(Cow<'a, [i16]>),
    #[serde(rename = "i32[]")]
    ArrayI32(Cow<'a, [i32]>),
    #[serde(rename = "i64[]")]
    ArrayI64(Cow<'a, [i64]>),
    #[serde(rename = "f32[]")]
    ArrayF32(Cow<'a, [f32]>),
    #[serde(rename = "f64[]")]
    ArrayF64(Cow<'a, [f64]>),
    #[serde(rename = "str[]")]
    ArrayString(Vec<Cow<'a, str>>),
    #[serde(rename = "struct[]")]
    ArrayStructure(Cow<'a, [u8]>, Vec<StructureRaw<'a>>),
    #[serde(rename = "enum[]")]
    ArrayEnumeration(Cow<'a, [u8]>, Vec<EnumerationRaw<'a>>),
}

impl<'a> Value<'a> {
    unsafe fn deserialize_reader(reader: &mut BufferReader<'a>) -> Value<'a> {
        match reader.next_type() {
            Some(TYPE_UNIT) => Value::Unit,
            Some(TYPE_BOOLEAN) => Value::Boolean(reader.get_boolean()),
            Some(TYPE_U8) => Value::U8(reader.get_u8()),
            Some(TYPE_U16) => Value::U16(reader.get_u16()),
            Some(TYPE_U32) => Value::U32(reader.get_u32()),
            Some(TYPE_U64) => Value::U64(reader.get_u64()),
            Some(TYPE_I8) => Value::I8(reader.get_i8()),
            Some(TYPE_I16) => Value::I16(reader.get_i16()),
            Some(TYPE_I32) => Value::I32(reader.get_i32()),
            Some(TYPE_I64) => Value::I64(reader.get_i64()),
            Some(TYPE_F32) => Value::F32(reader.get_f32()),
            Some(TYPE_F64) => Value::F64(reader.get_f64()),
            Some(TYPE_STRING) => Value::String(reader.get_string().into()),
            Some(TYPE_STRUCTURE) => {
                let (id, field_count) = reader.get_structure();
                let mut fields = Vec::with_capacity(field_count as usize);
                for _ in 0..field_count {
                    let field_id = reader.get_structure_field();
                    fields.push(StructureField {
                        id: field_id.into(),
                        value: Value::deserialize_reader(reader),
                    });
                }
                Value::Structure(Structure {
                    id: id.into(),
                    fields,
                })
            }
            Some(TYPE_ENUMERATION) => Value::Enumeration(Enumeration {
                id: reader.get_structure_field().into(),
                variant_id: reader.get_enumeration_value_raw().into(),
                value: Box::new(Value::deserialize_reader(reader)),
            }),
            Some(TYPE_ARRAY) => {
                let (ty, count) = reader.get_array();
                match ty {
                    TYPE_BOOLEAN => {
                        Value::ArrayBoolean(reader.get_boolean_bulk(count as usize).into())
                    }
                    TYPE_U8 => Value::ArrayU8(reader.get_u8_bulk(count as usize).into()),
                    TYPE_U16 => Value::ArrayU16(reader.get_u16_bulk(count as usize).into()),
                    TYPE_U32 => Value::ArrayU32(reader.get_u32_bulk(count as usize).into()),
                    TYPE_U64 => Value::ArrayU64(reader.get_u64_bulk(count as usize).into()),
                    TYPE_I8 => Value::ArrayI8(reader.get_i8_bulk(count as usize).into()),
                    TYPE_I16 => Value::ArrayI16(reader.get_i16_bulk(count as usize).into()),
                    TYPE_I32 => Value::ArrayI32(reader.get_i32_bulk(count as usize).into()),
                    TYPE_I64 => Value::ArrayI64(reader.get_i64_bulk(count as usize).into()),
                    TYPE_F32 => Value::ArrayF32(reader.get_f32_bulk(count as usize).into()),
                    TYPE_F64 => Value::ArrayF64(reader.get_f64_bulk(count as usize).into()),
                    TYPE_STRING => Value::ArrayString({
                        let mut strings = Vec::with_capacity(count as usize);
                        for _ in 0..count {
                            strings.push(reader.get_string().into());
                        }
                        strings
                    }),
                    TYPE_STRUCTURE => {
                        let mut structures = Vec::with_capacity(count as usize);
                        let structure_id = reader.get_structure_field();
                        for _ in 0..count {
                            let field_count = reader.get_structure_raw();
                            let mut fields = Vec::with_capacity(field_count as usize);
                            for _ in 0..field_count {
                                let field_id = reader.get_structure_field();
                                fields.push(StructureField {
                                    id: field_id.into(),
                                    value: Value::deserialize_reader(reader),
                                });
                            }
                            structures.push(StructureRaw { fields });
                        }
                        Value::ArrayStructure(structure_id.into(), structures)
                    }
                    TYPE_ENUMERATION => {
                        let mut enumerations = Vec::with_capacity(count as usize);
                        let enumeration_id = reader.get_structure_field();
                        for _ in 0..count {
                            let variant_id = reader.get_enumeration_value_raw();
                            enumerations.push(EnumerationRaw {
                                variant_id: variant_id.into(),
                                value: Box::new(Value::deserialize_reader(reader)),
                            });
                        }
                        Value::ArrayEnumeration(enumeration_id.into(), enumerations)
                    }
                    _ => panic!("unsupported array type"),
                }
            }
            _ => panic!("Invalid type"),
        }
    }

    pub unsafe fn deserialize(data: &'a [u8]) -> Value<'a> {
        let mut reader = BufferReader::new(data);
        Self::deserialize_reader(&mut reader)
    }

    fn serialize_writer(&self, writer: &mut BufferWriter) {
        match self {
            Value::Unit => writer.add_unit(),
            Value::Boolean(b) => writer.add_boolean(*b),
            Value::U8(v) => writer.add_u8(*v),
            Value::U16(v) => writer.add_u16(*v),
            Value::U32(v) => writer.add_u32(*v),
            Value::U64(v) => writer.add_u64(*v),
            Value::I8(v) => writer.add_i8(*v),
            Value::I16(v) => writer.add_i16(*v),
            Value::I32(v) => writer.add_i32(*v),
            Value::I64(v) => writer.add_i64(*v),
            Value::F32(v) => writer.add_f32(*v),
            Value::F64(v) => writer.add_f64(*v),
            Value::String(v) => writer.add_string(v),
            Value::Structure(v) => {
                writer.begin_structure(&v.id, v.fields.len() as u32);
                for field in &v.fields {
                    writer.add_structure_field(&field.id);
                    field.value.serialize_writer(writer);
                }
            }
            Value::Enumeration(v) => {
                writer.add_enumeration_value(&v.id, &v.variant_id);
                v.value.serialize_writer(writer);
            }
            Value::ArrayBoolean(v) => {
                writer.add_array_primitive(TYPE_BOOLEAN, v.len() as u32);
                writer.add_boolean_raw_bulk(v);
            }
            Value::ArrayU8(v) => {
                writer.add_array_primitive(TYPE_U8, v.len() as u32);
                writer.add_u8_raw_bulk(v);
            }
            Value::ArrayU16(v) => {
                writer.add_array_primitive(TYPE_U16, v.len() as u32);
                writer.add_u16_raw_bulk(v);
            }
            Value::ArrayU32(v) => {
                writer.add_array_primitive(TYPE_U32, v.len() as u32);
                writer.add_u32_raw_bulk(v);
            }
            Value::ArrayU64(v) => {
                writer.add_array_primitive(TYPE_U64, v.len() as u32);
                writer.add_u64_raw_bulk(v);
            }
            Value::ArrayI8(v) => {
                writer.add_array_primitive(TYPE_I8, v.len() as u32);
                writer.add_i8_raw_bulk(v);
            }
            Value::ArrayI16(v) => {
                writer.add_array_primitive(TYPE_I16, v.len() as u32);
                writer.add_i16_raw_bulk(v);
            }
            Value::ArrayI32(v) => {
                writer.add_array_primitive(TYPE_I32, v.len() as u32);
                writer.add_i32_raw_bulk(v);
            }
            Value::ArrayI64(v) => {
                writer.add_array_primitive(TYPE_I64, v.len() as u32);
                writer.add_i64_raw_bulk(v);
            }
            Value::ArrayF32(v) => {
                writer.add_array_primitive(TYPE_F32, v.len() as u32);
                writer.add_f32_raw_bulk(v);
            }
            Value::ArrayF64(v) => {
                writer.add_array_primitive(TYPE_F64, v.len() as u32);
                writer.add_f64_raw_bulk(v);
            }
            Value::ArrayString(v) => {
                writer.add_array_primitive(TYPE_STRING, v.len() as u32);
                for s in v {
                    // Untagged: the element type is `TYPE_STRING` from the array
                    // head, and the reader reads bare strings (no per-element
                    // tag). `add_string` would double the tag and never round-trip.
                    writer.add_string_raw(s);
                }
            }
            Value::ArrayStructure(id, v) => {
                writer.add_array_structure(id, v.len() as u32);
                for structure in v {
                    writer.begin_structure_raw(structure.fields.len() as u32);
                    for field in &structure.fields {
                        writer.add_structure_field(&field.id);
                        field.value.serialize_writer(writer);
                    }
                }
            }
            Value::ArrayEnumeration(id, v) => {
                writer.add_array_enumeration(id, v.len() as u32);
                for enumeration in v {
                    writer.add_enumeration_value_raw(&enumeration.variant_id);
                    enumeration.value.serialize_writer(writer);
                }
            }
        }
    }

    pub fn serialize(&self) -> Box<[u8]> {
        let mut writer = BufferWriter::new();
        self.serialize_writer(&mut writer);
        writer.finalize()
    }
}

// Tests.
//=====================================================================
#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::{bail, Result};
    use std::borrow::Cow;

    #[test]
    pub fn u8_yaml() -> Result<()> {
        let de = serde_yaml::Deserializer::from_str(U8_YAML);
        if let Value::U8(value) = serde_yaml::with::singleton_map_recursive::deserialize(de)? {
            assert_eq!(42, value);
        } else {
            bail!("parsed value was not an u8");
        }
        Ok(())
    }

    #[test]
    // The literals are arbitrary sample values for round-tripping an f32 array,
    // not intended to be std::f32::consts::PI / E.
    #[allow(clippy::approx_constant)]
    pub fn array_f32_yaml() -> Result<()> {
        let de = serde_yaml::Deserializer::from_str(ARRAY_F32_YAML);
        if let Value::ArrayF32(values) = serde_yaml::with::singleton_map_recursive::deserialize(de)?
        {
            assert_eq!(vec![3.14159, 2.718, 1.618], values.to_vec());
        } else {
            bail!("parsed value was not an array of f32");
        }
        Ok(())
    }

    // --- buffer round-trip: froto_borrowed_value's actual job -----------------

    fn id16(n: u8) -> Cow<'static, [u8]> {
        Cow::Owned(vec![n; 16])
    }

    fn round_trip(value: Value) {
        let bytes = value.serialize();
        let back = unsafe { Value::deserialize(&bytes) };
        assert_eq!(back, value, "buffer round-trip mismatch");
    }

    #[test]
    fn scalars_round_trip_through_the_buffer() {
        for value in [
            Value::Unit,
            Value::Boolean(true),
            Value::Boolean(false),
            Value::U8(42),
            Value::I32(-7),
            Value::F64(2.5),
            Value::String(Cow::Borrowed("hello")),
        ] {
            round_trip(value);
        }
    }

    #[test]
    fn arrays_round_trip_through_the_buffer() {
        for value in [
            Value::ArrayF64(Cow::Owned(vec![1.0, -2.0, 3.5])),
            Value::ArrayU8(Cow::Owned(vec![1, 2, 3, 4, 5])),
            Value::ArrayBoolean(Cow::Owned(vec![true, false, true])),
            Value::ArrayString(vec![
                Cow::Borrowed("a"),
                Cow::Borrowed(""),
                Cow::Borrowed("cee"),
            ]),
        ] {
            round_trip(value);
        }
    }

    #[test]
    fn structure_round_trips_through_the_buffer() {
        round_trip(Value::Structure(Structure {
            id: id16(0x10),
            fields: vec![
                StructureField {
                    id: id16(0x01),
                    value: Value::I32(7),
                },
                StructureField {
                    id: id16(0x02),
                    value: Value::String(Cow::Borrowed("field")),
                },
            ],
        }));
    }

    #[test]
    fn structure_array_round_trips_through_the_buffer() {
        let element = |x| StructureRaw {
            fields: vec![StructureField {
                id: id16(0x01),
                value: Value::F64(x),
            }],
        };
        round_trip(Value::ArrayStructure(
            id16(0x20),
            vec![element(1.0), element(2.0)],
        ));
    }

    #[test]
    fn enumeration_round_trips_through_the_buffer() {
        round_trip(Value::Enumeration(Enumeration {
            id: id16(0x30),
            variant_id: id16(0x31),
            value: Box::new(Value::U32(99)),
        }));
    }

    #[test]
    fn array_inside_a_struct_round_trips() {
        // A numeric-array field followed by another field: proves the bulk read
        // advances the cursor, so the trailing field reads from the right place.
        round_trip(Value::Structure(Structure {
            id: id16(0x40),
            fields: vec![
                StructureField {
                    id: id16(0x01),
                    value: Value::ArrayF64(Cow::Owned(vec![1.0, 2.0, 3.0])),
                },
                StructureField {
                    id: id16(0x02),
                    value: Value::U32(7),
                },
            ],
        }));
    }

    pub const U8_YAML: &str = "\
u8: 42
";

    pub const ARRAY_F32_YAML: &str = "\
f32[]: [3.14159, 2.718, 1.618]
";
}