syncular-protocol 0.1.0

Wire protocol and integrity types for Rust-first Syncular clients.
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
use crate::error::{ProtocolError, Result};
use serde_json::{Map, Number, Value};
use std::fmt;

const MAGIC: &[u8; 4] = b"SBT1";
const VERSION: u16 = 1;
const FLAG_NONE: u16 = 0;
const COLUMN_FLAG_NULLABLE: u8 = 1;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinarySnapshotColumnType {
    String,
    Integer,
    Float,
    Boolean,
    Json,
    Bytes,
}

impl BinarySnapshotColumnType {
    fn from_tag(tag: u8) -> Result<Self> {
        match tag {
            1 => Ok(Self::String),
            2 => Ok(Self::Integer),
            3 => Ok(Self::Float),
            4 => Ok(Self::Boolean),
            5 => Ok(Self::Json),
            6 => Ok(Self::Bytes),
            _ => Err(ProtocolError::message(format!(
                "unsupported binary snapshot type tag: {tag}"
            ))),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BinarySnapshotColumn {
    pub name: String,
    pub column_type: BinarySnapshotColumnType,
    pub nullable: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct DecodedBinarySnapshotTable {
    pub table: String,
    pub columns: Vec<BinarySnapshotColumn>,
    pub rows: Vec<Map<String, Value>>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum BinarySnapshotCell {
    Null,
    String(String),
    Integer(i64),
    Float(f64),
    Boolean(bool),
    Json(Value),
    Bytes(Vec<u8>),
}

impl BinarySnapshotCell {
    pub fn into_json_value(self) -> Value {
        match self {
            Self::Null => Value::Null,
            Self::String(value) => Value::String(value),
            Self::Integer(value) => Value::Number(Number::from(value)),
            Self::Float(value) => Number::from_f64(value)
                .map(Value::Number)
                .unwrap_or(Value::Null),
            Self::Boolean(value) => Value::Bool(value),
            Self::Json(value) => value,
            Self::Bytes(bytes) => Value::Array(
                bytes
                    .into_iter()
                    .map(|byte| Value::Number(Number::from(byte)))
                    .collect(),
            ),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct DecodedBinarySnapshotRows {
    pub table: String,
    pub columns: Vec<BinarySnapshotColumn>,
    pub rows: Vec<Vec<BinarySnapshotCell>>,
}

impl DecodedBinarySnapshotRows {
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }

    pub fn into_value_rows(self) -> Vec<Value> {
        self.into_maps().into_iter().map(Value::Object).collect()
    }

    pub fn into_maps(self) -> Vec<Map<String, Value>> {
        let columns = self.columns;
        self.rows
            .into_iter()
            .map(|row| {
                columns
                    .iter()
                    .zip(row)
                    .map(|(column, value)| (column.name.clone(), value.into_json_value()))
                    .collect()
            })
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct BinarySnapshotPayload {
    bytes: Vec<u8>,
    pub table: String,
    pub columns: Vec<BinarySnapshotColumn>,
    pub row_count: usize,
    rows_offset: usize,
}

impl BinarySnapshotPayload {
    pub fn row_count(&self) -> usize {
        self.row_count
    }

    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    pub fn row_cursor(&self) -> BinarySnapshotRowCursor<'_> {
        BinarySnapshotRowCursor {
            reader: BinarySnapshotReader {
                bytes: &self.bytes,
                offset: self.rows_offset,
            },
            columns: &self.columns,
            null_bitmap_bytes: self.columns.len().div_ceil(8),
            remaining: self.row_count,
        }
    }

    pub fn into_decoded_rows(self) -> Result<DecodedBinarySnapshotRows> {
        decode_binary_snapshot_rows(&self.bytes)
    }

    pub fn into_value_rows(self) -> Result<Vec<Value>> {
        self.into_decoded_rows()
            .map(DecodedBinarySnapshotRows::into_value_rows)
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BorrowedBinarySnapshotCell<'a> {
    Null,
    String(&'a str),
    Integer(i64),
    Float(f64),
    Boolean(bool),
    Json(&'a str),
    Bytes(&'a [u8]),
}

#[derive(Debug)]
pub enum BinarySnapshotVisitError<E> {
    Protocol(ProtocolError),
    Visitor(E),
}

impl<E> BinarySnapshotVisitError<E> {
    fn protocol(error: ProtocolError) -> Self {
        Self::Protocol(error)
    }

    fn visitor(error: E) -> Self {
        Self::Visitor(error)
    }
}

impl<E: fmt::Display> fmt::Display for BinarySnapshotVisitError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Protocol(error) => error.fmt(f),
            Self::Visitor(error) => error.fmt(f),
        }
    }
}

impl<E> std::error::Error for BinarySnapshotVisitError<E> where E: std::error::Error + 'static {}

pub trait BorrowedBinarySnapshotRawCellVisitor<'a> {
    type Error;

    fn visit_null(&mut self) -> std::result::Result<(), Self::Error>;
    fn visit_string_bytes(&mut self, value: &'a [u8]) -> std::result::Result<(), Self::Error>;
    fn visit_integer(&mut self, value: i64) -> std::result::Result<(), Self::Error>;
    fn visit_float(&mut self, value: f64) -> std::result::Result<(), Self::Error>;
    fn visit_boolean(&mut self, value: bool) -> std::result::Result<(), Self::Error>;
    fn visit_json_bytes(&mut self, value: &'a [u8]) -> std::result::Result<(), Self::Error>;
    fn visit_bytes(&mut self, value: &'a [u8]) -> std::result::Result<(), Self::Error>;
}

pub struct BinarySnapshotRowCursor<'a> {
    reader: BinarySnapshotReader<'a>,
    columns: &'a [BinarySnapshotColumn],
    null_bitmap_bytes: usize,
    remaining: usize,
}

impl<'a> BinarySnapshotRowCursor<'a> {
    pub fn read_next_row<F, E>(
        &mut self,
        mut on_cell: F,
    ) -> std::result::Result<bool, BinarySnapshotVisitError<E>>
    where
        F: FnMut(
            usize,
            &BinarySnapshotColumn,
            BorrowedBinarySnapshotCell<'a>,
        ) -> std::result::Result<(), E>,
    {
        if self.remaining == 0 {
            return Ok(false);
        }

        let null_bitmap = self
            .reader
            .read_bytes(self.null_bitmap_bytes, "binary snapshot row null bitmap")
            .map_err(BinarySnapshotVisitError::protocol)?;
        for (column_index, column) in self.columns.iter().enumerate() {
            let is_null = null_bitmap[column_index / 8] & (1u8 << (column_index % 8)) != 0;
            if is_null {
                if !column.nullable {
                    return Err(BinarySnapshotVisitError::protocol(ProtocolError::message(
                        format!("binary snapshot column {} is not nullable", column.name),
                    )));
                }
                on_cell(column_index, column, BorrowedBinarySnapshotCell::Null)
                    .map_err(BinarySnapshotVisitError::visitor)?;
                continue;
            }
            let value = self
                .reader
                .read_borrowed_cell(column.column_type, &column.name)
                .map_err(BinarySnapshotVisitError::protocol)?;
            on_cell(column_index, column, value).map_err(BinarySnapshotVisitError::visitor)?;
        }
        self.remaining -= 1;
        Ok(true)
    }

    pub fn read_next_row_with_raw_visitor_trusted<V>(
        &mut self,
        visitor: &mut V,
    ) -> std::result::Result<bool, BinarySnapshotVisitError<V::Error>>
    where
        V: BorrowedBinarySnapshotRawCellVisitor<'a>,
    {
        if self.remaining == 0 {
            return Ok(false);
        }

        let null_bitmap = self
            .reader
            .read_bytes(self.null_bitmap_bytes, "binary snapshot row null bitmap")
            .map_err(BinarySnapshotVisitError::protocol)?;
        for (column_index, column) in self.columns.iter().enumerate() {
            let is_null = null_bitmap[column_index / 8] & (1u8 << (column_index % 8)) != 0;
            if is_null {
                visitor
                    .visit_null()
                    .map_err(BinarySnapshotVisitError::visitor)?;
                continue;
            }
            self.reader
                .visit_raw_cell_trusted(column.column_type, visitor)?;
        }
        self.remaining -= 1;
        Ok(true)
    }

    pub fn assert_done(&self) -> Result<()> {
        self.reader.assert_done()
    }
}

pub fn decode_binary_snapshot_table(bytes: &[u8]) -> Result<DecodedBinarySnapshotTable> {
    let DecodedBinarySnapshotRows {
        table,
        columns,
        rows,
    } = decode_binary_snapshot_rows(bytes)?;
    let value_rows = rows
        .into_iter()
        .map(|row| {
            columns
                .iter()
                .zip(row)
                .map(|(column, value)| (column.name.clone(), value.into_json_value()))
                .collect()
        })
        .collect();
    Ok(DecodedBinarySnapshotTable {
        table,
        columns,
        rows: value_rows,
    })
}

pub fn decode_binary_snapshot_rows(bytes: &[u8]) -> Result<DecodedBinarySnapshotRows> {
    let mut reader = BinarySnapshotReader::new(bytes);
    let (table, columns, row_count, _) = read_binary_snapshot_header(&mut reader)?;
    let null_bitmap_bytes = columns.len().div_ceil(8);
    let mut rows = Vec::with_capacity(row_count);
    for _ in 0..row_count {
        let null_bitmap =
            reader.read_bytes(null_bitmap_bytes, "binary snapshot row null bitmap")?;
        let mut row = Vec::with_capacity(columns.len());
        for (column_index, column) in columns.iter().enumerate() {
            let is_null = null_bitmap[column_index / 8] & (1u8 << (column_index % 8) as u32) != 0;
            if is_null {
                if !column.nullable {
                    return Err(ProtocolError::message(format!(
                        "binary snapshot column {} is not nullable",
                        column.name
                    )));
                }
                row.push(BinarySnapshotCell::Null);
                continue;
            }
            row.push(reader.read_cell(column.column_type, &column.name)?);
        }
        rows.push(row);
    }
    reader.assert_done()?;

    Ok(DecodedBinarySnapshotRows {
        table,
        columns,
        rows,
    })
}

pub fn decode_binary_snapshot_payload(bytes: Vec<u8>) -> Result<BinarySnapshotPayload> {
    let mut reader = BinarySnapshotReader::new(&bytes);
    let (table, columns, row_count, rows_offset) = read_binary_snapshot_header(&mut reader)?;
    Ok(BinarySnapshotPayload {
        bytes,
        table,
        columns,
        row_count,
        rows_offset,
    })
}

fn read_binary_snapshot_header(
    reader: &mut BinarySnapshotReader<'_>,
) -> Result<(String, Vec<BinarySnapshotColumn>, usize, usize)> {
    reader.expect_magic(MAGIC, "binary snapshot table")?;

    let version = reader.read_u16("binary snapshot version")?;
    if version != VERSION {
        return Err(ProtocolError::message(format!(
            "unsupported binary snapshot version: {version}"
        )));
    }
    let flags = reader.read_u16("binary snapshot flags")?;
    if flags != FLAG_NONE {
        return Err(ProtocolError::message(format!(
            "unsupported binary snapshot flags: {flags}"
        )));
    }

    let table = reader.read_string16("binary snapshot table name")?;
    let column_count = reader.read_u16("binary snapshot column count")? as usize;
    let mut columns = Vec::with_capacity(column_count);
    for _ in 0..column_count {
        let name = reader.read_string16("binary snapshot column name")?;
        let column_type =
            BinarySnapshotColumnType::from_tag(reader.read_u8("binary snapshot column type")?)?;
        let column_flags = reader.read_u8("binary snapshot column flags")?;
        if column_flags & !COLUMN_FLAG_NULLABLE != 0 {
            return Err(ProtocolError::message(format!(
                "unsupported binary snapshot column flags: {column_flags}"
            )));
        }
        columns.push(BinarySnapshotColumn {
            name,
            column_type,
            nullable: column_flags & COLUMN_FLAG_NULLABLE != 0,
        });
    }

    let row_count = reader.read_u32("binary snapshot row count")? as usize;
    let rows_offset = reader.offset;
    Ok((table, columns, row_count, rows_offset))
}

struct BinarySnapshotReader<'a> {
    bytes: &'a [u8],
    offset: usize,
}

impl<'a> BinarySnapshotReader<'a> {
    fn new(bytes: &'a [u8]) -> Self {
        Self { bytes, offset: 0 }
    }

    fn expect_magic(&mut self, magic: &[u8], label: &str) -> Result<()> {
        let actual = self.read_bytes(magic.len(), &format!("{label} magic"))?;
        if actual != magic {
            return Err(ProtocolError::message(format!("unexpected {label} magic")));
        }
        Ok(())
    }

    fn read_u8(&mut self, label: &str) -> Result<u8> {
        self.require(1, label)?;
        let value = self.bytes[self.offset];
        self.offset += 1;
        Ok(value)
    }

    fn read_u16(&mut self, label: &str) -> Result<u16> {
        self.require(2, label)?;
        let value = u16::from_le_bytes(
            self.bytes[self.offset..self.offset + 2]
                .try_into()
                .expect("slice length checked"),
        );
        self.offset += 2;
        Ok(value)
    }

    fn read_u32(&mut self, label: &str) -> Result<u32> {
        self.require(4, label)?;
        let value = u32::from_le_bytes(
            self.bytes[self.offset..self.offset + 4]
                .try_into()
                .expect("slice length checked"),
        );
        self.offset += 4;
        Ok(value)
    }

    fn read_i64(&mut self, label: &str) -> Result<i64> {
        self.require(8, label)?;
        let value = i64::from_le_bytes(
            self.bytes[self.offset..self.offset + 8]
                .try_into()
                .expect("slice length checked"),
        );
        self.offset += 8;
        Ok(value)
    }

    fn read_f64(&mut self, label: &str) -> Result<f64> {
        self.require(8, label)?;
        let value = f64::from_le_bytes(
            self.bytes[self.offset..self.offset + 8]
                .try_into()
                .expect("slice length checked"),
        );
        self.offset += 8;
        Ok(value)
    }

    fn read_string16(&mut self, label: &str) -> Result<String> {
        let len = self.read_u16(&format!("{label} length"))? as usize;
        let bytes = self.read_bytes(len, label)?;
        String::from_utf8(bytes.to_vec())
            .map_err(|err| ProtocolError::message(format!("decode {label} as utf8: {err}")))
    }

    fn read_string32(&mut self, label: &str) -> Result<String> {
        let len = self.read_u32(&format!("{label} length"))? as usize;
        let bytes = self.read_bytes(len, label)?;
        String::from_utf8(bytes.to_vec())
            .map_err(|err| ProtocolError::message(format!("decode {label} as utf8: {err}")))
    }

    fn read_str32(&mut self, label: &str) -> Result<&'a str> {
        let len = self.read_u32(&format!("{label} length"))? as usize;
        let bytes = self.read_bytes(len, label)?;
        std::str::from_utf8(bytes)
            .map_err(|err| ProtocolError::message(format!("decode {label} as utf8: {err}")))
    }

    fn read_bytes32(&mut self, label: &str) -> Result<&'a [u8]> {
        let len = self.read_u32(&format!("{label} length"))? as usize;
        self.read_bytes(len, label)
    }

    fn read_bytes(&mut self, len: usize, label: &str) -> Result<&'a [u8]> {
        self.require(len, label)?;
        let bytes = &self.bytes[self.offset..self.offset + len];
        self.offset += len;
        Ok(bytes)
    }

    fn read_cell(
        &mut self,
        column_type: BinarySnapshotColumnType,
        column: &str,
    ) -> Result<BinarySnapshotCell> {
        match column_type {
            BinarySnapshotColumnType::String => Ok(BinarySnapshotCell::String(
                self.read_string32("binary snapshot string")?,
            )),
            BinarySnapshotColumnType::Integer => Ok(BinarySnapshotCell::Integer(
                self.read_i64("binary snapshot integer")?,
            )),
            BinarySnapshotColumnType::Float => {
                let value = self.read_f64("binary snapshot float")?;
                Number::from_f64(value).ok_or_else(|| {
                    ProtocolError::message(format!(
                        "binary snapshot {column} contained non-finite float"
                    ))
                })?;
                Ok(BinarySnapshotCell::Float(value))
            }
            BinarySnapshotColumnType::Boolean => {
                let value = self.read_u8("binary snapshot boolean")?;
                match value {
                    0 => Ok(BinarySnapshotCell::Boolean(false)),
                    1 => Ok(BinarySnapshotCell::Boolean(true)),
                    _ => Err(ProtocolError::message(format!(
                        "binary snapshot {column} expected boolean byte"
                    ))),
                }
            }
            BinarySnapshotColumnType::Json => {
                let value = self.read_string32("binary snapshot json")?;
                Ok(BinarySnapshotCell::Json(serde_json::from_str(&value)?))
            }
            BinarySnapshotColumnType::Bytes => {
                let len = self.read_u32("binary snapshot bytes length")? as usize;
                let bytes = self.read_bytes(len, "binary snapshot bytes")?;
                Ok(BinarySnapshotCell::Bytes(bytes.to_vec()))
            }
        }
    }

    fn read_borrowed_cell(
        &mut self,
        column_type: BinarySnapshotColumnType,
        column: &str,
    ) -> Result<BorrowedBinarySnapshotCell<'a>> {
        match column_type {
            BinarySnapshotColumnType::String => Ok(BorrowedBinarySnapshotCell::String(
                self.read_str32("binary snapshot string")?,
            )),
            BinarySnapshotColumnType::Integer => Ok(BorrowedBinarySnapshotCell::Integer(
                self.read_i64("binary snapshot integer")?,
            )),
            BinarySnapshotColumnType::Float => {
                let value = self.read_f64("binary snapshot float")?;
                Number::from_f64(value).ok_or_else(|| {
                    ProtocolError::message(format!(
                        "binary snapshot {column} contained non-finite float"
                    ))
                })?;
                Ok(BorrowedBinarySnapshotCell::Float(value))
            }
            BinarySnapshotColumnType::Boolean => {
                let value = self.read_u8("binary snapshot boolean")?;
                match value {
                    0 => Ok(BorrowedBinarySnapshotCell::Boolean(false)),
                    1 => Ok(BorrowedBinarySnapshotCell::Boolean(true)),
                    _ => Err(ProtocolError::message(format!(
                        "binary snapshot {column} expected boolean byte"
                    ))),
                }
            }
            BinarySnapshotColumnType::Json => Ok(BorrowedBinarySnapshotCell::Json(
                self.read_str32("binary snapshot json")?,
            )),
            BinarySnapshotColumnType::Bytes => {
                let len = self.read_u32("binary snapshot bytes length")? as usize;
                let bytes = self.read_bytes(len, "binary snapshot bytes")?;
                Ok(BorrowedBinarySnapshotCell::Bytes(bytes))
            }
        }
    }

    fn visit_raw_cell_trusted<V>(
        &mut self,
        column_type: BinarySnapshotColumnType,
        visitor: &mut V,
    ) -> std::result::Result<(), BinarySnapshotVisitError<V::Error>>
    where
        V: BorrowedBinarySnapshotRawCellVisitor<'a>,
    {
        match column_type {
            BinarySnapshotColumnType::String => {
                let value = self
                    .read_bytes32("binary snapshot string")
                    .map_err(BinarySnapshotVisitError::protocol)?;
                visitor
                    .visit_string_bytes(value)
                    .map_err(BinarySnapshotVisitError::visitor)
            }
            BinarySnapshotColumnType::Integer => {
                let value = self
                    .read_i64("binary snapshot integer")
                    .map_err(BinarySnapshotVisitError::protocol)?;
                visitor
                    .visit_integer(value)
                    .map_err(BinarySnapshotVisitError::visitor)
            }
            BinarySnapshotColumnType::Float => {
                let value = self
                    .read_f64("binary snapshot float")
                    .map_err(BinarySnapshotVisitError::protocol)?;
                if !value.is_finite() {
                    return Err(BinarySnapshotVisitError::protocol(ProtocolError::message(
                        "binary snapshot contained non-finite float",
                    )));
                }
                visitor
                    .visit_float(value)
                    .map_err(BinarySnapshotVisitError::visitor)
            }
            BinarySnapshotColumnType::Boolean => {
                let value = self
                    .read_u8("binary snapshot boolean")
                    .map_err(BinarySnapshotVisitError::protocol)?;
                match value {
                    0 => visitor
                        .visit_boolean(false)
                        .map_err(BinarySnapshotVisitError::visitor),
                    1 => visitor
                        .visit_boolean(true)
                        .map_err(BinarySnapshotVisitError::visitor),
                    _ => Err(BinarySnapshotVisitError::protocol(ProtocolError::message(
                        "binary snapshot expected boolean byte",
                    ))),
                }
            }
            BinarySnapshotColumnType::Json => {
                let value = self
                    .read_bytes32("binary snapshot json")
                    .map_err(BinarySnapshotVisitError::protocol)?;
                visitor
                    .visit_json_bytes(value)
                    .map_err(BinarySnapshotVisitError::visitor)
            }
            BinarySnapshotColumnType::Bytes => {
                let len =
                    self.read_u32("binary snapshot bytes length")
                        .map_err(BinarySnapshotVisitError::protocol)? as usize;
                let bytes = self
                    .read_bytes(len, "binary snapshot bytes")
                    .map_err(BinarySnapshotVisitError::protocol)?;
                visitor
                    .visit_bytes(bytes)
                    .map_err(BinarySnapshotVisitError::visitor)
            }
        }
    }

    fn assert_done(&self) -> Result<()> {
        if self.offset != self.bytes.len() {
            return Err(ProtocolError::message(
                "binary snapshot payload has trailing bytes",
            ));
        }
        Ok(())
    }

    fn require(&self, len: usize, label: &str) -> Result<()> {
        if self.offset + len > self.bytes.len() {
            return Err(ProtocolError::message(format!(
                "{label} exceeds binary snapshot payload bounds"
            )));
        }
        Ok(())
    }
}

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

    fn push_u16(bytes: &mut Vec<u8>, value: u16) {
        bytes.extend_from_slice(&value.to_le_bytes());
    }

    fn push_u32(bytes: &mut Vec<u8>, value: u32) {
        bytes.extend_from_slice(&value.to_le_bytes());
    }

    fn push_i64(bytes: &mut Vec<u8>, value: i64) {
        bytes.extend_from_slice(&value.to_le_bytes());
    }

    fn push_f64(bytes: &mut Vec<u8>, value: f64) {
        bytes.extend_from_slice(&value.to_le_bytes());
    }

    fn push_string16(bytes: &mut Vec<u8>, value: &str) {
        push_u16(bytes, value.len() as u16);
        bytes.extend_from_slice(value.as_bytes());
    }

    fn push_string32(bytes: &mut Vec<u8>, value: &str) {
        push_u32(bytes, value.len() as u32);
        bytes.extend_from_slice(value.as_bytes());
    }

    #[test]
    fn decodes_binary_snapshot_table_rows() {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(b"SBT1");
        push_u16(&mut bytes, 1);
        push_u16(&mut bytes, 0);
        push_string16(&mut bytes, "tasks");
        push_u16(&mut bytes, 6);
        for (name, tag, flags) in [
            ("id", 1u8, 0u8),
            ("completed", 4, 0),
            ("server_version", 2, 0),
            ("score", 3, 0),
            ("metadata", 5, COLUMN_FLAG_NULLABLE),
            ("payload", 6, 0),
        ] {
            push_string16(&mut bytes, name);
            bytes.push(tag);
            bytes.push(flags);
        }
        push_u32(&mut bytes, 2);

        bytes.push(0);
        push_string32(&mut bytes, "task-1");
        bytes.push(0);
        push_i64(&mut bytes, 42);
        push_f64(&mut bytes, 1.5);
        push_string32(&mut bytes, r#"{"priority":"high"}"#);
        push_u32(&mut bytes, 3);
        bytes.extend_from_slice(&[1, 2, 3]);

        bytes.push(1 << 4);
        push_string32(&mut bytes, "task-2");
        bytes.push(1);
        push_i64(&mut bytes, 43);
        push_f64(&mut bytes, 2.25);
        push_u32(&mut bytes, 0);

        let decoded = decode_binary_snapshot_table(&bytes).unwrap();

        assert_eq!(decoded.table, "tasks");
        assert_eq!(decoded.columns.len(), 6);
        assert_eq!(decoded.rows[0]["id"], json!("task-1"));
        assert_eq!(decoded.rows[0]["completed"], json!(false));
        assert_eq!(decoded.rows[0]["server_version"], json!(42));
        assert_eq!(decoded.rows[0]["score"], json!(1.5));
        assert_eq!(decoded.rows[0]["metadata"], json!({"priority": "high"}));
        assert_eq!(decoded.rows[0]["payload"], json!([1, 2, 3]));
        assert_eq!(decoded.rows[1]["metadata"], Value::Null);

        let payload = decode_binary_snapshot_payload(bytes).unwrap();
        let mut cursor = payload.row_cursor();
        let mut first_row = Vec::new();
        assert!(cursor
            .read_next_row(|_, _, value| {
                first_row.push(value);
                Ok::<(), ProtocolError>(())
            })
            .unwrap());
        assert_eq!(first_row[0], BorrowedBinarySnapshotCell::String("task-1"));
        assert_eq!(first_row[1], BorrowedBinarySnapshotCell::Boolean(false));
        assert_eq!(first_row[2], BorrowedBinarySnapshotCell::Integer(42));
        assert_eq!(first_row[3], BorrowedBinarySnapshotCell::Float(1.5));
        assert_eq!(
            first_row[4],
            BorrowedBinarySnapshotCell::Json(r#"{"priority":"high"}"#)
        );
        assert_eq!(first_row[5], BorrowedBinarySnapshotCell::Bytes(&[1, 2, 3]));

        #[derive(Debug, PartialEq)]
        enum RawCell<'a> {
            Null,
            String(&'a [u8]),
            Integer(i64),
            Float(f64),
            Boolean(bool),
            Json(&'a [u8]),
            Bytes(&'a [u8]),
        }

        struct RawRecordingVisitor<'a> {
            values: Vec<RawCell<'a>>,
        }

        impl<'a> BorrowedBinarySnapshotRawCellVisitor<'a> for RawRecordingVisitor<'a> {
            type Error = ProtocolError;

            fn visit_null(&mut self) -> Result<()> {
                self.values.push(RawCell::Null);
                Ok(())
            }

            fn visit_string_bytes(&mut self, value: &'a [u8]) -> Result<()> {
                self.values.push(RawCell::String(value));
                Ok(())
            }

            fn visit_integer(&mut self, value: i64) -> Result<()> {
                self.values.push(RawCell::Integer(value));
                Ok(())
            }

            fn visit_float(&mut self, value: f64) -> Result<()> {
                self.values.push(RawCell::Float(value));
                Ok(())
            }

            fn visit_boolean(&mut self, value: bool) -> Result<()> {
                self.values.push(RawCell::Boolean(value));
                Ok(())
            }

            fn visit_json_bytes(&mut self, value: &'a [u8]) -> Result<()> {
                self.values.push(RawCell::Json(value));
                Ok(())
            }

            fn visit_bytes(&mut self, value: &'a [u8]) -> Result<()> {
                self.values.push(RawCell::Bytes(value));
                Ok(())
            }
        }

        let mut cursor = payload.row_cursor();
        let mut raw_visitor = RawRecordingVisitor { values: Vec::new() };
        assert!(cursor
            .read_next_row_with_raw_visitor_trusted(&mut raw_visitor)
            .unwrap());
        assert_eq!(
            raw_visitor.values,
            vec![
                RawCell::String(&b"task-1"[..]),
                RawCell::Boolean(false),
                RawCell::Integer(42),
                RawCell::Float(1.5),
                RawCell::Json(&br#"{"priority":"high"}"#[..]),
                RawCell::Bytes(&[1, 2, 3]),
            ]
        );
    }
}