Skip to main content

dag/set/
id_static.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
8use std::any::Any;
9use std::borrow::Cow;
10use std::cmp;
11use std::fmt;
12use std::sync::Arc;
13use std::sync::atomic::Ordering;
14
15use nonblocking::non_blocking_result;
16
17use super::AsyncSetQuery;
18use super::BoxVertexStream;
19use super::Hints;
20use super::hints::Flags;
21use crate::Group;
22use crate::Id;
23use crate::IdSet;
24use crate::Result;
25use crate::Set;
26use crate::Vertex;
27use crate::idset::IdList;
28use crate::idset::OrderedSpan;
29use crate::ops::DagAlgorithm;
30use crate::ops::IdConvert;
31use crate::protocol::disable_remote_protocol;
32
33/// A set backed by [`IdSet`] + [`IdMap`].
34/// Efficient for DAG calculation.
35#[derive(Clone)]
36pub struct IdStaticSet {
37    spans: IdSet,
38    pub(crate) map: Arc<dyn IdConvert + Send + Sync>,
39    pub(crate) dag: Arc<dyn DagAlgorithm + Send + Sync>,
40    hints: Hints,
41    // If true, iterate in ASC order instead of DESC.
42    iteration_order: IterationOrder,
43}
44
45/// Iteration order of the `IdStaticSet`.
46#[derive(Clone, Debug)]
47enum IterationOrder {
48    /// From smaller ids to larger ids.
49    Asc,
50    /// From larger ids to smaller ids.
51    Desc,
52    /// Custom iteration order. Must match `IdStaticSet.spans`.
53    Custom(IdList),
54    /// Custom iteration order, reversed.
55    CustomReversed(IdList),
56}
57
58/// Basic iteration order. A subset of `IterationOrder`.
59#[derive(Copy, Clone, Debug)]
60pub enum BasicIterationOrder {
61    /// From smaller ids to larger ids.
62    Asc,
63    /// From larger ids to smaller ids.
64    Desc,
65}
66
67struct Iter {
68    iter: Box<dyn DoubleEndedIterator<Item = Id> + Send + Sync + 'static>,
69    map: Arc<dyn IdConvert + Send + Sync>,
70    reversed: bool,
71    buf: Vec<Result<Vertex>>,
72}
73
74impl Iter {
75    fn into_box_stream(self) -> BoxVertexStream {
76        Box::pin(futures::stream::unfold(self, |this| this.next()))
77    }
78
79    async fn next(mut self) -> Option<(Result<Vertex>, Self)> {
80        if let Some(name) = self.buf.pop() {
81            return Some((name, self));
82        }
83        let map = &self.map;
84        let opt_id = if self.reversed {
85            self.iter.next_back()
86        } else {
87            self.iter.next()
88        };
89        match opt_id {
90            None => None,
91            Some(id) => {
92                let contains = map
93                    .contains_vertex_id_locally(&[id])
94                    .await
95                    .unwrap_or_default();
96                if contains == [true] {
97                    Some((map.vertex_name(id).await, self))
98                } else {
99                    // On demand prefetch in batch.
100                    let batch_size = crate::config::BATCH_SIZE.load(Ordering::Acquire);
101                    let mut ids = Vec::with_capacity(batch_size);
102                    ids.push(id);
103                    for _ in ids.len()..batch_size {
104                        if let Some(id) = if self.reversed {
105                            self.iter.next_back()
106                        } else {
107                            self.iter.next()
108                        } {
109                            ids.push(id);
110                        } else {
111                            break;
112                        }
113                    }
114                    ids.reverse();
115                    self.buf = match self.map.vertex_name_batch(&ids).await {
116                        Err(e) => return Some((Err(e), self)),
117                        Ok(names) => names,
118                    };
119                    if self.buf.len() != ids.len() {
120                        let result =
121                            crate::errors::bug("vertex_name_batch does not return enough items");
122                        return Some((result, self));
123                    }
124                    let name = self.buf.pop().expect("buf is not empty");
125                    Some((name, self))
126                }
127            }
128        }
129    }
130}
131
132struct DebugSpan {
133    // start, end are for debug fmt, not iteration order.
134    span: OrderedSpan,
135    end_name: Option<Vertex>,
136    start_name: Option<Vertex>,
137}
138
139impl fmt::Debug for DebugSpan {
140    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
141        match (
142            self.span.start == self.span.end,
143            &self.start_name,
144            &self.end_name,
145        ) {
146            (true, Some(name), _) => {
147                fmt::Debug::fmt(&name, f)?;
148                write!(f, "+{:?}", self.span.start)?;
149            }
150            (true, None, _) => {
151                write!(f, "{:?}", self.span.start)?;
152            }
153            (false, Some(start), Some(end)) => {
154                fmt::Debug::fmt(&start, f)?;
155                write!(f, ":")?;
156                fmt::Debug::fmt(&end, f)?;
157                write!(f, "+{:?}:{:?}", self.span.start, self.span.end)?;
158            }
159            (false, _, _) => {
160                write!(f, "{:?}:{:?}", self.span.start, self.span.end)?;
161            }
162        }
163        Ok(())
164    }
165}
166
167impl fmt::Debug for IdStaticSet {
168    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
169        write!(f, "<spans ")?;
170        let spans_iter: Box<dyn Iterator<Item = OrderedSpan>> = match self.iteration_order {
171            IterationOrder::Custom(ref list) | IterationOrder::CustomReversed(ref list) => {
172                Box::new(list.as_spans().iter().copied())
173            }
174            _ => Box::new(self.spans.as_spans().iter().map(|s| OrderedSpan {
175                start: s.low,
176                end: s.high,
177            })),
178        };
179
180        let len = spans_iter.size_hint().0;
181        let limit = f.width().unwrap_or(3);
182        f.debug_list()
183            .entries(spans_iter.take(limit).map(|span| DebugSpan {
184                span,
185                end_name: disable_remote_protocol(|| {
186                    non_blocking_result(self.map.vertex_name(span.end)).ok()
187                }),
188                start_name: disable_remote_protocol(|| {
189                    non_blocking_result(self.map.vertex_name(span.start)).ok()
190                }),
191            }))
192            .finish()?;
193        match len.saturating_sub(limit) {
194            0 => {}
195            1 => write!(f, " + 1 span")?,
196            n => write!(f, " + {n} spans")?,
197        }
198        match &self.iteration_order {
199            // + means ASC order.
200            IterationOrder::Asc => write!(f, " +")?,
201            // For compatibility with existing tests, do not show a sign for DESC (default) order.
202            // Otherwise this should show "-".
203            IterationOrder::Desc => {}
204            IterationOrder::Custom(_) => write!(f, " ?")?,
205            IterationOrder::CustomReversed(_) => write!(f, " ¿")?,
206        }
207        write!(f, ">")?;
208        Ok(())
209    }
210}
211
212impl IdStaticSet {
213    pub(crate) fn from_id_set_idmap_dag(
214        spans: IdSet,
215        map: Arc<dyn IdConvert + Send + Sync>,
216        dag: Arc<dyn DagAlgorithm + Send + Sync>,
217    ) -> Self {
218        let hints = Hints::new_with_idmap_dag(map.clone(), dag.clone());
219        hints.add_flags(Flags::ID_DESC | Flags::TOPO_DESC);
220        if spans.is_empty() {
221            hints.add_flags(Flags::EMPTY);
222        } else {
223            hints.set_min_id(spans.min().unwrap());
224            hints.set_max_id(spans.max().unwrap());
225        }
226        Self {
227            spans,
228            map,
229            hints,
230            dag,
231            iteration_order: IterationOrder::Desc,
232        }
233    }
234
235    /// Construct from `list`, `map`, `dag`. The ids in the `list` must match the map and dag.
236    pub(crate) fn from_id_list_idmap_dag(
237        list: IdList,
238        map: Arc<dyn IdConvert + Send + Sync>,
239        dag: Arc<dyn DagAlgorithm + Send + Sync>,
240    ) -> Self {
241        let hints = Hints::new_with_idmap_dag(map.clone(), dag.clone());
242
243        // Calculate hints (flags, min_id, max_id).
244        let mut flags = Flags::ID_DESC | Flags::TOPO_DESC | Flags::ID_ASC | Flags::EMPTY;
245        let mut min_id = None;
246        let mut max_id = None;
247        let mut last_min_id = None;
248        let mut last_max_id = None;
249        for span in list.as_spans() {
250            let (this_min_id, this_max_id) = (span.min(), span.max());
251            flags -= Flags::EMPTY;
252            if span.start < span.end || last_min_id.unwrap_or(Id::MAX) < this_max_id {
253                // Not DESC or TOPO.
254                flags -= Flags::ID_DESC | Flags::TOPO_DESC;
255            }
256            if span.start > span.end || last_max_id.unwrap_or(Id::MIN) > this_min_id {
257                // Not ASC.
258                flags -= Flags::ID_ASC;
259            }
260            (last_min_id, last_max_id) = (Some(this_min_id), Some(this_max_id));
261            min_id = Some(this_min_id.min(min_id.unwrap_or(Id::MAX)));
262            max_id = Some(this_max_id.max(max_id.unwrap_or(Id::MIN)));
263        }
264
265        hints.add_flags(flags);
266        if let Some(min_id) = min_id {
267            hints.set_min_id(min_id);
268        }
269        if let Some(max_id) = max_id {
270            hints.set_max_id(max_id);
271        }
272
273        let spans = list.to_set();
274
275        // If `list` is already sorted, then just use BasicIterationOrder.
276        let iteration_order = if flags.contains(Flags::ID_DESC) {
277            IterationOrder::Desc
278        } else if flags.contains(Flags::ID_ASC) {
279            IterationOrder::Asc
280        } else {
281            IterationOrder::Custom(list)
282        };
283
284        Self {
285            spans,
286            map,
287            hints,
288            dag,
289            iteration_order,
290        }
291    }
292
293    /// Get the low-level `IdSet`, which no longer preserves iteration order.
294    pub(crate) fn id_set_losing_order(&self) -> &IdSet {
295        &self.spans
296    }
297
298    /// Get the low-level `IdSet`, or `None` if iteration order cannot be preserved.
299    /// Note: `reserved` is not preserved and needs to be considered separately.
300    pub(crate) fn id_set_try_preserving_order(&self) -> Option<&IdSet> {
301        if self
302            .hints()
303            .flags()
304            .intersects(Flags::ID_DESC | Flags::ID_ASC)
305        {
306            Some(&self.spans)
307        } else {
308            None
309        }
310    }
311
312    /// If `lhs` and `rhs` are compatible, return a new IdStaticSet with:
313    /// - `map` and `dag` set to the newer version of `lhs` and `rhs`.
314    /// - `spans` set to `edit_spans(&lhs.spans, &rhs.spans)`.
315    ///
316    /// Otherwise return `None`.
317    ///
318    /// Iteration order will not be preserved.
319    pub(crate) fn from_edit_spans(
320        lhs: &Self,
321        rhs: &Self,
322        edit_spans: fn(&IdSet, &IdSet) -> IdSet,
323    ) -> Option<Self> {
324        let order = lhs.map.map_version().partial_cmp(rhs.map.map_version())?;
325        let spans = edit_spans(&lhs.spans, &rhs.spans);
326        let picked = match order {
327            cmp::Ordering::Less => rhs,
328            cmp::Ordering::Greater | cmp::Ordering::Equal => lhs,
329        };
330        let (map, dag) = (picked.map.clone(), picked.dag.clone());
331        let mut result = Self::from_id_set_idmap_dag(spans, map, dag);
332        if let Some(order) = lhs.iteration_order() {
333            result.set_iteration_order(order);
334        }
335        Some(result)
336    }
337
338    /// Change the iteration order between (DESC default) and ASC.
339    pub fn reversed(mut self) -> Self {
340        match self.iteration_order {
341            IterationOrder::Desc => {
342                self.hints.remove_flags(Flags::ID_DESC | Flags::TOPO_DESC);
343                self.hints.add_flags(Flags::ID_ASC);
344                self.iteration_order = IterationOrder::Asc
345            }
346            IterationOrder::Asc => {
347                self.hints.remove_flags(Flags::ID_ASC);
348                self.hints.add_flags(Flags::ID_DESC | Flags::TOPO_DESC);
349                self.iteration_order = IterationOrder::Desc
350            }
351            IterationOrder::Custom(list) => {
352                // Conservatively drop order-related flags.
353                self.hints
354                    .remove_flags(Flags::ID_ASC | Flags::ID_DESC | Flags::TOPO_DESC);
355                self.iteration_order = IterationOrder::CustomReversed(list);
356            }
357            IterationOrder::CustomReversed(list) => {
358                self.hints
359                    .remove_flags(Flags::ID_ASC | Flags::ID_DESC | Flags::TOPO_DESC);
360                self.iteration_order = IterationOrder::Custom(list);
361            }
362        }
363        self
364    }
365
366    /// Update iteration order. Only `Asc` and `Desc` is accepted.
367    pub(crate) fn set_iteration_order(&mut self, order: BasicIterationOrder) {
368        // Only reuse Asc or Desc order. Cannot handle custom order.
369        match order {
370            BasicIterationOrder::Asc => {
371                self.hints.remove_flags(Flags::ID_DESC | Flags::TOPO_DESC);
372                self.hints.add_flags(Flags::ID_ASC);
373                self.iteration_order = IterationOrder::Asc;
374            }
375            BasicIterationOrder::Desc => {
376                self.hints.remove_flags(Flags::ID_ASC);
377                self.hints.add_flags(Flags::ID_DESC | Flags::TOPO_DESC);
378                self.iteration_order = IterationOrder::Desc
379            }
380        }
381    }
382
383    /// Obtain the iteration order. Only `Asc` and `Desc` is returned. Otherwise report as `None`.
384    pub(crate) fn iteration_order(&self) -> Option<BasicIterationOrder> {
385        match self.iteration_order {
386            IterationOrder::Asc => Some(BasicIterationOrder::Asc),
387            IterationOrder::Desc => Some(BasicIterationOrder::Desc),
388            #[allow(unreachable_patterns)]
389            _ => None,
390        }
391    }
392
393    async fn max(&self) -> Result<Option<Vertex>> {
394        debug_assert_eq!(self.spans.max(), self.spans.iter_desc().nth(0));
395        self.resolve_optional_id(self.spans.max()).await
396    }
397
398    async fn min(&self) -> Result<Option<Vertex>> {
399        debug_assert_eq!(self.spans.min(), self.spans.iter_desc().rev().nth(0));
400        self.resolve_optional_id(self.spans.min()).await
401    }
402
403    async fn resolve_optional_id(&self, id: Option<Id>) -> Result<Option<Vertex>> {
404        match id {
405            Some(id) => {
406                let map = &self.map;
407                let name = map.vertex_name(id).await?;
408                Ok(Some(name))
409            }
410            None => Ok(None),
411        }
412    }
413
414    pub(crate) fn slice_spans(mut self, skip: u64, take: u64) -> Self {
415        let len = self.spans.count();
416        let (skip, mut take) = match self.iteration_order {
417            IterationOrder::Asc | IterationOrder::CustomReversed(_) => {
418                // [---take1----][skip]
419                // [skip2][take2][skip]
420                // [--------len-------]
421                let take1 = len.saturating_sub(skip);
422                let take2 = take1.min(take);
423                let skip2 = take1 - take2;
424                (skip2, take2)
425            }
426            IterationOrder::Desc | IterationOrder::Custom(_) => {
427                // [skip][take][---]
428                // [------len------]
429                (skip, take)
430            }
431        };
432        if skip >= len {
433            take = 0;
434        } else if skip.saturating_add(take) >= len {
435            take = u64::MAX;
436        }
437        if skip != 0 || take != u64::MAX {
438            match self.iteration_order {
439                IterationOrder::Custom(ref mut list)
440                | IterationOrder::CustomReversed(ref mut list) => {
441                    match (skip, take) {
442                        (0, _) => *list = list.take(take),
443                        (_, u64::MAX) => *list = list.skip(skip),
444                        _ => *list = list.skip(skip).take(take),
445                    };
446                    self.spans = list.to_set();
447                }
448                _ => match (skip, take) {
449                    (0, _) => self.spans = self.spans.take(take),
450                    (_, u64::MAX) => self.spans = self.spans.skip(skip),
451                    _ => self.spans = self.spans.skip(skip).take(take),
452                },
453            }
454            // No longer sound to keep the ANCESTORS hint.
455            self.hints.remove_flags(Flags::ANCESTORS);
456        }
457        self
458    }
459
460    // used by iter and iter_rev.
461    fn get_iter_and_reversed(
462        &self,
463    ) -> (
464        Box<dyn DoubleEndedIterator<Item = Id> + Send + Sync + 'static>,
465        bool,
466    ) {
467        let iter: Box<dyn DoubleEndedIterator<Item = Id> + Send + Sync + 'static> =
468            match self.iteration_order {
469                IterationOrder::Custom(ref list) | IterationOrder::CustomReversed(ref list) => {
470                    Box::new(list.into_iter())
471                }
472                _ => Box::new(self.spans.clone().into_iter()),
473            };
474        let reversed = matches!(
475            self.iteration_order,
476            IterationOrder::Asc | IterationOrder::CustomReversed(_)
477        );
478        (iter, reversed)
479    }
480}
481
482#[async_trait::async_trait]
483impl AsyncSetQuery for IdStaticSet {
484    async fn iter(&self) -> Result<BoxVertexStream> {
485        let (iter, reversed) = self.get_iter_and_reversed();
486        let iter = Iter {
487            iter,
488            map: self.map.clone(),
489            reversed,
490            buf: Default::default(),
491        };
492        Ok(iter.into_box_stream())
493    }
494
495    async fn iter_rev(&self) -> Result<BoxVertexStream> {
496        let (iter, reversed) = self.get_iter_and_reversed();
497        let iter = Iter {
498            iter,
499            map: self.map.clone(),
500            reversed: !reversed,
501            buf: Default::default(),
502        };
503        Ok(iter.into_box_stream())
504    }
505
506    // Usually, the "count" should not be manually implemented so the universal fast path can
507    // apply. However, the IdStaticSet does not need a separate "universal fast path".
508    // So let's just override the "count".
509    async fn count(&self) -> Result<u64> {
510        Ok(self.spans.count())
511    }
512
513    async fn count_slow(&self) -> Result<u64> {
514        Ok(self.spans.count())
515    }
516
517    async fn size_hint(&self) -> (u64, Option<u64>) {
518        let size = self.spans.count();
519        (size, Some(size))
520    }
521
522    async fn first(&self) -> Result<Option<Vertex>> {
523        match self.iteration_order {
524            IterationOrder::Asc => self.min().await,
525            IterationOrder::Desc => self.max().await,
526            IterationOrder::Custom(ref list) => {
527                self.resolve_optional_id(list.into_iter().next()).await
528            }
529            IterationOrder::CustomReversed(ref list) => {
530                self.resolve_optional_id(list.into_iter().next_back()).await
531            }
532        }
533    }
534
535    async fn last(&self) -> Result<Option<Vertex>> {
536        match self.iteration_order {
537            IterationOrder::Asc => self.max().await,
538            IterationOrder::Desc => self.min().await,
539            IterationOrder::Custom(ref list) => {
540                self.resolve_optional_id(list.into_iter().next_back()).await
541            }
542            IterationOrder::CustomReversed(ref list) => {
543                self.resolve_optional_id(list.into_iter().next()).await
544            }
545        }
546    }
547
548    async fn is_empty(&self) -> Result<bool> {
549        Ok(self.spans.is_empty())
550    }
551
552    async fn contains(&self, name: &Vertex) -> Result<bool> {
553        let result = match self.map.vertex_id_with_max_group(name, Group::MAX).await? {
554            Some(id) => self.spans.contains(id),
555            None => false,
556        };
557        Ok(result)
558    }
559
560    async fn contains_fast(&self, name: &Vertex) -> Result<Option<bool>> {
561        self.contains(name).await.map(Some)
562    }
563
564    fn as_any(&self) -> &dyn Any {
565        self
566    }
567
568    fn hints(&self) -> &Hints {
569        &self.hints
570    }
571
572    fn id_convert(&self) -> Option<&dyn IdConvert> {
573        Some(self.map.as_ref() as &dyn IdConvert)
574    }
575
576    fn specialized_reverse(&self) -> Option<Set> {
577        Some(Set::from_query(self.clone().reversed()))
578    }
579
580    fn specialized_take(&self, take: u64) -> Option<Set> {
581        Some(Set::from_query(self.clone().slice_spans(0, take)))
582    }
583
584    fn specialized_skip(&self, skip: u64) -> Option<Set> {
585        Some(Set::from_query(self.clone().slice_spans(skip, u64::MAX)))
586    }
587
588    /// Specialized "flatten_id" implementation.
589    fn specialized_flatten_id(&self) -> Option<Cow<'_, IdStaticSet>> {
590        Some(Cow::Borrowed(self))
591    }
592}
593
594#[cfg(test)]
595#[allow(clippy::redundant_clone)]
596pub(crate) mod tests {
597    use std::ops::Deref;
598    use std::sync::atomic::Ordering::Acquire;
599
600    use futures::TryStreamExt;
601    use nonblocking::non_blocking_result as r;
602
603    use super::super::Set;
604    use super::super::tests::*;
605    use super::*;
606    use crate::Dag;
607    use crate::DagAlgorithm;
608    use crate::ops::IdMapSnapshot;
609    use crate::ops::ToIdSet;
610    use crate::set::difference::DifferenceSet;
611    use crate::set::intersection::IntersectionSet;
612    use crate::set::slice::SliceSet;
613    use crate::set::union::UnionSet;
614    use crate::tests::build_segments;
615
616    /// Test with a predefined DAG.
617    pub(crate) fn with_dag<R, F: Fn(&Dag) -> R>(func: F) -> R {
618        let built = build_segments(
619            r#"
620            A--B--C--D
621                \--E--F--G"#,
622            "D G",
623            2,
624        );
625        //  0--1--2--3
626        //      \--4--5--6
627        func(&built.name_dag)
628    }
629
630    #[test]
631    fn test_dag_invariants() -> Result<()> {
632        with_dag(|dag| {
633            let bef = r(dag.range("B".into(), "F".into()))?;
634            check_invariants(bef.deref())?;
635            assert_eq!(nb(bef.size_hint()), (3, Some(3)));
636
637            Ok(())
638        })
639    }
640
641    #[test]
642    fn test_dag_fast_paths() -> Result<()> {
643        with_dag(|dag| {
644            let abcd = r(dag.ancestors("D".into()))?;
645            let abefg = r(dag.ancestors("G".into()))?;
646
647            let ab = abcd.intersection(&abefg);
648            check_invariants(ab.deref())?;
649
650            assert!(nb(abcd.contains(&vec![b'A'].into()))?);
651            assert!(!nb(abcd.contains(&vec![b'E'].into()))?);
652
653            // should not be "<and <...> <...>>"
654            assert_eq!(dbg(&ab), "<spans [A:B+0:1]>");
655
656            let abcdefg = abcd.union(&abefg);
657            check_invariants(abcd.deref())?;
658            // should not be "<or <...> <...>>"
659            assert_eq!(dbg(&abcdefg), "<spans [A:G+0:6]>");
660
661            let cd = abcd.difference(&abefg);
662            check_invariants(cd.deref())?;
663            // should not be "<difference <...> <...>>"
664            assert_eq!(dbg(&cd), "<spans [C:D+2:3]>");
665
666            Ok(())
667        })
668    }
669
670    #[test]
671    fn test_dag_fast_path_set_ops() -> Result<()> {
672        with_dag(|dag| {
673            let abcd = r(dag.ancestors("D".into()))?.reverse();
674            let unordered = abcd.take(2).union_zip(&abcd.skip(3));
675
676            // Intersection and difference can flatten the "unordered" set because rhs order does
677            // not matter.
678            assert_eq!(
679                dbg(abcd.intersection(&unordered)),
680                "<spans [D+3, A:B+0:1] +>"
681            );
682            assert_eq!(dbg(abcd.difference(&unordered)), "<spans [C+2] +>");
683
684            // but lhs order matters (no fast path if lhs order is to be preserved).
685            assert_eq!(
686                dbg(unordered.intersection(&abcd)),
687                "<and <or <spans [A:B+0:1] +> <spans [D+3] +> (order=Zip)> <spans [A:D+0:3] +>>"
688            );
689            assert_eq!(
690                dbg(unordered.difference(&abcd)),
691                "<diff <or <spans [A:B+0:1] +> <spans [D+3] +> (order=Zip)> <spans [A:D+0:3] +>>"
692            );
693
694            // Union drops order (by flattening) aggressively on both sides.
695            assert_eq!(dbg(abcd.union(&unordered)), "<spans [A:D+0:3] +>");
696
697            // Union (preserving order) cannot flatten sets for fast paths.
698            assert_eq!(
699                dbg(abcd.union_preserving_order(&unordered)),
700                "<or <spans [A:D+0:3] +> <or <spans [A:B+0:1] +> <spans [D+3] +> (order=Zip)>>"
701            );
702
703            Ok(())
704        })
705    }
706
707    /// Show set iteration and flatten set iteration for debugging purpose.
708    fn dbg_flat(set: &Set) -> String {
709        let flat = set.specialized_flatten_id();
710        let flat_str = match flat {
711            Some(flat) => format!(" flat:{}", fmt_iter(&Set::from_query(flat.into_owned()))),
712            None => String::new(),
713        };
714        format!("{}{}", fmt_iter(set), flat_str)
715    }
716
717    // Construct diff, intersection, union sets directly to bypass fast paths.
718    fn set_ops(a: &Set, b: &Set) -> (Set, Set, Set) {
719        let difference = DifferenceSet::new(a.clone(), b.clone());
720        let intersection = IntersectionSet::new(a.clone(), b.clone());
721        let union = UnionSet::new(a.clone(), b.clone());
722        (
723            Set::from_query(difference),
724            Set::from_query(intersection),
725            Set::from_query(union),
726        )
727    }
728
729    #[test]
730    fn test_dag_specialized_flatten_id_fast_path_with_set_ops() -> Result<()> {
731        with_dag(|dag| {
732            let mut abcd = "A B C D"
733                .split_whitespace()
734                .map(|s: &'static str| r(dag.sort(&s.into())).unwrap())
735                .collect::<Vec<_>>();
736            let d = abcd.pop().unwrap();
737            let c = abcd.pop().unwrap();
738            let b = abcd.pop().unwrap();
739            let a = abcd.pop().unwrap();
740
741            let acb = a.union_preserving_order(&b.union_preserving_order(&c).reverse());
742            let bcd = b.union_preserving_order(&c).union_preserving_order(&d);
743
744            // All set operations can use fast paths.
745            let diff = acb.difference(&bcd);
746            let intersect = acb.intersection(&bcd);
747            let union1 = diff.union_preserving_order(&intersect);
748            let reversed1 = union1.reverse();
749            let union2 = reversed1.union_zip(&diff);
750            let reversed2 = union2.reverse();
751
752            // Show the values of the sets.
753            assert_eq!(dbg_flat(&diff), "[A] flat:[A]");
754            assert_eq!(dbg_flat(&intersect), "[C, B] flat:[C, B]");
755            assert_eq!(dbg_flat(&union1), "[A, C, B] flat:[C, B, A]");
756            assert_eq!(dbg_flat(&reversed1), "[B, C, A] flat:[A, B, C]");
757            assert_eq!(dbg_flat(&union2), "[B, C, A] flat:[A, B, C]");
758            assert_eq!(dbg_flat(&reversed2), "[A, C, B] flat:[C, B, A]");
759
760            // The union2 should use a fast path to "count".
761            let count1 = union2
762                .as_any()
763                .downcast_ref::<UnionSet>()
764                .unwrap()
765                .test_slow_count
766                .load(Acquire);
767            let _ = r(union2.count())?;
768            let count2 = union2
769                .as_any()
770                .downcast_ref::<UnionSet>()
771                .unwrap()
772                .test_slow_count
773                .load(Acquire);
774            assert_eq!(count1, count2, "union.count() should not use slow path");
775
776            // dag.sort(reversed2) should have a fast path.
777            let count1 = dag.internal_stats.sort_slow_path_count.load(Acquire);
778            let _ = r(dag.sort(&reversed2))?;
779            let count2 = dag.internal_stats.sort_slow_path_count.load(Acquire);
780            assert_eq!(count1, count2, "dag.sort() should not use slow path");
781
782            // Show the debug format. This shows whether internal structure is flattened or not.
783            assert_eq!(
784                wrap_dbg_lines(&reversed2),
785                r#"
786                <reverse
787                  <or
788                    <reverse
789                      <or
790                        <diff
791                          <or <spans [A+0]> <reverse <or <spans [B+1]> <spans [C+2]>>>>
792                          <or <or <spans [B+1]> <spans [C+2]>> <spans [D+3]>>>
793                        <and
794                          <or <spans [A+0]> <reverse <or <spans [B+1]> <spans [C+2]>>>>
795                          <or <or <spans [B+1]> <spans [C+2]>> <spans [D+3]>>>>>
796                    <diff
797                      <or <spans [A+0]> <reverse <or <spans [B+1]> <spans [C+2]>>>>
798                      <or <or <spans [B+1]> <spans [C+2]>> <spans [D+3]>>> (order=Zip)>>"#
799            );
800
801            // Flattened turns the tree into a single set.
802            let flattened = reversed2.specialized_flatten_id().unwrap();
803            assert_eq!(dbg(&flattened), "<spans [A:C+0:2]>");
804
805            Ok(())
806        })
807    }
808
809    #[test]
810    fn test_dag_specialized_flatten_id_fast_path_with_slices() -> Result<()> {
811        // SliceSet cannot use fast paths easily. It must check the order.
812        with_dag(|dag| {
813            let abcd = r(dag.ancestors("D".into()))?.reverse();
814            let abefg = r(dag.ancestors("G".into()))?.reverse();
815
816            let slice12 =
817                |a: &Set| -> Set { Set::from_query(SliceSet::new(a.clone(), 1, Some(2))) };
818
819            let (d, i, u) = set_ops(&abcd, &abefg);
820            assert_eq!(dbg_flat(&d), "[C, D] flat:[C, D]");
821            assert_eq!(dbg_flat(&i), "[A, B] flat:[A, B]");
822            assert_eq!(
823                dbg_flat(&u),
824                "[A, B, C, D, E, F, G] flat:[A, B, C, D, E, F, G]"
825            );
826            assert_eq!(dbg_flat(&slice12(&d)), "[D] flat:[D]");
827            assert_eq!(dbg_flat(&slice12(&i)), "[B] flat:[B]");
828            assert_eq!(dbg_flat(&slice12(&u)), "[B, C]"); // no fast path for union_preserving_order
829
830            // Make abcd and abefg use different order.
831            let (d, i, u) = set_ops(&abcd.reverse(), &abefg);
832            assert_eq!(dbg_flat(&d), "[D, C] flat:[D, C]");
833            assert_eq!(dbg_flat(&i), "[B, A] flat:[B, A]");
834            assert_eq!(
835                dbg_flat(&u),
836                "[D, C, B, A, E, F, G] flat:[G, F, E, D, C, B, A]"
837            );
838            assert_eq!(dbg_flat(&slice12(&d)), "[C] flat:[C]");
839            assert_eq!(dbg_flat(&slice12(&i)), "[A] flat:[A]");
840            assert_eq!(dbg_flat(&slice12(&u)), "[C, B]"); // no fast path for union_preserving_order
841
842            // Set without either order.
843            let unordered = abcd.skip(1).take(2).union_zip(&abefg.take(2));
844            assert!(
845                !unordered
846                    .hints()
847                    .flags()
848                    .intersects(Flags::ID_ASC | Flags::ID_DESC)
849            );
850            assert_eq!(dbg_flat(&unordered), "[B, A, C] flat:[A, B, C]");
851
852            // S & unordered; or S - unordered can preserve order and maintain fast path.
853            assert_eq!(
854                dbg_flat(&slice12(&abcd.intersection(&unordered))),
855                "[B, C] flat:[B, C]"
856            );
857            assert_eq!(
858                dbg_flat(&slice12(&abefg.difference(&unordered))),
859                "[F, G] flat:[F, G]"
860            );
861
862            // S + unordered (any order) usually does not have a fast path.
863            assert_eq!(
864                dbg_flat(&slice12(&abcd.union_preserving_order(&unordered))),
865                "[B, C]"
866            );
867            assert_eq!(dbg_flat(&slice12(&abcd.union_zip(&unordered))), "[B, C]");
868
869            // "union" does not promise order and might have a fast path.
870            assert_eq!(
871                dbg_flat(&slice12(&abcd.union(&unordered))),
872                "[B, C] flat:[B, C]"
873            );
874
875            Ok(())
876        })
877    }
878
879    #[test]
880    fn test_dag_no_fast_paths() -> Result<()> {
881        let f = |s: Set| -> String { dbg(s) };
882        with_dag(|dag1| -> Result<()> {
883            with_dag(|dag2| -> Result<()> {
884                let abcd = r(dag1.ancestors("D".into()))?;
885                let abefg = r(dag2.ancestors("G".into()))?;
886
887                // Since abcd and abefg are from 2 "separate" Dags, fast paths should not
888                // be used for intersection, union, and difference.
889
890                let ab = abcd.intersection(&abefg);
891                check_invariants(ab.deref())?;
892                // should not be "<spans ...>"
893                assert_eq!(
894                    dbg(&ab),
895                    "<and <spans [A:D+0:3]> <spans [E:G+4:6, A:B+0:1]>>"
896                );
897
898                let abcdefg = abcd.union(&abefg);
899                check_invariants(abcd.deref())?;
900                // should not be "<spans ...>"
901                assert_eq!(
902                    dbg(&abcdefg),
903                    "<or <spans [A:D+0:3]> <spans [E:G+4:6, A:B+0:1]>>"
904                );
905
906                let cd = abcd.difference(&abefg);
907                check_invariants(cd.deref())?;
908                // should not be "<spans ...>"
909                assert_eq!(
910                    dbg(&cd),
911                    "<diff <spans [A:D+0:3]> <spans [E:G+4:6, A:B+0:1]>>"
912                );
913
914                // Should not use FULL hint fast paths for "&, |, -" operations, because
915                // dag1 and dag2 are not considered compatible.
916                let a1 = || r(dag1.all()).unwrap();
917                let a2 = || r(dag2.all()).unwrap();
918                assert_eq!(f(a1() & a2()), "<and <spans [A:G+0:6]> <spans [A:G+0:6]>>");
919                assert_eq!(f(a1() | a2()), "<or <spans [A:G+0:6]> <spans [A:G+0:6]>>");
920                assert_eq!(f(a1() - a2()), "<diff <spans [A:G+0:6]> <spans [A:G+0:6]>>");
921
922                // No fast path for manually constructed StaticSet either, because
923                // the StaticSets do not have DAG associated to test compatibility.
924                // However, "all & z" is changed to "z & all" for performance.
925                let z = || Set::from("Z");
926                assert_eq!(f(z() & a2()), "<and <static [Z]> <spans [A:G+0:6]>>");
927                assert_eq!(f(z() | a2()), "<or <static [Z]> <spans [A:G+0:6]>>");
928                assert_eq!(f(z() - a2()), "<diff <static [Z]> <spans [A:G+0:6]>>");
929                assert_eq!(f(a1() & z()), "<and <static [Z]> <spans [A:G+0:6]>>");
930                assert_eq!(f(a1() | z()), "<or <spans [A:G+0:6]> <static [Z]>>");
931                assert_eq!(f(a1() - z()), "<diff <spans [A:G+0:6]> <static [Z]>>");
932
933                // EMPTY fast paths can still be used.
934                let e = Set::empty;
935                assert_eq!(f(e() & a1()), "<empty>");
936                assert_eq!(f(e() | a1()), "<spans [A:G+0:6]>");
937                assert_eq!(f(e() - a1()), "<empty>");
938                assert_eq!(f(a1() & e()), "<empty>");
939                assert_eq!(f(a1() | e()), "<spans [A:G+0:6]>");
940                assert_eq!(f(a1() - e()), "<spans [A:G+0:6]>");
941
942                // dag.sort() has to use slow path for an incompatible set.
943                let count1 = dag1.internal_stats.sort_slow_path_count.load(Acquire);
944                let _ = r(dag1.sort(&abefg))?;
945                let count2 = dag1.internal_stats.sort_slow_path_count.load(Acquire);
946                assert_eq!(
947                    count1 + 1,
948                    count2,
949                    "dag.sort() should use slow path for incompatible set"
950                );
951
952                Ok(())
953            })
954        })
955    }
956
957    #[test]
958    fn test_to_id_set_no_fast_paths() -> Result<()> {
959        let dag1 = build_segments("Z-A", "A", 2).name_dag;
960        let dag2 = build_segments("A", "A", 2).name_dag;
961        let dag1_a_set = r(dag1.sort(&"A".into()))?;
962        let dag2_a_set = r(dag2.sort(&"A".into()))?;
963        // For dag1, "A" is assigned Id(1). For dag2, "A" is assigned Id(0).
964        let dag1_a_id_set = r(dag1.to_id_set(&dag1_a_set))?;
965        let dag2_a_id_set = r(dag2.to_id_set(&dag2_a_set))?;
966        assert_eq!(dbg(dag1_a_id_set), "1");
967        assert_eq!(dbg(dag2_a_id_set), "0");
968        // If we use dag2.to_id_set, it should report "A" in dag2, aka. "0".
969        // If we use dag1.to_id_set, it should report "A" in dag1, aka. "1".
970        let dag21_a_id_set = r(dag2.to_id_set(&dag1_a_set))?;
971        let dag12_a_id_set = r(dag1.to_id_set(&dag2_a_set))?;
972        assert_eq!(dbg(dag21_a_id_set), "0");
973        assert_eq!(dbg(dag12_a_id_set), "1");
974        Ok(())
975    }
976
977    #[test]
978    fn test_dag_all() -> Result<()> {
979        with_dag(|dag| {
980            let all = r(dag.all())?;
981            assert_eq!(dbg(&all), "<spans [A:G+0:6]>");
982
983            let ac: Set = "A C".into();
984            let ac = r(dag.sort(&ac))?;
985
986            let intersection = all.intersection(&ac);
987            // should not be "<and ...>"
988            assert_eq!(dbg(&intersection), "<spans [C+2, A+0]>");
989            Ok(())
990        })
991    }
992
993    #[test]
994    fn test_sort() -> Result<()> {
995        with_dag(|dag| -> Result<()> {
996            let set = "G C A E".into();
997            let sorted = r(dag.sort(&set))?;
998            assert_eq!(dbg(&sorted), "<spans [G+6, E+4, C+2] + 1 span>");
999            Ok(())
1000        })
1001    }
1002
1003    #[test]
1004    fn test_reversed() -> Result<()> {
1005        with_dag(|dag| {
1006            let desc = r(dag.all())?;
1007            let asc = desc
1008                .as_any()
1009                .downcast_ref::<IdStaticSet>()
1010                .unwrap()
1011                .clone()
1012                .reversed();
1013            check_invariants(&asc)?;
1014            assert_eq!(dbg(&asc), "<spans [A:G+0:6] +>");
1015            assert_eq!(
1016                dbg(r(r(asc.iter())?.try_collect::<Vec<_>>())?),
1017                "[A, B, C, D, E, F, G]"
1018            );
1019
1020            Ok(())
1021        })
1022    }
1023
1024    #[test]
1025    fn test_intersect_difference_preserve_reverse_order() -> Result<()> {
1026        with_dag(|dag| -> Result<()> {
1027            let abc = "A B C".into();
1028            let cd = "C D".into();
1029            let cba = r(dag.sort(&abc))?; // DESC
1030            let dc = r(dag.sort(&cd))?;
1031            let abc = cba.reverse();
1032
1033            let ab = abc.clone() - dc.clone();
1034            check_invariants(&*ab)?;
1035            assert_eq!(fmt_iter(&ab), "[A, B]");
1036
1037            let abc2 = abc.clone() & cba.clone();
1038            check_invariants(&*abc2)?;
1039            assert_eq!(fmt_iter(&abc2), "[A, B, C]");
1040
1041            let cba2 = cba & abc;
1042            check_invariants(&*cba2)?;
1043            assert_eq!(fmt_iter(&cba2), "[C, B, A]");
1044            Ok(())
1045        })
1046    }
1047
1048    #[test]
1049    fn test_skip_take_reverse() -> Result<()> {
1050        with_dag(|dag| {
1051            let set = r(dag.sort(&Set::from("A B C")))?;
1052            check_skip_take_reverse(set)
1053        })
1054    }
1055
1056    #[test]
1057    fn test_dag_hints_ancestors() -> Result<()> {
1058        with_dag(|dag| -> Result<()> {
1059            let abc = r(dag.ancestors("B C".into()))?;
1060            let abe = r(dag.common_ancestors("E".into()))?;
1061            let f: Set = "F".into();
1062            let all = r(dag.all())?;
1063
1064            assert!(has_ancestors_flag(abc.clone()));
1065            assert!(has_ancestors_flag(abe.clone()));
1066            assert!(has_ancestors_flag(all.clone()));
1067            assert!(has_ancestors_flag(r(dag.roots(abc.clone()))?));
1068            assert!(has_ancestors_flag(r(dag.parents(all.clone()))?));
1069
1070            assert!(!has_ancestors_flag(f.clone()));
1071            assert!(!has_ancestors_flag(r(dag.roots(f.clone()))?));
1072            assert!(!has_ancestors_flag(r(dag.parents(f.clone()))?));
1073
1074            Ok(())
1075        })
1076    }
1077
1078    #[test]
1079    fn test_dag_hints_ancestors_inheritance() -> Result<()> {
1080        with_dag(|dag1| -> Result<()> {
1081            with_dag(|dag2| -> Result<()> {
1082                let abc = r(dag1.ancestors("B C".into()))?;
1083
1084                // The ANCESTORS flag is kept by 'sort', 'parents', 'roots' on
1085                // the same dag.
1086                assert!(has_ancestors_flag(r(dag1.sort(&abc))?));
1087                assert!(has_ancestors_flag(r(dag1.parents(abc.clone()))?));
1088                assert!(has_ancestors_flag(r(dag1.roots(abc.clone()))?));
1089
1090                // The ANCESTORS flag is removed on a different dag, since the
1091                // different dag does not assume same graph / ancestry
1092                // relationship.
1093                assert!(!has_ancestors_flag(r(dag2.sort(&abc))?));
1094                assert!(!has_ancestors_flag(r(dag2.parents(abc.clone()))?));
1095                assert!(!has_ancestors_flag(r(dag2.roots(abc.clone()))?));
1096
1097                Ok(())
1098            })
1099        })
1100    }
1101
1102    #[test]
1103    fn test_dag_hints_ancestors_fast_paths() -> Result<()> {
1104        with_dag(|dag| -> Result<()> {
1105            let bfg: Set = "B F G".into();
1106
1107            // Set the ANCESTORS flag. It's incorrect but make it easier to test fast paths.
1108            bfg.hints().add_flags(Flags::ANCESTORS);
1109
1110            // Fast paths are not used if the set is not "bound" to the dag.
1111            assert_eq!(dbg(r(dag.ancestors(bfg.clone()))?), "<static [B, F, G]>");
1112            assert_eq!(dbg(r(dag.heads(bfg.clone()))?), "<spans [G+6]>");
1113
1114            // Binding to the Dag enables fast paths.
1115            let bfg = r(dag.sort(&bfg))?;
1116            bfg.hints().add_flags(Flags::ANCESTORS);
1117            assert_eq!(
1118                dbg(r(dag.ancestors(bfg.clone()))?),
1119                "<spans [F:G+5:6, B+1]>"
1120            );
1121
1122            // 'heads' has a fast path that uses 'heads_ancestors' to do the calculation.
1123            // (in this case the result is incorrect because the hints are wrong).
1124            assert_eq!(dbg(r(dag.heads(bfg.clone()))?), "<spans [G+6]>");
1125
1126            // 'ancestors' has a fast path that returns set as-is.
1127            // (in this case the result is incorrect because the hints are wrong).
1128            assert_eq!(
1129                dbg(r(dag.ancestors(bfg.clone()))?),
1130                "<spans [F:G+5:6, B+1]>"
1131            );
1132
1133            let g: Set = "G".into();
1134            let g_ancestors = r(dag.ancestors(g))?;
1135            assert!(g_ancestors.hints().contains(Flags::ANCESTORS));
1136
1137            // g_ancestors.take(1) should lose the ANCESTORS hint.
1138            assert!(!g_ancestors.take(1).hints().contains(Flags::ANCESTORS));
1139            assert_eq!(
1140                dbg(r(dag.first_ancestors(g_ancestors.take(1)))?),
1141                "<spans [E:G+4:6, A:B+0:1]>",
1142            );
1143
1144            // g_ancestors.take(99) keeps the ANCESTORS hint because it preserves the entire set.
1145            assert!(g_ancestors.take(99).hints().contains(Flags::ANCESTORS));
1146
1147            Ok(())
1148        })
1149    }
1150
1151    #[test]
1152    fn test_custom_order_hints() -> Result<()> {
1153        with_dag(|dag| -> Result<()> {
1154            // Valid Ids are 0 to 6.
1155            let map = dag.id_map_snapshot()?;
1156            let dag = dag.dag_snapshot()?;
1157            let show_hints = move |ids: &[u64]| {
1158                let list = IdList::from_ids(ids.iter().map(|&id| Id(id)));
1159                let set = IdStaticSet::from_id_list_idmap_dag(list, map.clone(), dag.clone());
1160                check_invariants(&set).unwrap();
1161                let set_reversed = set.clone().reversed();
1162                check_invariants(&set_reversed).unwrap();
1163                let hints = set.hints();
1164                format!(
1165                    "Order: {:?} Min: {:?} Max: {:?} {:?}",
1166                    set.iteration_order(),
1167                    hints.min_id(),
1168                    hints.max_id(),
1169                    hints.flags(),
1170                )
1171            };
1172
1173            assert_eq!(
1174                show_hints(&[]),
1175                "Order: Some(Desc) Min: None Max: None Flags(EMPTY | ID_DESC | ID_ASC | TOPO_DESC | ANCESTORS)"
1176            );
1177            assert_eq!(
1178                show_hints(&[2]),
1179                "Order: Some(Desc) Min: Some(2) Max: Some(2) Flags(ID_DESC | ID_ASC | TOPO_DESC | HAS_MIN_ID | HAS_MAX_ID)"
1180            );
1181            assert_eq!(
1182                show_hints(&[1, 2]),
1183                "Order: Some(Asc) Min: Some(1) Max: Some(2) Flags(ID_ASC | HAS_MIN_ID | HAS_MAX_ID)"
1184            );
1185            assert_eq!(
1186                show_hints(&[2, 1]),
1187                "Order: Some(Desc) Min: Some(1) Max: Some(2) Flags(ID_DESC | TOPO_DESC | HAS_MIN_ID | HAS_MAX_ID)"
1188            );
1189            assert_eq!(
1190                show_hints(&[1, 2, 4, 5]),
1191                "Order: Some(Asc) Min: Some(1) Max: Some(5) Flags(ID_ASC | HAS_MIN_ID | HAS_MAX_ID)"
1192            );
1193            assert_eq!(
1194                show_hints(&[5, 4, 2, 1]),
1195                "Order: Some(Desc) Min: Some(1) Max: Some(5) Flags(ID_DESC | TOPO_DESC | HAS_MIN_ID | HAS_MAX_ID)"
1196            );
1197            assert_eq!(
1198                show_hints(&[4, 5, 1, 2]),
1199                "Order: None Min: Some(1) Max: Some(5) Flags(HAS_MIN_ID | HAS_MAX_ID)"
1200            );
1201            assert_eq!(
1202                show_hints(&[2, 1, 5, 4]),
1203                "Order: None Min: Some(1) Max: Some(5) Flags(HAS_MIN_ID | HAS_MAX_ID)"
1204            );
1205            assert_eq!(
1206                show_hints(&[4, 5, 1]),
1207                "Order: None Min: Some(1) Max: Some(5) Flags(HAS_MIN_ID | HAS_MAX_ID)"
1208            );
1209            assert_eq!(
1210                show_hints(&[2, 1, 5]),
1211                "Order: None Min: Some(1) Max: Some(5) Flags(HAS_MIN_ID | HAS_MAX_ID)"
1212            );
1213
1214            Ok(())
1215        })
1216    }
1217
1218    #[test]
1219    fn test_custom_order_debug_fmt() -> Result<()> {
1220        with_dag(|dag| -> Result<()> {
1221            let map = dag.id_map_snapshot()?;
1222            let dag = dag.dag_snapshot()?;
1223            let list = move |ids: &[u64]| {
1224                let list = IdList::from_ids(ids.iter().map(|&id| Id(id)));
1225                IdStaticSet::from_id_list_idmap_dag(list, map.clone(), dag.clone())
1226            };
1227
1228            assert_eq!(dbg(list(&[1, 3, 2])), "<spans [B+1, D:C+3:2] ?>");
1229            assert_eq!(dbg(list(&[1, 3, 2]).reversed()), "<spans [B+1, D:C+3:2] ¿>");
1230
1231            Ok(())
1232        })
1233    }
1234
1235    fn has_ancestors_flag(set: Set) -> bool {
1236        set.hints().contains(Flags::ANCESTORS)
1237    }
1238
1239    /// Break <nested <nested <nested ... >>> into multi-lines.
1240    fn wrap_dbg_lines(value: &dyn fmt::Debug) -> String {
1241        #[derive(Default, Debug)]
1242        struct Fmt<'a> {
1243            head: &'a str,
1244            tail: &'a str,
1245            body: Vec<Fmt<'a>>,
1246            len: usize,
1247        }
1248
1249        fn indent(s: &str, prefix: &str) -> String {
1250            format!(
1251                "\n{}{}",
1252                prefix,
1253                s.trim().replace('\n', &format!("\n{prefix}"))
1254            )
1255        }
1256
1257        impl<'a> Fmt<'a> {
1258            // to_parse -> (Fmt, rest)
1259            fn parse(mut s: &'a str) -> (Self, &'a str) {
1260                let mut out = Self::default();
1261                let mut seen_left = false;
1262                let mut i = 0;
1263                while i < s.len() {
1264                    let ch = s.as_bytes()[i];
1265                    match ch {
1266                        b'<' => {
1267                            if seen_left {
1268                                if out.head.is_empty() {
1269                                    out.head = s[..i].trim();
1270                                    out.len += out.head.len();
1271                                }
1272                                let (nested, rest) = Self::parse(&s[i..]);
1273                                out.len += nested.len;
1274                                out.body.push(nested);
1275                                s = rest;
1276                                i = 0;
1277                                continue;
1278                            } else {
1279                                seen_left = true;
1280                                i += 1;
1281                            }
1282                        }
1283                        b'>' => {
1284                            out.tail = s[..i + 1].trim();
1285                            out.len += out.tail.len();
1286                            if out.head.is_empty() {
1287                                (out.head, out.tail) = out.tail.split_once(' ').unwrap();
1288                            }
1289                            let rest = &s[i + 1..];
1290                            return (out, rest);
1291                        }
1292                        _ => i += 1,
1293                    }
1294                }
1295                panic!("unbalanced <> in fmt string");
1296            }
1297
1298            fn pretty(&self) -> String {
1299                let mut out = String::new();
1300                let need_wrap = !self.body.is_empty() && self.len > 80;
1301                out.push_str(self.head);
1302                for f in &self.body {
1303                    let mut s = f.pretty();
1304                    if need_wrap {
1305                        s = indent(&s, "  ");
1306                    } else {
1307                        s = format!(" {s}");
1308                    }
1309                    out.push_str(&s);
1310                }
1311                if self.tail != ">" {
1312                    out.push(' ');
1313                }
1314                out.push_str(self.tail);
1315                out
1316            }
1317        }
1318
1319        let s = dbg(value);
1320        let f = Fmt::parse(&s).0;
1321        indent(&f.pretty(), "                ")
1322    }
1323}