Skip to main content

dag/set/
hints.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::cmp;
9use std::fmt;
10use std::sync::Arc;
11use std::sync::atomic::AtomicU32;
12use std::sync::atomic::AtomicU64;
13use std::sync::atomic::Ordering::Acquire;
14use std::sync::atomic::Ordering::Relaxed;
15use std::sync::atomic::Ordering::Release;
16
17use bitflags::bitflags;
18
19use crate::Id;
20use crate::VerLink;
21use crate::ops::DagAlgorithm;
22use crate::ops::IdConvert;
23
24bitflags! {
25    #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
26    pub struct Flags: u32 {
27        /// Full. A full Set & other set X with compatible Dag results in X.
28        const FULL = 0x1;
29
30        /// Empty (also implies ID_DESC | ID_ASC | TOPO_DESC).
31        const EMPTY = 0x2;
32
33        /// Sorted by Id. Descending (head -> root).
34        const ID_DESC = 0x4;
35
36        /// Sorted by Id. Ascending (root -> head).
37        const ID_ASC = 0x8;
38
39        /// Sorted topologically. Descending (head -> root).
40        const TOPO_DESC = 0x10;
41
42        /// Minimal Id is known.
43        const HAS_MIN_ID = 0x20;
44
45        /// Maximum Id is known.
46        const HAS_MAX_ID = 0x40;
47
48        /// A "filter" set. It provides "contains" but iteration is inefficient.
49        const FILTER = 0x80;
50
51        /// The set contains ancestors. If X in set, any ancestor of X is also in set.
52        const ANCESTORS = 0x100;
53    }
54}
55
56/// Optimization hints.
57#[derive(Default)]
58pub struct Hints {
59    // Atomic is used for interior mutability.
60    flags: AtomicU32,
61    min_id: AtomicU64,
62    max_id: AtomicU64,
63    id_map: IdMapSnapshot,
64    dag: DagSnapshot,
65}
66
67impl Hints {
68    pub fn new_with_idmap_dag(
69        id_map: impl Into<IdMapSnapshot>,
70        dag: impl Into<DagSnapshot>,
71    ) -> Self {
72        Self {
73            id_map: id_map.into(),
74            dag: dag.into(),
75            ..Default::default()
76        }
77    }
78
79    pub fn new_inherit_idmap_dag(hints: &Self) -> Self {
80        Self::new_with_idmap_dag(hints, hints)
81    }
82
83    /// Attempt to inherit properties (IdMap and Dag snapshots) from a list of
84    /// hints. The returned hints have IdMap and Dag set to be compatible with
85    /// all other hints in the list (or set to be None if that's not possible).
86    pub fn union(hints_list: &[&Self]) -> Self {
87        let default = Self::default();
88        // Find the id_map that is compatible with all other id_maps.
89        debug_assert!(default.id_map().is_none());
90        let id_map = hints_list
91            .iter()
92            .try_fold(&default, |a, b| {
93                match a.id_map_version().partial_cmp(&b.id_map_version()) {
94                    None => None, // Incompatible sets
95                    Some(cmp::Ordering::Equal) | Some(cmp::Ordering::Greater) => Some(a),
96                    Some(cmp::Ordering::Less) => Some(*b),
97                }
98            })
99            .and_then(|a| a.id_map());
100        // Find the dag that is compatible with all other dags.
101        debug_assert!(default.dag().is_none());
102        let dag = hints_list
103            .iter()
104            .try_fold(&default, |a, b| {
105                match a.dag_version().partial_cmp(&b.dag_version()) {
106                    None => None,
107                    Some(cmp::Ordering::Equal) | Some(cmp::Ordering::Greater) => Some(a),
108                    Some(cmp::Ordering::Less) => Some(*b),
109                }
110            })
111            .and_then(|a| a.dag());
112        Self {
113            id_map: IdMapSnapshot(id_map),
114            dag: DagSnapshot(dag),
115            ..Self::default()
116        }
117    }
118
119    pub fn flags(&self) -> Flags {
120        let flags = self.flags.load(Relaxed);
121        Flags::from_bits_truncate(flags)
122    }
123
124    pub fn contains(&self, flags: Flags) -> bool {
125        self.flags().contains(flags)
126    }
127
128    pub fn min_id(&self) -> Option<Id> {
129        if self.contains(Flags::HAS_MIN_ID) {
130            Some(Id(self.min_id.load(Acquire)))
131        } else {
132            None
133        }
134    }
135
136    pub fn max_id(&self) -> Option<Id> {
137        if self.contains(Flags::HAS_MAX_ID) {
138            Some(Id(self.max_id.load(Acquire)))
139        } else {
140            None
141        }
142    }
143
144    pub fn update_flags_with(&self, func: impl Fn(Flags) -> Flags) -> &Self {
145        let mut flags = func(self.flags());
146        // Automatically add "derived" flags.
147        if flags.contains(Flags::EMPTY) {
148            flags.insert(Flags::ID_ASC | Flags::ID_DESC | Flags::TOPO_DESC | Flags::ANCESTORS);
149        }
150        if flags.contains(Flags::FULL) {
151            flags.insert(Flags::ANCESTORS);
152        }
153        self.flags.store(flags.bits(), Relaxed);
154        self
155    }
156
157    pub fn add_flags(&self, flags: Flags) -> &Self {
158        self.update_flags_with(|f| f | flags);
159        self
160    }
161
162    pub fn remove_flags(&self, flags: Flags) -> &Self {
163        self.update_flags_with(|f| f - flags);
164        self
165    }
166
167    pub fn set_min_id(&self, min_id: Id) -> &Self {
168        self.min_id.store(min_id.0, Release);
169        self.add_flags(Flags::HAS_MIN_ID);
170        self
171    }
172
173    pub fn set_max_id(&self, max_id: Id) -> &Self {
174        self.max_id.store(max_id.0, Release);
175        self.add_flags(Flags::HAS_MAX_ID);
176        self
177    }
178
179    pub fn inherit_flags_min_max_id(&self, other: &Hints) -> &Self {
180        self.update_flags_with(|_| other.flags());
181        if let Some(id) = other.min_id() {
182            self.set_min_id(id);
183        }
184        if let Some(id) = other.max_id() {
185            self.set_max_id(id);
186        }
187        self
188    }
189
190    pub fn dag(&self) -> Option<Arc<dyn DagAlgorithm + Send + Sync>> {
191        self.dag.0.clone()
192    }
193
194    pub fn id_map(&self) -> Option<Arc<dyn IdConvert + Send + Sync>> {
195        self.id_map.0.clone()
196    }
197
198    /// The `VerLink` of the Dag. `None` if there is no Dag associated.
199    pub fn dag_version(&self) -> Option<&VerLink> {
200        self.dag.0.as_ref().map(|d| d.dag_version())
201    }
202
203    /// The `VerLink` of the IdMap. `None` if there is no IdMap associated.
204    pub fn id_map_version(&self) -> Option<&VerLink> {
205        self.id_map.0.as_ref().map(|d| d.map_version())
206    }
207}
208
209#[derive(Clone, Default)]
210pub struct DagSnapshot(Option<Arc<dyn DagAlgorithm + Send + Sync>>);
211
212impl From<&Hints> for DagSnapshot {
213    fn from(hints: &Hints) -> Self {
214        hints.dag.clone()
215    }
216}
217
218impl From<Arc<dyn DagAlgorithm + Send + Sync>> for DagSnapshot {
219    fn from(dag: Arc<dyn DagAlgorithm + Send + Sync>) -> Self {
220        DagSnapshot(Some(dag))
221    }
222}
223
224#[derive(Clone, Default)]
225pub struct IdMapSnapshot(Option<Arc<dyn IdConvert + Send + Sync>>);
226
227impl From<&Hints> for IdMapSnapshot {
228    fn from(hints: &Hints) -> Self {
229        hints.id_map.clone()
230    }
231}
232
233impl From<Arc<dyn IdConvert + Send + Sync>> for IdMapSnapshot {
234    fn from(dag: Arc<dyn IdConvert + Send + Sync>) -> Self {
235        IdMapSnapshot(Some(dag))
236    }
237}
238
239#[derive(Clone, Default)]
240pub struct DagVersion<'a>(Option<&'a VerLink>);
241
242impl<'a> From<&'a Hints> for DagVersion<'a> {
243    fn from(hints: &'a Hints) -> Self {
244        Self(match &hints.dag.0 {
245            Some(d) => Some(d.dag_version()),
246            None => None,
247        })
248    }
249}
250
251impl<'a> From<&'a VerLink> for DagVersion<'a> {
252    fn from(version: &'a VerLink) -> Self {
253        Self(Some(version))
254    }
255}
256
257#[derive(Clone, Default)]
258pub struct IdMapVersion<'a>(Option<&'a VerLink>);
259
260impl<'a> From<&'a Hints> for IdMapVersion<'a> {
261    fn from(hints: &'a Hints) -> Self {
262        Self(match &hints.id_map.0 {
263            Some(m) => Some(m.map_version()),
264            None => None,
265        })
266    }
267}
268
269impl<'a> From<&'a VerLink> for IdMapVersion<'a> {
270    fn from(version: &'a VerLink) -> Self {
271        Self(Some(version))
272    }
273}
274
275impl Clone for Hints {
276    fn clone(&self) -> Self {
277        Self {
278            flags: AtomicU32::new(self.flags.load(Acquire)),
279            min_id: AtomicU64::new(self.min_id.load(Acquire)),
280            max_id: AtomicU64::new(self.max_id.load(Acquire)),
281            id_map: self.id_map.clone(),
282            dag: self.dag.clone(),
283        }
284    }
285}
286
287impl fmt::Debug for Hints {
288    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
289        write!(
290            f,
291            "Hints({:?}",
292            self.flags() - (Flags::HAS_MIN_ID | Flags::HAS_MAX_ID)
293        )?;
294        match (self.min_id(), self.max_id()) {
295            (Some(min), Some(max)) => write!(f, ", {}..={}", min.0, max.0)?,
296            (Some(min), None) => write!(f, ", {}..", min.0)?,
297            (None, Some(max)) => write!(f, ", ..={}", max.0)?,
298            (None, None) => {}
299        }
300        write!(f, ")")?;
301        Ok(())
302    }
303}
304
305#[cfg(test)]
306#[test]
307fn test_incompatilbe_union() {
308    use crate::tests::dummy_dag::DummyDag;
309    let dag1 = DummyDag::new();
310    let dag2 = DummyDag::new();
311
312    let hints1 = Hints {
313        dag: DagSnapshot(Some(dag1.dag_snapshot().unwrap())),
314        ..Default::default()
315    };
316
317    let hints2 = Hints {
318        dag: DagSnapshot(Some(dag2.dag_snapshot().unwrap())),
319        ..Default::default()
320    };
321
322    assert_eq!(
323        Hints::union(&[&hints1, &hints1]).dag_version(),
324        hints1.dag_version()
325    );
326
327    assert_eq!(Hints::union(&[&hints1, &hints2]).dag_version(), None);
328    assert_eq!(Hints::union(&[&hints2, &hints1]).dag_version(), None);
329    assert_eq!(
330        Hints::union(&[&hints2, &hints1, &hints2]).dag_version(),
331        None
332    );
333}