Skip to main content

dag_types/
id.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//! # id
9//!
10//! Defines types around [`Id`].
11
12use std::fmt;
13use std::io;
14use std::ops;
15
16pub use minibytes::Bytes;
17use serde::Deserialize;
18use serde::Serialize;
19
20/// An integer [`Id`] representing a node in the graph.
21/// [`Id`]s are topologically sorted.
22#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
23#[derive(Serialize, Deserialize)]
24pub struct Id(pub u64);
25
26/// Name of a vertex in the graph.
27#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
28#[serde(transparent)]
29pub struct Vertex(pub Bytes);
30
31impl AsRef<[u8]> for Vertex {
32    fn as_ref(&self) -> &[u8] {
33        &self.0
34    }
35}
36
37impl Vertex {
38    pub fn to_hex(&self) -> String {
39        const HEX_CHARS: &[u8] = b"0123456789abcdef";
40        let mut v = Vec::with_capacity(self.0.len() * 2);
41        for &byte in self.as_ref() {
42            v.push(HEX_CHARS[(byte >> 4) as usize]);
43            v.push(HEX_CHARS[(byte & 0xf) as usize]);
44        }
45        unsafe { String::from_utf8_unchecked(v) }
46    }
47
48    /// Convert from hex.
49    ///
50    /// If `len(hex)` is an odd number, hex + '0' will be used.
51    pub fn from_hex(hex: &[u8]) -> io::Result<Self> {
52        let mut bytes = vec![0u8; hex.len().div_ceil(2)];
53        for (i, byte) in hex.iter().enumerate() {
54            let value = match byte {
55                b'0'..=b'9' => byte - b'0',
56                b'a'..=b'f' => byte - b'a' + 10,
57                b'A'..=b'F' => byte - b'A' + 10,
58                _ => {
59                    return Err(io::Error::new(
60                        io::ErrorKind::InvalidInput,
61                        format!("{:?} is not a hex character", *byte as char),
62                    ));
63                }
64            };
65            if i & 1 == 0 {
66                bytes[i / 2] |= value << 4;
67            } else {
68                bytes[i / 2] |= value;
69            }
70        }
71        Ok(Vertex(Bytes::from(bytes)))
72    }
73
74    pub fn copy_from(value: &[u8]) -> Self {
75        Self(value.to_vec().into())
76    }
77}
78
79impl<T> From<T> for Vertex
80where
81    Bytes: From<T>,
82{
83    fn from(value: T) -> Self {
84        Self(Bytes::from(value))
85    }
86}
87
88impl fmt::Debug for Vertex {
89    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90        if self.0.len() >= 4 || !looks_like_ascii_identifier(self.as_ref()) {
91            // Use hex format for long names (ex. binary commit hashes).
92            let hex = self.to_hex();
93            // Truncate to specified width (ex. '{:#.12}').
94            if let Some(width) = f.precision() {
95                let truncated = hex.get(..width).unwrap_or(&hex);
96                f.write_str(truncated)
97            } else {
98                f.write_str(&hex)
99            }
100        } else {
101            // Do not use hex if it looks like an ASCII identifier.
102            match std::str::from_utf8(self.as_ref()) {
103                Ok(s) => write!(f, "{s}"),
104                Err(_) => write!(f, "{}", self.to_hex()),
105            }
106        }
107    }
108}
109
110fn looks_like_ascii_identifier(bytes: &[u8]) -> bool {
111    let mut iter = bytes.iter().copied();
112    if !(iter.next().unwrap_or(b'\0') as char).is_ascii_alphabetic() {
113        return false;
114    }
115    iter.all(|b| b.is_ascii_alphanumeric())
116}
117
118/// An integer that separates distinct groups of [`Id`]s.
119///
120/// This can be seen as a way to pre-allocate consecutive integers
121/// for one group to make segments less fragmented.
122///
123/// `(Group, Id)` are also topologically sorted.
124#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
125#[derive(Serialize, Deserialize)]
126pub struct Group(pub usize);
127
128impl Group {
129    /// The "master" group. usually `ancestors(master)`.
130    /// - Expected to have most of the commits in a repo.
131    /// - Ideally free from fragmentation. In other words,
132    ///   `ancestors(master)` can be represented in a single Span.
133    /// - Ideally has limited heads. Does not scale with too many heads.
134    /// - Vertexes (commit hashes) might be lazy.
135    pub const MASTER: Self = Self(0);
136
137    /// The "non-master" group.
138    /// - Concrete vertexes not in the "master" group. For example, public
139    ///   release branches, local feature branches.
140    /// - Expected to have multiple heads. In other words, is fragmented.
141    /// - Expected to be sparse referred. For example, the "visible heads"
142    ///   will refer to a bounded subset in this group.
143    /// - Expected to be non-lazy. Code paths assume Vertexes
144    ///   (commit hashes) are known in this group.
145    pub const NON_MASTER: Self = Self(1);
146
147    /// The "virtual" group.
148    /// - Typically, "null" and "wdir()".
149    /// - Should not be written to disk.
150    /// - Not lazy.
151    pub const VIRTUAL: Self = Self(2);
152
153    /// Groups designed to be persisted to disk.
154    pub const PERSIST: [Self; 2] = [Self::MASTER, Self::NON_MASTER];
155
156    pub const ALL: [Self; 3] = [Self::MASTER, Self::NON_MASTER, Self::VIRTUAL];
157    pub const MAX: Self = Self::ALL[Self::COUNT - 1];
158
159    pub const COUNT: usize = Self::ALL.len();
160
161    // 1 byte for Group so it's easier to remove everything in a group.
162    pub const BITS: u32 = 8;
163    pub const BYTES: usize = 1;
164
165    /// The first [`Id`] in this group.
166    pub const fn min_id(self) -> Id {
167        Id((self.0 as u64) << (64 - Self::BITS))
168    }
169
170    /// The maximum [`Id`] in this group.
171    pub const fn max_id(self) -> Id {
172        Id(self.min_id().0 + ((1u64 << (64 - Self::BITS)) - 1))
173    }
174
175    /// Convert to array.
176    pub const fn bytes(self) -> [u8; 1] {
177        [self.0 as u8]
178    }
179
180    /// Convert to hex array.
181    pub fn hex_bytes(self) -> [u8; 2] {
182        if self.0 < 10 {
183            [b'0', b'0' + (self.0 as u8)]
184        } else {
185            unreachable!()
186        }
187    }
188
189    /// Test if the `Group` is valid.
190    pub fn is_valid(self) -> bool {
191        self.0 <= Self::MAX.0
192    }
193}
194
195impl Id {
196    /// The [`Group`] of an Id.
197    pub fn group(self) -> Group {
198        let group = (self.0 >> (64 - Group::BITS)) as usize;
199        Group(group)
200    }
201
202    /// Test if the `Id` is valid.
203    pub fn is_valid(self) -> bool {
204        self.group().is_valid()
205    }
206
207    /// Similar to `self..=other`.
208    pub fn to(self, other: Id) -> IdIter {
209        IdIter {
210            current: self,
211            end: other,
212        }
213    }
214
215    /// Convert to a byte array. Useful for indexedlog range query.
216    pub fn to_bytearray(self) -> [u8; 8] {
217        // The field can be used for index range query. So it has to be BE.
218        self.0.to_be().to_ne_bytes()
219    }
220
221    /// Similar to `to_bytearray`, but insert a `prefix` at the head.
222    /// Useful for segment queries where `level` is the `prefix`.
223    pub fn to_prefixed_bytearray(self, prefix: u8) -> [u8; 9] {
224        let a = self.to_bytearray();
225        [prefix, a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]]
226    }
227
228    /// Test if this `Id` is in the VIRTUAL group.
229    pub fn is_virtual(self) -> bool {
230        self.group() == Group::VIRTUAL
231    }
232
233    pub const MAX: Self = Group::ALL[Group::COUNT - 1].max_id();
234    pub const MIN: Self = Group::ALL[0].min_id();
235}
236
237impl fmt::Display for Id {
238    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
239        let group = self.group();
240        match group {
241            Group::NON_MASTER => write!(f, "N")?,
242            Group::VIRTUAL => write!(f, "V")?,
243            _ => {}
244        }
245        write!(f, "{}", self.0 - group.min_id().0)
246    }
247}
248
249impl fmt::Debug for Id {
250    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
251        write!(f, "{self}")
252    }
253}
254
255impl fmt::Display for Group {
256    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
257        match *self {
258            Group::MASTER => write!(f, "Group Master"),
259            Group::NON_MASTER => write!(f, "Group Non-Master"),
260            Group::VIRTUAL => write!(f, "Group Virtual"),
261            _ => write!(f, "Group {}", self.0),
262        }
263    }
264}
265
266impl ops::Add<u64> for Id {
267    type Output = Id;
268
269    fn add(self, other: u64) -> Self {
270        Self(self.0 + other)
271    }
272}
273
274impl ops::Sub<u64> for Id {
275    type Output = Id;
276
277    fn sub(self, other: u64) -> Self {
278        Self(self.0 - other)
279    }
280}
281
282impl ops::Add<u8> for Group {
283    type Output = Group;
284
285    fn add(self, other: u8) -> Self {
286        Self(self.0 + other as usize)
287    }
288}
289
290impl ops::Sub<u8> for Group {
291    type Output = Group;
292
293    fn sub(self, other: u8) -> Self {
294        Self(self.0 - other as usize)
295    }
296}
297
298// Consider replacing this with iter::Step once it's stable.
299pub struct IdIter {
300    current: Id,
301    end: Id,
302}
303
304impl Iterator for IdIter {
305    type Item = Id;
306
307    fn next(&mut self) -> Option<Id> {
308        if self.current > self.end {
309            None
310        } else {
311            let result = self.current;
312            self.current = self.current + 1;
313            Some(result)
314        }
315    }
316}
317
318#[cfg(any(test, feature = "for-tests"))]
319use quickcheck::Arbitrary;
320#[cfg(any(test, feature = "for-tests"))]
321use quickcheck::Gen;
322
323#[cfg(any(test, feature = "for-tests"))]
324impl Arbitrary for Id {
325    fn arbitrary(g: &mut Gen) -> Self {
326        let group = Group((u32::arbitrary(g) & 1) as usize);
327        group.min_id() + u64::arbitrary(g) % (group.max_id().0 - group.min_id().0)
328    }
329}
330
331// For convenience.
332impl std::cmp::PartialEq<u64> for Id {
333    fn eq(&self, other: &u64) -> bool {
334        self.0 == *other
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use quickcheck::quickcheck;
341
342    use super::*;
343
344    #[test]
345    fn test_vertex_from_hex_odd() {
346        let vertex = Vertex::from_hex(b"a").unwrap();
347        let vertex2 = Vertex::from_hex(b"a0").unwrap();
348        assert_eq!(vertex, vertex2);
349        assert_eq!(vertex.to_hex(), "a0");
350    }
351
352    quickcheck! {
353        fn test_vertex_hex_roundtrip(slice: Vec<u8>) -> bool {
354            let vertex = Vertex::from(slice);
355            let hex = vertex.to_hex();
356            let vertex2 = Vertex::from_hex(hex.as_bytes()).unwrap();
357            vertex2 == vertex
358        }
359    }
360}