Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 3.3 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Hex prefixes of object ids: what a short id given on the command line
5//! names.
6
7use braid_format::ObjectId;
8
9/// The first hex digits of an id, as their values, one per digit.
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub(crate) struct HexPrefix {
12 digits: Vec<u8>,
13}
14
15impl HexPrefix {
16 /// Reads lowercase hex digits, at most as many as a full id has. Anything
17 /// else is not a prefix.
18 pub(crate) fn parse(text: &str) -> Option<HexPrefix> {
19 if text.len() > 2 * ObjectId::LEN {
20 return None;
21 }
22 let digits = text
23 .bytes()
24 .map(|digit| match digit {
25 b'0'..=b'9' => Some(digit - b'0'),
26 b'a'..=b'f' => Some(digit - b'a' + 10),
27 _ => None,
28 })
29 .collect::<Option<Vec<u8>>>()?;
30 Some(HexPrefix { digits })
31 }
32
33 /// The first bytes the ids that start with these digits can have.
34 pub(crate) fn first_bytes(&self) -> std::ops::RangeInclusive<u8> {
35 match self.digits.as_slice() {
36 [] => 0..=255,
37 [high] => (high << 4)..=(high << 4 | 0x0f),
38 [high, low, ..] => {
39 let byte = high << 4 | low;
40 byte..=byte
41 }
42 }
43 }
44
45 /// Whether the hex form of `id` starts with these digits.
46 pub(crate) fn matches(&self, id: &ObjectId) -> bool {
47 let bytes = id.as_bytes();
48 self.digits.iter().enumerate().all(|(at, digit)| {
49 let byte = bytes[at / 2];
50 let found = if at % 2 == 0 { byte >> 4 } else { byte & 0x0f };
51 found == *digit
52 })
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59 use braid_format::Kind;
60
61 #[test]
62 fn prefixes_of_every_length_match() {
63 let id = ObjectId::hash(Kind::Blob, b"hello\n");
64 let hex = id.to_hex();
65 for len in 0..=64 {
66 let prefix = HexPrefix::parse(&hex[..len]).unwrap();
67 assert!(prefix.matches(&id), "{len} digits");
68 }
69 let other = ObjectId::hash(Kind::Blob, b"other\n");
70 let shared = hex
71 .bytes()
72 .zip(other.to_hex().bytes())
73 .take_while(|(a, b)| a == b)
74 .count();
75 assert!(
76 !HexPrefix::parse(&hex[..shared + 1])
77 .unwrap()
78 .matches(&other)
79 );
80 }
81
82 #[test]
83 fn first_bytes_bound_the_ids_a_prefix_matches() {
84 let id = ObjectId::hash(Kind::Blob, b"hello\n");
85 let hex = id.to_hex();
86 for len in 0..=4 {
87 let prefix = HexPrefix::parse(&hex[..len]).unwrap();
88 assert!(prefix.first_bytes().contains(&id.as_bytes()[0]), "{len}");
89 }
90 assert_eq!(HexPrefix::parse("").unwrap().first_bytes(), 0..=255);
91 assert_eq!(HexPrefix::parse("a").unwrap().first_bytes(), 0xa0..=0xaf);
92 assert_eq!(HexPrefix::parse("a7f").unwrap().first_bytes(), 0xa7..=0xa7);
93 }
94
95 #[test]
96 fn only_lowercase_hex_digits_are_a_prefix() {
97 for bad in ["ABC", "xyz", "12 4", "-1", &"0".repeat(65)] {
98 assert_eq!(HexPrefix::parse(bad), None, "{bad:?}");
99 }
100 assert_eq!(HexPrefix::parse("").unwrap().digits, Vec::<u8>::new());
101 assert_eq!(HexPrefix::parse("0af").unwrap().digits, [0, 10, 15]);
102 }
103}