Skip to main content

gix_hash/
oid.rs

1use gix_error::{Result, message};
2use std::{hash, ops::Range};
3
4use crate::{Kind, ObjectId, Prefix};
5
6#[cfg(feature = "sha1")]
7use crate::{EMPTY_BLOB_SHA1, EMPTY_TREE_SHA1, SIZE_OF_SHA1_DIGEST};
8
9#[cfg(feature = "sha256")]
10use crate::{EMPTY_BLOB_SHA256, EMPTY_TREE_SHA256, SIZE_OF_SHA256_DIGEST};
11
12/// A borrowed reference to a hash identifying objects.
13///
14/// # Future Proofing
15///
16/// In case we wish to support multiple hashes with the same length we cannot discriminate
17/// using the slice length anymore. To make that work, we will use the high bits of the
18/// internal `bytes` slice length (a fat pointer, pointing to data and its length in bytes)
19/// to encode additional information. Before accessing or returning the bytes, a new adjusted
20/// slice will be constructed, while the high bits will be used to help resolving the
21/// hash [`kind()`][oid::kind()].
22/// We expect to have quite a few bits available for such 'conflict resolution' as most hashes aren't longer
23/// than 64 bytes.
24#[derive(PartialEq, Eq, Ord, PartialOrd)]
25#[repr(transparent)]
26#[expect(non_camel_case_types, reason = "the name mirrors 'str'")]
27#[cfg_attr(feature = "serde", derive(serde::Serialize))]
28pub struct oid {
29    bytes: [u8],
30}
31
32// False positive:
33// Using an automatic implementation of `Hash` for `oid` would lead to
34// it attempting to hash the length of the slice first. On 32 bit systems
35// this can lead to issues with the custom `gix_hashtable` `Hasher` implementation,
36// and it currently ends up being discarded there anyway.
37impl hash::Hash for oid {
38    fn hash<H: hash::Hasher>(&self, state: &mut H) {
39        state.write(self.as_bytes());
40    }
41}
42
43/// A utility able to format itself with the given number of characters in hex.
44#[derive(PartialEq, Eq, Hash, Ord, PartialOrd)]
45pub struct HexDisplay<'a> {
46    inner: &'a oid,
47    hex_len: usize,
48}
49
50impl std::fmt::Display for HexDisplay<'_> {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        let mut hex = Kind::hex_buf();
53        let hex = self.inner.hex_to_buf(hex.as_mut());
54        let max_len = hex.len();
55        f.write_str(&hex[..self.hex_len.min(max_len)])
56    }
57}
58
59impl HexDisplay<'_> {
60    pub(crate) fn eq_str(&self, other: &str) -> bool {
61        let mut hex = Kind::hex_buf();
62        let hex = self.inner.hex_to_buf(hex.as_mut());
63        hex[..self.hex_len.min(hex.len())] == *other
64    }
65}
66
67// Keep this directional as truncated displays aren't uniquely identified by their text.
68impl_partial_eq_str_one_way!(HexDisplay<'_>);
69
70impl std::fmt::Debug for oid {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        write!(
73            f,
74            "{}({})",
75            match self.kind() {
76                #[cfg(feature = "sha1")]
77                Kind::Sha1 => "Sha1",
78                #[cfg(feature = "sha256")]
79                Kind::Sha256 => "Sha256",
80            },
81            self.to_hex(),
82        )
83    }
84}
85
86/// Conversion
87impl oid {
88    /// Try to create a shared object id from a slice of bytes representing a hash `digest`
89    #[inline]
90    pub fn try_from_bytes(digest: &[u8]) -> Result<&Self> {
91        match digest.len() {
92            #[cfg(feature = "sha1")]
93            SIZE_OF_SHA1_DIGEST => Ok(Self::from_bytes(digest)),
94            #[cfg(feature = "sha256")]
95            SIZE_OF_SHA256_DIGEST => Ok(Self::from_bytes(digest)),
96            len => Err(message!("Cannot instantiate git hash from a digest of length {len}").validation_error()),
97        }
98    }
99
100    /// Create an `oid` from the input `value` slice without performing any length check.
101    /// Use only once you are sure that `value` is a hash of valid length, or panics will occur on most uses.
102    pub fn from_bytes_unchecked(value: &[u8]) -> &Self {
103        Self::from_bytes(value)
104    }
105
106    /// Only from code that statically assures correct sizes using array conversions.
107    #[inline]
108    pub(crate) fn from_bytes(value: &[u8]) -> &Self {
109        // SAFETY: `oid` is `#[repr(transparent)]` over `[u8]`, so both have the same layout, and the
110        //         pointer cast keeps the slice length as metadata. The returned reference borrows `value`.
111        //         An unexpected length is memory-safe; `kind()` panics on it.
112        #[expect(unsafe_code)]
113        unsafe {
114            &*(std::ptr::from_ref::<[u8]>(value) as *const oid)
115        }
116    }
117}
118
119/// Access
120impl oid {
121    /// The kind of hash used for this instance.
122    #[inline]
123    pub fn kind(&self) -> Kind {
124        Kind::from_len_in_bytes(self.bytes.len())
125    }
126
127    /// The first byte of the hash, commonly used to partition a set of object ids.
128    #[inline]
129    pub fn first_byte(&self) -> u8 {
130        self.bytes[0]
131    }
132
133    /// Interpret this object id as raw byte slice.
134    #[inline]
135    pub fn as_bytes(&self) -> &[u8] {
136        &self.bytes
137    }
138
139    /// Return a type which can display itself in hexadecimal form with the `len` amount of characters.
140    #[gix_macros::unstable(since = "2021-12-21")]
141    #[inline]
142    pub fn to_hex_with_len(&self, len: usize) -> HexDisplay<'_> {
143        HexDisplay {
144            inner: self,
145            hex_len: len,
146        }
147    }
148
149    /// Return a type which displays this `oid` as hex in full.
150    #[gix_macros::unstable(since = "2020-07-16")]
151    #[inline]
152    pub fn to_hex(&self) -> HexDisplay<'_> {
153        HexDisplay {
154            inner: self,
155            hex_len: self.bytes.len() * 2,
156        }
157    }
158
159    /// Return the bytes in `range` as a standalone, byte-aligned [`Prefix`].
160    ///
161    /// The range addresses raw hash bytes, not hexadecimal digits. Thus, each selected byte contributes two hexadecimal
162    /// digits to the returned prefix. The selected bytes become the beginning of the prefix, independently of where they
163    /// occurred in this object ID.
164    ///
165    /// # Panics
166    ///
167    /// If `range` is out of bounds or has its start after its end.
168    #[inline]
169    pub fn to_prefix(&self, range: Range<usize>) -> Prefix {
170        let selected = &self.bytes[range];
171        let mut bytes = ObjectId::null(self.kind());
172        bytes.as_mut_slice()[..selected.len()].copy_from_slice(selected);
173        Prefix {
174            bytes,
175            hex_len: selected.len() * 2,
176        }
177    }
178
179    /// Write ourselves to the `out` in hexadecimal notation, returning the hex-string ready for display.
180    ///
181    /// # Panics
182    ///
183    /// If the buffer isn't big enough to hold twice as many bytes as the current binary size.
184    #[inline]
185    #[must_use]
186    pub fn hex_to_buf<'a>(&self, buf: &'a mut [u8]) -> &'a mut str {
187        let num_hex_bytes = self.bytes.len() * 2;
188        faster_hex::hex_encode(&self.bytes, &mut buf[..num_hex_bytes])
189            .expect("buffer size must be at least twice the hash digest size in bytes")
190    }
191
192    /// Write ourselves to `out` in hexadecimal notation.
193    #[inline]
194    pub fn write_hex_to(&self, out: &mut dyn std::io::Write) -> std::io::Result<()> {
195        let mut hex = Kind::hex_buf();
196        let hex_len = self.hex_to_buf(&mut hex).len();
197        out.write_all(&hex[..hex_len])
198    }
199
200    pub(crate) fn eq_str(&self, other: &str) -> bool {
201        self.to_hex().eq_str(other)
202    }
203
204    /// Returns `true` if this hash consists of all null bytes.
205    #[inline]
206    #[doc(alias = "is_zero", alias = "git2")]
207    pub fn is_null(&self) -> bool {
208        match self.kind() {
209            #[cfg(feature = "sha1")]
210            Kind::Sha1 => &self.bytes == oid::null_sha1().as_bytes(),
211            #[cfg(feature = "sha256")]
212            Kind::Sha256 => &self.bytes == oid::null_sha256().as_bytes(),
213        }
214    }
215
216    /// Returns `true` if this hash is equal to an empty blob.
217    #[inline]
218    pub fn is_empty_blob(&self) -> bool {
219        match self.kind() {
220            #[cfg(feature = "sha1")]
221            Kind::Sha1 => &self.bytes == oid::empty_blob_sha1().as_bytes(),
222            #[cfg(feature = "sha256")]
223            Kind::Sha256 => &self.bytes == oid::empty_blob_sha256().as_bytes(),
224        }
225    }
226
227    /// Returns `true` if this hash is equal to an empty tree.
228    #[inline]
229    pub fn is_empty_tree(&self) -> bool {
230        match self.kind() {
231            #[cfg(feature = "sha1")]
232            Kind::Sha1 => &self.bytes == oid::empty_tree_sha1().as_bytes(),
233            #[cfg(feature = "sha256")]
234            Kind::Sha256 => &self.bytes == oid::empty_tree_sha256().as_bytes(),
235        }
236    }
237}
238
239/// Methods for creating special-case `oid`s (null, empty blob, empty tree)
240impl oid {
241    /// Returns a SHA1 digest with all bytes being initialized to zero.
242    #[inline]
243    #[cfg(feature = "sha1")]
244    pub(crate) fn null_sha1() -> &'static Self {
245        oid::from_bytes([0u8; SIZE_OF_SHA1_DIGEST].as_ref())
246    }
247
248    /// Returns a SHA256 digest with all bytes being initialized to zero.
249    #[inline]
250    #[cfg(feature = "sha256")]
251    pub(crate) fn null_sha256() -> &'static Self {
252        oid::from_bytes([0u8; SIZE_OF_SHA256_DIGEST].as_ref())
253    }
254
255    /// Returns an `oid` representing the SHA1 hash of an empty blob.
256    #[inline]
257    #[cfg(feature = "sha1")]
258    pub(crate) fn empty_blob_sha1() -> &'static Self {
259        oid::from_bytes(EMPTY_BLOB_SHA1)
260    }
261
262    /// Returns an `oid` representing the SHA256 hash of an empty blob.
263    #[inline]
264    #[cfg(feature = "sha256")]
265    pub(crate) fn empty_blob_sha256() -> &'static Self {
266        oid::from_bytes(EMPTY_BLOB_SHA256)
267    }
268
269    /// Returns an `oid` representing the SHA1 hash of an empty tree.
270    #[inline]
271    #[cfg(feature = "sha1")]
272    pub(crate) fn empty_tree_sha1() -> &'static Self {
273        oid::from_bytes(EMPTY_TREE_SHA1)
274    }
275
276    /// Returns an `oid` representing the SHA256 hash of an empty tree.
277    #[inline]
278    #[cfg(feature = "sha256")]
279    pub(crate) fn empty_tree_sha256() -> &'static Self {
280        oid::from_bytes(EMPTY_TREE_SHA256)
281    }
282}
283
284impl AsRef<oid> for &oid {
285    fn as_ref(&self) -> &oid {
286        self
287    }
288}
289
290impl<'a> TryFrom<&'a [u8]> for &'a oid {
291    type Error = gix_error::Error;
292
293    fn try_from(value: &'a [u8]) -> Result<Self> {
294        oid::try_from_bytes(value)
295    }
296}
297
298impl ToOwned for oid {
299    type Owned = ObjectId;
300
301    fn to_owned(&self) -> Self::Owned {
302        match self.kind() {
303            #[cfg(feature = "sha1")]
304            Kind::Sha1 => ObjectId::Sha1(self.bytes.try_into().expect("no bug in hash detection")),
305            #[cfg(feature = "sha256")]
306            Kind::Sha256 => ObjectId::Sha256(self.bytes.try_into().expect("no bug in hash detection")),
307        }
308    }
309}
310
311#[cfg(feature = "sha1")]
312impl<'a> From<&'a [u8; SIZE_OF_SHA1_DIGEST]> for &'a oid {
313    fn from(v: &'a [u8; SIZE_OF_SHA1_DIGEST]) -> Self {
314        oid::from_bytes(v.as_ref())
315    }
316}
317
318#[cfg(feature = "sha256")]
319impl<'a> From<&'a [u8; SIZE_OF_SHA256_DIGEST]> for &'a oid {
320    fn from(v: &'a [u8; SIZE_OF_SHA256_DIGEST]) -> Self {
321        oid::from_bytes(v.as_ref())
322    }
323}
324
325impl std::fmt::Display for &oid {
326    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
327        let mut buf = Kind::hex_buf();
328        f.write_str(self.hex_to_buf(&mut buf))
329    }
330}
331
332impl PartialEq<ObjectId> for &oid {
333    fn eq(&self, other: &ObjectId) -> bool {
334        *self == other.as_ref()
335    }
336}
337
338impl PartialEq<String> for &oid {
339    fn eq(&self, other: &String) -> bool {
340        self.eq_str(other)
341    }
342}
343
344impl PartialEq<&oid> for String {
345    fn eq(&self, other: &&oid) -> bool {
346        other.eq_str(self)
347    }
348}
349
350impl_partial_eq_str!(oid);
351
352/// Manually created from a version that uses a slice, and we forcefully try to convert it into a borrowed array of the desired size
353/// Could be improved by fitting this into serde.
354/// Unfortunately the `serde::Deserialize` derive wouldn't work for borrowed arrays.
355#[cfg(feature = "serde")]
356impl<'de: 'a, 'a> serde::Deserialize<'de> for &'a oid {
357    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, <D as serde::Deserializer<'de>>::Error>
358    where
359        D: serde::Deserializer<'de>,
360    {
361        struct __Visitor<'de: 'a, 'a> {
362            marker: std::marker::PhantomData<&'a oid>,
363            lifetime: std::marker::PhantomData<&'de ()>,
364        }
365        impl<'de: 'a, 'a> serde::de::Visitor<'de> for __Visitor<'de, 'a> {
366            type Value = &'a oid;
367            fn expecting(&self, __formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368                std::fmt::Formatter::write_str(__formatter, "tuple struct Digest")
369            }
370            #[inline]
371            fn visit_newtype_struct<__E>(self, __e: __E) -> std::result::Result<Self::Value, __E::Error>
372            where
373                __E: serde::Deserializer<'de>,
374            {
375                let __field0: &'a [u8] = match <&'a [u8] as serde::Deserialize>::deserialize(__e) {
376                    Ok(__val) => __val,
377                    Err(__err) => {
378                        return Err(__err);
379                    }
380                };
381                Ok(oid::try_from_bytes(__field0).expect("hash of known length"))
382            }
383            #[inline]
384            fn visit_seq<__A>(self, mut __seq: __A) -> std::result::Result<Self::Value, __A::Error>
385            where
386                __A: serde::de::SeqAccess<'de>,
387            {
388                let __field0 = match match serde::de::SeqAccess::next_element::<&'a [u8]>(&mut __seq) {
389                    Ok(__val) => __val,
390                    Err(__err) => {
391                        return Err(__err);
392                    }
393                } {
394                    Some(__value) => __value,
395                    None => {
396                        return Err(serde::de::Error::invalid_length(
397                            0usize,
398                            &"tuple struct Digest with 1 element",
399                        ));
400                    }
401                };
402                Ok(oid::try_from_bytes(__field0).expect("hash of known length"))
403            }
404        }
405        serde::Deserializer::deserialize_newtype_struct(
406            deserializer,
407            "Digest",
408            __Visitor {
409                marker: std::marker::PhantomData::<&'a oid>,
410                lifetime: std::marker::PhantomData,
411            },
412        )
413    }
414}