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
use std::{
    fmt::{Debug, Display},
    marker::PhantomData,
    ops::Index,
    str::Utf8Error,
};

use num::ToPrimitive;
use string_interner::{symbol::SymbolU16, Symbol};

use crate::filter::default::VaryHasher;

pub trait MySerializePar {
    /// Must match the `Ok` type of our `Serializer`.
    type Ok;

    /// Must match the `Error` type of our `Serializer`.
    type Error: Error;

    /// Serialize a sequence element.
    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: MySerialize + Keyed<usize>;

    /// Finish serializing a sequence.
    fn end(self) -> Result<Self::Ok, Self::Error>;
}
pub trait MySerializeSco {
    /// Must match the `Ok` type of our `Serializer`.
    type Ok;

    /// Must match the `Error` type of our `Serializer`.
    type Error: Error;

    /// Serialize a sequence element.
    fn serialize_object<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: MySerialize + Keyed<usize>;

    /// Finish serializing a sequence.
    fn end(self, s: &str) -> Result<Self::Ok, Self::Error>;
}

pub trait Keyed<T> {
    fn key(&self) -> T;
}

pub trait Error: Sized + std::error::Error {
    fn custom<T>(msg: T) -> Self
    where
        T: Display;
}

pub trait MySerializer: Sized {
    /// The output type produced by this `Serializer` during successful
    /// serialization. Most serializers that produce text or binary output
    /// should set `Ok = ()` and serialize into an [`io::Write`] or buffer
    /// contained within the `Serializer` instance. Serializers that build
    /// in-memory data structures may be simplified by using `Ok` to propagate
    /// the data structure around.
    ///
    /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
    type Ok;

    /// The error type when some error occurs during serialization.
    type Error: Error;

    /// Type returned from [`serialize_seq`] for serializing the content of the
    /// sequence.
    ///
    /// [`serialize_seq`]: #tymethod.serialize_seq
    type SerializePar: MySerializePar<Ok = Self::Ok, Error = Self::Error>;
    type SerializeSco: MySerializeSco<Ok = Self::Ok, Error = Self::Error>;

    fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: Display;

    fn serialize_par(self, len: Option<usize>) -> Result<Self::SerializePar, Self::Error>;

    fn serialize_sco(self, len: Option<usize>) -> Result<Self::SerializeSco, Self::Error>;
}

pub trait MySerialize {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: MySerializer;
}

pub struct Table<T> {
    offsets: Vec<u32>,
    choices: Vec<u16>,
    buf: Vec<T>,
}

impl<T> Default for Table<T> {
    fn default() -> Self {
        Self {
            offsets: Default::default(),
            choices: Default::default(),
            buf: Default::default(),
        }
    }
}

impl<T> Index<SymbolU16> for Table<T> {
    type Output = [T];

    fn index(&self, index: SymbolU16) -> &Self::Output {
        let index = index.to_usize();
        let o = self.offsets[index] as usize;
        let c = self.choices[index] as usize;
        &self.buf[o..o + c]
    }
}

impl<T> Table<T> {
    fn insert(&mut self, index: usize, v: Vec<T>) -> SymbolU16 {
        assert_ne!(v.len(), 0);
        if self.offsets.len() <= index {
            self.offsets.resize(index + 1, 0);
            self.choices.resize(index + 1, 0);
        }
        if self.offsets[index] != 0 {
            assert!(self.choices[index] == v.len().to_u16().unwrap());
            return SymbolU16::try_from_usize(index).unwrap();
        }
        self.offsets[index] = self.buf.len().to_u32().unwrap();
        self.choices[index] = v.len().to_u16().unwrap();
        self.buf.extend(v);
        SymbolU16::try_from_usize(index).unwrap()
    }
}

#[derive(Debug)]
pub struct CachedHasherError(String);

impl Display for CachedHasherError {
    fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Ok(())
    }
}
impl From<std::io::Error> for CachedHasherError {
    fn from(e: std::io::Error) -> Self {
        Self(e.to_string())
    }
}
impl From<Utf8Error> for CachedHasherError {
    fn from(e: Utf8Error) -> Self {
        Self(e.to_string())
    }
}

impl std::error::Error for CachedHasherError {}

impl Error for CachedHasherError {
    fn custom<T>(msg: T) -> Self
    where
        T: std::fmt::Display,
    {
        Self(msg.to_string())
    }
}

/// Could simplify structurally, fusioning Auxilary serializers
pub struct CachedHasher<'a, I, S, H: VaryHasher<S>> {
    pub(crate) index: I,
    pub(crate) table: &'a mut Table<H>,
    pub(crate) phantom: PhantomData<(*const H, *const S)>,
}
impl<'a, I, S, H: VaryHasher<S>> CachedHasher<'a, I, S, H> {
    pub fn new(table: &'a mut Table<H>, index: I) -> Self {
        Self {
            index,
            table: table,
            phantom: PhantomData,
        }
    }
}
impl<H: VaryHasher<u8>> CachedHasher<'static, usize, u8, H> {
    pub fn once<T: MySerialize + Keyed<usize>>(x: T) -> Vec<u8> {
        let mut table = Default::default();
        let s = CachedHasher::<usize, u8, H> {
            index: x.key(),
            table: &mut table,
            phantom: PhantomData,
        };
        match x.serialize(s) {
            Ok(x) => table[x].iter().map(|x| x.finish()).collect(),
            Err(e) => {
                log::error!("error {} with hashing of {}", e, x.key());
                vec![]
            }
        }
    }
}

impl<'a, H: VaryHasher<u16>> CachedHasher<'a, usize, u16, H> {
    pub fn once<T: MySerialize + Keyed<usize>>(x: T) -> Vec<u16> {
        let mut table = Default::default();
        let s = CachedHasher::<usize, u16, H> {
            index: x.key(),
            table: &mut table,
            phantom: PhantomData,
        };
        match x.serialize(s) {
            Ok(x) => table[x].iter().map(|x| x.finish()).collect(),
            Err(e) => {
                log::error!("error {} with hashing of {}", e, x.key());
                vec![]
            }
        }
    }
}

impl<'a, H: 'a + VaryHasher<u8>> MySerializer for CachedHasher<'a, usize, u8, H> {
    type Ok = SymbolU16; // TODO use an u8 symbol

    type Error = CachedHasherError;

    type SerializePar = CachedHasherAux<'a, usize, u8, H>;
    type SerializeSco = CachedHasherAux<'a, usize, u8, H>;

    fn serialize_par(self, _: Option<usize>) -> Result<Self::SerializePar, Self::Error> {
        Ok(CachedHasherAux {
            index: self.index,
            table: self.table,
            acc: Default::default(),
            _phantom: PhantomData,
        })
    }

    fn serialize_sco(self, _: Option<usize>) -> Result<Self::SerializeSco, Self::Error> {
        Ok(CachedHasherAux {
            index: self.index,
            table: self.table,
            acc: Default::default(),
            _phantom: PhantomData,
        })
    }

    fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: Display,
    {
        let mut h = H::new(0);
        h.write(value.to_string().as_bytes());
        let x = self.table.insert(self.index, vec![h]);
        Ok(x)
    }
}

impl<'a, H: 'a + VaryHasher<u16>> MySerializer for CachedHasher<'a, usize, u16, H> {
    type Ok = SymbolU16;

    type Error = CachedHasherError;

    type SerializePar = CachedHasherAux<'a, usize, u16, H>;
    type SerializeSco = CachedHasherAux<'a, usize, u16, H>;

    fn serialize_par(self, _: Option<usize>) -> Result<Self::SerializePar, Self::Error> {
        Ok(CachedHasherAux {
            index: self.index,
            table: self.table,
            acc: Default::default(),
            _phantom: PhantomData,
        })
    }

    fn serialize_sco(self, _: Option<usize>) -> Result<Self::SerializeSco, Self::Error> {
        Ok(CachedHasherAux {
            index: self.index,
            table: self.table,
            acc: Default::default(),
            _phantom: PhantomData,
        })
    }

    fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: Display,
    {
        let mut h = H::new(0);
        h.write(value.to_string().as_bytes());
        let x = self.table.insert(self.index, vec![h]);
        Ok(x)
    }
}

pub struct CachedHasherAux<'a, I, S, H: VaryHasher<S>> {
    index: I,
    table: &'a mut Table<H>,
    acc: Vec<H>,
    _phantom: PhantomData<*const S>,
}

impl<'a, H: VaryHasher<u8>> MySerializePar for CachedHasherAux<'a, usize, u8, H> {
    type Ok = SymbolU16;

    type Error = CachedHasherError;

    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: MySerialize + Keyed<usize>,
    {
        let x = value.serialize(CachedHasher::<_, _, H> {
            index: value.key(),
            table: self.table,
            phantom: PhantomData,
        })?;
        for x in &self.table[x] {
            let h = x.clone();
            self.acc.push(h);
        }
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        if self.acc.is_empty() {
            Err(CachedHasherError::custom("empty element"))
        } else {
            Ok(self.table.insert(self.index, self.acc))
        }
    }
}

impl<'a, H: VaryHasher<u16>> MySerializePar for CachedHasherAux<'a, usize, u16, H> {
    type Ok = SymbolU16;

    type Error = CachedHasherError;

    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: MySerialize + Keyed<usize>,
    {
        let x = value.serialize(CachedHasher::<_, _, H> {
            index: value.key(),
            table: self.table,
            phantom: PhantomData,
        })?;
        for x in &self.table[x] {
            let h = x.clone();
            self.acc.push(h);
        }
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        if self.acc.is_empty() {
            Err(CachedHasherError::custom("empty element"))
        } else {
            Ok(self.table.insert(self.index, self.acc))
        }
    }
}
impl<'a, H: VaryHasher<u8>> MySerializeSco for CachedHasherAux<'a, usize, u8, H> {
    type Ok = SymbolU16;

    type Error = CachedHasherError;

    fn serialize_object<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: MySerialize + Keyed<usize>,
    {
        let x = value.serialize(CachedHasher::<_, _, H> {
            index: value.key(),
            table: self.table,
            phantom: PhantomData,
        })?;
        for x in &self.table[x] {
            let h = x.clone();
            self.acc.push(h);
        }
        Ok(())
    }

    fn end(mut self, s: &str) -> Result<Self::Ok, Self::Error> {
        for h in &mut self.acc {
            h.write(s.as_bytes());
        }
        Ok(self.table.insert(self.index, self.acc))
    }
}
impl<'a, H: VaryHasher<u16>> MySerializeSco for CachedHasherAux<'a, usize, u16, H> {
    type Ok = SymbolU16;

    type Error = CachedHasherError;

    fn serialize_object<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: MySerialize + Keyed<usize>,
    {
        let x = value.serialize(CachedHasher::<_, _, H> {
            index: value.key(),
            table: self.table,
            phantom: PhantomData,
        })?;
        for x in &self.table[x] {
            let h = x.clone();
            self.acc.push(h);
        }
        Ok(())
    }

    fn end(mut self, s: &str) -> Result<Self::Ok, Self::Error> {
        for h in &mut self.acc {
            h.write(s.as_bytes());
        }
        Ok(self.table.insert(self.index, self.acc))
    }
}