Skip to main content

gix_hash/
object_id.rs

1use gix_error::Result;
2use std::{
3    borrow::Borrow,
4    hash::{Hash, Hasher},
5    ops::Deref,
6};
7
8#[cfg(feature = "bstr")]
9use bstr::{BStr, BString, ByteSlice};
10
11use crate::{Kind, borrowed::oid};
12
13#[cfg(feature = "sha1")]
14use crate::{EMPTY_BLOB_SHA1, EMPTY_TREE_SHA1, SIZE_OF_SHA1_DIGEST};
15
16#[cfg(feature = "sha256")]
17use crate::{EMPTY_BLOB_SHA256, EMPTY_TREE_SHA256, SIZE_OF_SHA256_DIGEST};
18
19/// An owned hash identifying objects, most commonly `Sha1`
20#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Copy)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22#[non_exhaustive]
23pub enum ObjectId {
24    /// A SHA1 hash digest
25    #[cfg(feature = "sha1")]
26    Sha1([u8; SIZE_OF_SHA1_DIGEST]),
27    /// A SHA256 hash digest
28    #[cfg(feature = "sha256")]
29    Sha256([u8; SIZE_OF_SHA256_DIGEST]),
30}
31
32// False positive: https://github.com/rust-lang/rust-clippy/issues/2627
33// ignoring some fields while hashing is perfectly valid and just leads to
34// increased HashCollisions. One SHA1 being a prefix of another SHA256 is
35// extremely unlikely to begin with so it doesn't matter.
36// This implementation matches the `Hash` implementation for `oid`
37// and allows the usage of custom Hashers that only copy a truncated ShaHash
38impl Hash for ObjectId {
39    fn hash<H: Hasher>(&self, state: &mut H) {
40        state.write(self.as_slice());
41    }
42}
43
44#[expect(missing_docs)]
45pub mod decode {
46    use gix_error::{Result, message};
47    use std::str::FromStr;
48
49    use crate::object_id::ObjectId;
50
51    #[cfg(feature = "sha1")]
52    use crate::{SIZE_OF_SHA1_DIGEST, SIZE_OF_SHA1_HEX_DIGEST};
53
54    #[cfg(feature = "sha256")]
55    use crate::{SIZE_OF_SHA256_DIGEST, SIZE_OF_SHA256_HEX_DIGEST};
56
57    /// Hash decoding
58    impl ObjectId {
59        /// Create an instance from a `buffer` of 40 bytes or 64 bytes encoded with hexadecimal
60        /// notation. The former will be interpreted as SHA1 while the latter will be interpreted
61        /// as SHA256 when it is enabled.
62        ///
63        /// Such a buffer can be obtained using [`oid::write_hex_to(buffer)`][super::oid::write_hex_to()]
64        pub fn from_hex(buffer: &[u8]) -> Result<ObjectId> {
65            match buffer.len() {
66                #[cfg(feature = "sha1")]
67                SIZE_OF_SHA1_HEX_DIGEST => Ok({
68                    ObjectId::Sha1({
69                        let mut buf = [0; SIZE_OF_SHA1_DIGEST];
70                        faster_hex::hex_decode(buffer, &mut buf)
71                            .map_err(|_| message("Invalid character encountered").validation_error())?;
72                        buf
73                    })
74                }),
75                #[cfg(feature = "sha256")]
76                SIZE_OF_SHA256_HEX_DIGEST => Ok({
77                    ObjectId::Sha256({
78                        let mut buf = [0; SIZE_OF_SHA256_DIGEST];
79                        faster_hex::hex_decode(buffer, &mut buf)
80                            .map_err(|_| message("Invalid character encountered").validation_error())?;
81                        buf
82                    })
83                }),
84                len => Err(message!("A hash sized {len} hexadecimal characters is invalid").validation_error()),
85            }
86        }
87    }
88
89    impl FromStr for ObjectId {
90        type Err = gix_error::Error;
91
92        fn from_str(s: &str) -> Result<Self> {
93            Self::from_hex(s.as_bytes())
94        }
95    }
96}
97
98/// Access and conversion
99impl ObjectId {
100    /// Returns the kind of hash used in this instance.
101    #[inline]
102    pub fn kind(&self) -> Kind {
103        match self {
104            #[cfg(feature = "sha1")]
105            ObjectId::Sha1(_) => Kind::Sha1,
106            #[cfg(feature = "sha256")]
107            ObjectId::Sha256(_) => Kind::Sha256,
108        }
109    }
110    /// Return the raw byte slice representing this hash.
111    #[inline]
112    pub fn as_slice(&self) -> &[u8] {
113        match self {
114            #[cfg(feature = "sha1")]
115            Self::Sha1(b) => b.as_ref(),
116            #[cfg(feature = "sha256")]
117            Self::Sha256(b) => b.as_ref(),
118        }
119    }
120    /// Return the raw mutable byte slice representing this hash.
121    #[inline]
122    pub fn as_mut_slice(&mut self) -> &mut [u8] {
123        match self {
124            #[cfg(feature = "sha1")]
125            Self::Sha1(b) => b.as_mut(),
126            #[cfg(feature = "sha256")]
127            Self::Sha256(b) => b.as_mut(),
128        }
129    }
130
131    /// The hash of an empty blob.
132    #[inline]
133    pub const fn empty_blob(hash: Kind) -> ObjectId {
134        match hash {
135            #[cfg(feature = "sha1")]
136            Kind::Sha1 => ObjectId::Sha1(*EMPTY_BLOB_SHA1),
137            #[cfg(feature = "sha256")]
138            Kind::Sha256 => ObjectId::Sha256(*EMPTY_BLOB_SHA256),
139        }
140    }
141
142    /// The hash of an empty tree.
143    #[inline]
144    pub const fn empty_tree(hash: Kind) -> ObjectId {
145        match hash {
146            #[cfg(feature = "sha1")]
147            Kind::Sha1 => ObjectId::Sha1(*EMPTY_TREE_SHA1),
148            #[cfg(feature = "sha256")]
149            Kind::Sha256 => ObjectId::Sha256(*EMPTY_TREE_SHA256),
150        }
151    }
152
153    /// Returns an instances whose bytes are all zero.
154    #[inline]
155    #[doc(alias = "zero", alias = "git2")]
156    pub const fn null(kind: Kind) -> ObjectId {
157        match kind {
158            #[cfg(feature = "sha1")]
159            Kind::Sha1 => Self::null_sha1(),
160            #[cfg(feature = "sha256")]
161            Kind::Sha256 => Self::null_sha256(),
162        }
163    }
164
165    /// Returns `true` if this hash consists of all null bytes.
166    #[inline]
167    #[doc(alias = "is_zero", alias = "git2")]
168    pub fn is_null(&self) -> bool {
169        match self {
170            #[cfg(feature = "sha1")]
171            ObjectId::Sha1(digest) => &digest[..] == oid::null_sha1().as_bytes(),
172            #[cfg(feature = "sha256")]
173            ObjectId::Sha256(digest) => &digest[..] == oid::null_sha256().as_bytes(),
174        }
175    }
176
177    /// Returns `true` if this hash is equal to an empty blob.
178    #[inline]
179    pub fn is_empty_blob(&self) -> bool {
180        self == &Self::empty_blob(self.kind())
181    }
182
183    /// Returns `true` if this hash is equal to an empty tree.
184    #[inline]
185    pub fn is_empty_tree(&self) -> bool {
186        self == &Self::empty_tree(self.kind())
187    }
188}
189
190/// Lifecycle
191impl ObjectId {
192    /// Convert `bytes` into an owned object Id or panic if the slice length doesn't indicate a supported hash.
193    ///
194    /// Use `Self::try_from(bytes)` for a fallible version.
195    pub fn from_bytes_or_panic(bytes: &[u8]) -> Self {
196        match bytes.len() {
197            #[cfg(feature = "sha1")]
198            SIZE_OF_SHA1_DIGEST => Self::Sha1(bytes.try_into().expect("prior length validation")),
199            #[cfg(feature = "sha256")]
200            SIZE_OF_SHA256_DIGEST => Self::Sha256(bytes.try_into().expect("prior length validation")),
201            other => panic!("BUG: unsupported hash len: {other}"),
202        }
203    }
204}
205
206/// Methods related to SHA1 and SHA256
207impl ObjectId {
208    /// Instantiate an `ObjectId` from a 20 bytes SHA1 digest.
209    #[inline]
210    #[cfg(feature = "sha1")]
211    fn new_sha1(id: [u8; SIZE_OF_SHA1_DIGEST]) -> Self {
212        ObjectId::Sha1(id)
213    }
214
215    /// Instantiate an `ObjectId` from a 32 bytes SHA256 digest.
216    #[inline]
217    #[cfg(feature = "sha256")]
218    fn new_sha256(id: [u8; SIZE_OF_SHA256_DIGEST]) -> Self {
219        ObjectId::Sha256(id)
220    }
221
222    /// Instantiate an `ObjectId` from a borrowed 20 bytes SHA1 digest.
223    ///
224    /// Panics if the slice doesn't have a length of 20.
225    #[inline]
226    #[cfg(feature = "sha1")]
227    pub(crate) fn from_20_bytes(b: &[u8]) -> ObjectId {
228        let mut id = [0; SIZE_OF_SHA1_DIGEST];
229        id.copy_from_slice(b);
230        ObjectId::Sha1(id)
231    }
232
233    /// Instantiate an `ObjectId` from a borrowed 32 bytes SHA256 digest.
234    ///
235    /// Panics if the slice doesn't have a length of 32.
236    #[inline]
237    #[cfg(feature = "sha256")]
238    pub(crate) fn from_32_bytes(b: &[u8]) -> ObjectId {
239        let mut id = [0; SIZE_OF_SHA256_DIGEST];
240        id.copy_from_slice(b);
241        ObjectId::Sha256(id)
242    }
243
244    /// Returns an `ObjectId` representing a SHA1 whose memory is zeroed.
245    #[inline]
246    #[cfg(feature = "sha1")]
247    pub(crate) const fn null_sha1() -> ObjectId {
248        ObjectId::Sha1([0u8; SIZE_OF_SHA1_DIGEST])
249    }
250
251    /// Returns an `ObjectId` representing a SHA256 whose memory is zeroed.
252    #[inline]
253    #[cfg(feature = "sha256")]
254    pub(crate) const fn null_sha256() -> ObjectId {
255        ObjectId::Sha256([0u8; SIZE_OF_SHA256_DIGEST])
256    }
257}
258
259impl std::fmt::Debug for ObjectId {
260    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261        match self {
262            #[cfg(feature = "sha1")]
263            ObjectId::Sha1(_hash) => f.write_str("Sha1(")?,
264            #[cfg(feature = "sha256")]
265            ObjectId::Sha256(_) => f.write_str("Sha256(")?,
266        }
267        for b in self.as_bytes() {
268            write!(f, "{b:02x}")?;
269        }
270        f.write_str(")")
271    }
272}
273
274#[cfg(feature = "sha1")]
275impl From<[u8; SIZE_OF_SHA1_DIGEST]> for ObjectId {
276    fn from(v: [u8; SIZE_OF_SHA1_DIGEST]) -> Self {
277        Self::new_sha1(v)
278    }
279}
280
281#[cfg(feature = "sha256")]
282impl From<[u8; SIZE_OF_SHA256_DIGEST]> for ObjectId {
283    fn from(v: [u8; SIZE_OF_SHA256_DIGEST]) -> Self {
284        Self::new_sha256(v)
285    }
286}
287
288impl From<&oid> for ObjectId {
289    fn from(v: &oid) -> Self {
290        match v.kind() {
291            #[cfg(feature = "sha1")]
292            Kind::Sha1 => ObjectId::from_20_bytes(v.as_bytes()),
293            #[cfg(feature = "sha256")]
294            Kind::Sha256 => ObjectId::from_32_bytes(v.as_bytes()),
295        }
296    }
297}
298
299impl TryFrom<&[u8]> for ObjectId {
300    type Error = gix_error::Error;
301
302    fn try_from(bytes: &[u8]) -> Result<Self> {
303        Ok(oid::try_from_bytes(bytes)?.into())
304    }
305}
306
307impl Deref for ObjectId {
308    type Target = oid;
309
310    fn deref(&self) -> &Self::Target {
311        self.as_ref()
312    }
313}
314
315impl AsRef<oid> for ObjectId {
316    fn as_ref(&self) -> &oid {
317        oid::from_bytes_unchecked(self.as_slice())
318    }
319}
320
321impl Borrow<oid> for ObjectId {
322    fn borrow(&self) -> &oid {
323        self.as_ref()
324    }
325}
326
327impl std::fmt::Display for ObjectId {
328    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
329        write!(f, "{}", self.to_hex())
330    }
331}
332
333impl ObjectId {
334    fn eq_str(&self, other: &str) -> bool {
335        self.as_ref().eq_str(other)
336    }
337
338    #[cfg(feature = "bstr")]
339    fn eq_bstr(&self, other: &BStr) -> bool {
340        let mut hex = Kind::hex_buf();
341        self.as_ref().hex_to_buf(&mut hex).as_bytes() == other.as_bytes()
342    }
343}
344
345impl_partial_eq_str!(ObjectId);
346
347#[cfg(feature = "bstr")]
348impl PartialEq<BStr> for ObjectId {
349    fn eq(&self, other: &BStr) -> bool {
350        self.eq_bstr(other)
351    }
352}
353
354#[cfg(feature = "bstr")]
355impl PartialEq<&BStr> for ObjectId {
356    fn eq(&self, other: &&BStr) -> bool {
357        self.eq_bstr(other)
358    }
359}
360
361#[cfg(feature = "bstr")]
362impl PartialEq<BString> for ObjectId {
363    fn eq(&self, other: &BString) -> bool {
364        self.eq_bstr(other.as_bstr())
365    }
366}
367
368#[cfg(feature = "bstr")]
369impl PartialEq<ObjectId> for BStr {
370    fn eq(&self, other: &ObjectId) -> bool {
371        other.eq_bstr(self)
372    }
373}
374
375#[cfg(feature = "bstr")]
376impl PartialEq<ObjectId> for &BStr {
377    fn eq(&self, other: &ObjectId) -> bool {
378        other.eq_bstr(self)
379    }
380}
381
382#[cfg(feature = "bstr")]
383impl PartialEq<ObjectId> for BString {
384    fn eq(&self, other: &ObjectId) -> bool {
385        other.eq_bstr(self.as_bstr())
386    }
387}
388
389impl PartialEq<&oid> for ObjectId {
390    fn eq(&self, other: &&oid) -> bool {
391        self.as_ref() == *other
392    }
393}