-
Notifications
You must be signed in to change notification settings - Fork 32
/
child.rs
2401 lines (2099 loc) · 86.7 KB
/
child.rs
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
//! Child layer implementation
//!
//! A child layer stores a reference to a base layer, as well as
//! triple additions and removals, and any new dictionary entries that
//! this layer needs for its additions.
use super::layer::*;
use crate::storage::*;
use crate::structure::*;
use futures::future;
use futures::prelude::*;
use futures::stream;
use std::cmp::Ordering;
use std::collections::BTreeSet;
use std::io;
use std::sync::Arc;
/// A child layer.
///
/// This layer type has a parent. It stores triple additions and removals.
#[derive(Clone)]
pub struct ChildLayer<M: 'static + AsRef<[u8]> + Clone + Send + Sync> {
name: [u32; 5],
parent: Arc<dyn Layer>,
node_dictionary: PfcDict<M>,
predicate_dictionary: PfcDict<M>,
value_dictionary: PfcDict<M>,
pos_subjects: MonotonicLogArray<M>,
pos_objects: MonotonicLogArray<M>,
pos_s_p_adjacency_list: AdjacencyList<M>,
pos_sp_o_adjacency_list: AdjacencyList<M>,
pos_o_ps_adjacency_list: AdjacencyList<M>,
neg_subjects: MonotonicLogArray<M>,
neg_objects: MonotonicLogArray<M>,
neg_s_p_adjacency_list: AdjacencyList<M>,
neg_sp_o_adjacency_list: AdjacencyList<M>,
neg_o_ps_adjacency_list: AdjacencyList<M>,
pos_predicate_wavelet_tree: WaveletTree<M>,
neg_predicate_wavelet_tree: WaveletTree<M>,
}
impl<M: 'static + AsRef<[u8]> + Clone + Send + Sync> ChildLayer<M> {
pub fn load_from_files<F: FileLoad<Map = M> + FileStore + Clone>(
name: [u32; 5],
parent: Arc<dyn Layer>,
files: &ChildLayerFiles<F>,
) -> impl Future<Item = Self, Error = std::io::Error> {
files
.map_all()
.map(move |maps| Self::load(name, parent, maps))
}
pub fn load(name: [u32; 5], parent: Arc<dyn Layer>, maps: ChildLayerMaps<M>) -> ChildLayer<M> {
let node_dictionary = PfcDict::parse(
maps.node_dictionary_maps.blocks_map,
maps.node_dictionary_maps.offsets_map,
)
.unwrap();
let predicate_dictionary = PfcDict::parse(
maps.predicate_dictionary_maps.blocks_map,
maps.predicate_dictionary_maps.offsets_map,
)
.unwrap();
let value_dictionary = PfcDict::parse(
maps.value_dictionary_maps.blocks_map,
maps.value_dictionary_maps.offsets_map,
)
.unwrap();
let pos_subjects =
MonotonicLogArray::from_logarray(LogArray::parse(maps.pos_subjects_map).unwrap());
let pos_objects =
MonotonicLogArray::from_logarray(LogArray::parse(maps.pos_objects_map).unwrap());
let neg_subjects =
MonotonicLogArray::from_logarray(LogArray::parse(maps.neg_subjects_map).unwrap());
let neg_objects =
MonotonicLogArray::from_logarray(LogArray::parse(maps.neg_objects_map).unwrap());
let pos_s_p_adjacency_list = AdjacencyList::parse(
maps.pos_s_p_adjacency_list_maps.nums_map,
maps.pos_s_p_adjacency_list_maps.bitindex_maps.bits_map,
maps.pos_s_p_adjacency_list_maps.bitindex_maps.blocks_map,
maps.pos_s_p_adjacency_list_maps.bitindex_maps.sblocks_map,
);
let pos_sp_o_adjacency_list = AdjacencyList::parse(
maps.pos_sp_o_adjacency_list_maps.nums_map,
maps.pos_sp_o_adjacency_list_maps.bitindex_maps.bits_map,
maps.pos_sp_o_adjacency_list_maps.bitindex_maps.blocks_map,
maps.pos_sp_o_adjacency_list_maps.bitindex_maps.sblocks_map,
);
let pos_o_ps_adjacency_list = AdjacencyList::parse(
maps.pos_o_ps_adjacency_list_maps.nums_map,
maps.pos_o_ps_adjacency_list_maps.bitindex_maps.bits_map,
maps.pos_o_ps_adjacency_list_maps.bitindex_maps.blocks_map,
maps.pos_o_ps_adjacency_list_maps.bitindex_maps.sblocks_map,
);
let neg_s_p_adjacency_list = AdjacencyList::parse(
maps.neg_s_p_adjacency_list_maps.nums_map,
maps.neg_s_p_adjacency_list_maps.bitindex_maps.bits_map,
maps.neg_s_p_adjacency_list_maps.bitindex_maps.blocks_map,
maps.neg_s_p_adjacency_list_maps.bitindex_maps.sblocks_map,
);
let neg_sp_o_adjacency_list = AdjacencyList::parse(
maps.neg_sp_o_adjacency_list_maps.nums_map,
maps.neg_sp_o_adjacency_list_maps.bitindex_maps.bits_map,
maps.neg_sp_o_adjacency_list_maps.bitindex_maps.blocks_map,
maps.neg_sp_o_adjacency_list_maps.bitindex_maps.sblocks_map,
);
let neg_o_ps_adjacency_list = AdjacencyList::parse(
maps.neg_o_ps_adjacency_list_maps.nums_map,
maps.neg_o_ps_adjacency_list_maps.bitindex_maps.bits_map,
maps.neg_o_ps_adjacency_list_maps.bitindex_maps.blocks_map,
maps.neg_o_ps_adjacency_list_maps.bitindex_maps.sblocks_map,
);
let pos_predicate_wavelet_tree_width = pos_s_p_adjacency_list.nums().width();
let pos_predicate_wavelet_tree = WaveletTree::from_parts(
BitIndex::from_maps(
maps.pos_predicate_wavelet_tree_maps.bits_map,
maps.pos_predicate_wavelet_tree_maps.blocks_map,
maps.pos_predicate_wavelet_tree_maps.sblocks_map,
),
pos_predicate_wavelet_tree_width,
);
let neg_predicate_wavelet_tree_width = neg_s_p_adjacency_list.nums().width();
let neg_predicate_wavelet_tree = WaveletTree::from_parts(
BitIndex::from_maps(
maps.neg_predicate_wavelet_tree_maps.bits_map,
maps.neg_predicate_wavelet_tree_maps.blocks_map,
maps.neg_predicate_wavelet_tree_maps.sblocks_map,
),
neg_predicate_wavelet_tree_width,
);
ChildLayer {
name,
parent: parent,
node_dictionary: node_dictionary,
predicate_dictionary: predicate_dictionary,
value_dictionary: value_dictionary,
pos_subjects,
pos_objects,
neg_subjects,
neg_objects,
pos_s_p_adjacency_list,
pos_sp_o_adjacency_list,
pos_o_ps_adjacency_list,
neg_s_p_adjacency_list,
neg_sp_o_adjacency_list,
neg_o_ps_adjacency_list,
pos_predicate_wavelet_tree,
neg_predicate_wavelet_tree,
}
}
fn lookup_layer_object_addition_mapped(&self, mapped_object: u64) -> impl LayerObjectLookup {
if mapped_object == 0 || mapped_object as usize > self.pos_objects.len() {
panic!("unknown mapped object requested");
}
let object = self.pos_objects.entry((mapped_object - 1) as usize);
let sp_slice = self.pos_o_ps_adjacency_list.get(mapped_object);
let subjects = self.pos_subjects.clone();
let s_p_adjacency_list = self.pos_s_p_adjacency_list.clone();
ChildLayerObjectLookup {
object,
sp_slice,
s_p_adjacency_list,
subjects,
}
}
fn lookup_layer_object_removal_mapped(&self, mapped_object: u64) -> impl LayerObjectLookup {
if mapped_object == 0 || mapped_object as usize > self.neg_objects.len() {
panic!("unknown mapped object requested");
}
let object = self.neg_objects.entry((mapped_object - 1) as usize);
let sp_slice = self.neg_o_ps_adjacency_list.get(mapped_object);
let subjects = self.neg_subjects.clone();
let s_p_adjacency_list = self.neg_s_p_adjacency_list.clone();
ChildLayerObjectLookup {
object,
sp_slice,
s_p_adjacency_list,
subjects,
}
}
}
impl<M: 'static + AsRef<[u8]> + Clone + Send + Sync> Layer for ChildLayer<M> {
fn name(&self) -> [u32; 5] {
self.name
}
fn parent(&self) -> Option<&dyn Layer> {
Some(&*self.parent)
}
fn node_dict_id(&self, subject: &str) -> Option<u64> {
self.node_dictionary.id(subject)
}
fn node_dict_len(&self) -> usize {
self.node_dictionary.len()
}
fn node_dict_get(&self, id: usize) -> Option<String> {
self.node_dictionary.get(id)
}
fn value_dict_get(&self, id: usize) -> Option<String> {
self.value_dictionary.get(id)
}
fn value_dict_id(&self, value: &str) -> Option<u64> {
self.value_dictionary.id(value)
}
fn value_dict_len(&self) -> usize {
self.value_dictionary.len()
}
fn node_and_value_count(&self) -> usize {
let mut parent_option = self.parent();
let mut count = self.node_dictionary.len() + self.value_dictionary.len();
while let Some(parent) = parent_option {
count += parent.node_dict_len() + parent.value_dict_len();
parent_option = parent.parent();
}
count
}
fn predicate_dict_len(&self) -> usize {
self.predicate_dictionary.len()
}
fn predicate_dict_id(&self, predicate: &str) -> Option<u64> {
self.predicate_dictionary.id(predicate)
}
fn predicate_dict_get(&self, id: usize) -> Option<String> {
self.predicate_dictionary.get(id)
}
fn predicate_count(&self) -> usize {
let mut parent_option = self.parent();
let mut count = self.predicate_dictionary.len();
while let Some(parent) = parent_option {
count += parent.predicate_dict_len();
parent_option = parent.parent();
}
count
}
fn subject_id<'a>(&'a self, subject: &str) -> Option<u64> {
let to_result = |layer: &'a dyn Layer| (layer.node_dict_id(subject), layer.parent());
let mut result = to_result(self);
while let (None, Some(layer)) = result {
result = to_result(layer);
}
let (id_option, parent_option) = result;
id_option.map(|id| 1 + id + parent_option.map_or(0, |p| p.node_and_value_count() as u64))
}
fn predicate_id<'a>(&'a self, predicate: &str) -> Option<u64> {
let to_result = |layer: &'a dyn Layer| (layer.predicate_dict_id(predicate), layer.parent());
let mut result = to_result(self);
while let (None, Some(layer)) = result {
result = to_result(layer);
}
let (id_option, parent_option) = result;
id_option.map(|id| 1 + id + parent_option.map_or(0, |p| p.predicate_count() as u64))
}
fn object_node_id<'a>(&'a self, subject: &str) -> Option<u64> {
let to_result = |layer: &'a dyn Layer| (layer.node_dict_id(subject), layer.parent());
let mut result = to_result(self);
while let (None, Some(layer)) = result {
result = to_result(layer);
}
let (id_option, parent_option) = result;
id_option.map(|id| 1 + id + parent_option.map_or(0, |p| p.node_and_value_count() as u64))
}
fn object_value_id<'a>(&'a self, value: &str) -> Option<u64> {
let to_result = |layer: &'a dyn Layer| {
(
layer
.value_dict_id(value)
.map(|i| i + layer.node_dict_len() as u64),
layer.parent(),
)
};
let mut result = to_result(self);
while let (None, Some(layer)) = result {
result = to_result(layer);
}
let (id_option, parent_option) = result;
id_option.map(|id| 1 + id + parent_option.map_or(0, |p| p.node_and_value_count() as u64))
}
fn id_subject(&self, id: u64) -> Option<String> {
if id == 0 {
return None;
}
let mut corrected_id = id - 1;
let mut current_option: Option<&dyn Layer> = Some(self);
let mut parent_count = self.node_and_value_count() as u64;
while let Some(current_layer) = current_option {
parent_count = parent_count
- current_layer.node_dict_len() as u64
- current_layer.value_dict_len() as u64;
if corrected_id >= parent_count as u64 {
// subject, if it exists, is in this layer
corrected_id -= parent_count;
return current_layer.node_dict_get(corrected_id as usize);
} else {
current_option = current_layer.parent();
}
}
return None;
}
fn id_predicate(&self, id: u64) -> Option<String> {
if id == 0 {
return None;
}
let mut corrected_id = id - 1;
let mut current_option: Option<&dyn Layer> = Some(self);
let mut parent_count = self.predicate_count() as u64;
while let Some(current_layer) = current_option {
let parent = current_layer.parent();
if parent.is_none() {
return current_layer.id_predicate(id);
}
parent_count = parent_count - current_layer.predicate_dict_len() as u64;
if corrected_id >= parent_count as u64 {
// subject, if it exists, is in this layer
corrected_id -= parent_count;
return current_layer.predicate_dict_get(corrected_id as usize);
} else {
current_option = current_layer.parent();
}
}
return None;
}
fn id_object(&self, id: u64) -> Option<ObjectType> {
if id == 0 {
return None;
}
let mut corrected_id = id - 1;
let mut current_option: Option<&dyn Layer> = Some(self);
let mut parent_count = self.node_and_value_count() as u64;
while let Some(current_layer) = current_option {
let parent = current_layer.parent();
if parent.is_none() {
return current_layer.id_object(id);
}
parent_count = parent_count
- current_layer.node_dict_len() as u64
- current_layer.value_dict_len() as u64;
if corrected_id >= parent_count {
// object, if it exists, is in this layer
corrected_id -= parent_count;
if corrected_id >= current_layer.node_dict_len() as u64 {
// object, if it exists, must be a value
corrected_id -= current_layer.node_dict_len() as u64;
return current_layer
.value_dict_get(corrected_id as usize)
.map(ObjectType::Value);
} else {
return current_layer
.node_dict_get(corrected_id as usize)
.map(ObjectType::Node);
}
} else {
current_option = current_layer.parent();
}
}
return None;
}
fn subject_additions(&self) -> Box<dyn Iterator<Item = Box<dyn LayerSubjectLookup>>> {
let s_p_adjacency_list = self.pos_s_p_adjacency_list.clone();
let sp_o_adjacency_list = self.pos_sp_o_adjacency_list.clone();
Box::new(
self.pos_subjects
.clone()
.into_iter()
.enumerate()
.map(move |(c, s)| {
Box::new(ChildLayerSubjectLookup {
subject: s,
adjacencies: AdjacencyStuff {
predicates: s_p_adjacency_list.get((c as u64) + 1),
sp_offset: s_p_adjacency_list.offset_for((c as u64) + 1),
sp_o_adjacency_list: sp_o_adjacency_list.clone(),
},
}) as Box<dyn LayerSubjectLookup>
}),
)
}
fn subject_removals(&self) -> Box<dyn Iterator<Item = Box<dyn LayerSubjectLookup>>> {
let s_p_adjacency_list = self.neg_s_p_adjacency_list.clone();
let sp_o_adjacency_list = self.neg_sp_o_adjacency_list.clone();
Box::new(
self.neg_subjects
.clone()
.into_iter()
.enumerate()
.map(move |(c, s)| {
Box::new(ChildLayerSubjectLookup {
subject: s,
adjacencies: AdjacencyStuff {
predicates: s_p_adjacency_list.get((c as u64) + 1),
sp_offset: s_p_adjacency_list.offset_for((c as u64) + 1),
sp_o_adjacency_list: sp_o_adjacency_list.clone(),
},
}) as Box<dyn LayerSubjectLookup>
}),
)
}
fn lookup_subject_addition(&self, subject: u64) -> Option<Box<dyn LayerSubjectLookup>> {
if subject == 0 {
return None;
}
let index = self.pos_subjects.index_of(subject);
if index.is_none() {
return None;
}
let mapped_subject = index.unwrap() as u64 + 1;
if mapped_subject <= self.pos_s_p_adjacency_list.left_count() as u64 {
let predicates = self.pos_s_p_adjacency_list.get(mapped_subject);
let sp_offset = self.pos_s_p_adjacency_list.offset_for(mapped_subject);
Some(Box::new(ChildLayerSubjectLookup {
subject,
adjacencies: AdjacencyStuff {
predicates,
sp_offset,
sp_o_adjacency_list: self.pos_sp_o_adjacency_list.clone(),
},
}))
} else {
None
}
}
fn lookup_subject_removal(&self, subject: u64) -> Option<Box<dyn LayerSubjectLookup>> {
if subject == 0 {
return None;
}
let index = self.neg_subjects.index_of(subject);
if index.is_none() {
return None;
}
let mapped_subject = index.unwrap() as u64 + 1;
if mapped_subject <= self.neg_s_p_adjacency_list.left_count() as u64 {
let predicates = self.neg_s_p_adjacency_list.get(mapped_subject);
let sp_offset = self.neg_s_p_adjacency_list.offset_for(mapped_subject);
Some(Box::new(ChildLayerSubjectLookup {
subject,
adjacencies: AdjacencyStuff {
predicates,
sp_offset,
sp_o_adjacency_list: self.neg_sp_o_adjacency_list.clone(),
},
}))
} else {
None
}
}
fn object_additions(&self) -> Box<dyn Iterator<Item = Box<dyn LayerObjectLookup>>> {
let cloned = self.clone();
Box::new((0..self.pos_objects.len()).map(move |mapped_object| {
Box::new(cloned.lookup_layer_object_addition_mapped((mapped_object + 1) as u64))
as Box<dyn LayerObjectLookup>
}))
}
fn object_removals(&self) -> Box<dyn Iterator<Item = Box<dyn LayerObjectLookup>>> {
let cloned = self.clone();
Box::new((0..self.neg_objects.len()).map(move |mapped_object| {
Box::new(cloned.lookup_layer_object_removal_mapped((mapped_object + 1) as u64))
as Box<dyn LayerObjectLookup>
}))
}
fn lookup_object_addition(&self, object: u64) -> Option<Box<dyn LayerObjectLookup>> {
self.pos_objects.index_of(object).map(|index| {
Box::new(self.lookup_layer_object_addition_mapped((index as u64) + 1))
as Box<dyn LayerObjectLookup>
})
}
fn lookup_object_removal(&self, object: u64) -> Option<Box<dyn LayerObjectLookup>> {
self.neg_objects.index_of(object).map(|index| {
Box::new(self.lookup_layer_object_removal_mapped((index as u64) + 1))
as Box<dyn LayerObjectLookup>
})
}
fn lookup_predicate_addition(&self, predicate: u64) -> Option<Box<dyn LayerPredicateLookup>> {
self.pos_predicate_wavelet_tree
.lookup(predicate)
.map(|lookup| {
Box::new(ChildLayerPredicateLookup {
predicate,
lookup,
subjects: self.pos_subjects.clone(),
s_p_adjacency_list: self.pos_s_p_adjacency_list.clone(),
sp_o_adjacency_list: self.pos_sp_o_adjacency_list.clone(),
}) as Box<dyn LayerPredicateLookup>
})
}
fn lookup_predicate_removal(&self, predicate: u64) -> Option<Box<dyn LayerPredicateLookup>> {
self.neg_predicate_wavelet_tree
.lookup(predicate)
.map(|lookup| {
Box::new(ChildLayerPredicateLookup {
predicate,
lookup,
subjects: self.neg_subjects.clone(),
s_p_adjacency_list: self.neg_s_p_adjacency_list.clone(),
sp_o_adjacency_list: self.neg_sp_o_adjacency_list.clone(),
}) as Box<dyn LayerPredicateLookup>
})
}
fn clone_boxed(&self) -> Box<dyn Layer> {
Box::new(self.clone())
}
}
#[derive(Clone)]
struct AdjacencyStuff<M: 'static + AsRef<[u8]> + Clone> {
predicates: LogArraySlice<M>,
sp_offset: u64,
sp_o_adjacency_list: AdjacencyList<M>,
}
struct ChildLayerSubjectLookup<M: 'static + AsRef<[u8]> + Clone> {
subject: u64,
adjacencies: AdjacencyStuff<M>,
}
impl<M: AsRef<[u8]> + Clone> LayerSubjectLookup for ChildLayerSubjectLookup<M> {
fn subject(&self) -> u64 {
self.subject
}
fn predicates(&self) -> Box<dyn Iterator<Item = Box<dyn LayerSubjectPredicateLookup>>> {
let subject = self.subject;
let offset = self.adjacencies.sp_offset;
let aj = self.adjacencies.sp_o_adjacency_list.clone();
Box::new(
self.adjacencies
.predicates
.clone()
.into_iter()
.enumerate()
.map(move |(c, p)| {
Box::new(ChildLayerSubjectPredicateLookup {
subject: subject,
predicate: p,
objects: aj.get(offset + (c as u64) + 1),
}) as Box<dyn LayerSubjectPredicateLookup>
}),
)
}
fn lookup_predicate(&self, predicate: u64) -> Option<Box<dyn LayerSubjectPredicateLookup>> {
self.adjacencies
.predicates
.iter()
.position(|p| p == predicate)
.map(|pos| {
self.adjacencies
.sp_o_adjacency_list
.get(self.adjacencies.sp_offset + (pos as u64) + 1)
})
.map(|objects| {
Box::new(ChildLayerSubjectPredicateLookup {
subject: self.subject,
predicate: predicate,
objects: objects,
}) as Box<dyn LayerSubjectPredicateLookup>
})
}
}
struct ChildLayerSubjectPredicateLookup<M: 'static + AsRef<[u8]> + Clone> {
subject: u64,
predicate: u64,
objects: LogArraySlice<M>,
}
impl<M: 'static + AsRef<[u8]> + Clone> LayerSubjectPredicateLookup
for ChildLayerSubjectPredicateLookup<M>
{
fn subject(&self) -> u64 {
self.subject
}
fn predicate(&self) -> u64 {
self.predicate
}
fn objects(&self) -> Box<dyn Iterator<Item = u64>> {
Box::new(self.objects.clone().into_iter())
}
fn has_object(&self, object: u64) -> bool {
self.objects.iter().find(|&x| x == object).is_some()
}
}
struct ChildLayerObjectLookup<M: 'static + AsRef<[u8]> + Clone> {
object: u64,
sp_slice: LogArraySlice<M>,
s_p_adjacency_list: AdjacencyList<M>,
subjects: MonotonicLogArray<M>,
}
impl<M: 'static + AsRef<[u8]> + Clone> LayerObjectLookup for ChildLayerObjectLookup<M> {
fn object(&self) -> u64 {
self.object
}
fn subject_predicate_pairs(&self) -> Box<dyn Iterator<Item = (u64, u64)>> {
let sp_slice = self.sp_slice.clone();
let s_p_adjacency_list = self.s_p_adjacency_list.clone();
let subjects = self.subjects.clone();
Box::new(
sp_slice
.into_iter()
.map(move |index| s_p_adjacency_list.pair_at_pos(index - 1))
.map(move |(mapped_subject, predicate)| {
(subjects.entry((mapped_subject as usize) - 1), predicate)
}),
)
}
}
struct ChildLayerPredicateLookup<M: 'static + AsRef<[u8]> + Clone> {
predicate: u64,
lookup: WaveletLookup<M>,
subjects: MonotonicLogArray<M>,
s_p_adjacency_list: AdjacencyList<M>,
sp_o_adjacency_list: AdjacencyList<M>,
}
impl<M: 'static + AsRef<[u8]> + Clone> LayerPredicateLookup for ChildLayerPredicateLookup<M> {
fn predicate(&self) -> u64 {
self.predicate
}
fn subject_predicate_pairs(
&self,
) -> Box<dyn Iterator<Item = Box<dyn LayerSubjectPredicateLookup>>> {
let predicate = self.predicate;
let subjects = self.subjects.clone();
let s_p_adjacency_list = self.s_p_adjacency_list.clone();
let sp_o_adjacency_list = self.sp_o_adjacency_list.clone();
Box::new(self.lookup.iter().map(move |pos| {
let (mapped_subject, _predicate) = s_p_adjacency_list.pair_at_pos(pos);
Box::new(ChildLayerSubjectPredicateLookup {
subject: subjects.entry((mapped_subject as usize) - 1),
predicate: predicate,
objects: sp_o_adjacency_list.get(pos + 1),
}) as Box<dyn LayerSubjectPredicateLookup>
}))
}
}
/// A builder for a child layer.
///
/// This builder takes node, predicate and value strings in lexical
/// order through the corresponding `add_<thing>` methods. When
/// they're all added, `into_phase2()` is to be called to turn this
/// builder into a second builder that takes triple data.
pub struct ChildLayerFileBuilder<F: 'static + FileLoad + FileStore + Clone + Send + Sync> {
parent: Arc<dyn Layer>,
files: ChildLayerFiles<F>,
node_dictionary_builder: PfcDictFileBuilder<F::Write>,
predicate_dictionary_builder: PfcDictFileBuilder<F::Write>,
value_dictionary_builder: PfcDictFileBuilder<F::Write>,
}
impl<F: 'static + FileLoad + FileStore + Clone + Send + Sync> ChildLayerFileBuilder<F> {
/// Create the builder from the given files.
pub fn from_files(parent: Arc<dyn Layer>, files: &ChildLayerFiles<F>) -> Self {
let node_dictionary_builder = PfcDictFileBuilder::new(
files.node_dictionary_files.blocks_file.open_write(),
files.node_dictionary_files.offsets_file.open_write(),
);
let predicate_dictionary_builder = PfcDictFileBuilder::new(
files.predicate_dictionary_files.blocks_file.open_write(),
files.predicate_dictionary_files.offsets_file.open_write(),
);
let value_dictionary_builder = PfcDictFileBuilder::new(
files.value_dictionary_files.blocks_file.open_write(),
files.value_dictionary_files.offsets_file.open_write(),
);
Self {
parent,
files: files.clone(),
node_dictionary_builder,
predicate_dictionary_builder,
value_dictionary_builder,
}
}
/// Add a node string.
///
/// Does nothing if the node already exists in the paretn, and
/// panics if the given node string is not a lexical successor of
/// the previous node string.
pub fn add_node(
self,
node: &str,
) -> Box<dyn Future<Item = (u64, Self), Error = std::io::Error> + Send> {
match self.parent.subject_id(node) {
None => {
let ChildLayerFileBuilder {
parent,
files,
node_dictionary_builder,
predicate_dictionary_builder,
value_dictionary_builder,
} = self;
Box::new(node_dictionary_builder.add(node).map(
move |(result, node_dictionary_builder)| {
(
result,
ChildLayerFileBuilder {
parent,
files,
node_dictionary_builder,
predicate_dictionary_builder,
value_dictionary_builder,
},
)
},
))
}
Some(id) => Box::new(future::ok((id, self))),
}
}
/// Add a predicate string.
///
/// Does nothing if the predicate already exists in the paretn, and
/// panics if the given predicate string is not a lexical successor of
/// the previous predicate string.
pub fn add_predicate(
self,
predicate: &str,
) -> Box<dyn Future<Item = (u64, Self), Error = std::io::Error> + Send> {
match self.parent.predicate_id(predicate) {
None => {
let ChildLayerFileBuilder {
parent,
files,
node_dictionary_builder,
predicate_dictionary_builder,
value_dictionary_builder,
} = self;
Box::new(predicate_dictionary_builder.add(predicate).map(
move |(result, predicate_dictionary_builder)| {
(
result,
ChildLayerFileBuilder {
parent,
files,
node_dictionary_builder,
predicate_dictionary_builder,
value_dictionary_builder,
},
)
},
))
}
Some(id) => Box::new(future::ok((id, self))),
}
}
/// Add a value string.
///
/// Does nothing if the value already exists in the paretn, and
/// panics if the given value string is not a lexical successor of
/// the previous value string.
pub fn add_value(
self,
value: &str,
) -> Box<dyn Future<Item = (u64, Self), Error = std::io::Error> + Send> {
match self.parent.object_value_id(value) {
None => {
let ChildLayerFileBuilder {
parent,
files,
node_dictionary_builder,
predicate_dictionary_builder,
value_dictionary_builder,
} = self;
Box::new(value_dictionary_builder.add(value).map(
move |(result, value_dictionary_builder)| {
(
result,
ChildLayerFileBuilder {
parent,
files,
node_dictionary_builder,
predicate_dictionary_builder,
value_dictionary_builder,
},
)
},
))
}
Some(id) => Box::new(future::ok((id, self))),
}
}
/// Add nodes from an iterable.
///
/// Panics if the nodes are not in lexical order, or if previous
/// added nodes are a lexical succesor of any of these
/// nodes. Skips any nodes that are already part of the base
/// layer.
pub fn add_nodes<I: 'static + IntoIterator<Item = String>>(
self,
nodes: I,
) -> impl Future<Item = (Vec<u64>, Self), Error = std::io::Error> {
stream::iter_ok(nodes.into_iter()).fold(
(Vec::new(), self),
|(mut result, builder), node| {
builder.add_node(&node).map(|(id, builder)| {
result.push(id);
(result, builder)
})
},
)
}
/// Add predicates from an iterable.
///
/// Panics if the predicates are not in lexical order, or if
/// previous added predicates are a lexical succesor of any of
/// these predicates. Skips any predicates that are already part
/// of the base layer.
pub fn add_predicates<I: 'static + IntoIterator<Item = String>>(
self,
predicates: I,
) -> impl Future<Item = (Vec<u64>, Self), Error = std::io::Error> {
stream::iter_ok(predicates.into_iter()).fold(
(Vec::new(), self),
|(mut result, builder), predicate| {
builder.add_predicate(&predicate).map(|(id, builder)| {
result.push(id);
(result, builder)
})
},
)
}
/// Add values from an iterable.
///
/// Panics if the values are not in lexical order, or if previous
/// added values are a lexical succesor of any of these
/// values. Skips any nodes that are already part of the base
/// layer.
pub fn add_values<I: 'static + IntoIterator<Item = String>>(
self,
values: I,
) -> impl Future<Item = (Vec<u64>, Self), Error = std::io::Error> {
stream::iter_ok(values.into_iter()).fold(
(Vec::new(), self),
|(mut result, builder), value| {
builder.add_value(&value).map(|(id, builder)| {
result.push(id);
(result, builder)
})
},
)
}
/// Turn this builder into a phase 2 builder that will take triple data.
pub fn into_phase2(
self,
) -> impl Future<Item = ChildLayerFileBuilderPhase2<F>, Error = std::io::Error> {
let ChildLayerFileBuilder {
parent,
files,
node_dictionary_builder,
predicate_dictionary_builder,
value_dictionary_builder,
} = self;
let finalize_nodedict: Box<dyn Future<Item = (), Error = std::io::Error> + Send> =
Box::new(node_dictionary_builder.finalize());
let finalize_preddict: Box<dyn Future<Item = (), Error = std::io::Error> + Send> =
Box::new(predicate_dictionary_builder.finalize());
let finalize_valdict: Box<dyn Future<Item = (), Error = std::io::Error> + Send> =
Box::new(value_dictionary_builder.finalize());
let dict_maps_fut = vec![
files.node_dictionary_files.blocks_file.map(),
files.node_dictionary_files.offsets_file.map(),
files.predicate_dictionary_files.blocks_file.map(),
files.predicate_dictionary_files.offsets_file.map(),
files.value_dictionary_files.blocks_file.map(),
files.value_dictionary_files.offsets_file.map(),
];
future::join_all(vec![finalize_nodedict, finalize_preddict, finalize_valdict])
.and_then(move |_| future::join_all(dict_maps_fut))
.and_then(move |dict_maps| {
let node_dict_r = PfcDict::parse(dict_maps[0].clone(), dict_maps[1].clone());
if node_dict_r.is_err() {
return future::err(node_dict_r.err().unwrap().into());
}
let node_dict = node_dict_r.unwrap();
let pred_dict_r = PfcDict::parse(dict_maps[2].clone(), dict_maps[3].clone());
if pred_dict_r.is_err() {
return future::err(pred_dict_r.err().unwrap().into());
}
let pred_dict = pred_dict_r.unwrap();
let val_dict_r = PfcDict::parse(dict_maps[4].clone(), dict_maps[5].clone());
if val_dict_r.is_err() {
return future::err(val_dict_r.err().unwrap().into());
}
let val_dict = val_dict_r.unwrap();
let num_nodes = node_dict.len();
let num_predicates = pred_dict.len();
let num_values = val_dict.len();
future::ok(ChildLayerFileBuilderPhase2::new(
parent,
files,
num_nodes,
num_predicates,
num_values,
))
})
}
}
/// Second phase of child layer building.
///
/// This builder takes ordered triple additions and removals. When all
/// data has been added, `finalize()` will build a layer.
pub struct ChildLayerFileBuilderPhase2<F: 'static + FileLoad + FileStore + Clone + Send + Sync> {
parent: Arc<dyn Layer>,
files: ChildLayerFiles<F>,
pos_subjects: Vec<u64>,
neg_subjects: Vec<u64>,