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
use crate::internal::encodings::compress;
use crate::internal::encodings::varint::*;
use crate::prelude::*;
use num_traits::{AsPrimitive, Bounded};
use simple_16::compress as compress_simple_16;
use std::any::TypeId;
use std::convert::{TryFrom, TryInto};
use std::mem::transmute;
use std::vec::IntoIter;

#[derive(Copy, Clone)]
struct U0;

impl Bounded for U0 {
    fn min_value() -> Self {
        U0
    }
    fn max_value() -> Self {
        U0
    }
}

fn write_u0<T>(_data: &[T], _max: T, _bytes: &mut Vec<u8>, _lens: &mut Vec<usize>) -> ArrayTypeId {
    unreachable!();
}

macro_rules! impl_lowerable {
    ($Ty:ty, $fn:ident, $Lty:ty, $lfn:ident, ($($lower:ty),*), ($($compressions:ty),+)) => {
        impl TryFrom<$Ty> for U0 {
            type Error=();
            fn try_from(_value: $Ty) -> Result<U0, Self::Error> {
                Err(())
            }
        }
        impl TryFrom<U0> for $Ty {
            type Error=();
            fn try_from(_value: U0) -> Result<$Ty, Self::Error> {
                Err(())
            }
        }
        impl AsPrimitive<U0> for $Ty {
            fn as_(self) -> U0 {
                unreachable!()
            }
        }

        #[cfg(feature = "write")]
        impl<'a> Writable<'a> for $Ty {
            type WriterArray = Vec<$Ty>;
            fn write_root<'b: 'a>(value: &'b Self, bytes: &mut Vec<u8>, _lens: &mut Vec<usize>) -> RootTypeId {
                write_root_uint(*value as u64, bytes)
            }
        }

        #[cfg(feature = "write")]
        impl<'a> WriterArray<'a> for Vec<$Ty> {
            type Write = $Ty;
            fn buffer<'b: 'a>(&mut self, value: &'b Self::Write) {
                self.push(*value);
            }
            fn flush(self, bytes: &mut Vec<u8>, lens: &mut Vec<usize>) -> ArrayTypeId {
                let max = self.iter().max();
                if let Some(max) = max {
                    $fn(&self, *max, bytes, lens)
                } else {
                    ArrayTypeId::Void
                }
            }
        }

        #[cfg(feature = "read")]
        impl Readable for $Ty {
            type ReaderArray = IntoIter<$Ty>;
            fn read(sticks: DynRootBranch<'_>) -> ReadResult<Self> {
                match sticks {
                    DynRootBranch::Integer(root_int) => {
                        match root_int {
                            RootInteger::U(v) => v.try_into().map_err(|_| ReadError::SchemaMismatch),
                            _ => Err(ReadError::SchemaMismatch),
                        }
                    }
                    _ => Err(ReadError::SchemaMismatch),
                }
            }
        }

        #[cfg(feature = "read")]
        impl ReaderArray for IntoIter<$Ty> {
            type Read = $Ty;
            fn new(sticks: DynArrayBranch<'_>) -> ReadResult<Self> {
                match sticks {
                    // TODO: Support eg: delta/zigzag
                    DynArrayBranch::Integer(array_int) => {
                        let ArrayInteger { bytes, encoding } = array_int;
                        match encoding {
                            ArrayIntegerEncoding::PrefixVarInt => {
                                let v: Vec<$Ty> = read_all(
                                        bytes,
                                        |bytes, offset| {
                                            let r: $Ty = decode_prefix_varint(bytes, offset)?.try_into().map_err(|_| ReadError::SchemaMismatch)?;
                                            Ok(r)
                                        }
                                )?;
                                Ok(v.into_iter())
                            }
                            ArrayIntegerEncoding::Simple16 => {
                                let mut v = Vec::new();
                                simple_16::decompress(bytes, &mut v).map_err(|_| ReadError::InvalidFormat(InvalidFormat::DecompressionError))?;
                                let result: Result<Vec<_>, _> = v.into_iter().map(TryInto::<$Ty>::try_into).collect();
                                let v = result.map_err(|_| ReadError::SchemaMismatch)?;
                                Ok(v.into_iter())
                            }
                        }
                    }
                    _ => Err(ReadError::SchemaMismatch),
                }
            }
            fn read_next(&mut self) -> ReadResult<Self::Read> {
                self.next().ok_or_else(|| ReadError::InvalidFormat(InvalidFormat::ShortArray))
            }
        }

        #[cfg(feature = "write")]
        fn $fn<T: Copy + std::fmt::Debug + AsPrimitive<$Ty> + AsPrimitive<U0> + AsPrimitive<u8> + AsPrimitive<$Lty> $(+ AsPrimitive<$lower>)*>
            (data: &[T], max: T, bytes: &mut Vec<u8>, lens: &mut Vec<usize>) -> ArrayTypeId {
            let lower_max: Result<$Ty, _> = <$Lty as Bounded>::max_value().try_into();

            if let Ok(lower_max) = lower_max {
                if lower_max >= max.as_() {
                    return $lfn(data, max, bytes, lens)
                }
            }

            fn write_inner(data: &[$Ty], bytes: &mut Vec<u8>, lens: &mut Vec<usize>) -> ArrayTypeId {
                let start = bytes.len();
                // TODO: (Performance) Remove allocations
                let compressors: Vec<Box<dyn Compressor<Data=$Ty>>> = vec![
                    $(Box::new(<$compressions>::new())),+
                ];
                let type_id = compress(data, bytes, &compressors[..]);
                lens.push(bytes.len() - start);
                type_id
            }

            // Convert data to as<T>, using a transmute if that's already correct
            if TypeId::of::<$Ty>() == TypeId::of::<T>() {
                // Safety - this is a unit conversion.
                let data = unsafe { transmute(data) };
                write_inner(data, bytes, lens)
            } else {
                // TODO: Use second-stack
                let mut v = Vec::new();
                for item in data.iter() {
                    v.push(item.as_());
                }
                write_inner(&v, bytes, lens)
            }
        }
    };
}

// TODO: This does all kinds of silly things. Eg: Perhaps we have u32 and simple16 is best.
// This may downcast to u16 then back up to u32. I'm afraid the final result is just going to
// be a bunch of hairy special code for each type with no generality.
//
// Broadly we only want to downcast if it allows for some other kind of compressor to be used.

// Type, array writer, next lower, next lower writer, non-inferred lowers
impl_lowerable!(u64, write_u64, u32, write_u32, (u16), (PrefixVarIntCompressor::<u64>));
impl_lowerable!(u32, write_u32, u16, write_u16, (), (Simple16Compressor::<u32>, PrefixVarIntCompressor::<u32>)); // TODO: Consider replacing PrefixVarInt at this level with Fixed.
impl_lowerable!(u16, write_u16, u8, write_u8, (), (Simple16Compressor::<u16>, PrefixVarIntCompressor::<u16>));
impl_lowerable!(u8, write_u8, U0, write_u0, (), (Simple16Compressor::<u8>, PrefixVarIntCompressor::<u8>));

#[cfg(feature = "write")]
fn write_root_uint(value: u64, bytes: &mut Vec<u8>) -> RootTypeId {
    let le = value.to_le_bytes();
    match value {
        0 => RootTypeId::Zero,
        1 => RootTypeId::One,
        2..=255 => {
            bytes.push(le[0]);
            RootTypeId::IntU8
        }
        256..=65535 => {
            bytes.extend_from_slice(&le[..2]);
            RootTypeId::IntU16
        }
        65536..=16777215 => {
            bytes.extend_from_slice(&le[..3]);
            RootTypeId::IntU24
        }
        16777216..=4294967295 => {
            bytes.extend_from_slice(&le[..4]);
            RootTypeId::IntU32
        }
        4294967296..=1099511627775 => {
            bytes.extend_from_slice(&le[..5]);
            RootTypeId::IntU40
        }
        1099511627776..=281474976710655 => {
            bytes.extend_from_slice(&le[..6]);
            RootTypeId::IntU48
        }
        281474976710656..=72057594037927936 => {
            bytes.extend_from_slice(&le[..7]);
            RootTypeId::IntU56
        }
        _ => {
            bytes.extend_from_slice(&le);
            RootTypeId::IntU64
        }
    }
}

struct PrefixVarIntCompressor<T> {
    _marker: std::marker::PhantomData<*const T>,
}

impl<T: Into<u64> + Copy> PrefixVarIntCompressor<T> {
    pub fn new() -> Self {
        Self { _marker: Default::default() }
    }
}

impl<T: Into<u64> + Copy> Compressor<'_> for PrefixVarIntCompressor<T> {
    type Data = T;
    fn fast_size_for(&self, data: &[Self::Data]) -> Option<usize> {
        let mut size = 0;
        for item in data {
            size += size_for_varint((*item).into());
        }
        Some(size)
    }
    fn compress(&self, data: &[Self::Data], bytes: &mut Vec<u8>) -> Result<ArrayTypeId, ()> {
        for item in data {
            encode_prefix_varint((*item).into(), bytes);
        }
        Ok(ArrayTypeId::IntPrefixVar)
    }
}

struct Simple16Compressor<T> {
    _marker: std::marker::PhantomData<*const T>,
}

impl<T: Into<u32> + Copy> Simple16Compressor<T> {
    pub fn new() -> Self {
        Self { _marker: Default::default() }
    }
}

impl<T: Into<u32> + Copy> Compressor<'_> for Simple16Compressor<T> {
    type Data = T;

    fn compress(&self, data: &[Self::Data], bytes: &mut Vec<u8>) -> Result<ArrayTypeId, ()> {
        // TODO: (Performance) Use second-stack.
        // TODO: (Performance) This just copies to another Vec in the case where T is u32
        let mut v = Vec::new();
        for item in data {
            let item = *item;
            let item = item.try_into().map_err(|_| ())?;
            v.push(item);
        }

        compress_simple_16(&v, bytes).map_err(|_| ())?;

        Ok(ArrayTypeId::IntSimple16)
    }
}

// TODO: Bitpacking https://crates.io/crates/bitpacking
// TODO: Mayda https://crates.io/crates/mayda