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#[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
32impl hash::Hash for oid {
38 fn hash<H: hash::Hasher>(&self, state: &mut H) {
39 state.write(self.as_bytes());
40 }
41}
42
43#[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
67impl_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
86impl oid {
88 #[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 pub fn from_bytes_unchecked(value: &[u8]) -> &Self {
103 Self::from_bytes(value)
104 }
105
106 #[inline]
108 pub(crate) fn from_bytes(value: &[u8]) -> &Self {
109 #[expect(unsafe_code)]
113 unsafe {
114 &*(std::ptr::from_ref::<[u8]>(value) as *const oid)
115 }
116 }
117}
118
119impl oid {
121 #[inline]
123 pub fn kind(&self) -> Kind {
124 Kind::from_len_in_bytes(self.bytes.len())
125 }
126
127 #[inline]
129 pub fn first_byte(&self) -> u8 {
130 self.bytes[0]
131 }
132
133 #[inline]
135 pub fn as_bytes(&self) -> &[u8] {
136 &self.bytes
137 }
138
139 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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
239impl oid {
241 #[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 #[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 #[inline]
257 #[cfg(feature = "sha1")]
258 pub(crate) fn empty_blob_sha1() -> &'static Self {
259 oid::from_bytes(EMPTY_BLOB_SHA1)
260 }
261
262 #[inline]
264 #[cfg(feature = "sha256")]
265 pub(crate) fn empty_blob_sha256() -> &'static Self {
266 oid::from_bytes(EMPTY_BLOB_SHA256)
267 }
268
269 #[inline]
271 #[cfg(feature = "sha1")]
272 pub(crate) fn empty_tree_sha1() -> &'static Self {
273 oid::from_bytes(EMPTY_TREE_SHA1)
274 }
275
276 #[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#[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}