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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! Implementations of [Codec] for stdlib types.

use std::fmt::Debug;
use std::marker::PhantomData;

use arrow2::array::{
    Array, BinaryArray, BooleanArray, MutableArray, MutableBinaryArray, MutableBooleanArray,
    MutablePrimitiveArray, MutableUtf8Array, PrimitiveArray, Utf8Array,
};
use arrow2::bitmap::{Bitmap, MutableBitmap};
use arrow2::buffer::Buffer;
use arrow2::datatypes::DataType as ArrowLogicalType;
use arrow2::io::parquet::write::Encoding;
use arrow2::types::NativeType;
use bytes::BufMut;

use crate::columnar::sealed::ColumnRef;
use crate::columnar::{
    ColumnCfg, ColumnFormat, ColumnGet, ColumnPush, Data, DataType, PartDecoder, PartEncoder,
    Schema,
};
use crate::dyn_struct::{
    ColumnsMut, ColumnsRef, DynStruct, DynStructCfg, DynStructCol, DynStructMut, DynStructRef,
};
use crate::stats::{BytesStats, OptionStats, PrimitiveStats, StatsFn, StructStats};
use crate::{Codec, Codec64, Opaque, ShardId};

/// An implementation of [Schema] for [()].
#[derive(Debug, Default)]
pub struct UnitSchema;

impl PartEncoder<'_, ()> for UnitSchema {
    fn encode(&mut self, _val: &()) {}
}

impl PartDecoder<'_, ()> for UnitSchema {
    fn decode(&self, _idx: usize, _val: &mut ()) {}
}

impl Schema<()> for UnitSchema {
    type Encoder<'a> = Self;
    type Decoder<'a> = Self;

    fn columns(&self) -> DynStructCfg {
        DynStructCfg::from(Vec::new())
    }

    fn decoder<'a>(&self, cols: ColumnsRef<'a>) -> Result<Self::Decoder<'a>, String> {
        let () = cols.finish()?;
        Ok(UnitSchema)
    }

    fn encoder<'a>(&self, cols: ColumnsMut<'a>) -> Result<Self::Encoder<'a>, String> {
        let (_len, ()) = cols.finish()?;
        Ok(UnitSchema)
    }
}

impl Codec for () {
    type Storage = ();
    type Schema = UnitSchema;

    fn codec_name() -> String {
        "()".into()
    }

    fn encode<B>(&self, _buf: &mut B)
    where
        B: BufMut,
    {
        // No-op.
    }

    fn decode<'a>(buf: &'a [u8]) -> Result<Self, String> {
        if !buf.is_empty() {
            return Err(format!("decode expected empty buf got {} bytes", buf.len()));
        }
        Ok(())
    }
}

/// An implementation of [PartEncoder] for a single column.
pub struct SimpleEncoder<'a, X, T: Data>(&'a mut usize, SimpleEncoderFn<'a, X, T>);

enum SimpleEncoderFn<'a, X, T: Data> {
    Cast {
        col: &'a mut T::Mut,
        encode: for<'b> fn(&'b X) -> T::Ref<'b>,
    },
    Push {
        col: &'a mut T::Mut,
        encode: fn(&mut T::Mut, &X),
    },
}

impl<'a, X, T: Data> PartEncoder<'a, X> for SimpleEncoder<'a, X, T> {
    fn encode(&mut self, val: &X) {
        *self.0 += 1;
        match &mut self.1 {
            SimpleEncoderFn::Cast { col, encode } => ColumnPush::<T>::push(*col, encode(val)),
            SimpleEncoderFn::Push { col, encode } => encode(col, val),
        }
    }
}

/// An implementation of [PartDecoder] for a single column.
pub struct SimpleDecoder<'a, X, T: Data> {
    col: &'a T::Col,
    decode: fn(T::Ref<'a>, &mut X),
}

impl<'a, X, T: Data> PartDecoder<'a, X> for SimpleDecoder<'a, X, T> {
    fn decode(&self, idx: usize, val: &mut X) {
        (self.decode)(ColumnGet::<T>::get(self.col, idx), val)
    }
}

/// A helper for writing Schemas of a single column.
pub struct SimpleSchema<X, T: Data>(PhantomData<(X, T)>);

// TODO: Feels like it should be possible to write a single impl of Schema to
// cover StringSchema, VecU8Schema, MaelstromKeySchema, etc in terms of
// ColumnRef and ColumnMut. We might have to pull in the rust experts though,
// the lifetimes get tricky.
impl<X, T: Data> SimpleSchema<X, T> {
    /// A helper for [Schema::columns] impls of a single column.
    pub fn columns(cfg: &T::Cfg) -> DynStructCfg {
        DynStructCfg::from(vec![("".to_owned(), cfg.as_type(), StatsFn::Default)])
    }

    /// A helper for [Schema::decoder] impls of a single column.
    pub fn decoder<'a>(
        mut cols: ColumnsRef<'a>,
        decode: fn(T::Ref<'a>, &mut X),
    ) -> Result<SimpleDecoder<'a, X, T>, String> {
        let col = cols.col::<T>("")?;
        let () = cols.finish()?;
        Ok(SimpleDecoder { col, decode })
    }

    /// A helper for [Schema::encoder] impls of a single column.
    pub fn encoder<'a>(
        mut cols: ColumnsMut<'a>,
        encode: for<'b> fn(&'b X) -> T::Ref<'b>,
    ) -> Result<SimpleEncoder<'a, X, T>, String> {
        let col = cols.col::<T>("")?;
        let (len, ()) = cols.finish()?;
        Ok(SimpleEncoder(len, SimpleEncoderFn::Cast { col, encode }))
    }

    /// A helper for [Schema::encoder] impls of a single column.
    pub fn push_encoder<'a>(
        mut cols: ColumnsMut<'a>,
        encode: fn(&mut T::Mut, &X),
    ) -> Result<SimpleEncoder<'a, X, T>, String> {
        let col = cols.col::<T>("")?;
        let (len, ()) = cols.finish()?;
        Ok(SimpleEncoder(len, SimpleEncoderFn::Push { col, encode }))
    }
}

/// An implementation of [Schema] for [String].
#[derive(Debug, Clone, Default)]
pub struct StringSchema;

impl Schema<String> for StringSchema {
    type Encoder<'a> = SimpleEncoder<'a, String, String>;

    type Decoder<'a> = SimpleDecoder<'a, String, String>;

    fn columns(&self) -> DynStructCfg {
        SimpleSchema::<String, String>::columns(&())
    }

    fn decoder<'a>(&self, cols: ColumnsRef<'a>) -> Result<Self::Decoder<'a>, String> {
        SimpleSchema::<String, String>::decoder(cols, |val, ret| val.clone_into(ret))
    }

    fn encoder<'a>(&self, cols: ColumnsMut<'a>) -> Result<Self::Encoder<'a>, String> {
        SimpleSchema::<String, String>::encoder(cols, |val| val.as_str())
    }
}

impl Codec for String {
    type Storage = ();
    type Schema = StringSchema;

    fn codec_name() -> String {
        "String".into()
    }

    fn encode<B>(&self, buf: &mut B)
    where
        B: BufMut,
    {
        buf.put(self.as_bytes())
    }

    fn decode<'a>(buf: &'a [u8]) -> Result<Self, String> {
        String::from_utf8(buf.to_owned()).map_err(|err| err.to_string())
    }
}

/// An implementation of [Schema] for [`Vec<u8>`].
#[derive(Debug, Clone, Default)]
pub struct VecU8Schema;

impl Schema<Vec<u8>> for VecU8Schema {
    type Encoder<'a> = SimpleEncoder<'a, Vec<u8>, Vec<u8>>;

    type Decoder<'a> = SimpleDecoder<'a, Vec<u8>, Vec<u8>>;

    fn columns(&self) -> DynStructCfg {
        SimpleSchema::<Vec<u8>, Vec<u8>>::columns(&())
    }

    fn decoder<'a>(&self, cols: ColumnsRef<'a>) -> Result<Self::Decoder<'a>, String> {
        SimpleSchema::<Vec<u8>, Vec<u8>>::decoder(cols, |val, ret| val.clone_into(ret))
    }

    fn encoder<'a>(&self, cols: ColumnsMut<'a>) -> Result<Self::Encoder<'a>, String> {
        SimpleSchema::<Vec<u8>, Vec<u8>>::encoder(cols, |val| val.as_slice())
    }
}

impl Codec for Vec<u8> {
    type Storage = ();
    type Schema = VecU8Schema;

    fn codec_name() -> String {
        "Vec<u8>".into()
    }

    fn encode<B>(&self, buf: &mut B)
    where
        B: BufMut,
    {
        buf.put(self.as_slice())
    }

    fn decode<'a>(buf: &'a [u8]) -> Result<Self, String> {
        Ok(buf.to_owned())
    }
}

impl Codec for ShardId {
    type Storage = ();
    type Schema = ShardIdSchema;
    fn codec_name() -> String {
        "ShardId".into()
    }
    fn encode<B: BufMut>(&self, buf: &mut B) {
        buf.put(self.to_string().as_bytes())
    }
    fn decode<'a>(buf: &'a [u8]) -> Result<Self, String> {
        let shard_id = String::from_utf8(buf.to_owned()).map_err(|err| err.to_string())?;
        shard_id.parse()
    }
}

/// An implementation of [Schema] for [ShardId].
#[derive(Debug)]
pub struct ShardIdSchema;

impl Schema<ShardId> for ShardIdSchema {
    type Encoder<'a> = SimpleEncoder<'a, ShardId, String>;

    type Decoder<'a> = SimpleDecoder<'a, ShardId, String>;

    fn columns(&self) -> DynStructCfg {
        SimpleSchema::<ShardId, String>::columns(&())
    }

    fn decoder<'a>(&self, cols: ColumnsRef<'a>) -> Result<Self::Decoder<'a>, String> {
        SimpleSchema::<ShardId, String>::decoder(cols, |val, ret| {
            *ret = val.parse().expect("should be valid ShardId")
        })
    }

    fn encoder<'a>(&self, cols: ColumnsMut<'a>) -> Result<Self::Encoder<'a>, String> {
        SimpleSchema::<ShardId, String>::push_encoder(cols, |col, val| {
            ColumnPush::<String>::push(col, &val.to_string())
        })
    }
}

impl Codec64 for i64 {
    fn codec_name() -> String {
        "i64".to_owned()
    }

    fn encode(&self) -> [u8; 8] {
        self.to_le_bytes()
    }

    fn decode(buf: [u8; 8]) -> Self {
        i64::from_le_bytes(buf)
    }
}

impl Codec64 for u64 {
    fn codec_name() -> String {
        "u64".to_owned()
    }

    fn encode(&self) -> [u8; 8] {
        self.to_le_bytes()
    }

    fn decode(buf: [u8; 8]) -> Self {
        u64::from_le_bytes(buf)
    }
}

impl Opaque for u64 {
    fn initial() -> Self {
        u64::MIN
    }
}

// TODO: Remove this once we wrap coord epochs in an `Epoch` struct and impl
// Opaque on `Epoch` instead.
impl Opaque for i64 {
    fn initial() -> Self {
        i64::MIN
    }
}

impl Data for bool {
    type Cfg = ();
    type Ref<'a> = bool;
    type Col = Bitmap;
    type Mut = MutableBitmap;
    type Stats = PrimitiveStats<bool>;
}

impl ColumnCfg<bool> for () {
    fn as_type(&self) -> DataType {
        DataType {
            optional: false,
            format: ColumnFormat::Bool,
        }
    }
}

impl Data for Option<bool> {
    type Cfg = ();
    type Ref<'a> = Option<bool>;
    type Col = BooleanArray;
    type Mut = MutableBooleanArray;
    type Stats = OptionStats<PrimitiveStats<bool>>;
}

impl ColumnCfg<Option<bool>> for () {
    fn as_type(&self) -> DataType {
        DataType {
            optional: true,
            format: ColumnFormat::Bool,
        }
    }
}

macro_rules! data_primitive {
    ($data:ident, $format:expr) => {
        impl Data for $data {
            type Cfg = ();
            type Ref<'a> = $data;
            type Col = Buffer<$data>;
            type Mut = Vec<$data>;
            type Stats = PrimitiveStats<$data>;
        }

        impl ColumnCfg<$data> for () {
            fn as_type(&self) -> DataType {
                DataType {
                    optional: false,
                    format: $format,
                }
            }
        }

        impl Data for Option<$data> {
            type Cfg = ();
            type Ref<'a> = Option<$data>;
            type Col = PrimitiveArray<$data>;
            type Mut = MutablePrimitiveArray<$data>;
            type Stats = OptionStats<PrimitiveStats<$data>>;
        }

        impl ColumnCfg<Option<$data>> for () {
            fn as_type(&self) -> DataType {
                DataType {
                    optional: true,
                    format: $format,
                }
            }
        }
    };
}

data_primitive!(u8, ColumnFormat::U8);
data_primitive!(u16, ColumnFormat::U16);
data_primitive!(u32, ColumnFormat::U32);
data_primitive!(u64, ColumnFormat::U64);
data_primitive!(i8, ColumnFormat::I8);
data_primitive!(i16, ColumnFormat::I16);
data_primitive!(i32, ColumnFormat::I32);
data_primitive!(i64, ColumnFormat::I64);
data_primitive!(f32, ColumnFormat::F32);
data_primitive!(f64, ColumnFormat::F64);

impl Data for Vec<u8> {
    type Cfg = ();
    type Ref<'a> = &'a [u8];
    // TODO: Something that more obviously isn't optional.
    type Col = BinaryArray<i32>;
    type Mut = MutableBinaryArray<i32>;
    type Stats = BytesStats;
}

impl ColumnCfg<Vec<u8>> for () {
    fn as_type(&self) -> DataType {
        DataType {
            optional: false,
            format: ColumnFormat::Bytes,
        }
    }
}

impl Data for Option<Vec<u8>> {
    type Cfg = ();
    type Ref<'a> = Option<&'a [u8]>;
    type Col = BinaryArray<i32>;
    type Mut = MutableBinaryArray<i32>;
    type Stats = OptionStats<BytesStats>;
}

impl ColumnCfg<Option<Vec<u8>>> for () {
    fn as_type(&self) -> DataType {
        DataType {
            optional: true,
            format: ColumnFormat::Bytes,
        }
    }
}

impl Data for String {
    type Cfg = ();
    type Ref<'a> = &'a str;
    // TODO: Something that more obviously isn't optional.
    type Col = Utf8Array<i32>;
    type Mut = MutableUtf8Array<i32>;
    type Stats = PrimitiveStats<String>;
}

impl ColumnCfg<String> for () {
    fn as_type(&self) -> DataType {
        DataType {
            optional: false,
            format: ColumnFormat::String,
        }
    }
}

impl Data for Option<String> {
    type Cfg = ();
    type Ref<'a> = Option<&'a str>;
    type Col = Utf8Array<i32>;
    type Mut = MutableUtf8Array<i32>;
    type Stats = OptionStats<PrimitiveStats<String>>;
}

impl ColumnCfg<Option<String>> for () {
    fn as_type(&self) -> DataType {
        DataType {
            optional: true,
            format: ColumnFormat::String,
        }
    }
}

impl Data for DynStruct {
    type Cfg = DynStructCfg;
    type Ref<'a> = DynStructRef<'a>;
    type Col = DynStructCol;
    type Mut = DynStructMut;
    type Stats = StructStats;
}

impl ColumnCfg<DynStruct> for DynStructCfg {
    fn as_type(&self) -> DataType {
        DataType {
            optional: false,
            format: ColumnFormat::Struct(self.clone()),
        }
    }
}

impl Data for Option<DynStruct> {
    type Cfg = DynStructCfg;
    type Ref<'a> = Option<DynStructRef<'a>>;
    type Col = DynStructCol;
    type Mut = DynStructMut;
    type Stats = OptionStats<StructStats>;
}

impl ColumnCfg<Option<DynStruct>> for DynStructCfg {
    fn as_type(&self) -> DataType {
        DataType {
            optional: true,
            format: ColumnFormat::Struct(self.clone()),
        }
    }
}

impl ColumnRef<()> for Bitmap {
    fn cfg(&self) -> &() {
        &()
    }
    fn len(&self) -> usize {
        self.len()
    }
    fn to_arrow(&self) -> (Encoding, Box<dyn Array>) {
        let array = BooleanArray::new(ArrowLogicalType::Boolean, self.clone(), None);
        (Encoding::Plain, Box::new(array))
    }
    fn from_arrow(_cfg: &(), array: &Box<dyn Array>) -> Result<Self, String> {
        let array = array
            .as_any()
            .downcast_ref::<BooleanArray>()
            .ok_or_else(|| format!("expected BooleanArray but was {:?}", array.data_type()))?;
        if array.validity().is_some() {
            return Err("unexpected validity for non-optional bool".to_owned());
        }
        Ok(array.values().clone())
    }
}

impl ColumnGet<bool> for Bitmap {
    fn get<'a>(&'a self, idx: usize) -> bool {
        self.get_bit(idx)
    }
}

impl ColumnPush<bool> for MutableBitmap {
    fn push<'a>(&mut self, val: bool) {
        <MutableBitmap>::push(self, val)
    }
}

impl ColumnRef<()> for BooleanArray {
    fn cfg(&self) -> &() {
        &()
    }
    fn len(&self) -> usize {
        self.len()
    }
    fn to_arrow(&self) -> (Encoding, Box<dyn Array>) {
        (Encoding::Plain, Box::new(self.clone()))
    }
    fn from_arrow(_cfg: &(), array: &Box<dyn Array>) -> Result<Self, String> {
        let array = array
            .as_any()
            .downcast_ref::<BooleanArray>()
            .ok_or_else(|| format!("expected BooleanArray but was {:?}", array.data_type()))?;
        Ok(array.clone())
    }
}

impl ColumnGet<Option<bool>> for BooleanArray {
    fn get<'a>(&'a self, idx: usize) -> Option<bool> {
        if self.validity().map_or(true, |x| x.get_bit(idx)) {
            Some(self.value(idx))
        } else {
            None
        }
    }
}

impl ColumnPush<Option<bool>> for MutableBooleanArray {
    fn push<'a>(&mut self, val: Option<bool>) {
        <MutableBooleanArray>::push(self, val)
    }
}

macro_rules! arrowable_primitive {
    ($data:ident, $encoding:expr) => {
        impl ColumnRef<()> for Buffer<$data> {
            fn cfg(&self) -> &() {
                &()
            }
            fn len(&self) -> usize {
                self.len()
            }
            fn to_arrow(&self) -> (Encoding, Box<dyn Array>) {
                let array = PrimitiveArray::new($data::PRIMITIVE.into(), self.clone(), None);
                ($encoding, Box::new(array.clone()))
            }
            fn from_arrow(_cfg: &(), array: &Box<dyn Array>) -> Result<Self, String> {
                let array = array
                    .as_any()
                    .downcast_ref::<PrimitiveArray<$data>>()
                    .ok_or_else(|| {
                        format!(
                            "expected {} but was {:?}",
                            std::any::type_name::<PrimitiveArray<$data>>(),
                            array.data_type()
                        )
                    })?;
                if array.validity().is_some() {
                    return Err(format!(
                        "unexpected validity for non-optional {}",
                        std::any::type_name::<$data>()
                    ));
                }
                Ok(array.values().clone())
            }
        }

        impl ColumnGet<$data> for Buffer<$data> {
            fn get<'a>(&'a self, idx: usize) -> $data {
                self[idx]
            }
        }

        impl ColumnPush<$data> for Vec<$data> {
            fn push<'a>(&mut self, val: $data) {
                <Vec<$data>>::push(self, val)
            }
        }

        impl ColumnRef<()> for PrimitiveArray<$data> {
            fn cfg(&self) -> &() {
                &()
            }
            fn len(&self) -> usize {
                self.len()
            }
            fn to_arrow(&self) -> (Encoding, Box<dyn Array>) {
                ($encoding, Box::new(self.clone()))
            }
            fn from_arrow(_cfg: &(), array: &Box<dyn Array>) -> Result<Self, String> {
                let array = array
                    .as_any()
                    .downcast_ref::<PrimitiveArray<$data>>()
                    .ok_or_else(|| {
                        format!(
                            "expected {} but was {:?}",
                            std::any::type_name::<PrimitiveArray<$data>>(),
                            array.data_type()
                        )
                    })?;
                Ok(array.clone())
            }
        }

        impl ColumnGet<Option<$data>> for PrimitiveArray<$data> {
            fn get<'a>(&'a self, idx: usize) -> Option<$data> {
                if self.validity().map_or(true, |x| x.get_bit(idx)) {
                    Some(self.value(idx))
                } else {
                    None
                }
            }
        }

        impl ColumnPush<Option<$data>> for MutablePrimitiveArray<$data> {
            fn push<'a>(&mut self, val: Option<$data>) {
                <MutablePrimitiveArray<$data>>::push(self, val)
            }
        }
    };
}

arrowable_primitive!(u8, Encoding::Plain);
arrowable_primitive!(u16, Encoding::Plain);
arrowable_primitive!(u32, Encoding::Plain);
arrowable_primitive!(u64, Encoding::Plain);
arrowable_primitive!(i8, Encoding::Plain);
arrowable_primitive!(i16, Encoding::Plain);
arrowable_primitive!(i32, Encoding::Plain);
arrowable_primitive!(i64, Encoding::Plain);
arrowable_primitive!(f32, Encoding::Plain);
arrowable_primitive!(f64, Encoding::Plain);

impl ColumnRef<()> for BinaryArray<i32> {
    fn cfg(&self) -> &() {
        &()
    }
    fn len(&self) -> usize {
        self.len()
    }
    fn to_arrow(&self) -> (Encoding, Box<dyn Array>) {
        (Encoding::Plain, Box::new(self.clone()))
    }
    fn from_arrow(_cfg: &(), array: &Box<dyn Array>) -> Result<Self, String> {
        let array = array
            .as_any()
            .downcast_ref::<BinaryArray<i32>>()
            .ok_or_else(|| format!("expected BinaryArray<i32> but was {:?}", array.data_type()))?;
        Ok(array.clone())
    }
}

impl ColumnGet<Vec<u8>> for BinaryArray<i32> {
    fn get<'a>(&'a self, idx: usize) -> &'a [u8] {
        assert!(self.validity().is_none());
        self.value(idx)
    }
}

impl ColumnGet<Option<Vec<u8>>> for BinaryArray<i32> {
    fn get<'a>(&'a self, idx: usize) -> Option<&'a [u8]> {
        if self.validity().map_or(true, |x| x.get_bit(idx)) {
            Some(self.value(idx))
        } else {
            None
        }
    }
}

impl ColumnPush<Vec<u8>> for MutableBinaryArray<i32> {
    fn push<'a>(&mut self, val: &'a [u8]) {
        assert!(self.validity().is_none());
        <MutableBinaryArray<i32>>::push(self, Some(val))
    }
}

impl ColumnPush<Option<Vec<u8>>> for MutableBinaryArray<i32> {
    fn push<'a>(&mut self, val: Option<&'a [u8]>) {
        <MutableBinaryArray<i32>>::push(self, val)
    }
}

impl ColumnRef<()> for Utf8Array<i32> {
    fn cfg(&self) -> &() {
        &()
    }
    fn len(&self) -> usize {
        self.len()
    }
    fn to_arrow(&self) -> (Encoding, Box<dyn Array>) {
        (Encoding::Plain, Box::new(self.clone()))
    }
    fn from_arrow(_cfg: &(), array: &Box<dyn Array>) -> Result<Self, String> {
        let array = array
            .as_any()
            .downcast_ref::<Utf8Array<i32>>()
            .ok_or_else(|| format!("expected Utf8Array<i32> but was {:?}", array.data_type()))?;
        Ok(array.clone())
    }
}

impl ColumnGet<String> for Utf8Array<i32> {
    fn get<'a>(&'a self, idx: usize) -> &'a str {
        assert!(self.validity().is_none());
        self.value(idx)
    }
}

impl ColumnGet<Option<String>> for Utf8Array<i32> {
    fn get<'a>(&'a self, idx: usize) -> Option<&'a str> {
        if self.validity().map_or(true, |x| x.get_bit(idx)) {
            Some(self.value(idx))
        } else {
            None
        }
    }
}

impl ColumnPush<String> for MutableUtf8Array<i32> {
    fn push<'a>(&mut self, val: &'a str) {
        assert!(self.validity().is_none());
        <MutableUtf8Array<i32>>::push(self, Some(val))
    }
}

impl ColumnPush<Option<String>> for MutableUtf8Array<i32> {
    fn push<'a>(&mut self, val: Option<&'a str>) {
        <MutableUtf8Array<i32>>::push(self, val)
    }
}

/// A placeholder for a [Codec] impl that hasn't yet gotten a real [Schema].
#[derive(Debug)]
pub struct TodoSchema<T>(PhantomData<T>);

impl<T> Default for TodoSchema<T> {
    fn default() -> Self {
        Self(Default::default())
    }
}

impl<T> PartEncoder<'_, T> for TodoSchema<T> {
    fn encode(&mut self, _val: &T) {
        panic!("TODO")
    }
}

impl<T> PartDecoder<'_, T> for TodoSchema<T> {
    fn decode(&self, _idx: usize, _val: &mut T) {
        panic!("TODO")
    }
}

impl<T: Debug + Send + Sync> Schema<T> for TodoSchema<T> {
    type Encoder<'a> = Self;
    type Decoder<'a> = Self;

    fn columns(&self) -> DynStructCfg {
        panic!("TODO")
    }

    fn decoder<'a>(&self, _cols: ColumnsRef<'a>) -> Result<Self::Decoder<'a>, String> {
        panic!("TODO")
    }

    fn encoder<'a>(&self, _cols: ColumnsMut<'a>) -> Result<Self::Encoder<'a>, String> {
        panic!("TODO")
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use serde::{Deserialize, Serialize};
    use serde_json::json;

    use super::*;

    #[mz_ore::test]
    fn fmt_ids() {
        assert_eq!(
            format!("{}", ShardId([0u8; 16])),
            "s00000000-0000-0000-0000-000000000000"
        );
        assert_eq!(
            format!("{:?}", ShardId([0u8; 16])),
            "ShardId(00000000-0000-0000-0000-000000000000)"
        );

        // ShardId can be parsed back from its Display/to_string format.
        assert_eq!(
            ShardId::from_str("s00000000-0000-0000-0000-000000000000"),
            Ok(ShardId([0u8; 16]))
        );
        assert_eq!(
            ShardId::from_str("x00000000-0000-0000-0000-000000000000"),
            Err(
                "invalid ShardId x00000000-0000-0000-0000-000000000000: incorrect prefix"
                    .to_string()
            )
        );
        assert_eq!(
            ShardId::from_str("s0"),
            Err(
                "invalid ShardId s0: invalid length: expected length 32 for simple format, found 1"
                    .to_string()
            )
        );
        assert_eq!(
            ShardId::from_str("s00000000-0000-0000-0000-000000000000FOO"),
            Err("invalid ShardId s00000000-0000-0000-0000-000000000000FOO: invalid character: expected an optional prefix of `urn:uuid:` followed by [0-9a-fA-F-], found `O` at 38".to_string())
        );
    }

    #[mz_ore::test]
    fn shard_id_human_readable_serde() {
        #[derive(Debug, Serialize, Deserialize)]
        struct ShardIdContainer {
            shard_id: ShardId,
        }

        // roundtrip id through json
        let id =
            ShardId::from_str("s00000000-1234-5678-0000-000000000000").expect("valid shard id");
        assert_eq!(
            id,
            serde_json::from_value(serde_json::to_value(id).expect("serializable"))
                .expect("deserializable")
        );

        // deserialize a serialized string directly
        assert_eq!(
            id,
            serde_json::from_str("\"s00000000-1234-5678-0000-000000000000\"")
                .expect("deserializable")
        );

        // roundtrip shard id through a container type
        let json = json!({ "shard_id": id });
        assert_eq!(
            "{\"shard_id\":\"s00000000-1234-5678-0000-000000000000\"}",
            &json.to_string()
        );
        let container: ShardIdContainer = serde_json::from_value(json).expect("deserializable");
        assert_eq!(container.shard_id, id);
    }
}