/
mod.rs
1303 lines (1174 loc) · 43.2 KB
/
mod.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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//! # nameset
//!
//! See [`NameSet`] for the main structure.
use std::any::Any;
use std::cmp;
use std::fmt;
use std::fmt::Debug;
use std::ops::BitAnd;
use std::ops::BitOr;
use std::ops::Deref;
use std::ops::Sub;
use std::pin::Pin;
use std::sync::Arc;
use futures::future::BoxFuture;
use futures::Stream;
use futures::StreamExt;
use nonblocking::non_blocking;
use crate::default_impl;
use crate::ops::DagAlgorithm;
use crate::ops::IdConvert;
use crate::ops::IdMapSnapshot;
use crate::ops::Parents;
use crate::Id;
use crate::IdSet;
use crate::Result;
use crate::VertexName;
pub mod difference;
pub mod hints;
pub mod id_lazy;
pub mod id_static;
pub mod intersection;
pub mod lazy;
#[cfg(any(test, feature = "indexedlog-backend"))]
pub mod legacy;
pub mod meta;
pub mod slice;
pub mod r#static;
pub mod union;
use self::hints::Flags;
use self::hints::Hints;
use self::id_static::IdStaticSet;
use self::meta::MetaSet;
use self::r#static::StaticSet;
/// A [`NameSet`] contains an immutable list of names.
///
/// It provides order-preserving iteration and set operations,
/// and is cheaply clonable.
#[derive(Clone)]
pub struct NameSet(Arc<dyn AsyncNameSetQuery>);
impl NameSet {
pub(crate) fn from_query(query: impl AsyncNameSetQuery) -> Self {
Self(Arc::new(query))
}
/// Creates an empty set.
pub fn empty() -> Self {
Self::from_query(r#static::StaticSet::empty())
}
/// Creates from a (short) list of known names.
pub fn from_static_names(names: impl IntoIterator<Item = VertexName>) -> NameSet {
Self::from_query(r#static::StaticSet::from_names(names))
}
/// Creates from a (lazy) iterator of names.
pub fn from_iter<I>(iter: I, hints: Hints) -> NameSet
where
I: IntoIterator<Item = Result<VertexName>> + 'static,
<I as IntoIterator>::IntoIter: Send + Sync,
{
Self::from_query(lazy::LazySet::from_iter(iter, hints))
}
/// Creates from a (lazy) stream of names with hints.
pub fn from_stream(stream: BoxVertexStream, hints: Hints) -> NameSet {
Self::from_query(lazy::LazySet::from_stream(stream, hints))
}
/// Creates from a (lazy) iterator of Ids, an IdMap, and a Dag.
pub fn from_id_iter_idmap_dag<I>(
iter: I,
map: Arc<dyn IdConvert + Send + Sync>,
dag: Arc<dyn DagAlgorithm + Send + Sync>,
) -> NameSet
where
I: IntoIterator<Item = Result<Id>> + 'static,
<I as IntoIterator>::IntoIter: Send + Sync,
{
Self::from_query(id_lazy::IdLazySet::from_iter_idmap_dag(iter, map, dag))
}
/// Creates from a (lazy) iterator of Ids and a struct with snapshot abilities.
pub fn from_id_iter_dag<I>(
iter: I,
dag: &(impl DagAlgorithm + IdMapSnapshot),
) -> Result<NameSet>
where
I: IntoIterator<Item = Result<Id>> + 'static,
<I as IntoIterator>::IntoIter: Send + Sync,
{
let map = dag.id_map_snapshot()?;
let dag = dag.dag_snapshot()?;
Ok(Self::from_id_iter_idmap_dag(iter, map, dag))
}
/// Creates from [`IdSet`], [`IdMap`] and [`DagAlgorithm`].
pub fn from_spans_idmap_dag(
spans: IdSet,
map: Arc<dyn IdConvert + Send + Sync>,
dag: Arc<dyn DagAlgorithm + Send + Sync>,
) -> NameSet {
Self::from_query(IdStaticSet::from_spans_idmap_dag(spans, map, dag))
}
/// Creates from [`IdSet`] and a struct with snapshot abilities.
pub fn from_spans_dag(spans: IdSet, dag: &(impl DagAlgorithm + IdMapSnapshot)) -> Result<Self> {
let map = dag.id_map_snapshot()?;
let dag = dag.dag_snapshot()?;
Ok(Self::from_spans_idmap_dag(spans, map, dag))
}
/// Creates from a function that evaluates to a [`NameSet`], and a
/// `contains` fast path.
pub fn from_evaluate_contains<C>(
evaluate: impl Fn() -> Result<NameSet> + Send + Sync + 'static,
contains: C,
hints: Hints,
) -> NameSet
where
C: for<'a> Fn(&'a MetaSet, &'a VertexName) -> Result<bool>,
C: Send + Sync + 'static,
{
let evaluate = move || -> BoxFuture<_> {
let result = evaluate();
Box::pin(async move { result })
};
let contains = Arc::new(contains);
Self::from_async_evaluate_contains(
Box::new(evaluate),
Box::new(move |m, v| {
let contains = contains.clone();
Box::pin(async move { contains(m, v) })
}),
hints,
)
}
/// Creates from an async function that evaluates to a [`NameSet`], and a
/// async `contains` fast path.
pub fn from_async_evaluate_contains(
evaluate: Box<dyn Fn() -> BoxFuture<'static, Result<NameSet>> + Send + Sync>,
contains: Box<
dyn for<'a> Fn(&'a MetaSet, &'a VertexName) -> BoxFuture<'a, Result<bool>>
+ Send
+ Sync,
>,
hints: Hints,
) -> NameSet {
Self::from_query(MetaSet::from_evaluate_hints(evaluate, hints).with_contains(contains))
}
/// Calculates the subset that is only in self, not in other.
pub fn difference(&self, other: &NameSet) -> NameSet {
if other.hints().contains(Flags::FULL)
&& other.hints().dag_version() >= self.hints().dag_version()
&& self.hints().dag_version() > None
{
tracing::debug!(
target: "dag::algo::difference",
"difference(x={:.6?}, y={:.6?}) = () (fast path 1)",
self,
other
);
return Self::empty();
}
if self.hints().contains(Flags::EMPTY) || other.hints().contains(Flags::EMPTY) {
tracing::debug!(
target: "dag::algo::difference",
"difference(x={:.6?}, y={:.6?}) = x (fast path 2)",
self,
other
);
return self.clone();
}
if let (Some(this), Some(other)) = (
self.as_any().downcast_ref::<IdStaticSet>(),
other.as_any().downcast_ref::<IdStaticSet>(),
) {
let order = this.map.map_version().partial_cmp(other.map.map_version());
if order.is_some() {
// Fast path for IdStaticSet
let result = Self::from_spans_idmap_dag(
this.spans.difference(&other.spans),
this.map.clone(),
this.dag.clone(),
);
tracing::debug!(
target: "dag::algo::difference",
"difference(x={:.6?}, y={:.6?}) = {:.6?} (fast path 3)",
self,
other,
&result
);
return result;
}
}
tracing::warn!(
target: "dag::algo::difference",
"difference(x={:.6?}, y={:.6?}) (slow path)", self, other);
Self::from_query(difference::DifferenceSet::new(self.clone(), other.clone()))
}
/// Calculates the intersection of two sets.
pub fn intersection(&self, other: &NameSet) -> NameSet {
if self.hints().contains(Flags::FULL)
&& self.hints().dag_version() >= other.hints().dag_version()
&& other.hints().dag_version() > None
{
tracing::debug!(
target: "dag::algo::intersection",
"intersection(x={:.6?}, y={:.6?}) = y (fast path 1)",
self,
other
);
return other.clone();
}
if other.hints().contains(Flags::FULL)
&& other.hints().dag_version() >= self.hints().dag_version()
&& self.hints().dag_version() > None
{
tracing::debug!(
target: "dag::algo::intersection",
"intersection(x={:.6?}, y={:.6?}) = x (fast path 2)",
self,
other
);
return self.clone();
}
if self.hints().contains(Flags::EMPTY) || other.hints().contains(Flags::EMPTY) {
tracing::debug!(
target: "dag::algo::intersection",
"intersection(x={:.6?}, y={:.6?}) = () (fast path 3)",
self,
other
);
return Self::empty();
}
if let (Some(this), Some(other)) = (
self.as_any().downcast_ref::<IdStaticSet>(),
other.as_any().downcast_ref::<IdStaticSet>(),
) {
let order = this.map.map_version().partial_cmp(other.map.map_version());
if let Some(order) = order {
// Fast path for IdStaticSet
let result = Self::from_spans_idmap_dag(
this.spans.intersection(&other.spans),
pick(order, &this.map, &other.map).clone(),
pick(order, &this.dag, &other.dag).clone(),
);
tracing::debug!(
target: "dag::algo::intersection",
"intersection(x={:.6?}, y={:.6?}) = {:?} (IdStatic fast path)",
self,
other,
&result
);
return result;
}
}
tracing::warn!(
target: "dag::algo::intersection",
"intersection(x={:.6?}, y={:.6?}) (slow path)", self, other);
Self::from_query(intersection::IntersectionSet::new(
self.clone(),
other.clone(),
))
}
/// Calculates the union of two sets.
pub fn union(&self, other: &NameSet) -> NameSet {
if (self.hints().contains(Flags::FULL)
&& self.hints().dag_version() >= other.hints().dag_version()
&& other.hints().dag_version() > None)
|| other.hints().contains(Flags::EMPTY)
{
tracing::debug!(
target: "dag::algo::union",
"union(x={:.6?}, y={:.6?}) = x (fast path 1)", self, other);
return self.clone();
}
if self.hints().contains(Flags::EMPTY)
|| (other.hints().contains(Flags::FULL)
&& other.hints().dag_version() >= self.hints().dag_version()
&& self.hints().dag_version() > None)
{
tracing::debug!(
target: "dag::algo::union",
"union(x={:.6?}, y={:.6?}) = y (fast path 2)", self, other);
return other.clone();
}
if let (Some(this), Some(other)) = (
self.as_any().downcast_ref::<IdStaticSet>(),
other.as_any().downcast_ref::<IdStaticSet>(),
) {
let order = this.map.map_version().partial_cmp(other.map.map_version());
if let Some(order) = order {
// Fast path for IdStaticSet
let result = Self::from_spans_idmap_dag(
this.spans.union(&other.spans),
pick(order, &this.map, &other.map).clone(),
pick(order, &this.dag, &other.dag).clone(),
);
tracing::debug!(
target: "dag::algo::union",
"union(x={:.6?}, y={:.6?}) = {:.6?} (fast path 3)",
self,
other,
&result
);
return result;
}
}
tracing::warn!(
target: "dag::algo::union",
"union(x={:.6?}, y={:.6?}) (slow path)", self, other);
Self::from_query(union::UnionSet::new(self.clone(), other.clone()))
}
/// Filter using the given async function. If `filter_func` returns `true`
/// for a vertex, then the vertex will be taken, other it will be skipped.
pub fn filter(
&self,
filter_func: Box<dyn Fn(&VertexName) -> BoxFuture<Result<bool>> + Send + Sync + 'static>,
) -> Self {
let filter_func = Arc::new(filter_func);
let this = self.clone();
let hints = {
// Drop ANCESTORS | FULL and add FILTER.
let hints = self.hints().clone();
hints.update_flags_with(|f| (f - Flags::ANCESTORS - Flags::FULL) | Flags::FILTER);
hints
};
let result = Self::from_async_evaluate_contains(
Box::new({
let filter_func = filter_func.clone();
let this = this.clone();
let hints = hints.clone();
move || {
let filter_func = filter_func.clone();
let this = this.clone();
let hints = hints.clone();
Box::pin(async move {
let stream = this.0.iter().await?;
let stream = stream.filter_map(move |v| {
let filter_func = filter_func.clone();
async move {
match v {
Ok(v) => match filter_func(&v).await {
Ok(true) => Some(Ok(v)),
Ok(false) => None,
Err(e) => Some(Err(e)),
},
Err(e) => Some(Err(e)),
}
}
});
Ok(Self::from_stream(Box::pin(stream), hints))
})
}
}),
Box::new(move |_, v| {
let filter_func = filter_func.clone();
let this = this.clone();
Box::pin(async move { Ok(this.0.contains(v).await? && filter_func(v).await?) })
}),
hints,
);
result.hints().add_flags(Flags::FILTER);
result
}
/// Convert the set to a graph containing only the vertexes in the set. This can be slow on
/// larger sets.
pub async fn to_parents(&self) -> Result<Option<impl Parents>> {
default_impl::set_to_parents(self).await
}
/// Obtain the attached dag if available.
pub fn dag(&self) -> Option<Arc<dyn DagAlgorithm + Send + Sync>> {
self.hints().dag()
}
/// Obtain the attached IdMap if available.
pub fn id_map(&self) -> Option<Arc<dyn IdConvert + Send + Sync>> {
self.hints().id_map()
}
/// Convert the current set into a flat static set so it can be used in some
/// fast paths. This is useful for some common sets like `obsolete()` that
/// might be represented by a complex expression.
pub async fn flatten(&self) -> Result<NameSet> {
match (self.id_map(), self.dag()) {
(Some(id_map), Some(dag)) => {
// Convert to IdStaticSet
self.flatten_id(id_map, dag).await
}
_ => {
// Convert to StaticSet
self.flatten_names().await
}
}
}
/// Convert this set to a static id set.
pub async fn flatten_id(
&self,
id_map: Arc<dyn IdConvert + Send + Sync>,
dag: Arc<dyn DagAlgorithm + Send + Sync>,
) -> Result<NameSet> {
if self.as_any().is::<IdStaticSet>() {
return Ok(self.clone());
}
let mut ids = Vec::with_capacity(self.count()?);
for vertex in self.iter()? {
let id = id_map.vertex_id(vertex?).await?;
ids.push(id);
}
ids.sort_unstable_by_key(|i| u64::MAX - i.0);
let spans = IdSet::from_sorted_spans(ids);
let flat_set = NameSet::from_spans_idmap_dag(spans, id_map, dag);
flat_set.hints().inherit_flags_min_max_id(self.hints());
Ok(flat_set)
}
/// Convert this set to a static name set.
pub async fn flatten_names(&self) -> Result<NameSet> {
if self.as_any().is::<StaticSet>() {
return Ok(self.clone());
}
let names = self.iter()?.collect::<Result<Vec<_>>>()?;
let flat_set = Self::from_static_names(names);
flat_set.hints().inherit_flags_min_max_id(self.hints());
Ok(flat_set)
}
/// Take the first `n` items.
pub fn take(&self, n: u64) -> NameSet {
if let Some(set) = self.as_any().downcast_ref::<IdStaticSet>() {
tracing::debug!("take(x={:.6?}, {}) (fast path)", self, n);
Self::from_spans_idmap_dag(set.spans.take(n), set.map.clone(), set.dag.clone())
} else {
tracing::debug!("take(x={:.6?}, {}) (slow path)", self, n);
let set = slice::SliceSet::new(self.clone(), 0, Some(n));
Self::from_query(set)
}
}
/// Skip the first `n` items.
pub fn skip(&self, n: u64) -> NameSet {
if n == 0 {
return self.clone();
}
if let Some(set) = self.as_any().downcast_ref::<IdStaticSet>() {
tracing::debug!("skip(x={:.6?}, {}) (fast path)", self, n);
Self::from_spans_idmap_dag(set.spans.skip(n), set.map.clone(), set.dag.clone())
} else {
tracing::debug!("skip(x={:.6?}, {}) (slow path)", self, n);
let set = slice::SliceSet::new(self.clone(), n, None);
Self::from_query(set)
}
}
/// Converts to `(IdSet, IdConvert)` pair in O(1). If the underlying set
/// cannot provide such information in O(1), return `None`.
///
/// Useful if the callsite wants to have random access (ex. bisect) and
/// control how to resolve in batches.
pub fn to_id_set_and_id_map_in_o1(&self) -> Option<(IdSet, Arc<dyn IdConvert + Send + Sync>)> {
let id_map = self.id_map()?;
let id_set = self.as_any().downcast_ref::<IdStaticSet>()?.spans.clone();
Some((id_set, id_map))
}
}
impl BitAnd for NameSet {
type Output = Self;
fn bitand(self, other: Self) -> Self {
self.intersection(&other)
}
}
impl BitOr for NameSet {
type Output = Self;
fn bitor(self, other: Self) -> Self {
self.union(&other)
}
}
impl Sub for NameSet {
type Output = Self;
fn sub(self, other: Self) -> Self {
self.difference(&other)
}
}
impl Deref for NameSet {
type Target = dyn AsyncNameSetQuery;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
impl fmt::Debug for NameSet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
/// Read-only queries required by [`NameSet`]: Iteration, length and contains.
///
/// Types implementating this trait should rewrite methods to use fast paths
/// when possible.
#[async_trait::async_trait]
pub trait AsyncNameSetQuery: Any + Debug + Send + Sync {
/// Iterate through the set in defined order.
async fn iter(&self) -> Result<BoxVertexStream>;
/// Iterate through the set in the reversed order.
async fn iter_rev(&self) -> Result<BoxVertexStream> {
let mut iter = self.iter().await?;
let mut items = Vec::new();
while let Some(item) = iter.next().await {
items.push(item);
}
Ok(Box::pin(futures::stream::iter(items.into_iter().rev())))
}
/// Number of names in this set.
async fn count(&self) -> Result<usize> {
let mut iter = self.iter().await?;
let mut count = 0;
while let Some(item) = iter.next().await {
item?;
count += 1;
}
Ok(count)
}
/// The first name in the set.
async fn first(&self) -> Result<Option<VertexName>> {
self.iter().await?.next().await.transpose()
}
/// The last name in the set.
async fn last(&self) -> Result<Option<VertexName>> {
self.iter_rev().await?.next().await.transpose()
}
/// Test if this set is empty.
async fn is_empty(&self) -> Result<bool> {
self.first().await.map(|n| n.is_none())
}
/// Test if this set contains a given name.
async fn contains(&self, name: &VertexName) -> Result<bool> {
let mut iter = self.iter().await?;
while let Some(item) = iter.next().await {
if &item? == name {
return Ok(true);
}
}
Ok(false)
}
/// Test contains in less than O(N) time.
/// Returns None if cannot achieve in less than O(N) time.
async fn contains_fast(&self, name: &VertexName) -> Result<Option<bool>> {
let _ = name;
Ok(None)
}
/// For downcasting.
fn as_any(&self) -> &dyn Any;
/// Get or set optimization hints.
fn hints(&self) -> &Hints;
/// Get an optional IdConvert interface to check hints.
fn id_convert(&self) -> Option<&dyn IdConvert> {
None
}
}
/// Sync version of `AsyncNameSetQuery`.
pub trait SyncNameSetQuery {
/// Iterate through the set in defined order.
fn iter(&self) -> Result<Box<dyn NameIter>>;
/// Iterate through the set in the reversed order.
fn iter_rev(&self) -> Result<Box<dyn NameIter>>;
/// Number of names in this set.
fn count(&self) -> Result<usize>;
/// The first name in the set.
fn first(&self) -> Result<Option<VertexName>>;
/// The last name in the set.
fn last(&self) -> Result<Option<VertexName>>;
/// Test if this set is empty.
fn is_empty(&self) -> Result<bool>;
/// Test if this set contains a given name.
fn contains(&self, name: &VertexName) -> Result<bool>;
/// For downcasting.
fn as_any(&self) -> &dyn Any;
/// Get or set optimization hints.
fn hints(&self) -> &Hints;
/// Get an optional IdConvert interface to check hints.
fn id_convert(&self) -> Option<&dyn IdConvert>;
}
impl<T: AsyncNameSetQuery> SyncNameSetQuery for T {
fn iter(&self) -> Result<Box<dyn NameIter>> {
non_blocking(AsyncNameSetQuery::iter(self))?.map(to_iter)
}
fn iter_rev(&self) -> Result<Box<dyn NameIter>> {
non_blocking(AsyncNameSetQuery::iter_rev(self))?.map(to_iter)
}
fn count(&self) -> Result<usize> {
non_blocking(AsyncNameSetQuery::count(self))?
}
fn first(&self) -> Result<Option<VertexName>> {
non_blocking(AsyncNameSetQuery::first(self))?
}
fn last(&self) -> Result<Option<VertexName>> {
non_blocking(AsyncNameSetQuery::last(self))?
}
fn is_empty(&self) -> Result<bool> {
non_blocking(AsyncNameSetQuery::is_empty(self))?
}
fn contains(&self, name: &VertexName) -> Result<bool> {
non_blocking(AsyncNameSetQuery::contains(self, name))?
}
fn as_any(&self) -> &dyn Any {
AsyncNameSetQuery::as_any(self)
}
fn hints(&self) -> &Hints {
AsyncNameSetQuery::hints(self)
}
fn id_convert(&self) -> Option<&dyn IdConvert> {
AsyncNameSetQuery::id_convert(self)
}
}
impl SyncNameSetQuery for NameSet {
fn iter(&self) -> Result<Box<dyn NameIter>> {
non_blocking(AsyncNameSetQuery::iter(self.0.deref()))?.map(to_iter)
}
fn iter_rev(&self) -> Result<Box<dyn NameIter>> {
non_blocking(AsyncNameSetQuery::iter_rev(self.0.deref()))?.map(to_iter)
}
fn count(&self) -> Result<usize> {
non_blocking(AsyncNameSetQuery::count(self.0.deref()))?
}
fn first(&self) -> Result<Option<VertexName>> {
non_blocking(AsyncNameSetQuery::first(self.0.deref()))?
}
fn last(&self) -> Result<Option<VertexName>> {
non_blocking(AsyncNameSetQuery::last(self.0.deref()))?
}
fn is_empty(&self) -> Result<bool> {
non_blocking(AsyncNameSetQuery::is_empty(self.0.deref()))?
}
fn contains(&self, name: &VertexName) -> Result<bool> {
non_blocking(AsyncNameSetQuery::contains(self.0.deref(), name))?
}
fn as_any(&self) -> &dyn Any {
AsyncNameSetQuery::as_any(self.0.deref())
}
fn hints(&self) -> &Hints {
AsyncNameSetQuery::hints(self.0.deref())
}
fn id_convert(&self) -> Option<&dyn IdConvert> {
AsyncNameSetQuery::id_convert(self.0.deref())
}
}
/// Iterator of [`NameSet`].
/// Types implementing this should consider replacing `iter_rev` with a fast
/// path if possible.
pub trait NameIter: Iterator<Item = Result<VertexName>> + Send {}
impl<T> NameIter for T where T: Iterator<Item = Result<VertexName>> + Send {}
/// Abstract async iterator that yields `Vertex`es.
pub trait VertexStream: Stream<Item = Result<VertexName>> + Send {}
impl<T> VertexStream for T where T: Stream<Item = Result<VertexName>> + Send {}
/// Boxed async iterator that yields `Vertex`es.
pub type BoxVertexStream = Pin<Box<dyn VertexStream>>;
/// A wrapper that converts `VertexStream` to `NameIter`.
struct NonblockingNameIter(BoxVertexStream);
impl Iterator for NonblockingNameIter {
type Item = Result<VertexName>;
fn next(&mut self) -> Option<Self::Item> {
match non_blocking(self.0.next()) {
Err(e) => Some(Err(e.into())),
Ok(v) => v,
}
}
}
fn to_iter(stream: BoxVertexStream) -> Box<dyn NameIter> {
Box::new(NonblockingNameIter(stream))
}
impl From<VertexName> for NameSet {
fn from(name: VertexName) -> NameSet {
NameSet::from_static_names(std::iter::once(name))
}
}
impl From<&VertexName> for NameSet {
fn from(name: &VertexName) -> NameSet {
NameSet::from_static_names(std::iter::once(name.clone()))
}
}
/// Pick `left` if `order` is "greater or equal".
/// Pick `right` otherwise.
fn pick<T>(order: cmp::Ordering, left: T, right: T) -> T {
match order {
cmp::Ordering::Greater | cmp::Ordering::Equal => left,
cmp::Ordering::Less => right,
}
}
#[cfg(test)]
pub(crate) mod tests {
use nonblocking::non_blocking_result as r;
use super::*;
use crate::Id;
pub(crate) fn nb<F, R>(future: F) -> R
where
F: std::future::Future<Output = R>,
{
non_blocking(future).unwrap()
}
// Converts async Stream to Iterator.
pub(crate) fn ni<F>(future: F) -> Result<Box<dyn NameIter>>
where
F: std::future::Future<Output = Result<BoxVertexStream>>,
{
nb(future).map(to_iter)
}
// For easier testing.
impl From<&str> for NameSet {
fn from(name: &str) -> NameSet {
NameSet::from_static_names(
name.split_whitespace()
.map(|n| VertexName::copy_from(n.as_bytes())),
)
}
}
impl NameSet {
pub(crate) fn assert_eq(&self, other: NameSet) {
assert!(
other.count().unwrap() == self.count().unwrap()
&& (other.clone() & self.clone()).count().unwrap() == self.count().unwrap(),
"set {:?} ({:?}) != {:?} ({:?})",
self,
self.iter().unwrap().map(|i| i.unwrap()).collect::<Vec<_>>(),
&other,
other
.iter()
.unwrap()
.map(|i| i.unwrap())
.collect::<Vec<_>>(),
);
}
}
#[derive(Default, Debug)]
pub(crate) struct VecQuery(Vec<VertexName>, Hints);
#[async_trait::async_trait]
impl AsyncNameSetQuery for VecQuery {
async fn iter(&self) -> Result<BoxVertexStream> {
let iter = self.0.clone().into_iter().map(Ok);
Ok(Box::pin(futures::stream::iter(iter)))
}
fn as_any(&self) -> &dyn Any {
self
}
fn hints(&self) -> &Hints {
&self.1
}
}
impl VecQuery {
/// Quickly create [`VecQuery`] that contains `len(bytes)` items.
pub(crate) fn from_bytes(bytes: &[u8]) -> Self {
let mut used = [false; 256];
Self(
bytes
.iter()
.filter_map(|&b| {
if used[b as usize] {
None
} else {
used[b as usize] = true;
Some(to_name(b))
}
})
.collect(),
Hints::default(),
)
}
}
/// Create a [`VertexName`] from `u8` by repeating them.
pub(crate) fn to_name(value: u8) -> VertexName {
VertexName::from(vec![value; 2])
}
/// Shorten a [`VertexName`] result.
pub(crate) fn shorten_name(name: VertexName) -> String {
name.to_hex()[..2].to_string()
}
/// Shorten a [`NameIter`] result.
pub(crate) fn shorten_iter(iter: Result<Box<dyn NameIter>>) -> Vec<String> {
iter.unwrap()
.map(|v| shorten_name(v.unwrap()))
.collect::<Vec<_>>()
}
#[test]
fn test_empty_query() -> Result<()> {
let query = VecQuery::default();
check_invariants(&query)?;
assert_eq!(SyncNameSetQuery::iter(&query)?.count(), 0);
assert_eq!(SyncNameSetQuery::iter_rev(&query)?.count(), 0);
assert_eq!(SyncNameSetQuery::first(&query)?, None);
assert_eq!(SyncNameSetQuery::last(&query)?, None);
assert_eq!(SyncNameSetQuery::count(&query)?, 0);
assert!(SyncNameSetQuery::is_empty(&query)?);
assert!(!SyncNameSetQuery::contains(&query, &to_name(0))?);
Ok(())
}
#[test]
fn test_vec_query() -> Result<()> {
let query = VecQuery::from_bytes(b"\xab\xef\xcd");
check_invariants(&query)?;
assert_eq!(
shorten_iter(SyncNameSetQuery::iter(&query)),
["ab", "ef", "cd"]
);
assert_eq!(
shorten_iter(SyncNameSetQuery::iter_rev(&query)),
["cd", "ef", "ab"]
);
assert_eq!(
shorten_name(SyncNameSetQuery::first(&query)?.unwrap()),
"ab"
);
assert_eq!(shorten_name(SyncNameSetQuery::last(&query)?.unwrap()), "cd");
assert!(!SyncNameSetQuery::is_empty(&query)?);
assert!(SyncNameSetQuery::contains(&query, &to_name(0xef))?);
assert!(!SyncNameSetQuery::contains(&query, &to_name(0))?);
Ok(())
}
#[test]
fn test_debug() {
let set = NameSet::from_static_names(vec![to_name(2)])
.union(&NameSet::from_static_names(vec![to_name(1)]))
.difference(
&NameSet::from_static_names(vec![to_name(3)])
.intersection(&NameSet::from_static_names(vec![to_name(2), to_name(3)])),
);
assert_eq!(
format!("{:?}", &set),
"<diff <or <static [0202]> <static [0101]>> <and <static [0303]> <static [0202, 0303]>>>"
);
assert_eq!(
format!("\n{:#?}", &set),
r#"
<diff
<or
<static [
0202,
]>
<static [
0101,
]>>
<and
<static [
0303,
]>
<static [
0202,
0303,
]>>>"#
);
}
#[test]
fn test_flatten() {
let set = NameSet::from_static_names(vec![to_name(2)])
.union(&NameSet::from_static_names(vec![to_name(1)]))
.difference(
&NameSet::from_static_names(vec![to_name(3)])
.intersection(&NameSet::from_static_names(vec![to_name(2), to_name(3)])),
);
assert_eq!(
format!("{:?}", r(set.flatten()).unwrap()),
"<static [0202, 0101]>"
);
}
#[test]
fn test_ops() {
let ab: NameSet = "a b".into();
let bc: NameSet = "b c".into();
let s = |set: NameSet| -> Vec<String> { shorten_iter(set.iter()) };
assert_eq!(s(ab.clone() | bc.clone()), ["61", "62", "63"]);
assert_eq!(s(ab.clone() & bc.clone()), ["62"]);
assert_eq!(s(ab - bc), ["61"]);
}
#[test]
fn test_skip_take_slow_path() {
let s: NameSet = "a b c d".into();
let d = |set: NameSet| -> String { format!("{:?}", r(set.flatten_names()).unwrap()) };
assert_eq!(d(s.take(2)), "<static [a, b]>");
assert_eq!(d(s.skip(2)), "<static [c, d]>");
assert_eq!(d(s.skip(1).take(2)), "<static [b, c]>");
}
#[test]
fn test_hints_empty_full_fast_paths() {
let partial: NameSet = "a".into();
partial.hints().add_flags(Flags::ID_ASC);
let empty: NameSet = "".into();
let full: NameSet = "f".into();
full.hints().add_flags(Flags::FULL | Flags::ID_DESC);
assert_eq!(