1use crate::Error;
2use alloc::string::String;
3use core::{fmt, str::FromStr};
4use sha1::Digest;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
7pub enum ObjectFormat {
8 Sha1,
9 Sha256,
10}
11
12impl ObjectFormat {
13 pub const fn name(self) -> &'static str {
14 match self {
15 Self::Sha1 => "sha1",
16 Self::Sha256 => "sha256",
17 }
18 }
19
20 pub const fn raw_len(self) -> usize {
21 match self {
22 Self::Sha1 => 20,
23 Self::Sha256 => 32,
24 }
25 }
26
27 pub const fn hex_len(self) -> usize {
28 self.raw_len() * 2
29 }
30
31 pub fn from_name(name: &[u8]) -> Option<Self> {
32 match name {
33 b"sha1" => Some(Self::Sha1),
34 b"sha256" => Some(Self::Sha256),
35 _ => None,
36 }
37 }
38}
39
40pub(crate) enum Hasher {
41 Sha1(sha1::Sha1),
42 Sha256(sha2::Sha256),
43}
44
45impl Hasher {
46 pub(crate) fn new(format: ObjectFormat) -> Self {
47 match format {
48 ObjectFormat::Sha1 => Self::Sha1(sha1::Sha1::new()),
49 ObjectFormat::Sha256 => Self::Sha256(sha2::Sha256::new()),
50 }
51 }
52
53 pub(crate) fn update(&mut self, data: &[u8]) {
54 match self {
55 Self::Sha1(hasher) => hasher.update(data),
56 Self::Sha256(hasher) => hasher.update(data),
57 }
58 }
59
60 pub(crate) fn finish(self) -> ObjectId {
61 let mut bytes = [0; 32];
62 let format = match self {
63 Self::Sha1(hasher) => {
64 bytes[..20].copy_from_slice(&hasher.finalize());
65 ObjectFormat::Sha1
66 }
67 Self::Sha256(hasher) => {
68 bytes.copy_from_slice(&hasher.finalize());
69 ObjectFormat::Sha256
70 }
71 };
72 ObjectId { format, bytes }
73 }
74}
75
76#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
77pub struct ObjectId {
78 format: ObjectFormat,
79 bytes: [u8; 32],
80}
81
82impl ObjectId {
83 pub fn from_raw(format: ObjectFormat, raw: &[u8]) -> Option<Self> {
84 if raw.len() != format.raw_len() {
85 return None;
86 }
87 let mut bytes = [0; 32];
88 bytes[..raw.len()].copy_from_slice(raw);
89 Some(Self { format, bytes })
90 }
91
92 pub fn from_hex(hex: &[u8]) -> Option<Self> {
93 match hex.len() {
94 40 => Self::parse_hex(ObjectFormat::Sha1, hex),
95 64 => Self::parse_hex(ObjectFormat::Sha256, hex),
96 _ => None,
97 }
98 }
99
100 pub(crate) fn parse_hex(format: ObjectFormat, hex: &[u8]) -> Option<Self> {
101 if hex.len() != format.hex_len() {
102 return None;
103 }
104 let mut bytes = [0; 32];
105 for (byte, [high, low]) in bytes.iter_mut().zip(hex.as_chunks::<2>().0) {
106 let high = char::from(*high).to_digit(16)?;
107 let low = char::from(*low).to_digit(16)?;
108 *byte = u8::try_from(high << 4 | low).ok()?;
109 }
110 Some(Self { format, bytes })
111 }
112
113 pub const fn format(&self) -> ObjectFormat {
114 self.format
115 }
116
117 pub fn as_bytes(&self) -> &[u8] {
118 &self.bytes[..self.format.raw_len()]
119 }
120
121 pub fn is_null(&self) -> bool {
122 self.as_bytes().iter().all(|&byte| byte == 0)
123 }
124
125 pub fn to_hex(&self) -> String {
126 const DIGITS: &[u8; 16] = b"0123456789abcdef";
127 let mut hex = String::with_capacity(self.format.hex_len());
128 for &byte in self.as_bytes() {
129 hex.push(char::from(DIGITS[usize::from(byte >> 4)]));
130 hex.push(char::from(DIGITS[usize::from(byte & 15)]));
131 }
132 hex
133 }
134}
135
136impl FromStr for ObjectId {
137 type Err = Error;
138
139 fn from_str(hex: &str) -> Result<Self, Error> {
140 Self::from_hex(hex.as_bytes()).ok_or(Error::InvalidObjectId)
141 }
142}
143
144impl fmt::Display for ObjectId {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 f.write_str(&self.to_hex())
147 }
148}
149
150impl fmt::Debug for ObjectId {
151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152 write!(f, "ObjectId({self})")
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159
160 #[test]
161 fn hex_round_trips_in_both_formats() {
162 let sha1 = "22d081ff2d3a40755e97629de92e3bcbfa7cf2ed";
163 let oid: ObjectId = sha1.parse().unwrap();
164 assert_eq!(oid.format(), ObjectFormat::Sha1);
165 assert_eq!(oid.to_hex(), sha1);
166 let upper: ObjectId = sha1.to_ascii_uppercase().parse().unwrap();
167 assert_eq!(upper, oid);
168 let sha256 = "a".repeat(64);
169 assert_eq!(
170 sha256.parse::<ObjectId>().unwrap().format(),
171 ObjectFormat::Sha256
172 );
173 }
174
175 #[test]
176 fn rejects_abbreviated_and_non_hex_ids() {
177 assert_eq!("22d081f".parse::<ObjectId>(), Err(Error::InvalidObjectId));
178 assert_eq!(
179 "g".repeat(40).parse::<ObjectId>(),
180 Err(Error::InvalidObjectId)
181 );
182 assert!(ObjectId::parse_hex(ObjectFormat::Sha256, &[b'0'; 40]).is_none());
183 assert!(ObjectId::from_raw(ObjectFormat::Sha1, &[0; 32]).is_none());
184 }
185}