gix-hash 0.26.2

Borrowed and owned git hash digests used to identify git objects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use std::{
    borrow::Borrow,
    hash::{Hash, Hasher},
    ops::Deref,
};

#[cfg(feature = "bstr")]
use bstr::{BStr, BString, ByteSlice};

use crate::{Kind, borrowed::oid};

#[cfg(feature = "sha1")]
use crate::{EMPTY_BLOB_SHA1, EMPTY_TREE_SHA1, SIZE_OF_SHA1_DIGEST};

#[cfg(feature = "sha256")]
use crate::{EMPTY_BLOB_SHA256, EMPTY_TREE_SHA256, SIZE_OF_SHA256_DIGEST};

/// An owned hash identifying objects, most commonly `Sha1`
#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ObjectId {
    /// A SHA1 hash digest
    #[cfg(feature = "sha1")]
    Sha1([u8; SIZE_OF_SHA1_DIGEST]),
    /// A SHA256 hash digest
    #[cfg(feature = "sha256")]
    Sha256([u8; SIZE_OF_SHA256_DIGEST]),
}

// False positive: https://github.com/rust-lang/rust-clippy/issues/2627
// ignoring some fields while hashing is perfectly valid and just leads to
// increased HashCollisions. One SHA1 being a prefix of another SHA256 is
// extremely unlikely to begin with so it doesn't matter.
// This implementation matches the `Hash` implementation for `oid`
// and allows the usage of custom Hashers that only copy a truncated ShaHash
impl Hash for ObjectId {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write(self.as_slice());
    }
}

#[expect(missing_docs)]
pub mod decode {
    use std::str::FromStr;

    use crate::object_id::ObjectId;

    #[cfg(feature = "sha1")]
    use crate::{SIZE_OF_SHA1_DIGEST, SIZE_OF_SHA1_HEX_DIGEST};

    #[cfg(feature = "sha256")]
    use crate::{SIZE_OF_SHA256_DIGEST, SIZE_OF_SHA256_HEX_DIGEST};

    /// An error returned by [`ObjectId::from_hex()`][crate::ObjectId::from_hex()]
    #[derive(Debug, thiserror::Error)]
    #[expect(missing_docs)]
    pub enum Error {
        #[error("A hash sized {0} hexadecimal characters is invalid")]
        InvalidHexEncodingLength(usize),
        #[error("Invalid character encountered")]
        Invalid,
    }

    /// Hash decoding
    impl ObjectId {
        /// Create an instance from a `buffer` of 40 bytes or 64 bytes encoded with hexadecimal
        /// notation. The former will be interpreted as SHA1 while the latter will be interpreted
        /// as SHA256 when it is enabled.
        ///
        /// Such a buffer can be obtained using [`oid::write_hex_to(buffer)`][super::oid::write_hex_to()]
        pub fn from_hex(buffer: &[u8]) -> Result<ObjectId, Error> {
            match buffer.len() {
                #[cfg(feature = "sha1")]
                SIZE_OF_SHA1_HEX_DIGEST => Ok({
                    ObjectId::Sha1({
                        let mut buf = [0; SIZE_OF_SHA1_DIGEST];
                        faster_hex::hex_decode(buffer, &mut buf).map_err(|err| match err {
                            faster_hex::Error::InvalidChar | faster_hex::Error::Overflow => Error::Invalid,
                            faster_hex::Error::InvalidLength(_) => {
                                unreachable!("BUG: This is already checked")
                            }
                        })?;
                        buf
                    })
                }),
                #[cfg(feature = "sha256")]
                SIZE_OF_SHA256_HEX_DIGEST => Ok({
                    ObjectId::Sha256({
                        let mut buf = [0; SIZE_OF_SHA256_DIGEST];
                        faster_hex::hex_decode(buffer, &mut buf).map_err(|err| match err {
                            faster_hex::Error::InvalidChar | faster_hex::Error::Overflow => Error::Invalid,
                            faster_hex::Error::InvalidLength(_) => {
                                unreachable!("BUG: This is already checked")
                            }
                        })?;
                        buf
                    })
                }),
                len => Err(Error::InvalidHexEncodingLength(len)),
            }
        }
    }

    impl FromStr for ObjectId {
        type Err = Error;

        fn from_str(s: &str) -> Result<Self, Self::Err> {
            Self::from_hex(s.as_bytes())
        }
    }
}

/// Access and conversion
impl ObjectId {
    /// Returns the kind of hash used in this instance.
    #[inline]
    pub fn kind(&self) -> Kind {
        match self {
            #[cfg(feature = "sha1")]
            ObjectId::Sha1(_) => Kind::Sha1,
            #[cfg(feature = "sha256")]
            ObjectId::Sha256(_) => Kind::Sha256,
        }
    }
    /// Return the raw byte slice representing this hash.
    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        match self {
            #[cfg(feature = "sha1")]
            Self::Sha1(b) => b.as_ref(),
            #[cfg(feature = "sha256")]
            Self::Sha256(b) => b.as_ref(),
        }
    }
    /// Return the raw mutable byte slice representing this hash.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        match self {
            #[cfg(feature = "sha1")]
            Self::Sha1(b) => b.as_mut(),
            #[cfg(feature = "sha256")]
            Self::Sha256(b) => b.as_mut(),
        }
    }

    /// The hash of an empty blob.
    #[inline]
    pub const fn empty_blob(hash: Kind) -> ObjectId {
        match hash {
            #[cfg(feature = "sha1")]
            Kind::Sha1 => ObjectId::Sha1(*EMPTY_BLOB_SHA1),
            #[cfg(feature = "sha256")]
            Kind::Sha256 => ObjectId::Sha256(*EMPTY_BLOB_SHA256),
        }
    }

    /// The hash of an empty tree.
    #[inline]
    pub const fn empty_tree(hash: Kind) -> ObjectId {
        match hash {
            #[cfg(feature = "sha1")]
            Kind::Sha1 => ObjectId::Sha1(*EMPTY_TREE_SHA1),
            #[cfg(feature = "sha256")]
            Kind::Sha256 => ObjectId::Sha256(*EMPTY_TREE_SHA256),
        }
    }

    /// Returns an instances whose bytes are all zero.
    #[inline]
    #[doc(alias = "zero", alias = "git2")]
    pub const fn null(kind: Kind) -> ObjectId {
        match kind {
            #[cfg(feature = "sha1")]
            Kind::Sha1 => Self::null_sha1(),
            #[cfg(feature = "sha256")]
            Kind::Sha256 => Self::null_sha256(),
        }
    }

    /// Returns `true` if this hash consists of all null bytes.
    #[inline]
    #[doc(alias = "is_zero", alias = "git2")]
    pub fn is_null(&self) -> bool {
        match self {
            #[cfg(feature = "sha1")]
            ObjectId::Sha1(digest) => &digest[..] == oid::null_sha1().as_bytes(),
            #[cfg(feature = "sha256")]
            ObjectId::Sha256(digest) => &digest[..] == oid::null_sha256().as_bytes(),
        }
    }

    /// Returns `true` if this hash is equal to an empty blob.
    #[inline]
    pub fn is_empty_blob(&self) -> bool {
        self == &Self::empty_blob(self.kind())
    }

    /// Returns `true` if this hash is equal to an empty tree.
    #[inline]
    pub fn is_empty_tree(&self) -> bool {
        self == &Self::empty_tree(self.kind())
    }
}

/// Lifecycle
impl ObjectId {
    /// Convert `bytes` into an owned object Id or panic if the slice length doesn't indicate a supported hash.
    ///
    /// Use `Self::try_from(bytes)` for a fallible version.
    pub fn from_bytes_or_panic(bytes: &[u8]) -> Self {
        match bytes.len() {
            #[cfg(feature = "sha1")]
            SIZE_OF_SHA1_DIGEST => Self::Sha1(bytes.try_into().expect("prior length validation")),
            #[cfg(feature = "sha256")]
            SIZE_OF_SHA256_DIGEST => Self::Sha256(bytes.try_into().expect("prior length validation")),
            other => panic!("BUG: unsupported hash len: {other}"),
        }
    }
}

/// Methods related to SHA1 and SHA256
impl ObjectId {
    /// Instantiate an `ObjectId` from a 20 bytes SHA1 digest.
    #[inline]
    #[cfg(feature = "sha1")]
    fn new_sha1(id: [u8; SIZE_OF_SHA1_DIGEST]) -> Self {
        ObjectId::Sha1(id)
    }

    /// Instantiate an `ObjectId` from a 32 bytes SHA256 digest.
    #[inline]
    #[cfg(feature = "sha256")]
    fn new_sha256(id: [u8; SIZE_OF_SHA256_DIGEST]) -> Self {
        ObjectId::Sha256(id)
    }

    /// Instantiate an `ObjectId` from a borrowed 20 bytes SHA1 digest.
    ///
    /// Panics if the slice doesn't have a length of 20.
    #[inline]
    #[cfg(feature = "sha1")]
    pub(crate) fn from_20_bytes(b: &[u8]) -> ObjectId {
        let mut id = [0; SIZE_OF_SHA1_DIGEST];
        id.copy_from_slice(b);
        ObjectId::Sha1(id)
    }

    /// Instantiate an `ObjectId` from a borrowed 32 bytes SHA256 digest.
    ///
    /// Panics if the slice doesn't have a length of 32.
    #[inline]
    #[cfg(feature = "sha256")]
    pub(crate) fn from_32_bytes(b: &[u8]) -> ObjectId {
        let mut id = [0; SIZE_OF_SHA256_DIGEST];
        id.copy_from_slice(b);
        ObjectId::Sha256(id)
    }

    /// Returns an `ObjectId` representing a SHA1 whose memory is zeroed.
    #[inline]
    #[cfg(feature = "sha1")]
    pub(crate) const fn null_sha1() -> ObjectId {
        ObjectId::Sha1([0u8; SIZE_OF_SHA1_DIGEST])
    }

    /// Returns an `ObjectId` representing a SHA256 whose memory is zeroed.
    #[inline]
    #[cfg(feature = "sha256")]
    pub(crate) const fn null_sha256() -> ObjectId {
        ObjectId::Sha256([0u8; SIZE_OF_SHA256_DIGEST])
    }
}

impl std::fmt::Debug for ObjectId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            #[cfg(feature = "sha1")]
            ObjectId::Sha1(_hash) => f.write_str("Sha1(")?,
            #[cfg(feature = "sha256")]
            ObjectId::Sha256(_) => f.write_str("Sha256(")?,
        }
        for b in self.as_bytes() {
            write!(f, "{b:02x}")?;
        }
        f.write_str(")")
    }
}

#[cfg(feature = "sha1")]
impl From<[u8; SIZE_OF_SHA1_DIGEST]> for ObjectId {
    fn from(v: [u8; SIZE_OF_SHA1_DIGEST]) -> Self {
        Self::new_sha1(v)
    }
}

#[cfg(feature = "sha256")]
impl From<[u8; SIZE_OF_SHA256_DIGEST]> for ObjectId {
    fn from(v: [u8; SIZE_OF_SHA256_DIGEST]) -> Self {
        Self::new_sha256(v)
    }
}

impl From<&oid> for ObjectId {
    fn from(v: &oid) -> Self {
        match v.kind() {
            #[cfg(feature = "sha1")]
            Kind::Sha1 => ObjectId::from_20_bytes(v.as_bytes()),
            #[cfg(feature = "sha256")]
            Kind::Sha256 => ObjectId::from_32_bytes(v.as_bytes()),
        }
    }
}

impl TryFrom<&[u8]> for ObjectId {
    type Error = crate::Error;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        Ok(oid::try_from_bytes(bytes)?.into())
    }
}

impl Deref for ObjectId {
    type Target = oid;

    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl AsRef<oid> for ObjectId {
    fn as_ref(&self) -> &oid {
        oid::from_bytes_unchecked(self.as_slice())
    }
}

impl Borrow<oid> for ObjectId {
    fn borrow(&self) -> &oid {
        self.as_ref()
    }
}

impl std::fmt::Display for ObjectId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_hex())
    }
}

impl ObjectId {
    fn eq_str(&self, other: &str) -> bool {
        self.as_ref().eq_str(other)
    }

    #[cfg(feature = "bstr")]
    fn eq_bstr(&self, other: &BStr) -> bool {
        let mut hex = Kind::hex_buf();
        self.as_ref().hex_to_buf(&mut hex).as_bytes() == other.as_bytes()
    }
}

impl_partial_eq_str!(ObjectId);

#[cfg(feature = "bstr")]
impl PartialEq<BStr> for ObjectId {
    fn eq(&self, other: &BStr) -> bool {
        self.eq_bstr(other)
    }
}

#[cfg(feature = "bstr")]
impl PartialEq<&BStr> for ObjectId {
    fn eq(&self, other: &&BStr) -> bool {
        self.eq_bstr(other)
    }
}

#[cfg(feature = "bstr")]
impl PartialEq<BString> for ObjectId {
    fn eq(&self, other: &BString) -> bool {
        self.eq_bstr(other.as_bstr())
    }
}

#[cfg(feature = "bstr")]
impl PartialEq<ObjectId> for BStr {
    fn eq(&self, other: &ObjectId) -> bool {
        other.eq_bstr(self)
    }
}

#[cfg(feature = "bstr")]
impl PartialEq<ObjectId> for &BStr {
    fn eq(&self, other: &ObjectId) -> bool {
        other.eq_bstr(self)
    }
}

#[cfg(feature = "bstr")]
impl PartialEq<ObjectId> for BString {
    fn eq(&self, other: &ObjectId) -> bool {
        other.eq_bstr(self.as_bstr())
    }
}

impl PartialEq<&oid> for ObjectId {
    fn eq(&self, other: &&oid) -> bool {
        self.as_ref() == *other
    }
}