-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathserialization.rs
More file actions
1633 lines (1361 loc) · 69.6 KB
/
Copy pathserialization.rs
File metadata and controls
1633 lines (1361 loc) · 69.6 KB
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![cfg_attr(rustfmt, rustfmt::skip)]
use std::{any::type_name, hash::Hasher, io::{BufRead, BufReader, BufWriter, Read, Seek, Write}, path::PathBuf};
use crate::{morphisms::Catamorphism, PathMap, zipper::{ZipperMoving, ZipperWriting}};
use crate::TrieValue;
extern crate alloc;
use alloc::collections::BTreeMap;
use crate::gxhash::GxHasher;
macro_rules! hex { () => { b'A'..=b'F' | b'0'..=b'9'}; }
//GOAT, Document this module and clean up this list of desiderata
//
// Serialization requirements:
// Should at least maintain the current sharing
// Serialization should not traverse all paths (i.e. use pointer caching)
// Needn't be finance/security correct
// Somewhat fast to (de)serialize
// Stable across machines
// Instant verification if serialized trees are the same (plus if this is true for subtrees, too)
// Version, val count, total path bytes count, and longest path in meta-data
// I added a few, let me know what you think @Luke Peterson @Remy_Clarke
// Big plus if we have skip-ahead (which allows for search, even better if it allows for partial deserialization) (modifié)
//GOAT TODO to make this a nice public-facing API:
// - We decided this format will be called the "topo_dag" format. Change function names to reflect that
// - Separate the trie optimization functionality from the format encode functionality, and move trie optimization
// (aka Merkle Tree optimization) to a separate module that can run independently or called from serialization
// - Figure out if / how we can get the overheads in the encoding in line with the path_serialization, and if
// we can't (or don't want to), then document why.
// - Make a single file format that encapsulates both the metadata and the serialized data, using separate sections.
// - We should specify a private header that includes a file version. LP: You have no idea how much time I've
// lost from my life debugging code when it had loaded an incompatible version of a private file format.
// - Look at a single-pass approach to generate the file, so there is no need for a 2-pass algorithm and a temporary file
// - Eliminate sub-file-names from the publicly exposed API. e.g. `pub const RAW_HEX_DATA_FILENAME`, etc.
// - Create separate entry points to encode it as either compressed or uncompressed.
// - Abstract away filesystem calls, and implement in terms of std::io traits. i.e. `std::io::Read`, `std::io::Write`, `std::io::Seek`
#[repr(u8)]
#[derive(Debug, Clone, Copy)]
enum Tag {
Path = Tag::PATH,
Value = Tag::VALUE,
ChildMask = Tag::CHILD_MASK,
Branches = Tag::BRANCHES,
PathNode = Tag::PATH_NODE,
ValueNode = Tag::VALUE_NODE,
BranchNode = Tag::BRANCH_NODE,
}
impl Tag {
const PATH : u8 = b'p';
const VALUE : u8 = b'v';
const CHILD_MASK : u8 = b'c';
const BRANCHES : u8 = b'b';
const PATH_NODE : u8 = b'P';
const VALUE_NODE : u8 = b'V';
const BRANCH_NODE : u8 = b'B';
}
const U64_BYTES : usize = u64::BITS as usize /8;
const OFFSET_LEN : usize = U64_BYTES;
// a big endian representation of a line offset.
type Offset = [u8; OFFSET_LEN];
const HEX_OFFSET_LEN : usize = OFFSET_LEN*2+1;
/// an ascii represntation of a [`Offset`]
/// the leading byte of a hex offset is a b'x'
type HexOffset = [u8; HEX_OFFSET_LEN];
pub struct SeOutputs {
pub raw_data_path : PathBuf,
pub zeroes_compressed_data_path : PathBuf,
pub meta_path : PathBuf,
}
/// Filename of the raw hex data file at the `out_dir_path` formal parameter in [`write_trie`]
pub const RAW_HEX_DATA_FILENAME : &'static str = "raw_hex.data";
/// Filename of the meta data file at the `out_dir_path` formal parameter in [`write_trie`]
pub const META_DATA_FILENAME : &'static str = "meta.json";
/// Filename of the zero compressesed data file at the `out_dir_path` formal parameter in [`write_trie`]
pub const ZERO_COMPRESSED_HEX_DATA_FILENAME : &'static str = "zero_compressed_hex.data";
pub fn write_trie<C :Catamorphism<V> ,V: TrieValue>(
memo : impl AsRef<str>,
cata : C,
serialize_value : impl for<'read, 'encode> Fn(&'read V, &'encode mut Vec<u8>)->ValueSlice<'read, 'encode>,
out_dir_path : impl AsRef<std::path::Path>
) -> Result<SeOutputs,std::io::Error>
{
core::debug_assert_eq!(
core::alloc::Layout::new::<Offset>().align(),
core::alloc::Layout::new::<u8>().align()
);
let mut data_path = out_dir_path.as_ref().to_path_buf();
data_path.push(RAW_HEX_DATA_FILENAME);
let mut meta_path = out_dir_path.as_ref().to_path_buf();
meta_path.push(META_DATA_FILENAME);
let _ = std::fs::remove_file(&data_path);
let mut data_file = std::fs::File::create_new(&data_path)?;
data_file.write_fmt(format_args!("{:?} :: {:?}\n", type_name::<PathMap<V>>(), memo.as_ref()))?;
let mut meta_file = std::fs::File::create(&meta_path)?;
let pos = data_file.stream_position()?;
let mut context = Ctx {
count : 0,
entry : BTreeMap::new(),
value_offsets : Vec::from([pos]),
data_file : BufWriter::new(data_file),
algf_scratch : AlgFScratch::zeroed(),
serialize_scratch : Vec::with_capacity(4096),
lazy_bytes_pool : Vec::with_capacity(256),
};
let ctx = &mut context;
let Accumulator { max_len, val_count, paths_count, .. } =
cata.into_cata_jumping_side_effect::<Result<Accumulator, std::io::Error>,_>(
|bytemask, accumulators, jump_length, maybe_val, origin_path| {
core::debug_assert!(bytemask.iter().count() == accumulators.len());
let acc0 = match accumulators {
// create nil or branching
[]| [ _, _, ..] => {
// reset the scratch buffer
ctx.algf_scratch.len = 0;
let jump_sub_slice = ctx.lazy_bytes_pool.pop().unwrap_or(Vec::new());
// with the exception of the hash, this is the basis of the "nil" node
let mut acc = Accumulator
{ hash_idx : (GxHasher::with_seed(0).finish_u128(), ctx.count), // note we are not aumulating on this field, this is just a dummy
max_len : origin_path.len(),
val_count : 0,
paths_count : 0,
jump_sub_slice
};
let mut hasher = GxHasher::with_seed(0); // the accumulation for the hash happens here
for each in accumulators {
let Accumulator { mut hash_idx, max_len, val_count, paths_count, jump_sub_slice } = core::mem::replace(each, Ok(Accumulator::zeroed()))?;
'_deal_with_lost_bytes : {
hash_idx = maybe_make_path_node(ctx, &jump_sub_slice, hash_idx)?;
ctx.lazy_bytes_pool.push(jump_sub_slice);
};
hasher.write_u128(hash_idx.0);
let offset = hash_idx.1.to_be_bytes();
let _type_check : Offset = offset;
ctx.algf_scratch.buffer[ctx.algf_scratch.len] = offset_to_hex_be(offset);
acc.max_len = acc.max_len.max(max_len);
acc.val_count += val_count;
acc.paths_count += paths_count;
ctx.algf_scratch.len+=1;
}
let branches_hash = hasher.finish_u128();
// we now have all needed hashes
// find correct offset
let branches_idx =
if let Some(&offset) = ctx.entry.get(&branches_hash) {
offset
} else {
// it does not exist we write it to the file
let Ctx { count, entry: values, value_offsets, data_file, algf_scratch, .. } = ctx;
let cur_idx = *count;
data_file.write(&[Tag::Branches as u8, b' '])?;
data_file.write_all(algf_scratch.buffer[0..algf_scratch.len].as_flattened())?;
data_file.write(&[b'\n'])?;
let new_pos = data_file.stream_position()?;
value_offsets.push(new_pos);
values.insert(branches_hash, cur_idx);
*count += INCR;
cur_idx
};
let branches_hash_idx = (branches_hash, branches_idx);
let child_mask_hash_idx = serialize_with_rollback( ctx,
Tag::ChildMask,
&mut bytemask.0.map(|word| word.reverse_bits().to_be_bytes()).as_flattened().into_iter().copied(),
)?;
let hash_idx = write_node(ctx, Tag::BranchNode, child_mask_hash_idx, branches_hash_idx)?;
Accumulator {
hash_idx,
.. acc
}
}
// collapse without building a child mask
[acc_] => {
let byte = bytemask.iter().next().unwrap();
let mut acc = std::mem::replace(acc_, Ok(Accumulator::zeroed()))?;
acc.jump_sub_slice.insert(0, byte);
let hash_idx = maybe_make_path_node(ctx, &acc.jump_sub_slice, acc.hash_idx)?;
Accumulator {
hash_idx,
.. acc
}
}
};
let mut acc1 = match maybe_val {
// attach value
Some(value) => { let value =
{
let mut tmp = core::mem::replace(&mut ctx.serialize_scratch, Vec::new());
let slice = serialize_value(value, &mut tmp);
let slice = match slice { ValueSlice::Encode(items) => { &*items},
ValueSlice::Read(items) => items,
};
let v = serialize_with_rollback( ctx, Tag::Value,
&mut slice.into_iter().copied(),
)?;
tmp.clear();
let _ = core::mem::replace(&mut ctx.serialize_scratch, tmp);
v
};
let cont = acc0;
let hash_idx = write_node(ctx, Tag::ValueNode, value, cont.hash_idx)?;
Accumulator {
hash_idx,
val_count : cont.val_count+1,
.. cont
}
}
None => { acc0 }
};
acc1.jump_sub_slice.clear();
if origin_path.len() == jump_length {
acc1.hash_idx = maybe_make_path_node(ctx, origin_path, acc1.hash_idx)?;
Ok(acc1)
} else {
acc1.jump_sub_slice.extend_from_slice(&origin_path[origin_path.len()-jump_length..origin_path.len()]);
Ok(acc1)
}
}
)?;
let Ctx { entry: values, value_offsets, mut data_file, .. } = context;
data_file.flush()?;
data_file.rewind()?;
let compressed = offset_and_childmask_zero_compressor(&data_file.into_inner()?, &out_dir_path)?;
let mut values_as_vec = values.into_iter().collect::<Vec<_>>();
values_as_vec.sort_unstable_by(|(_,idx_l), (_,idx_r)| idx_l.cmp(idx_r));
let values = values_as_vec
.iter().copied()
.map( |(h,_)| hash_to_hex_string(h) )
.collect::<Vec<_>>();
meta_file.write_fmt(format_args!("\
{{\
\n \"PATHS_COUNT\" : {paths_count:?},\
\n \"MAX_PATH_LEN\" : {max_len:?},\
\n \"VAL_COUNT\" : {val_count:?},\
\n \"RAW_FILE_OFFSETS\" : {value_offsets:?},\
\n \"ZEROES_COMPRESSED_FILE_OFFSETS\" : {zeroes_offsets:?},\
\n \"HASHES\" : {values:?}\
\n}}
\n",
zeroes_offsets=compressed.offsets
))?;
meta_file.flush()?;
Ok(SeOutputs {
raw_data_path : data_path,
zeroes_compressed_data_path : compressed.path,
meta_path,
})
}
fn rollback_or_advance (
context : &mut Ctx,
hash : u128,
rollback_pos : FilePos
) -> Result<(u128, Index), std::io::Error>
{
Ok(
if let Some(&offset) = context.entry.get(&hash) {
// rollback and use lookup value
let cur_pos = context.data_file.stream_position()?;
context.data_file.seek_relative(rollback_pos as i64 - cur_pos as i64)?;
(hash, offset)
} else {
// advance
let idx = context.count;
context.entry.insert(hash, idx);
context.count += INCR;
context.value_offsets.push(context.data_file.stream_position()?);
(hash, idx)
}
)
}
fn serialize_with_rollback (
context : &mut Ctx,
tag : Tag,
i : &mut dyn Iterator<Item = u8>
) -> Result<(u128, Index), std::io::Error>
{
let rollback_pos = *context.value_offsets.last().unwrap();
let mut hasher = GxHasher::with_seed(0);
hasher.write_u8(tag as u8);
context.data_file.write(&[tag as u8, b' '])?;
for b in i {
hasher.write_u8(b);
context.data_file.write( &byte_to_hex_pair_be(b) )?;
}
let hash = hasher.finish_u128();
context.data_file.write(&[b'\n'])?;
rollback_or_advance(context, hash, rollback_pos)
}
// new_hash === seed(0) -> write_u8(Tag) -> write_u128(Hash) -> write_u128(Hash)
fn write_node(
context : &mut Ctx,
tag : Tag,
(value_hash, value_idx) : (u128, Index),
(cont_hash, cont_idx) : (u128, Index)
) -> Result<(u128, Index), std::io::Error>
{
debug_assert_eq!( context.entry.get(&value_hash), Some(&value_idx) );
debug_assert_eq!( context.entry.get(&cont_hash), Some(&cont_idx) );
let mut hasher = GxHasher::with_seed(0);
hasher.write_u8(tag as u8);
hasher.write_u128(value_hash);
hasher.write_u128(cont_hash);
let hash = hasher.finish_u128();
match context.entry.get(&hash) {
Some(&offset) => Ok((hash, offset)),
None => {
let cur_idx = context.count;
let v_offset = value_idx.to_be_bytes();
let c_offset = cont_idx.to_be_bytes();
let _type_check : [Offset; 2] = [v_offset, c_offset];
context.data_file.write(&[tag as u8, b' '])?;
context.data_file.write(&offset_to_hex_be( v_offset ))?;
context.data_file.write(&offset_to_hex_be( c_offset ))?;
context.data_file.write(&[b'\n'])?;
context.entry.insert(hash, cur_idx);
context.count += INCR;
let new_pos = context.data_file.stream_position()?;
context.value_offsets.push(new_pos);
Ok((hash, cur_idx))
}
}
}
/// makes a path node if the sub_path supplied is non-empty, otherwise returns the passed in `cont_hash_idx`
fn maybe_make_path_node(
ctx : &mut Ctx,
sub_path : &[u8],
cont_hash_idx : (u128, usize)
) -> Result<(u128, usize), std::io::Error>
{
if sub_path.is_empty() {
// don't make a new node
return Ok(cont_hash_idx);
}
let p = serialize_with_rollback( ctx,
Tag::Path,
&mut sub_path.into_iter().copied(),
)?;
write_node(ctx, Tag::PathNode, p, cont_hash_idx)
}
/// helper function for metadata output
fn hash_to_hex_string(h : u128)->String
{
h.to_be_bytes()
.map(byte_to_hex_pair_be)
.into_iter()
.fold(String::new(), |mut acc, [t,b]| { acc.push(t as char); acc.push(b as char); acc})
}
// this being true means we need to add the nil hash to the map
#[cfg(test)]#[test] fn gxhash_finish_zero_is_zero() { core::assert!(GxHasher::with_seed(0).finish_u128() != 0) }
type ChildMask = [u64;4];
/// the position of the cursor in a file
type FilePos = u64;
/// a new Index is generated when the count of Ctx increments
type Index = usize;
struct Ctx{
/// the number of entries into the file
count : usize,
/// entries are hashed as the are serialized, we do this to track sharing, shared entries need to rollbacked if they had been written
entry : BTreeMap<u128, Index>,
/// this is used for "raw_hex_meta.data"
value_offsets : Vec<FilePos>,
/// the writer to the "raw_hex.data"
data_file : BufWriter<std::fs::File>,
algf_scratch : AlgFScratch,
serialize_scratch : Vec<u8>,
/// we need to keep some bytes from sub paths on jumps, and lazily use them on the next step to avoid making single byte paths for singleton paths with values
lazy_bytes_pool : Vec<Vec<u8>>,
}
struct AlgFScratch {
buffer : [ HexOffset; 256],
len : usize,
}
impl AlgFScratch {
const fn zeroed() -> Self { AlgFScratch { buffer: [[0; HEX_OFFSET_LEN];256], len: 0 } }
}
struct Accumulator {
/// The core of the accumulator, the hash is the "semantically identity", the index the "arbitrary identity".
/// We use the arbitrary identity for the file entries, and the hashes for calculating sharing.
hash_idx : (u128, Index),
/// to avoid making singleton branching entries, we thread the jump path to the next join point when needed, and make the path then
jump_sub_slice : Vec<u8>,
/// only accumulated for metadata
max_len : usize,
/// only accumulated for metadata
val_count : usize,
/// only accumulated for metadata
paths_count : usize,
}
impl Accumulator {
const fn zeroed() -> Self {
Accumulator {
hash_idx : (0,0),
max_len : 0,
val_count : 0,
paths_count : 0,
jump_sub_slice : Vec::new(),
}}
}
/// turns a big endian ordered pair of ascii hex bytes in to a byte
fn hex_pair_be_to_byte(pair : [u8;2])->u8{
core::debug_assert!(matches!(pair, [hex!(),hex!()]));
let [top,bot] = pair.map(|h|
match h {
b'0'..=b'9' => h - b'0',
b'A'..=b'F' => h - b'A' + 10,
_ => panic!("found {h}, as char '{}'", h as char)
}
);
(top << 4) | bot
}
/// turns a byte into a big endian ordered pair of ascii hex bytes
fn byte_to_hex_pair_be(b : u8) -> [u8;2] {
let top = b >> 4;
let bot = b & 0x_f;
let unchecked_to_hex = |b : u8| {
match b {
0..=9 => b + b'0',
10..=16 => b + b'A' - 10 ,
_ => panic!("found {b}, as char '{}'", b as char)
}
};
[top, bot].map(unchecked_to_hex)
}
#[cfg(test)] #[test]
fn byte_to_hex_inverses(){ for each in 0..u8::MAX { core::assert_eq!(each, hex_pair_be_to_byte(byte_to_hex_pair_be(each))) } }
/// converts an in memory numberic offset into a ascii hex
fn offset_to_hex_be(bytes : Offset) -> HexOffset {
unsafe {
let mut hex = core::mem::transmute::<_,[u8;OFFSET_LEN*2]>( bytes.map( byte_to_hex_pair_be ) );
let mut out = [0; HEX_OFFSET_LEN];
out[0] = b'x';
(&mut out[1..]).copy_from_slice(&mut hex);
out
}
}
// The datatype that describes what will be sent to the serializer
pub enum ValueSlice<'read, 'encode> {
/// if a value can transparently reveal a slice of bytes that represents enough data to serialize the data this variant can be used
Read(&'read [u8]),
/// if the value cannot be trivially read as bytes, one can encode it into the mutable buffer
Encode(&'encode mut Vec<u8>),
}
/// this constant exists purely for debugging compression of zeros
#[cfg(not(debug_assertions))]
const INCR : usize = 0x_1;
#[cfg(debug_assertions)]
const INCR : usize = 0x_1;
// const INCR : usize = 0x_100000;
struct ZeroCompressedFile {
path : PathBuf,
offsets : Vec<FilePos>
}
fn offset_and_childmask_zero_compressor(
f : &std::fs::File,
out_dir_path: impl AsRef<std::path::Path>
) -> Result<ZeroCompressedFile, std::io::Error> {
let mut path = out_dir_path.as_ref().to_path_buf();
path.push(ZERO_COMPRESSED_HEX_DATA_FILENAME);
let out_file = std::fs::File::create(&path)?;
let mut out = BufWriter::new(out_file);
let mut offsets : Vec<FilePos> = Vec::new();
let reader = BufReader::new(f);
let mut bytes = reader.bytes();
// get past header
while let Some(byte) = bytes.next() {
let x = byte?;
out.write(&[x])?;
if x == b'\n' {break}
}
offsets.push(out.stream_position()?);
let write_zeroes = |z : &mut _, file : &mut BufWriter<_>, boundary : bool| -> Result<(), std::io::Error>{
let dummy = [b'0'; 4];
let mut n = *z;
*z = 0;
match n {
0..=3 => {
file.write(&dummy[0..n])?;
}
4..=64 => {
if !boundary {
n -= 1;
}
let hex = byte_to_hex_pair_be((n) as u8);
file.write(&[b'/', hex[0], hex[1],])?;
if !boundary {
file.write(&[b'0'])?;
}
},
_ => core::unreachable!(),
}
Ok(())
};
let mut byte_boundary = true;
let zeroes = &mut 0;
let mut skip = false;
let mut hit_x = false;
while let Some(each) = bytes.next() {
byte_boundary = !byte_boundary;
let ascii = each?;
core::debug_assert!(ascii.is_ascii_alphanumeric() || ascii.is_ascii_whitespace());
match ascii {
b'v'
| b'p' => { skip = true;
out.write(&[ascii])?;
},
b'\n' => {
skip = false;
if *zeroes > 0 && !hit_x {
write_zeroes(zeroes, &mut out, byte_boundary)?;
}
if hit_x {
// only happens once for "nil"
out.write(b"00")?;
}
hit_x = false;
byte_boundary = false;
out.write(b"\n")?;
offsets.push(out.stream_position()?);
}
b'0' => {
if hit_x {
debug_assert!(*zeroes == 0);
continue;
}
if skip {
core::debug_assert!(*zeroes == 0);
out.write(b"0")?;
} else if !byte_boundary && *zeroes == 0 {
out.write(b"0")?;
hit_x = false;
} else {
*zeroes += 1;
}
}
b'x' => {
if *zeroes > 0 {
core::debug_assert!(!hit_x);
write_zeroes(zeroes, &mut out, byte_boundary)?;
}
if hit_x {panic!()}
out.write(b"x")?;
byte_boundary = false;
hit_x = true;
*zeroes = 0;
}
_ => {
if *zeroes > 0 {
core::debug_assert!(!hit_x);
write_zeroes(zeroes, &mut out, byte_boundary)?;
}
if hit_x && !byte_boundary {
out.write(b"0")?;
}
out.write(&[ascii])?;
hit_x = false
}
};
}
out.flush()?;
Ok(
ZeroCompressedFile {
path,
offsets
}
)
}
// ///////////////////
// DESERIALIZATION //
// /////////////////
/// deserialize the serialized pathmap
pub fn deserialize_file<V: TrieValue>(file_path : impl AsRef<std::path::Path>, de : impl Fn(&[u8])->V)-> Result<PathMap<V>, std::io::Error> {
let f = std::fs::File::open(file_path.as_ref())?;
let mut reader = BufReader::new(f);
let mut line = String::with_capacity(4096);
// strip header
reader.read_line(&mut line)?;
line.clear();
// ~ 1 gigabyte virtual allocation to start
let mut paths_buffer = Vec::with_capacity(2_usize.pow(30));
let mut branches_buffer = Vec::with_capacity(2_usize.pow(30)/U64_BYTES);
// we pay the price of looking at a tag, but it should pay off as we get constant lookup
enum Deserialized<V: Clone + Send + Sync> {
Path(std::ops::Range<usize>),
Value(V),
ChildMask(ChildMask),
Branches(std::ops::Range<usize>),
Node(PathMap<V>),
}
#[cfg(debug_assertions)]
impl<V: TrieValue> core::fmt::Debug for Deserialized<V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Deserialized::Path(range) => write!(f,"Path({}..{})", range.start, range.end),
Deserialized::Value(_) => write!(f,"Value"),
Deserialized::ChildMask(mask) => {
let s = mask.into_iter().flat_map(|n|format!("{:.>64b} ",n.reverse_bits()).chars().collect::<Vec<_>>()).collect::<String>();
write!(f,"ChildMask({:?})",s)
},
Deserialized::Branches(range) => write!(f,"Branches({}..{})", range.start, range.end),
Deserialized::Node(bytes_trie_map) => write!(f,"Node(empty?{})",bytes_trie_map.is_empty()),
}
}
}
let mut deserialized = Vec::with_capacity(4096);
let mut val_scratch = Vec::with_capacity(4096);
while let Ok(_) = reader.read_line(&mut line) {
let [bytes @ .. , b'\n'] = line.as_bytes() else {break};
let [ t @ ( Tag::PATH
| Tag::VALUE
| Tag::CHILD_MASK
| Tag::BRANCHES
| Tag::PATH_NODE
| Tag::VALUE_NODE
| Tag::BRANCH_NODE
),
b' ',data @ ..] = bytes else { return Err(std::io::Error::other("Malformed serialized ByteTrie, expected `<tag byte><space>`")); };
// // these are for debugging
// println!("0x{:_>16x} {} {:?}\n{:#?}", deserialized.len(), *t as char, std::str::from_utf8(data), deserialized);
// println!("0x{:_>16x} {} {:?}", deserialized.len(), *t as char, std::str::from_utf8(data));
match *t {
// paths currently have no compression yet
Tag::PATH => {
let start = paths_buffer.len();
let mut cur = data;
loop {
match cur {
[] => break,
[top,bot, rest @ ..] => {
let b = hex_pair_be_to_byte([*top,*bot]);
paths_buffer.push(b);
cur = rest
}
_ => return Err(std::io::Error::other("Malformed serialized ByteTrie, expected path as `(<hex_top><Hex_bot>)*`"))
}
}
let end = paths_buffer.len();
deserialized.push(Deserialized::Path(start..end));
}
// values currently have no compression yet
Tag::VALUE => {
val_scratch.clear();
let mut cur = data;
loop {
match cur {
[] => break,
[top,bot, rest @ ..] => {
let b = hex_pair_be_to_byte([*top,*bot]);
val_scratch.push(b);
cur = rest
}
_ => {
return Err(std::io::Error::other("Malformed serialized ByteTrie, expected value as `(<hex_top><Hex_bot>)*`"))
}
}
}
let value = de(&val_scratch);
val_scratch.clear();
deserialized.push(Deserialized::Value(value));
}
// child mask has compression but no b'x' bytes
Tag::CHILD_MASK => {
let mask_buf = decompress_zeros_compression_child_mask(data)?;
let mask = mask_buf.map(u64::from_be_bytes).map(u64::reverse_bits);
deserialized.push(Deserialized::ChildMask(mask));
}
// the rest have ofset compression with b'x' bytes
Tag::BRANCHES => {
let mut children_buf = [0_u64 ; 256];
let x_count = decompress_zeros_compression_offset(data, &mut children_buf)?;
let start = branches_buffer.len();
branches_buffer.extend_from_slice(&children_buf[0..x_count]);
let end = branches_buffer.len();
deserialized.push(Deserialized::Branches(start..end));
}
Tag::PATH_NODE => { let mut node_buf = [0_u64 ; 2];
decompress_zeros_compression_offset(data, &mut node_buf)?;
let [path_idx, node_idx] = node_buf.map(|x| x as usize);
let Deserialized::Path(path) = deserialized.get(path_idx).ok_or_else(|| std::io::Error::other("Malformed serialized ByteTrie, path offset out of bounds"))? else { return Err(std::io::Error::other("Malformed serialized ByteTrie, expected path")); };
let Deserialized::Node(node) = deserialized.get(node_idx).ok_or_else(|| std::io::Error::other("Malformed serialized ByteTrie, node offset out of bounds"))? else { return Err(std::io::Error::other("Malformed serialized ByteTrie, expected node")); };
let mut path_node = PathMap::new();
let mut wz = path_node.write_zipper();
wz.descend_to(&paths_buffer[path.start..path.end]);
wz.graft(&node.read_zipper());
drop(wz);
core::debug_assert!(!path_node.is_empty());
deserialized.push(Deserialized::Node(path_node));
}
Tag::VALUE_NODE => { let mut node_buf = [0_u64 ; 2];
decompress_zeros_compression_offset(data, &mut node_buf)?;
let [val_idx, node_idx] = node_buf.map(|x| x as usize);
let Deserialized::Value(value) = deserialized.get(val_idx).ok_or_else(|| std::io::Error::other("Malformed serialized ByteTrie, value offset out of bounds"))? else { return Err(std::io::Error::other("Malformed serialized ByteTrie, expected value")); };
let Deserialized::Node(node) = deserialized.get(node_idx).ok_or_else(|| std::io::Error::other("Malformed serialized ByteTrie, node offset out of bounds"))? else { return Err(std::io::Error::other("Malformed serialized ByteTrie, expected node")); };
let mut value_node = node.clone();
value_node.set_val_at(&[], value.clone());
deserialized.push(Deserialized::Node(value_node));
}
Tag::BRANCH_NODE => { let mut node_buf = [0_u64 ; 2];
decompress_zeros_compression_offset(data, &mut node_buf)?;
let [mask_idx, branches_idx] = node_buf.map(|x| x as usize);
let Deserialized::ChildMask(mask) = deserialized.get(mask_idx).ok_or_else(|| std::io::Error::other("Malformed serialized ByteTrie, childmask offset out of bounds"))? else { return Err(std::io::Error::other("Malformed serialized ByteTrie, expected childmask as `(/?<hex_top><Hex_bot>)*`")); };
let iter = crate::utils::ByteMaskIter::new(*mask);
let Deserialized::Branches(r) = deserialized.get(branches_idx).ok_or_else(|| std::io::Error::other("Malformed serialized ByteTrie, branches offset out of bounds"))? else { return Err(std::io::Error::other("Malformed serialized ByteTrie, expected branches")); };
let branches = &branches_buffer[r.start..r.end];
core::debug_assert_eq!(mask.into_iter().copied().map(u64::count_ones).sum::<u32>() as usize, branches.len());
let mut branch_node = PathMap::new();
let mut wz = branch_node.write_zipper();
for (byte, &idx) in iter.into_iter().zip(branches) {
let Deserialized::Node(node) = deserialized.get(idx as usize).ok_or_else(|| std::io::Error::other("Malformed serialized ByteTrie, child node offset out of bounds"))? else { return Err(std::io::Error::other("Malformed serialized ByteTrie, expected node")); };
core::debug_assert!(!node.is_empty());
wz.descend_to_byte(byte);
wz.graft(&node.read_zipper());
wz.ascend_byte();
}
drop(wz);
deserialized.push(Deserialized::Node(branch_node));
}
_ => core::unreachable!()
}
line.clear();
}
let Some(Deserialized::Node(n)) = deserialized.pop() else { return Err(std::io::Error::other("Malformed serialized ByteTrie, expected root node")); };
Ok(n)
}
// zeroes the buffer before decompressing
fn decompress_zeros_compression_offset(mut encoded_hex : &[u8], buffer : &mut [u64])->Result<usize, std::io::Error> {
for each in buffer.iter_mut() {
*each = 0;
}
let mut count = 0;
let mut x = false;
loop {
match encoded_hex {
[] => {
if x { count +=1; }
break
}
[b'x', rest @ .. ] => {
if x { count += 1; }
x = true;
encoded_hex = rest;
}
[b'/', top @ hex!(), bot @ hex!(), rest @ .. ] => { let hex_zeros = hex_pair_be_to_byte([*top,*bot]);
// whole bytes
let zeroes = hex_zeros/2;
debug_assert!(zeroes <= 6 );
buffer[count] <<= zeroes * u8::BITS as u8;
encoded_hex = rest;
}
[ top @ hex!(), bot @ hex!(), rest @ .. ] => { let b = hex_pair_be_to_byte([*top,*bot]);
buffer[count] <<= u8::BITS;
buffer[count] |= b as u64;
encoded_hex = rest;
}
_ => { return Err(std::io::Error::other("Malformed serialized ByteTrie")); }
}
}
#[cfg(debug_assertions)]
if INCR != 1 {
for each in buffer.iter_mut() {
*each >>= INCR.trailing_zeros();
}
}
Ok(count)
}
fn decompress_zeros_compression_child_mask(mut encoded_hex : &[u8], )->Result<[[u8;U64_BYTES];4], std::io::Error> {
let mut buffer = [[0_u8;U64_BYTES];4];
let mut bytes = 0;
let mut count = 0;
loop {
match encoded_hex {
[] => {
break
}
[b'/', top @ hex!(), bot @ hex!(), rest @ .. ] => { let hex_zeros = hex_pair_be_to_byte([*top,*bot]);
// whole bytes
let zeroes = hex_zeros/2;
let total :usize = bytes + zeroes as usize + count * U64_BYTES;
(count,bytes) = (total / U64_BYTES, total % U64_BYTES);
encoded_hex = rest;
}
[ top @ hex!(), bot @ hex!(), rest @ .. ] => { let b = hex_pair_be_to_byte([*top,*bot]);
buffer[count][bytes] = b;
bytes += 1;
count += bytes as usize / U64_BYTES;
bytes %= U64_BYTES;
encoded_hex = rest;
}
_ => { return Err(std::io::Error::other("Malformed serialized ByteTrie, childmask")); }
}
}
Ok(buffer)
}
#[cfg(test)]
mod test {
use super::*;
use std::sync::Arc;
fn write_serialized_fixture(dir : &tempfile::TempDir, name : &str, data : &[u8])->PathBuf {
let path = dir.path().join(name);
std::fs::write(&path, data).unwrap();
path
}
#[test]
fn deserialize_rejects_malformed_records() {
let temp_dir = tempfile::tempdir().unwrap();
let bad_tag = write_serialized_fixture(&temp_dir, "bad_tag.data", b"header\n? bad\n");
let err = deserialize_file::<Arc<[u8]>>(&bad_tag, |b| Arc::<[u8]>::from(b)).unwrap_err();