Skip to main content

dag/
set.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8//! # set
9//!
10//! See [`Set`] for the main structure.
11
12use std::any::Any;
13use std::borrow::Cow;
14use std::cmp;
15use std::fmt;
16use std::fmt::Debug;
17use std::ops::Add;
18use std::ops::BitAnd;
19use std::ops::BitOr;
20use std::ops::Deref;
21use std::ops::Sub;
22use std::pin::Pin;
23use std::sync::Arc;
24
25use futures::Stream;
26use futures::StreamExt;
27use futures::future::BoxFuture;
28use nonblocking::non_blocking;
29
30use crate::Id;
31use crate::IdList;
32use crate::IdSet;
33use crate::Result;
34use crate::Vertex;
35use crate::default_impl;
36use crate::ops::DagAlgorithm;
37use crate::ops::IdConvert;
38use crate::ops::IdMapSnapshot;
39use crate::ops::Parents;
40
41pub mod difference;
42pub mod hints;
43pub mod id_lazy;
44pub mod id_static;
45pub mod intersection;
46pub mod lazy;
47#[cfg(any(test, feature = "indexedlog-backend"))]
48pub mod legacy;
49pub mod meta;
50pub mod reverse;
51pub mod slice;
52pub mod r#static;
53pub mod union;
54
55use self::hints::Flags;
56use self::hints::Hints;
57use self::id_static::BasicIterationOrder;
58use self::id_static::IdStaticSet;
59use self::meta::MetaSet;
60use self::reverse::ReverseSet;
61use self::r#static::StaticSet;
62
63/// A [`Set`] contains an immutable list of names.
64///
65/// It provides order-preserving iteration and set operations,
66/// and is cheaply clonable.
67#[derive(Clone)]
68pub struct Set(Arc<dyn AsyncSetQuery>);
69
70impl Set {
71    pub(crate) fn from_query(query: impl AsyncSetQuery) -> Self {
72        Self(Arc::new(query))
73    }
74
75    /// Creates an empty set.
76    pub fn empty() -> Self {
77        Self::from_query(r#static::StaticSet::empty())
78    }
79
80    /// Creates from a (short) list of known names.
81    pub fn from_static_names(names: impl IntoIterator<Item = Vertex>) -> Set {
82        Self::from_query(r#static::StaticSet::from_names(names))
83    }
84
85    /// Creates from a (lazy) iterator of names.
86    pub fn from_iter<I>(iter: I, hints: Hints) -> Set
87    where
88        I: IntoIterator<Item = Result<Vertex>> + 'static,
89        <I as IntoIterator>::IntoIter: Send + Sync,
90    {
91        Self::from_query(lazy::LazySet::from_iter(iter, hints))
92    }
93
94    /// Creates from a (lazy) stream of names with hints.
95    pub fn from_stream(stream: BoxVertexStream, hints: Hints) -> Set {
96        Self::from_query(lazy::LazySet::from_stream(stream, hints))
97    }
98
99    /// Creates from a (lazy) iterator of Ids, an IdMap, and a Dag.
100    pub fn from_id_iter_idmap_dag<I>(
101        iter: I,
102        map: Arc<dyn IdConvert + Send + Sync>,
103        dag: Arc<dyn DagAlgorithm + Send + Sync>,
104    ) -> Set
105    where
106        I: IntoIterator<Item = Result<Id>> + 'static,
107        <I as IntoIterator>::IntoIter: Send + Sync,
108    {
109        Self::from_query(id_lazy::IdLazySet::from_iter_idmap_dag(iter, map, dag))
110    }
111
112    /// Creates from a (lazy) iterator of Ids and a struct with snapshot abilities.
113    pub fn from_id_iter_dag<I>(iter: I, dag: &(impl DagAlgorithm + IdMapSnapshot)) -> Result<Set>
114    where
115        I: IntoIterator<Item = Result<Id>> + 'static,
116        <I as IntoIterator>::IntoIter: Send + Sync,
117    {
118        let map = dag.id_map_snapshot()?;
119        let dag = dag.dag_snapshot()?;
120        Ok(Self::from_id_iter_idmap_dag(iter, map, dag))
121    }
122
123    /// Creates from [`IdSet`], [`IdMap`] and [`DagAlgorithm`].
124    /// Callsite must make sure `spans`, `map`, `dag` are using the same `Id` mappings.
125    /// Prefer `from_id_set_dag` if possible.
126    pub fn from_id_set_idmap_dag(
127        spans: IdSet,
128        map: Arc<dyn IdConvert + Send + Sync>,
129        dag: Arc<dyn DagAlgorithm + Send + Sync>,
130    ) -> Set {
131        Self::from_id_set_idmap_dag_order(spans, map, dag, None)
132    }
133
134    /// Creates from [`IdSet`], [`IdMap`], [`DagAlgorithm`], and [`BasicIterationOrder`].
135    /// Callsite must make sure `spans`, `map`, `dag` are using the same `Id` mappings.
136    pub fn from_id_set_idmap_dag_order(
137        spans: IdSet,
138        map: Arc<dyn IdConvert + Send + Sync>,
139        dag: Arc<dyn DagAlgorithm + Send + Sync>,
140        iteration_order: Option<BasicIterationOrder>,
141    ) -> Set {
142        let mut set = IdStaticSet::from_id_set_idmap_dag(spans, map, dag);
143        if let Some(order) = iteration_order {
144            set.set_iteration_order(order);
145        }
146        Self::from_query(set)
147    }
148
149    /// Creates from [`IdSet`] and a struct with snapshot abilities.
150    /// Callsite must make sure `spans`, `dag` are using the same `Id` mappings.
151    pub fn from_id_set_dag(
152        spans: IdSet,
153        dag: &(impl DagAlgorithm + IdMapSnapshot),
154    ) -> Result<Self> {
155        let map = dag.id_map_snapshot()?;
156        let dag = dag.dag_snapshot()?;
157        Ok(Self::from_id_set_idmap_dag(spans, map, dag))
158    }
159
160    /// Creates from [`IdList`] and a struct with snapshot abilities.
161    /// Unlike [`Self::from_id_set_dag`], the iteration order of `list` will be preserved.
162    /// Callsite must make sure `list`, `dag` are using the same `Id` mappings.
163    pub fn from_id_list_dag(
164        list: IdList,
165        dag: &(impl DagAlgorithm + IdMapSnapshot),
166    ) -> Result<Self> {
167        let map = dag.id_map_snapshot()?;
168        let dag = dag.dag_snapshot()?;
169        let set = IdStaticSet::from_id_list_idmap_dag(list, map, dag);
170        Ok(Self::from_query(set))
171    }
172
173    /// Creates from a function that evaluates to a [`Set`], and a
174    /// `contains` fast path.
175    pub fn from_evaluate_contains<C>(
176        evaluate: impl Fn() -> Result<Set> + Send + Sync + 'static,
177        contains: C,
178        hints: Hints,
179    ) -> Set
180    where
181        C: for<'a> Fn(&'a MetaSet, &'a Vertex) -> Result<bool>,
182        C: Send + Sync + 'static,
183    {
184        let evaluate = move || -> BoxFuture<_> {
185            let result = evaluate();
186            Box::pin(async move { result })
187        };
188        let contains = Arc::new(contains);
189        Self::from_async_evaluate_contains(
190            Box::new(evaluate),
191            Box::new(move |m, v| {
192                let contains = contains.clone();
193                Box::pin(async move { contains(m, v) })
194            }),
195            hints,
196        )
197    }
198
199    /// Creates from an async function that evaluates to a [`Set`], and a
200    /// async `contains` fast path.
201    pub fn from_async_evaluate_contains(
202        evaluate: Box<dyn Fn() -> BoxFuture<'static, Result<Set>> + Send + Sync>,
203        contains: Box<
204            dyn for<'a> Fn(&'a MetaSet, &'a Vertex) -> BoxFuture<'a, Result<bool>> + Send + Sync,
205        >,
206        hints: Hints,
207    ) -> Set {
208        Self::from_query(MetaSet::from_evaluate_hints(evaluate, hints).with_contains(contains))
209    }
210
211    /// Reverse the iteration order of the `Set`.
212    pub fn reverse(&self) -> Set {
213        match self.0.specialized_reverse() {
214            Some(set) => set,
215            None => Self::from_query(ReverseSet::new(self.clone())),
216        }
217    }
218
219    /// Calculates the subset that is only in self, not in other.
220    pub fn difference(&self, other: &Set) -> Set {
221        if other.hints().contains(Flags::FULL)
222            && other.hints().dag_version() >= self.hints().dag_version()
223            && self.hints().dag_version() > None
224        {
225            tracing::debug!(
226                target: "dag::algo::difference",
227                "difference(x={:.6?}, y={:.6?}) = () (fast path 1)",
228                self,
229                other
230            );
231            return Self::empty();
232        }
233        if self.hints().contains(Flags::EMPTY) || other.hints().contains(Flags::EMPTY) {
234            tracing::debug!(
235                target: "dag::algo::difference",
236                "difference(x={:.6?}, y={:.6?}) = x (fast path 2)",
237                self,
238                other
239            );
240            return self.clone();
241        }
242        if let (Some(this), Some(other)) = (
243            self.as_any().downcast_ref::<IdStaticSet>(),
244            // xs - ys; the order of ys does not matter
245            other.specialized_flatten_id(),
246        ) {
247            let order = this.map.map_version().partial_cmp(other.map.map_version());
248            if let (Some(_order), Some(this_id_set)) = (order, this.id_set_try_preserving_order()) {
249                // Fast path for IdStaticSet.
250                // The order is preserved, `this.is_id_sorted` is true.
251                let result = Self::from_id_set_idmap_dag_order(
252                    this_id_set.difference(other.id_set_losing_order()),
253                    this.map.clone(),
254                    this.dag.clone(),
255                    this.iteration_order(),
256                );
257                tracing::debug!(
258                    target: "dag::algo::difference",
259                    "difference(x={:.6?}, y={:.6?}) = {:.6?} (fast path 3)",
260                    self,
261                    other,
262                    &result
263                );
264                return result;
265            }
266        }
267        tracing::warn!(
268                target: "dag::algo::difference",
269            "difference(x={:.6?}, y={:.6?}) (slow path)", self, other);
270        Self::from_query(difference::DifferenceSet::new(self.clone(), other.clone()))
271    }
272
273    /// Calculates the intersection of two sets.
274    pub fn intersection(&self, other: &Set) -> Set {
275        if self.hints().contains(Flags::FULL)
276            && self.hints().dag_version() >= other.hints().dag_version()
277            && other.hints().dag_version() > None
278        {
279            tracing::debug!(
280                target: "dag::algo::intersection",
281                "intersection(x={:.6?}, y={:.6?}) = y (fast path 1)",
282                self,
283                other
284            );
285            return other.clone();
286        }
287        if other.hints().contains(Flags::FULL)
288            && other.hints().dag_version() >= self.hints().dag_version()
289            && self.hints().dag_version() > None
290        {
291            tracing::debug!(
292                target: "dag::algo::intersection",
293                "intersection(x={:.6?}, y={:.6?}) = x (fast path 2)",
294                self,
295                other
296            );
297            return self.clone();
298        }
299        if self.hints().contains(Flags::EMPTY) || other.hints().contains(Flags::EMPTY) {
300            tracing::debug!(
301                target: "dag::algo::intersection",
302                "intersection(x={:.6?}, y={:.6?}) = () (fast path 3)",
303                self,
304                other
305            );
306            return Self::empty();
307        }
308        if let (Some(this), Some(other)) = (
309            self.as_any().downcast_ref::<IdStaticSet>(),
310            // xs & ys; the order of ys does not matter
311            other.specialized_flatten_id(),
312        ) {
313            let order = this.map.map_version().partial_cmp(other.map.map_version());
314            if let (Some(order), Some(this_id_set)) = (order, this.id_set_try_preserving_order()) {
315                // Fast path for IdStaticSet
316                let result = Self::from_id_set_idmap_dag_order(
317                    this_id_set.intersection(other.id_set_losing_order()),
318                    pick(order, &this.map, &other.map).clone(),
319                    pick(order, &this.dag, &other.dag).clone(),
320                    this.iteration_order(),
321                );
322                tracing::debug!(
323                    target: "dag::algo::intersection",
324                    "intersection(x={:.6?}, y={:.6?}) = {:?} (IdStatic fast path)",
325                    self,
326                    other,
327                    &result
328                );
329                return result;
330            }
331        }
332        tracing::warn!(
333            target: "dag::algo::intersection",
334            "intersection(x={:.6?}, y={:.6?}) (slow path)", self, other);
335        Self::from_query(intersection::IntersectionSet::new(
336            self.clone(),
337            other.clone(),
338        ))
339    }
340
341    /// Union fast paths. Handles when one set is "FULL" or "EMPTY".
342    fn union_fast_paths(&self, other: &Self) -> Option<Self> {
343        if (self.hints().contains(Flags::FULL)
344            && self.hints().dag_version() >= other.hints().dag_version()
345            && other.hints().dag_version() > None)
346            || other.hints().contains(Flags::EMPTY)
347        {
348            tracing::debug!(
349                target: "dag::algo::union",
350                "union(x={:.6?}, y={:.6?}) = x (fast path 1)", self, other);
351            return Some(self.clone());
352        }
353        if self.hints().contains(Flags::EMPTY)
354            || (other.hints().contains(Flags::FULL)
355                && other.hints().dag_version() >= self.hints().dag_version()
356                && self.hints().dag_version() > None)
357        {
358            tracing::debug!(
359                target: "dag::algo::union",
360                "union(x={:.6?}, y={:.6?}) = y (fast path 2)", self, other);
361            return Some(other.clone());
362        }
363        None
364    }
365
366    /// Calculates the union of two sets. Iteration order might get lost.
367    pub fn union(&self, other: &Set) -> Set {
368        if let Some(set) = self.union_fast_paths(other) {
369            return set;
370        }
371
372        // This fast path aggressively flatten the sets. It does not preserve order.
373        if let (Some(this), Some(other)) = (
374            self.specialized_flatten_id(),
375            other.specialized_flatten_id(),
376        ) {
377            let order = this.map.map_version().partial_cmp(other.map.map_version());
378            if let Some(order) = order {
379                // Fast path for IdStaticSet
380                let result = Self::from_id_set_idmap_dag_order(
381                    this.id_set_losing_order()
382                        .union(other.id_set_losing_order()),
383                    pick(order, &this.map, &other.map).clone(),
384                    pick(order, &this.dag, &other.dag).clone(),
385                    this.iteration_order(),
386                );
387                tracing::debug!(
388                    target: "dag::algo::union",
389                    "union(x={:.6?}, y={:.6?}) = {:.6?} (fast path 3)",
390                    self,
391                    other,
392                    &result
393                );
394                return result;
395            }
396        }
397        tracing::warn!(
398            target: "dag::algo::union",
399            "union(x={:.6?}, y={:.6?}) (slow path)", self, other);
400        Self::from_query(union::UnionSet::new(self.clone(), other.clone()))
401    }
402
403    /// Union, but preserve the iteration order (self first, other next).
404    pub fn union_preserving_order(&self, other: &Self) -> Self {
405        if let Some(set) = self.union_fast_paths(other) {
406            return set;
407        }
408        tracing::debug!(target: "dag::algo::union_preserving_order", "union(x={:.6?}, y={:.6?})", self, other);
409        Self::from_query(union::UnionSet::new(self.clone(), other.clone()))
410    }
411
412    /// Similar to `union`, but without showfast paths, and force a "flatten zip" order.
413    /// For example `[1,2,3,4].union_zip([5,6])` produces this order: `[1,5,2,6,3,4]`.
414    pub fn union_zip(&self, other: &Set) -> Set {
415        tracing::debug!(
416            target: "dag::algo::union_zip",
417            "union_zip(x={:.6?}, y={:.6?}) (slow path)", self, other);
418        Self::from_query(
419            union::UnionSet::new(self.clone(), other.clone()).with_order(union::UnionOrder::Zip),
420        )
421    }
422
423    /// Filter using the given async function. If `filter_func` returns `true`
424    /// for a vertex, then the vertex will be taken, other it will be skipped.
425    pub fn filter(
426        &self,
427        filter_func: Box<dyn Fn(&Vertex) -> BoxFuture<Result<bool>> + Send + Sync + 'static>,
428    ) -> Self {
429        let filter_func = Arc::new(filter_func);
430        let this = self.clone();
431        let hints = {
432            // Drop ANCESTORS | FULL and add FILTER.
433            let hints = self.hints().clone();
434            hints.update_flags_with(|f| (f - Flags::ANCESTORS - Flags::FULL) | Flags::FILTER);
435            hints
436        };
437        let result = Self::from_async_evaluate_contains(
438            Box::new({
439                let filter_func = filter_func.clone();
440                let this = this.clone();
441                let hints = hints.clone();
442                move || {
443                    let filter_func = filter_func.clone();
444                    let this = this.clone();
445                    let hints = hints.clone();
446                    Box::pin(async move {
447                        let stream = this.0.iter().await?;
448                        let stream = stream.filter_map(move |v| {
449                            let filter_func = filter_func.clone();
450                            async move {
451                                match v {
452                                    Ok(v) => match filter_func(&v).await {
453                                        Ok(true) => Some(Ok(v)),
454                                        Ok(false) => None,
455                                        Err(e) => Some(Err(e)),
456                                    },
457                                    Err(e) => Some(Err(e)),
458                                }
459                            }
460                        });
461                        Ok(Self::from_stream(Box::pin(stream), hints))
462                    })
463                }
464            }),
465            Box::new(move |_, v| {
466                let filter_func = filter_func.clone();
467                let this = this.clone();
468                Box::pin(async move { Ok(this.0.contains(v).await? && filter_func(v).await?) })
469            }),
470            hints,
471        );
472        result.hints().add_flags(Flags::FILTER);
473        result
474    }
475
476    /// Convert the set to a graph containing only the vertexes in the set. This can be slow on
477    /// larger sets.
478    pub async fn to_parents(&self) -> Result<Option<impl Parents + use<>>> {
479        default_impl::set_to_parents(self).await
480    }
481
482    /// Obtain the attached dag if available.
483    pub fn dag(&self) -> Option<Arc<dyn DagAlgorithm + Send + Sync>> {
484        self.hints().dag()
485    }
486
487    /// Obtain the attached IdMap if available.
488    pub fn id_map(&self) -> Option<Arc<dyn IdConvert + Send + Sync>> {
489        self.hints().id_map()
490    }
491
492    /// Convert the current set into a flat static set so it can be used in some
493    /// fast paths. This is useful for some common sets like `obsolete()` that
494    /// might be represented by a complex expression.
495    ///
496    /// By flattening, the iteration order might be lost.
497    pub async fn flatten(&self) -> Result<Set> {
498        match (self.id_map(), self.dag()) {
499            (Some(id_map), Some(dag)) => {
500                // Convert to IdStaticSet
501                self.flatten_id(id_map, dag).await
502            }
503            _ => {
504                // Convert to StaticSet
505                self.flatten_names().await
506            }
507        }
508    }
509
510    /// Convert this set to a static id set.
511    ///
512    /// By flattening, the iteration order might be lost.
513    pub async fn flatten_id(
514        &self,
515        id_map: Arc<dyn IdConvert + Send + Sync>,
516        dag: Arc<dyn DagAlgorithm + Send + Sync>,
517    ) -> Result<Set> {
518        if self.as_any().is::<IdStaticSet>() {
519            return Ok(self.clone());
520        }
521        let mut ids = Vec::with_capacity(self.count()?.try_into()?);
522        for vertex in self.iter()? {
523            let id = id_map.vertex_id(vertex?).await?;
524            ids.push(id);
525        }
526        ids.sort_unstable_by_key(|i| u64::MAX - i.0);
527        let spans = IdSet::from_sorted_spans(ids);
528        let flat_set = Set::from_id_set_idmap_dag(spans, id_map, dag);
529        flat_set.hints().inherit_flags_min_max_id(self.hints());
530        Ok(flat_set)
531    }
532
533    /// Convert this set to a static name set.
534    pub async fn flatten_names(&self) -> Result<Set> {
535        if self.as_any().is::<StaticSet>() {
536            return Ok(self.clone());
537        }
538        let names = self.iter()?.collect::<Result<Vec<_>>>()?;
539        let flat_set = Self::from_static_names(names);
540        flat_set.hints().inherit_flags_min_max_id(self.hints());
541        Ok(flat_set)
542    }
543
544    /// Take the first `n` items.
545    pub fn take(&self, n: u64) -> Set {
546        match self.specialized_take(n) {
547            Some(set) => {
548                tracing::debug!("take(x={:.6?}, {}) (specialized path)", self, n);
549                set
550            }
551            _ => {
552                tracing::debug!("take(x={:.6?}, {}) (universal path)", self, n);
553                let set = slice::SliceSet::new(self.clone(), 0, Some(n));
554                Self::from_query(set)
555            }
556        }
557    }
558
559    /// Skip the first `n` items.
560    pub fn skip(&self, n: u64) -> Set {
561        if n == 0 {
562            return self.clone();
563        }
564        match self.specialized_skip(n) {
565            Some(set) => {
566                tracing::debug!("skip(x={:.6?}, {}) (specialized path)", self, n);
567                set
568            }
569            _ => {
570                tracing::debug!("skip(x={:.6?}, {}) (universal path)", self, n);
571                let set = slice::SliceSet::new(self.clone(), n, None);
572                Self::from_query(set)
573            }
574        }
575    }
576
577    /// Converts to `(IdSet, IdConvert)` pair in O(1). If the underlying set
578    /// cannot provide such information in O(1), return `None`.
579    ///
580    /// Useful if the callsite wants to have random access (ex.pathhistory)
581    /// and control how to resolve in batches.
582    pub fn to_id_set_and_id_map_in_o1(&self) -> Option<(IdSet, Arc<dyn IdConvert + Send + Sync>)> {
583        let id_set = self.specialized_flatten_id()?.into_owned();
584        Some((id_set.id_set_losing_order().clone(), id_set.map))
585    }
586}
587
588impl BitAnd for Set {
589    type Output = Self;
590
591    fn bitand(self, other: Self) -> Self {
592        self.intersection(&other)
593    }
594}
595
596impl BitOr for Set {
597    type Output = Self;
598
599    fn bitor(self, other: Self) -> Self {
600        self.union(&other)
601    }
602}
603
604impl Add for Set {
605    type Output = Self;
606
607    fn add(self, rhs: Self) -> Self::Output {
608        self.union_preserving_order(&rhs)
609    }
610}
611
612impl Sub for Set {
613    type Output = Self;
614
615    fn sub(self, other: Self) -> Self {
616        self.difference(&other)
617    }
618}
619
620impl Deref for Set {
621    type Target = dyn AsyncSetQuery;
622
623    fn deref(&self) -> &Self::Target {
624        self.0.deref()
625    }
626}
627
628impl fmt::Debug for Set {
629    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
630        self.0.fmt(f)
631    }
632}
633
634/// Read-only queries required by [`Set`]: Iteration, length and contains.
635///
636/// Types implementing this trait should rewrite methods to use fast paths
637/// when possible.
638#[async_trait::async_trait]
639pub trait AsyncSetQuery: Any + Debug + Send + Sync {
640    /// Iterate through the set in defined order.
641    async fn iter(&self) -> Result<BoxVertexStream>;
642
643    /// Iterate through the set in the reversed order.
644    async fn iter_rev(&self) -> Result<BoxVertexStream> {
645        let mut iter = self.iter().await?;
646        let mut items = Vec::new();
647        while let Some(item) = iter.next().await {
648            items.push(item);
649        }
650        Ok(Box::pin(futures::stream::iter(items.into_iter().rev())))
651    }
652
653    /// Number of names in this set. Do not override.
654    ///
655    /// This function has some built-in fast paths.
656    /// For individual set types, override count_slow, size_hint instead of count.
657    async fn count(&self) -> Result<u64> {
658        if let Some(flat) = self.specialized_flatten_id() {
659            return flat.count_slow().await;
660        }
661        self.count_slow().await
662    }
663
664    /// "Slow" count implementation. Intended to be overridden.
665    ///
666    /// This is intended to be implemented by individual set types as fallbacks
667    /// when the universal fast paths do not work.
668    async fn count_slow(&self) -> Result<u64> {
669        let mut iter = self.iter().await?;
670        let mut count = 0;
671        while let Some(item) = iter.next().await {
672            item?;
673            count += 1;
674        }
675        Ok(count)
676    }
677
678    /// Returns the bounds on the length of the set as a hint.
679    /// The first item is the lower bound.
680    /// The second item is the upper bound.
681    /// This method should not block on long operations like waiting for network.
682    async fn size_hint(&self) -> (u64, Option<u64>) {
683        (0, None)
684    }
685
686    /// The first name in the set.
687    async fn first(&self) -> Result<Option<Vertex>> {
688        self.iter().await?.next().await.transpose()
689    }
690
691    /// The last name in the set.
692    async fn last(&self) -> Result<Option<Vertex>> {
693        self.iter_rev().await?.next().await.transpose()
694    }
695
696    /// Test if this set is empty.
697    async fn is_empty(&self) -> Result<bool> {
698        self.first().await.map(|n| n.is_none())
699    }
700
701    /// Test if this set contains a given name.
702    async fn contains(&self, name: &Vertex) -> Result<bool> {
703        let mut iter = self.iter().await?;
704        while let Some(item) = iter.next().await {
705            if &item? == name {
706                return Ok(true);
707            }
708        }
709        Ok(false)
710    }
711
712    /// Test contains in less than O(N) time.
713    /// Returns None if cannot achieve in less than O(N) time.
714    async fn contains_fast(&self, name: &Vertex) -> Result<Option<bool>> {
715        let _ = name;
716        Ok(None)
717    }
718
719    /// For downcasting.
720    fn as_any(&self) -> &dyn Any;
721
722    /// Get or set optimization hints.
723    fn hints(&self) -> &Hints;
724
725    /// Get an optional IdConvert interface to check hints.
726    fn id_convert(&self) -> Option<&dyn IdConvert> {
727        None
728    }
729
730    /// Specialized "reverse" implementation.
731    /// Returns `None` to use the general purpose reverse implementation.
732    fn specialized_reverse(&self) -> Option<Set> {
733        None
734    }
735
736    /// Specialized "take" implementation.
737    /// Returns `None` to use the general purpose implementation.
738    fn specialized_take(&self, n: u64) -> Option<Set> {
739        let _ = n;
740        None
741    }
742
743    /// Specialized "take" implementation.
744    /// Returns `None` to use the general purpose implementation.
745    fn specialized_skip(&self, n: u64) -> Option<Set> {
746        let _ = n;
747        None
748    }
749
750    /// Specialized "flatten_id" implementation.
751    fn specialized_flatten_id(&self) -> Option<Cow<'_, IdStaticSet>> {
752        None
753    }
754}
755
756/// Sync version of `AsyncSetQuery`.
757pub trait SyncSetQuery {
758    /// Iterate through the set in defined order.
759    fn iter(&self) -> Result<Box<dyn NameIter>>;
760
761    /// Iterate through the set in the reversed order.
762    fn iter_rev(&self) -> Result<Box<dyn NameIter>>;
763
764    /// Number of names in this set.
765    fn count(&self) -> Result<u64>;
766
767    /// The first name in the set.
768    fn first(&self) -> Result<Option<Vertex>>;
769
770    /// The last name in the set.
771    fn last(&self) -> Result<Option<Vertex>>;
772
773    /// Test if this set is empty.
774    fn is_empty(&self) -> Result<bool>;
775
776    /// Test if this set contains a given name.
777    fn contains(&self, name: &Vertex) -> Result<bool>;
778
779    /// For downcasting.
780    fn as_any(&self) -> &dyn Any;
781
782    /// Get or set optimization hints.
783    fn hints(&self) -> &Hints;
784
785    /// Get an optional IdConvert interface to check hints.
786    fn id_convert(&self) -> Option<&dyn IdConvert>;
787}
788
789impl<T: AsyncSetQuery> SyncSetQuery for T {
790    fn iter(&self) -> Result<Box<dyn NameIter>> {
791        non_blocking(AsyncSetQuery::iter(self))?.map(to_iter)
792    }
793
794    fn iter_rev(&self) -> Result<Box<dyn NameIter>> {
795        non_blocking(AsyncSetQuery::iter_rev(self))?.map(to_iter)
796    }
797
798    fn count(&self) -> Result<u64> {
799        non_blocking(AsyncSetQuery::count_slow(self))?
800    }
801
802    fn first(&self) -> Result<Option<Vertex>> {
803        non_blocking(AsyncSetQuery::first(self))?
804    }
805
806    fn last(&self) -> Result<Option<Vertex>> {
807        non_blocking(AsyncSetQuery::last(self))?
808    }
809
810    fn is_empty(&self) -> Result<bool> {
811        non_blocking(AsyncSetQuery::is_empty(self))?
812    }
813
814    fn contains(&self, name: &Vertex) -> Result<bool> {
815        non_blocking(AsyncSetQuery::contains(self, name))?
816    }
817
818    fn as_any(&self) -> &dyn Any {
819        AsyncSetQuery::as_any(self)
820    }
821
822    fn hints(&self) -> &Hints {
823        AsyncSetQuery::hints(self)
824    }
825
826    fn id_convert(&self) -> Option<&dyn IdConvert> {
827        AsyncSetQuery::id_convert(self)
828    }
829}
830
831impl SyncSetQuery for Set {
832    fn iter(&self) -> Result<Box<dyn NameIter>> {
833        non_blocking(AsyncSetQuery::iter(self.0.deref()))?.map(to_iter)
834    }
835
836    fn iter_rev(&self) -> Result<Box<dyn NameIter>> {
837        non_blocking(AsyncSetQuery::iter_rev(self.0.deref()))?.map(to_iter)
838    }
839
840    fn count(&self) -> Result<u64> {
841        non_blocking(AsyncSetQuery::count_slow(self.0.deref()))?
842    }
843
844    fn first(&self) -> Result<Option<Vertex>> {
845        non_blocking(AsyncSetQuery::first(self.0.deref()))?
846    }
847
848    fn last(&self) -> Result<Option<Vertex>> {
849        non_blocking(AsyncSetQuery::last(self.0.deref()))?
850    }
851
852    fn is_empty(&self) -> Result<bool> {
853        non_blocking(AsyncSetQuery::is_empty(self.0.deref()))?
854    }
855
856    fn contains(&self, name: &Vertex) -> Result<bool> {
857        non_blocking(AsyncSetQuery::contains(self.0.deref(), name))?
858    }
859
860    fn as_any(&self) -> &dyn Any {
861        AsyncSetQuery::as_any(self.0.deref())
862    }
863
864    fn hints(&self) -> &Hints {
865        AsyncSetQuery::hints(self.0.deref())
866    }
867
868    fn id_convert(&self) -> Option<&dyn IdConvert> {
869        AsyncSetQuery::id_convert(self.0.deref())
870    }
871}
872
873/// Iterator of [`Set`].
874/// Types implementing this should consider replacing `iter_rev` with a fast
875/// path if possible.
876pub trait NameIter: Iterator<Item = Result<Vertex>> + Send {}
877impl<T> NameIter for T where T: Iterator<Item = Result<Vertex>> + Send {}
878
879/// Abstract async iterator that yields `Vertex`es.
880pub trait VertexStream: Stream<Item = Result<Vertex>> + Send {}
881impl<T> VertexStream for T where T: Stream<Item = Result<Vertex>> + Send {}
882
883/// Boxed async iterator that yields `Vertex`es.
884pub type BoxVertexStream = Pin<Box<dyn VertexStream>>;
885
886/// A wrapper that converts `VertexStream` to `NameIter`.
887struct NonblockingNameIter(BoxVertexStream);
888
889impl Iterator for NonblockingNameIter {
890    type Item = Result<Vertex>;
891
892    fn next(&mut self) -> Option<Self::Item> {
893        match non_blocking(self.0.next()) {
894            Err(e) => Some(Err(e.into())),
895            Ok(v) => v,
896        }
897    }
898}
899
900fn to_iter(stream: BoxVertexStream) -> Box<dyn NameIter> {
901    Box::new(NonblockingNameIter(stream))
902}
903
904impl From<Vertex> for Set {
905    fn from(name: Vertex) -> Set {
906        Set::from_static_names(std::iter::once(name))
907    }
908}
909
910impl From<&Vertex> for Set {
911    fn from(name: &Vertex) -> Set {
912        Set::from_static_names(std::iter::once(name.clone()))
913    }
914}
915
916/// Pick `left` if `order` is "greater or equal".
917/// Pick `right` otherwise.
918fn pick<T>(order: cmp::Ordering, left: T, right: T) -> T {
919    match order {
920        cmp::Ordering::Greater | cmp::Ordering::Equal => left,
921        cmp::Ordering::Less => right,
922    }
923}
924
925#[cfg(test)]
926pub(crate) mod tests {
927    use futures::TryStreamExt;
928    use nonblocking::non_blocking_result as r;
929
930    use super::*;
931    use crate::Id;
932    pub(crate) use crate::tests::dbg;
933
934    pub(crate) fn nb<F, R>(future: F) -> R
935    where
936        F: std::future::Future<Output = R>,
937    {
938        non_blocking(future).unwrap()
939    }
940
941    // Converts async Stream to Iterator.
942    pub(crate) fn ni<F>(future: F) -> Result<Box<dyn NameIter>>
943    where
944        F: std::future::Future<Output = Result<BoxVertexStream>>,
945    {
946        nb(future).map(to_iter)
947    }
948
949    // For easier testing.
950    impl From<&str> for Set {
951        fn from(name: &str) -> Set {
952            Set::from_static_names(
953                name.split_whitespace()
954                    .map(|n| Vertex::copy_from(n.as_bytes())),
955            )
956        }
957    }
958
959    impl Set {
960        pub(crate) fn assert_eq(&self, other: Set) {
961            assert!(
962                other.count().unwrap() == self.count().unwrap()
963                    && (other.clone() & self.clone()).count().unwrap() == self.count().unwrap(),
964                "set {:?} ({:?}) != {:?} ({:?})",
965                self,
966                self.iter().unwrap().map(|i| i.unwrap()).collect::<Vec<_>>(),
967                other,
968                other
969                    .iter()
970                    .unwrap()
971                    .map(|i| i.unwrap())
972                    .collect::<Vec<_>>(),
973            );
974        }
975    }
976
977    type SizeHint = (u64, Option<u64>);
978
979    #[derive(Default, Debug)]
980    pub(crate) struct VecQuery(Vec<Vertex>, Hints, SizeHint);
981
982    #[async_trait::async_trait]
983    impl AsyncSetQuery for VecQuery {
984        async fn iter(&self) -> Result<BoxVertexStream> {
985            let iter = self.0.clone().into_iter().map(Ok);
986            Ok(Box::pin(futures::stream::iter(iter)))
987        }
988
989        fn as_any(&self) -> &dyn Any {
990            self
991        }
992
993        fn hints(&self) -> &Hints {
994            &self.1
995        }
996
997        async fn size_hint(&self) -> SizeHint {
998            self.2
999        }
1000    }
1001
1002    impl VecQuery {
1003        /// Quickly create [`VecQuery`] that contains `len(bytes)` items.
1004        pub(crate) fn from_bytes(bytes: &[u8]) -> Self {
1005            let mut used = [false; 256];
1006            let v: Vec<Vertex> = bytes
1007                .iter()
1008                .filter_map(|&b| {
1009                    if used[b as usize] {
1010                        None
1011                    } else {
1012                        used[b as usize] = true;
1013                        Some(to_name(b))
1014                    }
1015                })
1016                .collect();
1017            let size_hint: SizeHint = (v.len() as u64, Some(v.len() as u64));
1018            Self(v, Hints::default(), size_hint)
1019        }
1020
1021        /// Adjust the "size_hint" to test various logic.
1022        /// - "size_min" will be reduced by the 1st bit of `adjust` (0 to 1).
1023        /// - "size_max" will be increased by the 2nd bit  of `adjust` (0 to 1).
1024        /// - If `adjust` is greater than 3, the "size_max" will be set to `None`.
1025        pub(crate) fn adjust_size_hint(mut self, adjust: u64) -> Self {
1026            assert!(adjust <= 6);
1027            self.2.0 = self.2.0.saturating_sub(adjust & 0b1);
1028            self.2.1 = self.2.1.map(|v| v + ((adjust >> 1) & 0b1));
1029            if adjust >= 4 {
1030                self.2.1 = None;
1031            }
1032            self
1033        }
1034    }
1035
1036    /// Create a [`Vertex`] from `u8` by repeating them.
1037    pub(crate) fn to_name(value: u8) -> Vertex {
1038        Vertex::from(vec![value; 2])
1039    }
1040
1041    /// Shorten a [`Vertex`] result.
1042    pub(crate) fn shorten_name(name: Vertex) -> String {
1043        name.to_hex()[..2].to_string()
1044    }
1045
1046    /// Shorten a [`NameIter`] result.
1047    pub(crate) fn shorten_iter(iter: Result<Box<dyn NameIter>>) -> Vec<String> {
1048        iter.unwrap()
1049            .map(|v| shorten_name(v.unwrap()))
1050            .collect::<Vec<_>>()
1051    }
1052
1053    #[test]
1054    fn test_empty_query() -> Result<()> {
1055        let query = VecQuery::default();
1056        check_invariants(&query)?;
1057        assert_eq!(SyncSetQuery::iter(&query)?.count(), 0);
1058        assert_eq!(SyncSetQuery::iter_rev(&query)?.count(), 0);
1059        assert_eq!(SyncSetQuery::first(&query)?, None);
1060        assert_eq!(SyncSetQuery::last(&query)?, None);
1061        assert_eq!(SyncSetQuery::count(&query)?, 0);
1062        assert!(SyncSetQuery::is_empty(&query)?);
1063        assert!(!SyncSetQuery::contains(&query, &to_name(0))?);
1064        Ok(())
1065    }
1066
1067    #[test]
1068    fn test_vec_query() -> Result<()> {
1069        let query = VecQuery::from_bytes(b"\xab\xef\xcd");
1070        check_invariants(&query)?;
1071        assert_eq!(shorten_iter(SyncSetQuery::iter(&query)), ["ab", "ef", "cd"]);
1072        assert_eq!(
1073            shorten_iter(SyncSetQuery::iter_rev(&query)),
1074            ["cd", "ef", "ab"]
1075        );
1076        assert_eq!(shorten_name(SyncSetQuery::first(&query)?.unwrap()), "ab");
1077        assert_eq!(shorten_name(SyncSetQuery::last(&query)?.unwrap()), "cd");
1078        assert!(!SyncSetQuery::is_empty(&query)?);
1079        assert!(SyncSetQuery::contains(&query, &to_name(0xef))?);
1080        assert!(!SyncSetQuery::contains(&query, &to_name(0))?);
1081        Ok(())
1082    }
1083
1084    #[test]
1085    fn test_debug() {
1086        let set = Set::from_static_names(vec![to_name(2)])
1087            .union(&Set::from_static_names(vec![to_name(1)]))
1088            .difference(
1089                &Set::from_static_names(vec![to_name(3)])
1090                    .intersection(&Set::from_static_names(vec![to_name(2), to_name(3)])),
1091            );
1092        assert_eq!(
1093            dbg(&set),
1094            "<diff <or <static [0202]> <static [0101]>> <and <static [0303]> <static [0202, 0303]>>>"
1095        );
1096        assert_eq!(
1097            format!("\n{set:#?}"),
1098            r#"
1099<diff
1100  <or
1101    <static [
1102        0202,
1103    ]>
1104    <static [
1105        0101,
1106    ]>>
1107  <and
1108    <static [
1109        0303,
1110    ]>
1111    <static [
1112        0202,
1113        0303,
1114    ]>>>"#
1115        );
1116    }
1117
1118    #[test]
1119    fn test_flatten() {
1120        let set = Set::from_static_names(vec![to_name(2)])
1121            .union(&Set::from_static_names(vec![to_name(1)]))
1122            .difference(
1123                &Set::from_static_names(vec![to_name(3)])
1124                    .intersection(&Set::from_static_names(vec![to_name(2), to_name(3)])),
1125            );
1126        assert_eq!(dbg(r(set.flatten()).unwrap()), "<static [0202, 0101]>");
1127    }
1128
1129    #[test]
1130    fn test_union_zip() {
1131        let set1 = Set::from_static_names(vec![to_name(1), to_name(2), to_name(3), to_name(4)]);
1132        let set2 = Set::from_static_names(vec![to_name(5), to_name(6)]);
1133        let unioned = set1.union_zip(&set2);
1134        let names = unioned.iter().unwrap().collect::<Result<Vec<_>>>().unwrap();
1135        assert_eq!(dbg(names), "[0101, 0505, 0202, 0606, 0303, 0404]");
1136    }
1137
1138    #[test]
1139    fn test_ops() {
1140        let ab: Set = "a b".into();
1141        let bc: Set = "b c".into();
1142        let s = |set: Set| -> Vec<String> { shorten_iter(set.iter()) };
1143        assert_eq!(s(ab.clone() | bc.clone()), ["61", "62", "63"]);
1144        assert_eq!(s(ab.clone() & bc.clone()), ["62"]);
1145        assert_eq!(s(ab - bc), ["61"]);
1146    }
1147
1148    #[test]
1149    fn test_skip_take_slow_path() {
1150        let s: Set = "a b c d".into();
1151        let d = |set: Set| -> String { dbg(r(set.flatten_names()).unwrap()) };
1152        assert_eq!(d(s.take(2)), "<static [a, b]>");
1153        assert_eq!(d(s.skip(2)), "<static [c, d]>");
1154        assert_eq!(d(s.skip(1).take(2)), "<static [b, c]>");
1155    }
1156
1157    #[test]
1158    fn test_hints_empty_full_fast_paths() {
1159        let partial: Set = "a".into();
1160        partial.hints().add_flags(Flags::ID_ASC);
1161        let empty: Set = "".into();
1162        let full: Set = "f".into();
1163        full.hints().add_flags(Flags::FULL | Flags::ID_DESC);
1164
1165        assert_eq!(
1166            hints_ops(&partial, &empty),
1167            [
1168                "- Hints(Flags(ID_ASC))",
1169                "  Hints(Flags(EMPTY | ID_DESC | ID_ASC | TOPO_DESC | ANCESTORS))",
1170                "& Hints(Flags(EMPTY | ID_DESC | ID_ASC | TOPO_DESC | ANCESTORS))",
1171                "  Hints(Flags(EMPTY | ID_DESC | ID_ASC | TOPO_DESC | ANCESTORS))",
1172                "| Hints(Flags(ID_ASC))",
1173                "  Hints(Flags(ID_ASC))"
1174            ]
1175        );
1176        // Fast paths are not used for "|" because there is no dag associated.
1177        assert_eq!(
1178            hints_ops(&partial, &full),
1179            [
1180                "- Hints(Flags(ID_ASC))",
1181                "  Hints(Flags(ID_DESC))",
1182                "& Hints(Flags(ID_ASC))",
1183                "  Hints(Flags(ID_ASC))",
1184                "| Hints(Flags(0x0))",
1185                "  Hints(Flags(0x0))"
1186            ]
1187        );
1188        assert_eq!(
1189            hints_ops(&empty, &full),
1190            [
1191                "- Hints(Flags(EMPTY | ID_DESC | ID_ASC | TOPO_DESC | ANCESTORS))",
1192                "  Hints(Flags(FULL | ID_DESC | ANCESTORS))",
1193                "& Hints(Flags(EMPTY | ID_DESC | ID_ASC | TOPO_DESC | ANCESTORS))",
1194                "  Hints(Flags(EMPTY | ID_DESC | ID_ASC | TOPO_DESC | ANCESTORS))",
1195                "| Hints(Flags(FULL | ID_DESC | ANCESTORS))",
1196                "  Hints(Flags(FULL | ID_DESC | ANCESTORS))"
1197            ]
1198        );
1199    }
1200
1201    #[test]
1202    fn test_hints_full_subset() {
1203        let mut t = crate::tests::TestDag::new();
1204        let a = r(t.dag.all()).unwrap(); // [] FULL EMPTY
1205        t.drawdag("X", &[]);
1206        let b = r(t.dag.all()).unwrap(); // [X] FULL
1207        t.drawdag("X--Y--Z", &[]);
1208        let c = r(t.dag.all()).unwrap(); // [X Y Z] FULL
1209        let d = r(t.dag.heads(r(t.dag.all()).unwrap())).unwrap(); // [Z]
1210
1211        let a = move || a.clone();
1212        let b = move || b.clone();
1213        let c = move || c.clone();
1214        let d = move || d.clone();
1215        let f = |set: Set| {
1216            let s = dbg(&set);
1217            let v = set
1218                .iter()
1219                .unwrap()
1220                .map(|i| String::from_utf8(i.unwrap().as_ref().to_vec()).unwrap())
1221                .collect::<Vec<String>>()
1222                .join(" ");
1223            format!("{s} = [{v}]")
1224        };
1225
1226        assert_eq!(f(a()), "<spans []> = []");
1227        assert_eq!(f(b()), "<spans [X+N0]> = [X]");
1228        assert_eq!(f(c()), "<spans [X:Z+N0:N2]> = [Z Y X]");
1229        assert_eq!(f(d()), "<spans [Z+N2]> = [Z]");
1230
1231        assert_eq!(f(a() - c()), "<empty> = []");
1232        assert_eq!(f(a() - d()), "<spans []> = []");
1233        assert_eq!(f(b() - c()), "<empty> = []");
1234        assert_eq!(f(b() - d()), "<spans [X+N0]> = [X]");
1235        assert_eq!(f(c() - b()), "<spans [Y:Z+N1:N2]> = [Z Y]");
1236        assert_eq!(f(c() - a()), "<spans [X:Z+N0:N2]> = [Z Y X]");
1237        assert_eq!(f(c() - d()), "<spans [X:Y+N0:N1]> = [Y X]");
1238        assert_eq!(f(d() - a()), "<spans [Z+N2]> = [Z]");
1239        assert_eq!(f(d() - b()), "<spans [Z+N2]> = [Z]");
1240        assert_eq!(f(d() - c()), "<empty> = []");
1241
1242        assert_eq!(f(a() | c()), "<spans [X:Z+N0:N2]> = [Z Y X]");
1243        assert_eq!(f(a() | b()), "<spans [X+N0]> = [X]");
1244        assert_eq!(f(a() | d()), "<spans [Z+N2]> = [Z]");
1245        assert_eq!(f(b() | a()), "<spans [X+N0]> = [X]");
1246        assert_eq!(f(b() | c()), "<spans [X:Z+N0:N2]> = [Z Y X]");
1247        assert_eq!(f(b() | d()), "<spans [Z+N2, X+N0]> = [Z X]");
1248        assert_eq!(f(c() | a()), "<spans [X:Z+N0:N2]> = [Z Y X]");
1249        assert_eq!(f(c() | b()), "<spans [X:Z+N0:N2]> = [Z Y X]");
1250        assert_eq!(f(c() | d()), "<spans [X:Z+N0:N2]> = [Z Y X]");
1251        assert_eq!(f(d() | a()), "<spans [Z+N2]> = [Z]");
1252        assert_eq!(f(d() | b()), "<spans [Z+N2, X+N0]> = [Z X]");
1253        assert_eq!(f(d() | c()), "<spans [X:Z+N0:N2]> = [Z Y X]");
1254
1255        assert_eq!(f(a() & c()), "<spans []> = []");
1256        assert_eq!(f(a() & d()), "<empty> = []");
1257        assert_eq!(f(b() & c()), "<spans [X+N0]> = [X]");
1258        assert_eq!(f(c() & a()), "<spans []> = []");
1259        assert_eq!(f(c() & b()), "<spans [X+N0]> = [X]");
1260        assert_eq!(f(c() & d()), "<spans [Z+N2]> = [Z]");
1261        assert_eq!(f(d() & a()), "<empty> = []");
1262        assert_eq!(f(d() & b()), "<spans []> = []");
1263        assert_eq!(f(d() & c()), "<spans [Z+N2]> = [Z]");
1264    }
1265
1266    #[test]
1267    fn test_hints_min_max_id() {
1268        let bc: Set = "b c".into();
1269        bc.hints().set_min_id(Id(20));
1270        bc.hints().add_flags(Flags::ID_DESC);
1271
1272        let ad: Set = "a d".into();
1273        ad.hints().set_max_id(Id(40));
1274        ad.hints().add_flags(Flags::ID_ASC);
1275
1276        assert_eq!(
1277            hints_ops(&bc, &ad),
1278            [
1279                "- Hints(Flags(ID_DESC), 20..)",
1280                "  Hints(Flags(ID_ASC), ..=40)",
1281                "& Hints(Flags(ID_DESC), 20..=40)",
1282                "  Hints(Flags(ID_ASC), 20..=40)",
1283                "| Hints(Flags(0x0))",
1284                "  Hints(Flags(0x0))"
1285            ]
1286        );
1287
1288        ad.hints().set_min_id(Id(10));
1289        bc.hints().set_max_id(Id(30));
1290        assert_eq!(
1291            hints_ops(&bc, &ad),
1292            [
1293                "- Hints(Flags(ID_DESC), 20..=30)",
1294                "  Hints(Flags(ID_ASC), 10..=40)",
1295                "& Hints(Flags(ID_DESC), 20..=30)",
1296                "  Hints(Flags(ID_ASC), 20..=30)",
1297                "| Hints(Flags(0x0))",
1298                "  Hints(Flags(0x0))"
1299            ]
1300        );
1301    }
1302
1303    #[test]
1304    fn test_hints_ancestors() {
1305        let a: Set = "a".into();
1306        a.hints().add_flags(Flags::ANCESTORS);
1307
1308        let b: Set = "b".into();
1309        assert_eq!(
1310            hints_ops(&a, &b),
1311            [
1312                "- Hints(Flags(0x0))",
1313                "  Hints(Flags(0x0))",
1314                "& Hints(Flags(0x0))",
1315                "  Hints(Flags(0x0))",
1316                "| Hints(Flags(0x0))",
1317                "  Hints(Flags(0x0))"
1318            ]
1319        );
1320
1321        b.hints().add_flags(Flags::ANCESTORS);
1322        assert_eq!(
1323            hints_ops(&a, &b),
1324            [
1325                "- Hints(Flags(0x0))",
1326                "  Hints(Flags(0x0))",
1327                "& Hints(Flags(ANCESTORS))",
1328                "  Hints(Flags(ANCESTORS))",
1329                "| Hints(Flags(ANCESTORS))",
1330                "  Hints(Flags(ANCESTORS))"
1331            ]
1332        );
1333    }
1334
1335    #[test]
1336    fn test_filter() {
1337        id_static::tests::with_dag(|dag| {
1338            let sets: Vec<Set> = vec!["C B A".into(), nb(dag.ancestors("C".into())).unwrap()];
1339            for abc in sets {
1340                let filter: Set = abc.filter(Box::new(|v: &Vertex| {
1341                    Box::pin(async move { Ok(v.as_ref() != b"A") })
1342                }));
1343                check_invariants(filter.0.as_ref()).unwrap();
1344                assert_eq!(abc.hints().dag_version(), filter.hints().dag_version());
1345                assert_eq!(
1346                    abc.hints().id_map_version(),
1347                    filter.hints().id_map_version()
1348                );
1349                assert!(filter.hints().flags().contains(Flags::FILTER));
1350                assert!(!filter.hints().flags().contains(Flags::ANCESTORS));
1351                assert_eq!(dbg(r(filter.flatten_names())), "Ok(<static [C, B]>)");
1352            }
1353        })
1354    }
1355
1356    #[test]
1357    fn test_reverse() {
1358        let ab: Set = "a b".into();
1359        let ba = ab.reverse();
1360        check_invariants(&*ba).unwrap();
1361        let names = ba.iter().unwrap().collect::<Result<Vec<_>>>().unwrap();
1362        assert_eq!(dbg(names), "[b, a]");
1363    }
1364
1365    // Print hints for &, |, - operations.
1366    fn hints_ops(lhs: &Set, rhs: &Set) -> Vec<String> {
1367        vec![
1368            (lhs.clone() - rhs.clone(), rhs.clone() - lhs.clone()),
1369            (lhs.clone() & rhs.clone(), rhs.clone() & lhs.clone()),
1370            (lhs.clone() | rhs.clone(), rhs.clone() | lhs.clone()),
1371        ]
1372        .into_iter()
1373        .zip("-&|".chars())
1374        .flat_map(|((set1, set2), ch)| {
1375            vec![
1376                format!("{} {:?}", ch, set1.hints()),
1377                format!("  {:?}", set2.hints()),
1378            ]
1379        })
1380        .collect()
1381    }
1382
1383    /// Check consistency of a `AsyncSetQuery`, such as `iter().nth(0)` matches
1384    /// `first()` etc.
1385    pub(crate) fn check_invariants(query: &dyn AsyncSetQuery) -> Result<()> {
1386        // Collect contains_fast result before calling other functions which might
1387        // change the internal set state.
1388        let contains_fast_vec: Vec<Option<bool>> = (0..=0xff)
1389            .map(|b| {
1390                let name = Vertex::from(vec![b; 20]);
1391                nb(query.contains_fast(&name)).unwrap_or(None)
1392            })
1393            .collect();
1394        let is_empty = nb(query.is_empty())?;
1395        let count = nb(query.count_slow())?;
1396        let (size_hint_min, size_hint_max) = nb(query.size_hint());
1397        let first = nb(query.first())?;
1398        let last = nb(query.last())?;
1399        let names: Vec<Vertex> = ni(query.iter())?.collect::<Result<Vec<_>>>()?;
1400        assert_eq!(
1401            first,
1402            names.first().cloned(),
1403            "first() should match iter().first() (set: {query:?})"
1404        );
1405        assert_eq!(
1406            last,
1407            names.last().cloned(),
1408            "last() should match iter().last() (set: {query:?})"
1409        );
1410        assert_eq!(
1411            count,
1412            names.len() as u64,
1413            "count() should match iter().count() (set: {query:?})"
1414        );
1415        assert!(
1416            size_hint_min <= count,
1417            "size_hint().0 ({size_hint_min}) must <= count ({count}) (set: {query:?})"
1418        );
1419        if let Some(size_hint_max) = size_hint_max {
1420            assert!(
1421                size_hint_max >= count,
1422                "size_hint().1 ({size_hint_max}) must >= count ({count}) (set: {query:?})"
1423            );
1424        }
1425        assert_eq!(
1426            is_empty,
1427            count == 0,
1428            "is_empty() should match count() == 0 (set: {query:?})"
1429        );
1430        assert!(
1431            names
1432                .iter()
1433                .all(|name| nb(query.contains(name)).ok() == Some(true)),
1434            "contains() should return true for names returned by iter() (set: {query:?})"
1435        );
1436        assert!(
1437            names
1438                .iter()
1439                .all(|name| nb(query.contains_fast(name)).unwrap_or(None) != Some(false)),
1440            "contains_fast() should not return false for names returned by iter() (set: {query:?})"
1441        );
1442        assert!(
1443            (0..=0xff).all(|b| {
1444                let name = Vertex::from(vec![b; 20]);
1445                nb(query.contains(&name)).ok() == Some(names.contains(&name))
1446            }),
1447            "contains() should return false for names not returned by iter() (set: {query:?})"
1448        );
1449        assert!(
1450            (0..=0xff)
1451                .zip(contains_fast_vec.into_iter())
1452                .all(|(b, old_contains)| {
1453                    let name = Vertex::from(vec![b; 20]);
1454                    let contains = nb(query.contains_fast(&name)).unwrap_or(None);
1455                    old_contains.is_none() || contains == old_contains
1456                }),
1457            "contains_fast() should be consistent (set: {query:?})"
1458        );
1459        assert!(
1460            (0..=0xff).all(|b| {
1461                let name = Vertex::from(vec![b; 20]);
1462                let contains = nb(query.contains_fast(&name)).unwrap_or(None);
1463                contains.is_none() || contains == Some(names.contains(&name))
1464            }),
1465            "contains_fast() should not return true for names not returned by iter() (set: {query:?})"
1466        );
1467        if let Some(flatten_id) = query.specialized_flatten_id() {
1468            let iter = r(AsyncSetQuery::iter(&*flatten_id))?;
1469            let mut flatten_names = r(iter.try_collect::<Vec<_>>())?;
1470            flatten_names.sort_unstable();
1471            let mut sorted_names = names.clone();
1472            sorted_names.sort_unstable();
1473            assert_eq!(
1474                &sorted_names, &flatten_names,
1475                "specialized_flatten_id() should return a same set, order could be different (set: {query:?})"
1476            );
1477        }
1478        let reversed: Vec<Vertex> = ni(query.iter_rev())?.collect::<Result<Vec<_>>>()?;
1479        if let Some(reversed_set) = query.specialized_reverse() {
1480            let iter = reversed_set.iter()?;
1481            let names = iter.collect::<Result<Vec<_>>>()?;
1482            assert_eq!(&names, &reversed);
1483        }
1484        assert_eq!(
1485            names,
1486            reversed.into_iter().rev().collect::<Vec<Vertex>>(),
1487            "iter() should match iter_rev().rev() (set: {query:?})"
1488        );
1489        Ok(())
1490    }
1491
1492    /// Generate 2 sets in a loop to test container set (intersection, union, difference) types.
1493    /// Focus on extra "size_hint" test.
1494    pub(crate) fn check_size_hint_sets<Q: AsyncSetQuery>(build_set: impl Fn(Set, Set) -> Q) {
1495        let lhs = b"\x11\x22\x33";
1496        let rhs = b"\x33\x55\x77";
1497        for lhs_start in 0..lhs.len() {
1498            for lhs_end in lhs_start..lhs.len() {
1499                for rhs_start in 0..rhs.len() {
1500                    for rhs_end in rhs_start..rhs.len() {
1501                        for lhs_size_hint_adjust in 0..7 {
1502                            for rhs_size_hint_adjust in 0..7 {
1503                                let lhs_set = VecQuery::from_bytes(&lhs[lhs_start..lhs_end])
1504                                    .adjust_size_hint(lhs_size_hint_adjust);
1505                                let rhs_set = VecQuery::from_bytes(&rhs[rhs_start..rhs_end])
1506                                    .adjust_size_hint(rhs_size_hint_adjust);
1507                                let set =
1508                                    build_set(Set::from_query(lhs_set), Set::from_query(rhs_set));
1509                                check_invariants(&set).unwrap();
1510                            }
1511                        }
1512                    }
1513                }
1514            }
1515        }
1516    }
1517
1518    pub(crate) fn check_skip_take_reverse(set: Set) -> Result<()> {
1519        let names: Vec<Vertex> = set.iter()?.collect::<Result<Vec<_>>>()?;
1520        let len = names.len();
1521        for reverse in [false, true] {
1522            for skip in 0..=(len + 2) {
1523                for take in 0..=(len + 2) {
1524                    for skip_first in [false, true] {
1525                        let mut test_set = set.clone();
1526                        let mut expected_names = names.clone();
1527                        if reverse {
1528                            test_set = test_set.reverse();
1529                            expected_names.reverse();
1530                        }
1531                        if skip_first {
1532                            test_set = test_set.skip(skip as _).take(take as _);
1533                            expected_names =
1534                                expected_names.into_iter().skip(skip).take(take).collect();
1535                        } else {
1536                            test_set = test_set.take(take as _).skip(skip as _);
1537                            expected_names =
1538                                expected_names.into_iter().take(take).skip(skip).collect();
1539                        }
1540                        let actual_names = test_set.iter()?.collect::<Result<Vec<_>>>()?;
1541                        assert_eq!(
1542                            actual_names, expected_names,
1543                            "check_skip_take_reverse {set:?} failed at reverse={reverse} skip={skip} take={take}"
1544                        );
1545                    }
1546                }
1547            }
1548        }
1549        Ok(())
1550    }
1551
1552    pub(crate) fn fmt_iter(set: &Set) -> String {
1553        let iter = r(AsyncSetQuery::iter(set.deref())).unwrap();
1554        let names = r(iter.try_collect::<Vec<_>>()).unwrap();
1555        dbg(names)
1556    }
1557}