yog-data 0.8.3

Yog Data — the one data model, text syntax, binary form and schema system of every Yog format.
Documentation
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! The schemas of plain types: numbers, strings, lists, maps.
use super::{
    BTreeMap, Decoder, HashMap, Packer, Reader, Schema, Seg, Shape, Unpacker, Value, ValueRef,
    Writer, is_metadata_key, typed,
};

/// What a typed value's string starts with (`@item:…`).
fn typed_mark() -> char {
    yog_ids::sep::TYPED.chars().next().unwrap_or_default()
}

// ── Plain types ─────────────────────────────────────────────────────────────

impl Schema for Value {
    fn shape() -> Shape {
        Shape::Any
    }
    fn read(v: &ValueRef<'_>, _: &mut Reader) -> Option<Self> {
        Some(v.to_value())
    }
    fn write(&self) -> Value {
        self.clone()
    }
}

impl Schema for bool {
    fn shape() -> Shape {
        Shape::Bool
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        v.as_bool().or_else(|| {
            cx.expected("true or false", v);
            None
        })
    }
    fn write(&self) -> Value {
        Value::Bool(*self)
    }
    fn encode(&self, w: &mut Writer) {
        w.bool(*self);
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        d.bool()
    }
    fn pack(&self, p: &mut Packer) {
        p.put_bool(*self);
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        u.get_bool()
    }
}

macro_rules! int_schema {
    ($($t:ty => $to_bits:ident, $of_bits:ident);*) => {$(
        impl Schema for $t {
            fn shape() -> Shape {
                Shape::Int { min: <$t>::MIN as i64, max: (<$t>::MAX as u64).min(i64::MAX as u64) as i64 }
            }
            fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
                let Some(n) = v.as_i64() else {
                    cx.expected("an integer", v);
                    return None;
                };
                <$t>::try_from(n).ok().or_else(|| {
                    cx.problem(format!("{n} is out of range ({}..={})", <$t>::MIN, <$t>::MAX));
                    None
                })
            }
            fn write(&self) -> Value {
                Value::Int(*self as i64)
            }
            fn encode(&self, w: &mut Writer) {
                w.int(*self as i64);
            }
            fn decode(d: &mut Decoder<'_>) -> Option<Self> {
                d.int().and_then(|n| <$t>::try_from(n).ok())
            }
            fn pack(&self, p: &mut Packer) {
                p.put_i(*self as i64);
            }
            fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
                u.get_i().and_then(|n| <$t>::try_from(n).ok())
            }
            fn pack_list(items: &[Self], p: &mut Packer) {
                p.put_uints(items.len(), items.iter().map(|&n| $to_bits(n as i128)));
            }
            fn unpack_list(u: &mut Unpacker<'_>) -> Option<Vec<Self>> {
                u.get_uints(|v| <$t>::try_from($of_bits(v)).ok())
            }
            fn encode_list(items: &[Self], w: &mut Writer) {
                w.ints(items.iter().map(|&n| n as i64));
            }
            fn decode_list(d: &mut Decoder<'_>) -> Option<Vec<Self>> {
                let n = d.ints()?;
                let mut out = Vec::with_capacity(n);
                for _ in 0..n {
                    out.push(<$t>::try_from(d.packed_int()?).ok()?);
                }
                Some(out)
            }
        }
    )*};
}
int_schema!(
    i8 => signed_bits, signed_of; i16 => signed_bits, signed_of; i32 => signed_bits, signed_of; i64 => signed_bits, signed_of;
    u8 => unsigned_bits, unsigned_of; u16 => unsigned_bits, unsigned_of; u32 => unsigned_bits, unsigned_of;
    u64 => unsigned_bits, unsigned_of; usize => unsigned_bits, unsigned_of
);

/// A signed number as a bit-packed list's bits: zigzagged, small either way.
fn signed_bits(n: i128) -> u64 {
    crate::binary::zigzag(n as i64)
}

fn signed_of(v: u64) -> i128 {
    i128::from(crate::binary::unzigzag(v))
}

/// An unsigned number as a bit-packed list's bits: itself.
fn unsigned_bits(n: i128) -> u64 {
    n as u64
}

fn unsigned_of(v: u64) -> i128 {
    i128::from(v)
}

macro_rules! float_schema {
    ($($t:ty => $one:ident, $many:ident, $read_many:ident, $put:ident, $get:ident, $puts:ident, $gets:ident);*) => {$(
        impl Schema for $t {
            fn shape() -> Shape {
                Shape::Float { bits: u8::BITS * std::mem::size_of::<$t>() as u32 }
            }
            fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
                v.as_f64().map(|f| f as $t).or_else(|| {
                    cx.expected("a number", v);
                    None
                })
            }
            fn write(&self) -> Value {
                Value::Float(*self as f64)
            }
            fn encode(&self, w: &mut Writer) {
                w.$one(*self);
            }
            fn decode(d: &mut Decoder<'_>) -> Option<Self> {
                d.float().map(|f| f as $t)
            }
            fn encode_list(items: &[Self], w: &mut Writer) {
                w.$many(items);
            }
            fn decode_list(d: &mut Decoder<'_>) -> Option<Vec<Self>> {
                d.$read_many()
            }
            fn pack(&self, p: &mut Packer) {
                p.$put(*self);
            }
            fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
                u.$get()
            }
            fn pack_list(items: &[Self], p: &mut Packer) {
                p.$puts(items);
            }
            fn unpack_list(u: &mut Unpacker<'_>) -> Option<Vec<Self>> {
                u.$gets()
            }
        }
    )*};
}
float_schema!(
    f32 => float32, floats32, floats32, put_f32, get_f32, put_f32s, get_f32s;
    f64 => float, floats, floats, put_f64, get_f64, put_f64s, get_f64s
);

impl Schema for String {
    fn shape() -> Shape {
        Shape::Str
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        match v {
            // Plain text, the usual case: copied once, into the result.
            ValueRef::Str(s) if !s.starts_with('@') => Some(s.to_string()),
            ValueRef::Str(s) => match typed::classify(s) {
                Ok(Value::Str(s)) => Some(s),
                Ok(other) => {
                    cx.problem(format!(
                        "expected plain text, found {} (write `@@` for a literal `@`)",
                        other.kind_name()
                    ));
                    None
                }
                Err(e) => {
                    cx.problem_of(yog_ids::data_problem::BAD_TYPED, e);
                    None
                }
            },
            other => {
                cx.expected("a string", other);
                None
            }
        }
    }
    fn write(&self) -> Value {
        Value::Str(self.clone())
    }
    fn encode(&self, w: &mut Writer) {
        w.str(self);
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        // A typed value (`@…`) is the slow way's to tell apart.
        d.str()
            .filter(|s| !s.starts_with(typed_mark()))
            .map(str::to_owned)
    }
    fn pack(&self, p: &mut Packer) {
        p.put_str(self);
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        u.get_str().map(str::to_owned)
    }
}

/// Text that may be a constant: borrowed where it's written, owned once read.
impl Schema for std::borrow::Cow<'static, str> {
    fn shape() -> Shape {
        Shape::Str
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        String::read(v, cx).map(Self::Owned)
    }
    fn write(&self) -> Value {
        Value::Str(self.to_string())
    }
    fn encode(&self, w: &mut Writer) {
        w.str(self);
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        String::decode(d).map(Self::Owned)
    }
    fn pack(&self, p: &mut Packer) {
        p.put_str(self);
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        String::unpack(u).map(Self::Owned)
    }
}

/// A file's path, as text (a path that isn't Unicode loses what isn't).
impl Schema for std::path::PathBuf {
    fn shape() -> Shape {
        Shape::Str
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        String::read(v, cx).map(Self::from)
    }
    fn write(&self) -> Value {
        Value::Str(self.to_string_lossy().into_owned())
    }
    fn encode(&self, w: &mut Writer) {
        w.str(&self.to_string_lossy());
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        String::decode(d).map(Self::from)
    }
    fn pack(&self, p: &mut Packer) {
        p.put_str(&self.to_string_lossy());
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        u.get_str().map(Self::from)
    }
}

/// Text everywhere but in a frame, which carries its number.
impl Schema for crate::Atom {
    fn shape() -> Shape {
        Shape::Atom
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        String::read(v, cx).map(|s| crate::Atom::new(&s))
    }
    fn write(&self) -> Value {
        Value::Str(self.as_str().to_owned())
    }
    fn encode(&self, w: &mut Writer) {
        w.str(self.as_str());
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        d.str()
            .filter(|s| !s.starts_with(typed_mark()))
            .map(crate::Atom::new)
    }
    fn pack(&self, p: &mut Packer) {
        p.put_u(u64::from(self.number()));
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        crate::Atom::from_number(u32::try_from(u.get_u()?).ok()?)
    }
}

impl<T: Schema> Schema for Option<T> {
    fn shape() -> Shape {
        Shape::Optional(T::shape)
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        if v.is_null() {
            Some(None)
        } else {
            T::read(v, cx).map(Some)
        }
    }
    fn write(&self) -> Value {
        self.as_ref().map_or(Value::Null, T::write)
    }
    fn encode(&self, w: &mut Writer) {
        match self {
            Some(v) => v.encode(w),
            None => {
                w.null();
            }
        }
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        if d.null() {
            Some(None)
        } else {
            T::decode(d).map(Some)
        }
    }
    fn pack(&self, p: &mut Packer) {
        p.put_bool(self.is_some());
        if let Some(v) = self {
            v.pack(p);
        }
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        if u.get_bool()? {
            T::unpack(u).map(Some)
        } else {
            Some(None)
        }
    }
    fn absent() -> Option<Self> {
        Some(None)
    }
    fn skip(&self) -> bool {
        self.is_none()
    }
}

impl<T: Schema> Schema for Box<T> {
    fn shape() -> Shape {
        T::shape()
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        T::read(v, cx).map(Box::new)
    }
    fn write(&self) -> Value {
        (**self).write()
    }
    fn encode(&self, w: &mut Writer) {
        (**self).encode(w);
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        T::decode(d).map(Box::new)
    }
    fn pack(&self, p: &mut Packer) {
        (**self).pack(p);
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        T::unpack(u).map(Box::new)
    }
    fn absent() -> Option<Self> {
        T::absent().map(Box::new)
    }
    fn skip(&self) -> bool {
        (**self).skip()
    }
}

impl<T: Schema> Schema for Vec<T> {
    fn shape() -> Shape {
        Shape::List(T::shape)
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        let ValueRef::List(items) = v else {
            cx.expected("a list", v);
            return None;
        };
        let mut out = Vec::with_capacity(items.len());
        let mut ok = true;
        for (i, item) in items.iter().enumerate() {
            match cx.at(Seg::Index(i), |cx| T::read(item, cx)) {
                Some(x) => out.push(x),
                None => ok = false,
            }
        }
        ok.then_some(out)
    }
    fn write(&self) -> Value {
        Value::List(self.iter().map(T::write).collect())
    }
    fn encode(&self, w: &mut Writer) {
        T::encode_list(self, w);
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        T::decode_list(d)
    }
    fn pack(&self, p: &mut Packer) {
        T::pack_list(self, p);
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        T::unpack_list(u)
    }
}

/// A set: a list, in order, each once.
impl<T: Schema + Ord + Clone> Schema for std::collections::BTreeSet<T> {
    fn shape() -> Shape {
        Shape::List(T::shape)
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        Vec::<T>::read(v, cx).map(Self::from_iter)
    }
    fn write(&self) -> Value {
        Value::List(self.iter().map(T::write).collect())
    }
    fn encode(&self, w: &mut Writer) {
        // As a list of them is written (numbers packed).
        T::encode_list(&self.iter().cloned().collect::<Vec<_>>(), w);
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        Vec::<T>::decode(d).map(Self::from_iter)
    }
}

/// A string that won't change: a pointer and a length, no spare capacity
/// (`String`'s third word) — what big tables of names keep.
impl Schema for Box<str> {
    fn shape() -> Shape {
        Shape::Str
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        String::read(v, cx).map(String::into_boxed_str)
    }
    fn write(&self) -> Value {
        Value::Str(self.to_string())
    }
    fn encode(&self, w: &mut Writer) {
        w.str(self);
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        String::decode(d).map(String::into_boxed_str)
    }
    fn pack(&self, p: &mut Packer) {
        p.put_str(self);
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        u.get_str().map(Into::into)
    }
}

/// A string shared without copying.
impl Schema for yog_sync::Arc<str> {
    fn shape() -> Shape {
        Shape::Str
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        String::read(v, cx).map(Into::into)
    }
    fn write(&self) -> Value {
        Value::Str(self.to_string())
    }
    fn encode(&self, w: &mut Writer) {
        w.str(self);
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        String::decode(d).map(Into::into)
    }
    fn pack(&self, p: &mut Packer) {
        p.put_str(self);
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        u.get_shared_str()
    }
}

/// A list that won't change: no spare capacity.
impl<T: Schema> Schema for Box<[T]> {
    fn shape() -> Shape {
        Shape::List(T::shape)
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        Vec::<T>::read(v, cx).map(Vec::into_boxed_slice)
    }
    fn write(&self) -> Value {
        Value::List(self.iter().map(T::write).collect())
    }
    fn encode(&self, w: &mut Writer) {
        T::encode_list(self, w);
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        T::decode_list(d).map(Vec::into_boxed_slice)
    }
    fn pack(&self, p: &mut Packer) {
        T::pack_list(self, p);
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        T::unpack_list(u).map(Vec::into_boxed_slice)
    }
}

impl<T: Schema, const N: usize> Schema for [T; N] {
    fn shape() -> Shape {
        Shape::List(T::shape)
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        let items = Vec::<T>::read(v, cx)?;
        let len = items.len();
        items.try_into().ok().or_else(|| {
            cx.problem(format!("expected {N} items, found {len}"));
            None
        })
    }
    fn write(&self) -> Value {
        Value::List(self.iter().map(T::write).collect())
    }
    fn encode(&self, w: &mut Writer) {
        T::encode_list(self, w);
    }
    fn decode(d: &mut Decoder<'_>) -> Option<Self> {
        T::decode_list(d)?.try_into().ok()
    }
    fn pack(&self, p: &mut Packer) {
        T::pack_list(self, p);
    }
    fn unpack(u: &mut Unpacker<'_>) -> Option<Self> {
        T::unpack_list(u)?.try_into().ok()
    }
}

/// Nothing: what a call answers when it only says it's done.
impl Schema for () {
    fn shape() -> Shape {
        Shape::Any
    }
    fn read(_v: &ValueRef<'_>, _cx: &mut Reader) -> Option<Self> {
        Some(())
    }
    fn write(&self) -> Value {
        Value::Null
    }
}

/// What may fail: `{ "ok": T }` or `{ "err": E }`.
impl<T: Schema, E: Schema> Schema for Result<T, E> {
    fn shape() -> Shape {
        Shape::Any
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        let ValueRef::Map(m) = v else {
            cx.expected("{ ok } or { err }", v);
            return None;
        };
        if let Some(ok) = m.get(RESULT_OK) {
            return cx
                .at(Seg::Key(RESULT_OK.into()), |cx| T::read(ok, cx))
                .map(Ok);
        }
        let Some(err) = m.get(RESULT_ERR) else {
            cx.expected("{ ok } or { err }", v);
            return None;
        };
        cx.at(Seg::Key(RESULT_ERR.into()), |cx| E::read(err, cx))
            .map(Err)
    }
    fn write(&self) -> Value {
        let (key, value) = match self {
            Ok(t) => (RESULT_OK, t.write()),
            Err(e) => (RESULT_ERR, e.write()),
        };
        Value::Map([(key.to_owned(), value)].into_iter().collect())
    }
}

/// The keys of a [`Result`]'s two sides.
pub(crate) const RESULT_OK: &str = "ok";
pub(crate) const RESULT_ERR: &str = "err";

/// A tuple, written as a list of its items in order: a pair `[a, b]` (a
/// point, a size), a triple `[x, y, z]` (a position).
macro_rules! tuples {
    ($($what:literal: $n:literal => ($($t:ident $i:tt),+);)+) => {$(
        impl<$($t: Schema),+> Schema for ($($t,)+) {
            fn shape() -> Shape {
                Shape::List(Value::shape)
            }
            fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
                let ValueRef::List(items) = v else {
                    cx.expected($what, v);
                    return None;
                };
                if items.len() != $n {
                    cx.problem(format!("expected {} items, found {}", $n, items.len()));
                    return None;
                }
                let read = ($(cx.at(Seg::Index($i), |cx| $t::read(&items[$i], cx)),)+);
                Some(($(read.$i?,)+))
            }
            fn write(&self) -> Value {
                Value::List(vec![$(self.$i.write()),+])
            }
        }
    )+};
}

tuples! {
    "a pair [a, b]": 2 => (A 0, B 1);
    "a triple [a, b, c]": 3 => (A 0, B 1, C 2);
    "four [a, b, c, d]": 4 => (A 0, B 1, C 2, D 3);
}

fn read_map<T: Schema>(
    v: &ValueRef,
    cx: &mut Reader,
    mut put: impl FnMut(String, T),
) -> Option<()> {
    let map = cx.map(v)?;
    let mut ok = true;
    for (k, item) in map.iter() {
        if is_metadata_key(k) {
            continue;
        }
        match cx.at(Seg::Key(k.to_string()), |cx| T::read(item, cx)) {
            Some(x) => put(k.to_string(), x),
            None => ok = false,
        }
    }
    ok.then_some(())
}

impl<T: Schema> Schema for BTreeMap<String, T> {
    fn shape() -> Shape {
        Shape::Map(T::shape)
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        let mut out = BTreeMap::new();
        read_map(v, cx, |k, x| {
            out.insert(k, x);
        })?;
        Some(out)
    }
    fn write(&self) -> Value {
        Value::Map(self.iter().map(|(k, v)| (k.clone(), v.write())).collect())
    }
}

impl<T: Schema> Schema for HashMap<String, T> {
    fn shape() -> Shape {
        Shape::Map(T::shape)
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        let mut out = HashMap::new();
        read_map(v, cx, |k, x| {
            out.insert(k, x);
        })?;
        Some(out)
    }
    fn write(&self) -> Value {
        let mut keys: Vec<&String> = self.keys().collect();
        keys.sort();
        Value::Map(
            keys.into_iter()
                .map(|k| (k.clone(), self[k].write()))
                .collect(),
        )
    }
}

/// An object kept in file order, values of one schema.
#[derive(Debug, Clone, PartialEq)]
pub struct Ordered<T>(pub Vec<(String, T)>);

impl<T> Default for Ordered<T> {
    fn default() -> Self {
        Self(Vec::new())
    }
}

impl<T: Schema> Schema for Ordered<T> {
    fn shape() -> Shape {
        Shape::Map(T::shape)
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        let mut out = Vec::new();
        read_map(v, cx, |k, x| out.push((k, x)))?;
        Some(Ordered(out))
    }
    fn write(&self) -> Value {
        Value::Map(self.0.iter().map(|(k, v)| (k.clone(), v.write())).collect())
    }
}