Debian Codegraph @

rust/hg-core/src/utils/docket.rs

raw
1 //! Utilities for docket files.
2 //!
3 //! A docket is a small metadata file that points to other files and records
4 //! information about their size and structure. For more information, see
5 //! mercurial/utils/docket.py.
6
7 use std::io::Write;
8
9 use bytes_cast::BytesCast;
10 use rand::Rng;
11
12 /// A unique identifier made of hex digits used as part of a filename.
13 #[derive(Debug, Copy, Clone, PartialEq, Eq, BytesCast)]
14 #[repr(transparent)]
15 pub struct FileUid([u8; UID_SIZE]);
16
17 /// Underlying integer type for a [`FileUid`].
18 type FileUidInt = u32;
19
20 /// Number of characters in a [`FileUid`].
21 pub const UID_SIZE: usize = std::mem::size_of::<FileUidInt>() * 2;
22
23 impl FileUid {
24 /// Returns a sentinel value representing an unset uid.
25 pub const fn unset() -> Self {
26 Self([b'0'; UID_SIZE])
27 }
28
29 /// Returns true if the uid is unset.
30 pub fn is_unset(&self) -> bool {
31 *self == Self::unset()
32 }
33
34 /// Returns `None` if the uid is unset.
35 pub fn none_if_unset(&self) -> Option<Self> {
36 if *self == Self::unset() {
37 None
38 } else {
39 Some(*self)
40 }
41 }
42
43 /// Generates a random uid. It will never equal [`Self::unset()`].
44 pub fn random() -> Self {
45 // TODO: support the `HGTEST_UUIDFILE` environment variable.
46 let mut id = [0; UID_SIZE];
47 let random: FileUidInt = rand::rng().random_range(1..=FileUidInt::MAX);
48 write!(&mut id[..], "{:0width$x}", random, width = UID_SIZE)
49 .expect("write cannot fail since size matches");
50 Self(id)
51 }
52
53 /// Returns this uid as bytes.
54 pub fn as_bytes(&self) -> &[u8] {
55 &self.0
56 }
57
58 /// Returns this uid as a string.
59 pub fn as_str(&self) -> &str {
60 std::str::from_utf8(&self.0).expect("hex digits are ASCII")
61 }
62 }