geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
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
//! The columnar block codec of the sort runs.
//!
//! A run is a sequence of blocks. A block holds a few thousand entries that
//! are already sorted by key, and stores them column by column:
//!
//! - the sort keys as the delta to the key before (the keys of a block are
//!   close, so a delta is one to three bytes where a key is nine),
//! - the layer, the geometry type, the feature id and the sort key,
//! - the geometry commands,
//! - the properties: a property set that one of the last [`SET_WINDOW`]
//!   sets of the block already stored is stored once and referenced; a
//!   string is stored once per block and referenced.
//!
//! Every column holds values of one kind, so the general-purpose compressor
//! that runs over the finished block finds the repeats a row layout hides.
//! Decoding reproduces every entry exactly, bit for bit.

use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
use std::sync::Arc;

use geolith::layer::Layer;
use geolith::tile::feature::{GeomType, PropValue, TileFeature};

use crate::sort::entry::SortEntry;

/// The block was cut: why a block cannot be decoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum BlockError {
    /// A column ends before its last value.
    #[error("a column ends too early")]
    ColumnEnds,
    /// A varint is longer than ten bytes or does not fit its type.
    #[error("a varint is out of range")]
    Varint,
    /// A layer or geometry type byte names no known variant.
    #[error("unknown layer or geometry type {0}")]
    UnknownKind(u8),
    /// A property value tag names no known variant.
    #[error("unknown property value tag {0}")]
    UnknownTag(u8),
    /// A string reference or property-set reference points past the table.
    #[error("a reference points outside its table")]
    Reference,
    /// A string is not UTF-8.
    #[error("a string is not valid UTF-8")]
    Utf8,
    /// The block holds fewer columns or bytes than its header says.
    #[error("the block layout is wrong")]
    Layout,
    /// More entries were asked for than the block holds.
    #[error("the block holds no more entries")]
    Exhausted,
    /// An entry cannot be stored: its key is below the key before it.
    #[error("the entries are not sorted by key")]
    NotSorted,
    /// An entry has a value this codec cannot store.
    #[error("a value of this type cannot be stored")]
    Unsupported,
}

/// The properties of a feature, shared by the entries that came from it.
type PropertySet = Arc<Vec<(String, PropValue)>>;

const COLUMNS: usize = 13;
const KEYS: usize = 0;
const LAYERS: usize = 1;
const GEOM_TYPES: usize = 2;
const IDS: usize = 3;
const SORT_KEYS: usize = 4;
const GEOM_LENS: usize = 5;
const GEOM_VALUES: usize = 6;
const PROP_REFS: usize = 7;
const PROP_COUNTS: usize = 8;
const PROP_TAGS: usize = 9;
const PROP_NUMS: usize = 10;
const STRINGS: usize = 11;
const STRING_REFS: usize = 12;

/// How many property sets back an entry may refer to. The decoder keeps this
/// many sets alive, which bounds its memory however long the block is.
pub const SET_WINDOW: usize = 1024;

const TAG_STR: u8 = 0;
const TAG_F64: u8 = 1;
const TAG_I64: u8 = 2;
const TAG_U64: u8 = 3;
const TAG_FALSE: u8 = 4;
const TAG_TRUE: u8 = 5;

/// A hasher for table keys that are already well spread (addresses).
#[derive(Default)]
struct AddressHasher(u64);

impl Hasher for AddressHasher {
    fn finish(&self) -> u64 {
        self.0
    }

    fn write(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
        }
    }

    fn write_usize(&mut self, n: usize) {
        self.0 = (n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
    }
}

type AddressMap<V> = HashMap<usize, V, BuildHasherDefault<AddressHasher>>;

/// Appends entries to one block.
#[derive(Default)]
pub struct BlockEncoder {
    columns: [Vec<u8>; COLUMNS],
    entries: u32,
    prev_key: u64,
    sets: AddressMap<u32>,
    set_count: u32,
    strings: HashMap<String, u32>,
}

impl BlockEncoder {
    /// An empty encoder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Entries added to the block so far.
    #[must_use]
    pub const fn len(&self) -> u32 {
        self.entries
    }

    /// Whether the block holds no entry.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.entries == 0
    }

    /// Bytes the block takes before compression, headers excluded.
    #[must_use]
    pub fn raw_len(&self) -> usize {
        self.columns.iter().map(Vec::len).sum()
    }

    /// Add one entry. Keys must not decrease from one call to the next.
    ///
    /// # Errors
    ///
    /// [`BlockError::NotSorted`] when `entry.key` is below the previous key;
    /// [`BlockError::Unsupported`] for a property value of an unknown type.
    pub fn push(&mut self, entry: &SortEntry) -> Result<(), BlockError> {
        let delta = entry
            .key
            .checked_sub(self.prev_key)
            .ok_or(BlockError::NotSorted)?;
        let feature = &entry.feature;
        let props = self.property_ref(&feature.properties)?;
        put_varint(&mut self.columns[KEYS], delta);
        self.columns[LAYERS].push(feature.layer as u8);
        self.columns[GEOM_TYPES].push(feature.geom_type as u8);
        put_varint(&mut self.columns[IDS], feature.id);
        put_varint(
            &mut self.columns[SORT_KEYS],
            zigzag(i64::from(feature.sort_key)),
        );
        put_varint(&mut self.columns[GEOM_LENS], feature.geometry.len() as u64);
        for &v in &feature.geometry {
            put_varint(&mut self.columns[GEOM_VALUES], u64::from(v));
        }
        put_varint(&mut self.columns[PROP_REFS], u64::from(props));
        self.prev_key = entry.key;
        self.entries += 1;
        Ok(())
    }

    /// The reference to a property set: 0 when the set is new (it is then
    /// stored in the property columns), else how many sets back it was stored.
    fn property_ref(&mut self, props: &PropertySet) -> Result<u32, BlockError> {
        let address = Arc::as_ptr(props) as usize;
        if let Some(&index) = self.sets.get(&address) {
            let distance = self.set_count - index;
            if distance as usize <= SET_WINDOW {
                return Ok(distance);
            }
        }
        put_varint(&mut self.columns[PROP_COUNTS], props.len() as u64);
        for (key, value) in props.iter() {
            self.put_string(key);
            match value {
                PropValue::Str(s) => {
                    self.columns[PROP_TAGS].push(TAG_STR);
                    self.put_string(s);
                }
                PropValue::F64(x) => {
                    self.columns[PROP_TAGS].push(TAG_F64);
                    self.columns[PROP_NUMS].extend_from_slice(&x.to_bits().to_le_bytes());
                }
                PropValue::I64(x) => {
                    self.columns[PROP_TAGS].push(TAG_I64);
                    put_varint(&mut self.columns[PROP_NUMS], zigzag(*x));
                }
                PropValue::U64(x) => {
                    self.columns[PROP_TAGS].push(TAG_U64);
                    put_varint(&mut self.columns[PROP_NUMS], *x);
                }
                PropValue::Bool(false) => self.columns[PROP_TAGS].push(TAG_FALSE),
                PropValue::Bool(true) => self.columns[PROP_TAGS].push(TAG_TRUE),
                _ => return Err(BlockError::Unsupported),
            }
        }
        self.sets.insert(address, self.set_count);
        self.set_count += 1;
        Ok(0)
    }

    /// A string reference: its number, or the next number and the string
    /// itself in the string column when the block has not met it yet.
    fn put_string(&mut self, s: &str) {
        let next = self.strings.len() as u32;
        if let Some(&number) = self.strings.get(s) {
            put_varint(&mut self.columns[STRING_REFS], u64::from(number));
            return;
        }
        put_varint(&mut self.columns[STRING_REFS], u64::from(next));
        put_varint(&mut self.columns[STRINGS], s.len() as u64);
        self.columns[STRINGS].extend_from_slice(s.as_bytes());
        self.strings.insert(s.to_owned(), next);
    }

    /// Write the block, with its column table, to `out` and reset the
    /// encoder for the next block. Returns the number of entries.
    pub fn finish_into(&mut self, out: &mut Vec<u8>) -> u32 {
        for column in &self.columns {
            out.extend_from_slice(&(column.len() as u32).to_le_bytes());
        }
        for column in &mut self.columns {
            out.extend_from_slice(column);
            column.clear();
        }
        let entries = self.entries;
        self.entries = 0;
        self.prev_key = 0;
        self.sets.clear();
        self.set_count = 0;
        self.strings.clear();
        entries
    }
}

/// Reads the entries of one decoded block in order.
pub struct BlockDecoder {
    raw: Vec<u8>,
    ranges: [(usize, usize); COLUMNS],
    at: [usize; COLUMNS],
    remaining: u32,
    prev_key: u64,
    sets: Vec<Option<PropertySet>>,
    set_count: u32,
    strings: Vec<(usize, usize)>,
}

impl BlockDecoder {
    /// A decoder with no block loaded.
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            raw: Vec::new(),
            ranges: [(0, 0); COLUMNS],
            at: [0; COLUMNS],
            remaining: 0,
            prev_key: 0,
            sets: Vec::new(),
            set_count: 0,
            strings: Vec::new(),
        }
    }

    /// The buffer to decompress the next block into. Call [`Self::load`]
    /// after it is filled.
    pub fn buffer(&mut self) -> &mut Vec<u8> {
        &mut self.raw
    }

    /// Parse the column table of the block in the buffer.
    ///
    /// # Errors
    ///
    /// [`BlockError::Layout`] when the columns do not add up to the buffer.
    pub fn load(&mut self, entries: u32) -> Result<(), BlockError> {
        let table = COLUMNS * 4;
        if self.raw.len() < table {
            return Err(BlockError::Layout);
        }
        let mut start = table;
        for (i, range) in self.ranges.iter_mut().enumerate() {
            let len = u32::from_le_bytes(
                self.raw[i * 4..i * 4 + 4]
                    .try_into()
                    .map_err(|_| BlockError::Layout)?,
            ) as usize;
            let end = start.checked_add(len).ok_or(BlockError::Layout)?;
            *range = (start, end);
            start = end;
        }
        if start != self.raw.len() {
            return Err(BlockError::Layout);
        }
        self.at = std::array::from_fn(|i| self.ranges[i].0);
        self.remaining = entries;
        self.prev_key = 0;
        self.sets.clear();
        self.sets.resize(SET_WINDOW, None);
        self.set_count = 0;
        self.strings.clear();
        Ok(())
    }

    /// Whether every column was read to its end: a block that decodes all
    /// its entries and leaves bytes behind is wrong.
    ///
    /// # Errors
    ///
    /// [`BlockError::Layout`] when a column has bytes left.
    pub fn check_complete(&self) -> Result<(), BlockError> {
        if self.remaining == 0 && (0..COLUMNS).all(|i| self.at[i] == self.ranges[i].1) {
            Ok(())
        } else {
            Err(BlockError::Layout)
        }
    }

    /// Entries not read yet.
    #[must_use]
    pub const fn remaining(&self) -> u32 {
        self.remaining
    }

    /// The next entry of the block.
    ///
    /// # Errors
    ///
    /// A [`BlockError`] when the block is cut or inconsistent.
    pub fn next_entry(&mut self) -> Result<SortEntry, BlockError> {
        if self.remaining == 0 {
            return Err(BlockError::Exhausted);
        }
        let delta = self.varint(KEYS)?;
        let key = self.prev_key.checked_add(delta).ok_or(BlockError::Varint)?;
        let layer_byte = self.byte(LAYERS)?;
        let layer = Layer::ALL
            .into_iter()
            .find(|l| *l as u8 == layer_byte)
            .ok_or(BlockError::UnknownKind(layer_byte))?;
        let geom_byte = self.byte(GEOM_TYPES)?;
        let geom_type = match geom_byte {
            1 => GeomType::Point,
            2 => GeomType::Line,
            3 => GeomType::Polygon,
            other => return Err(BlockError::UnknownKind(other)),
        };
        let id = self.varint(IDS)?;
        let sort_key =
            i32::try_from(unzigzag(self.varint(SORT_KEYS)?)).map_err(|_| BlockError::Varint)?;
        let geom_len = self.varint(GEOM_LENS)? as usize;
        let available = self.ranges[GEOM_VALUES].1 - self.at[GEOM_VALUES];
        if geom_len > available {
            return Err(BlockError::ColumnEnds);
        }
        let mut geometry = Vec::with_capacity(geom_len);
        for _ in 0..geom_len {
            geometry
                .push(u32::try_from(self.varint(GEOM_VALUES)?).map_err(|_| BlockError::Varint)?);
        }
        let reference = self.varint(PROP_REFS)? as usize;
        let properties = if reference == 0 {
            let set = Arc::new(self.property_set()?);
            let slot = self.set_count as usize % SET_WINDOW;
            self.sets[slot] = Some(Arc::clone(&set));
            self.set_count += 1;
            set
        } else {
            if reference > SET_WINDOW || reference > self.set_count as usize {
                return Err(BlockError::Reference);
            }
            let slot = (self.set_count as usize - reference) % SET_WINDOW;
            Arc::clone(self.sets[slot].as_ref().ok_or(BlockError::Reference)?)
        };
        self.prev_key = key;
        self.remaining -= 1;
        Ok(SortEntry::new(
            key,
            TileFeature {
                layer,
                id,
                geom_type,
                geometry,
                properties,
                sort_key,
            },
        ))
    }

    fn property_set(&mut self) -> Result<Vec<(String, PropValue)>, BlockError> {
        let count = self.varint(PROP_COUNTS)? as usize;
        let available = self.ranges[PROP_TAGS].1 - self.at[PROP_TAGS];
        if count > available {
            return Err(BlockError::ColumnEnds);
        }
        let mut set = Vec::with_capacity(count);
        for _ in 0..count {
            let key = self.string()?;
            let value = match self.byte(PROP_TAGS)? {
                TAG_STR => PropValue::Str(self.string()?),
                TAG_F64 => {
                    let at = self.at[PROP_NUMS];
                    let end = at.checked_add(8).ok_or(BlockError::ColumnEnds)?;
                    if end > self.ranges[PROP_NUMS].1 {
                        return Err(BlockError::ColumnEnds);
                    }
                    let bits = u64::from_le_bytes(
                        self.raw[at..end]
                            .try_into()
                            .map_err(|_| BlockError::ColumnEnds)?,
                    );
                    self.at[PROP_NUMS] = end;
                    PropValue::F64(f64::from_bits(bits))
                }
                TAG_I64 => PropValue::I64(unzigzag(self.varint(PROP_NUMS)?)),
                TAG_U64 => PropValue::U64(self.varint(PROP_NUMS)?),
                TAG_FALSE => PropValue::Bool(false),
                TAG_TRUE => PropValue::Bool(true),
                other => return Err(BlockError::UnknownTag(other)),
            };
            set.push((key, value));
        }
        Ok(set)
    }

    fn string(&mut self) -> Result<String, BlockError> {
        let number = self.varint(STRING_REFS)? as usize;
        let (at, end) = if let Some(&range) = self.strings.get(number) {
            range
        } else {
            if number != self.strings.len() {
                return Err(BlockError::Reference);
            }
            let len = self.varint(STRINGS)? as usize;
            let at = self.at[STRINGS];
            let end = at.checked_add(len).ok_or(BlockError::ColumnEnds)?;
            if end > self.ranges[STRINGS].1 {
                return Err(BlockError::ColumnEnds);
            }
            self.at[STRINGS] = end;
            self.strings.push((at, end));
            (at, end)
        };
        std::str::from_utf8(&self.raw[at..end])
            .map(str::to_owned)
            .map_err(|_| BlockError::Utf8)
    }

    fn byte(&mut self, column: usize) -> Result<u8, BlockError> {
        let at = self.at[column];
        if at >= self.ranges[column].1 {
            return Err(BlockError::ColumnEnds);
        }
        self.at[column] = at + 1;
        Ok(self.raw[at])
    }

    fn varint(&mut self, column: usize) -> Result<u64, BlockError> {
        let end = self.ranges[column].1;
        let mut at = self.at[column];
        let mut value = 0u64;
        for shift in (0..70).step_by(7) {
            if at >= end {
                return Err(BlockError::ColumnEnds);
            }
            let b = self.raw[at];
            at += 1;
            if shift == 63 && b > 1 {
                return Err(BlockError::Varint);
            }
            value |= u64::from(b & 0x7f) << shift;
            if b & 0x80 == 0 {
                self.at[column] = at;
                return Ok(value);
            }
        }
        Err(BlockError::Varint)
    }
}

fn put_varint(out: &mut Vec<u8>, mut value: u64) {
    while value >= 0x80 {
        out.push((value as u8 & 0x7f) | 0x80);
        value >>= 7;
    }
    out.push(value as u8);
}

const fn zigzag(v: i64) -> u64 {
    ((v << 1) ^ (v >> 63)) as u64
}

const fn unzigzag(v: u64) -> i64 {
    ((v >> 1) as i64) ^ -((v & 1) as i64)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entry(key: u64, id: u64, props: &Arc<Vec<(String, PropValue)>>) -> SortEntry {
        SortEntry::new(
            key,
            TileFeature {
                layer: Layer::Buildings,
                id,
                geom_type: GeomType::Polygon,
                geometry: vec![9, 50, 34, 26, 4, 0, 0, 4, 3, 15],
                properties: Arc::clone(props),
                sort_key: -7,
            },
        )
    }

    fn roundtrip(entries: &[SortEntry]) -> Vec<SortEntry> {
        let mut encoder = BlockEncoder::new();
        for e in entries {
            encoder.push(e).expect("push");
        }
        let mut raw = Vec::new();
        let count = encoder.finish_into(&mut raw);
        assert_eq!(count as usize, entries.len());
        let mut decoder = BlockDecoder::empty();
        decoder.buffer().extend_from_slice(&raw);
        decoder.load(count).expect("load");
        let out: Vec<SortEntry> = (0..count)
            .map(|_| decoder.next_entry().expect("entry"))
            .collect();
        decoder.check_complete().expect("complete");
        out
    }

    fn bytes(entries: &[SortEntry]) -> Vec<Vec<u8>> {
        entries
            .iter()
            .map(|e| e.to_bytes().expect("encode"))
            .collect()
    }

    #[test]
    fn every_value_kind_comes_back_bit_for_bit() {
        let props = Arc::new(vec![
            ("name".to_owned(), PropValue::Str("Zürich 駅 🚉".to_owned())),
            ("empty".to_owned(), PropValue::Str(String::new())),
            ("nan".to_owned(), PropValue::F64(f64::NAN)),
            ("neg0".to_owned(), PropValue::F64(-0.0)),
            ("inf".to_owned(), PropValue::F64(f64::NEG_INFINITY)),
            ("i".to_owned(), PropValue::I64(i64::MIN)),
            ("u".to_owned(), PropValue::U64(u64::MAX)),
            ("t".to_owned(), PropValue::Bool(true)),
            ("f".to_owned(), PropValue::Bool(false)),
        ]);
        let none: Arc<Vec<(String, PropValue)>> = Arc::new(Vec::new());
        let entries = vec![
            entry(0, 0, &none),
            entry(5, u64::MAX, &props),
            entry(5, 1, &props),
            entry(u64::MAX, 2, &none),
        ];
        let back = roundtrip(&entries);
        assert_eq!(bytes(&back), bytes(&entries));
    }

    #[test]
    fn a_shared_property_set_is_stored_once_and_shared_after_decoding() {
        let props = Arc::new(vec![("k".to_owned(), PropValue::Str("v".to_owned()))]);
        let entries: Vec<SortEntry> = (0..10).map(|i| entry(i, i, &props)).collect();
        let back = roundtrip(&entries);
        for pair in back.windows(2) {
            assert!(Arc::ptr_eq(
                &pair[0].feature.properties,
                &pair[1].feature.properties
            ));
        }
        let mut shared = BlockEncoder::new();
        let mut distinct = BlockEncoder::new();
        // The entries stay alive: the encoder tells sets apart by address.
        let kept: Vec<SortEntry> = (0..10)
            .map(|i| entry(i, i, &Arc::new(props.as_ref().clone())))
            .collect();
        for (i, own) in kept.iter().enumerate() {
            shared.push(&entry(i as u64, 0, &props)).expect("push");
            distinct.push(own).expect("push");
        }
        assert!(shared.raw_len() < distinct.raw_len());
    }

    #[test]
    fn a_property_set_beyond_the_window_is_stored_again() {
        let first = Arc::new(vec![("a".to_owned(), PropValue::I64(1))]);
        let mut entries = vec![entry(0, 0, &first)];
        for i in 0..(SET_WINDOW as u64 + 5) {
            let other = Arc::new(vec![("b".to_owned(), PropValue::I64(i as i64))]);
            entries.push(entry(i + 1, i + 1, &other));
        }
        entries.push(entry(SET_WINDOW as u64 + 10, 9, &first));
        let back = roundtrip(&entries);
        assert_eq!(bytes(&back), bytes(&entries));
    }

    #[test]
    fn keys_that_go_down_are_refused() {
        let props = Arc::new(Vec::new());
        let mut encoder = BlockEncoder::new();
        encoder.push(&entry(10, 0, &props)).expect("push");
        assert_eq!(
            encoder.push(&entry(9, 0, &props)),
            Err(BlockError::NotSorted)
        );
    }

    #[test]
    fn a_cut_block_is_an_error_at_every_length() {
        let props = Arc::new(vec![
            ("k".to_owned(), PropValue::Str("v".to_owned())),
            ("n".to_owned(), PropValue::F64(1.5)),
        ]);
        let entries: Vec<SortEntry> = (0..20).map(|i| entry(i, i, &props)).collect();
        let mut encoder = BlockEncoder::new();
        for e in &entries {
            encoder.push(e).expect("push");
        }
        let mut raw = Vec::new();
        let count = encoder.finish_into(&mut raw);
        for cut in 0..raw.len() {
            let mut decoder = BlockDecoder::empty();
            decoder.buffer().extend_from_slice(&raw[..cut]);
            let outcome = decoder.load(count).and_then(|()| {
                for _ in 0..count {
                    decoder.next_entry()?;
                }
                decoder.check_complete()
            });
            assert!(outcome.is_err(), "a block cut at {cut} must not decode");
        }
    }

    #[test]
    fn garbage_never_panics_the_decoder() {
        let mut seed = 0x1234_5678_9abc_def0_u64;
        for _ in 0..2000 {
            let len = (seed % 300) as usize;
            let raw: Vec<u8> = (0..len)
                .map(|_| {
                    seed = seed
                        .wrapping_mul(6_364_136_223_846_793_005)
                        .wrapping_add(1_442_695_040_888_963_407);
                    (seed >> 33) as u8
                })
                .collect();
            let mut decoder = BlockDecoder::empty();
            decoder.buffer().extend_from_slice(&raw);
            if decoder.load(5).is_ok() {
                for _ in 0..5 {
                    if decoder.next_entry().is_err() {
                        break;
                    }
                }
            }
        }
    }
}