1use core::fmt;
4
5use crate::error::Error;
6
7#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
13pub struct CommitId(pub(crate) [u8; 32]);
14
15impl CommitId {
16 pub fn as_bytes(&self) -> &[u8; 32] {
18 &self.0
19 }
20
21 pub fn from_bytes(bytes: [u8; 32]) -> Self {
28 CommitId(bytes)
29 }
30
31 pub fn to_hex(self) -> String {
33 let mut s = String::with_capacity(64);
34 for b in self.0 {
35 s.push(hex_digit(b >> 4));
36 s.push(hex_digit(b & 0x0f));
37 }
38 s
39 }
40
41 pub fn from_hex(s: &str) -> Result<Self, Error> {
43 let bytes = s.as_bytes();
44 if bytes.len() != 64 {
45 return Err(Error::BadCommitId(s.to_owned()));
46 }
47 let mut out = [0u8; 32];
48 for (i, pair) in bytes.chunks_exact(2).enumerate() {
49 let hi = hex_value(pair[0]).ok_or_else(|| Error::BadCommitId(s.to_owned()))?;
50 let lo = hex_value(pair[1]).ok_or_else(|| Error::BadCommitId(s.to_owned()))?;
51 out[i] = (hi << 4) | lo;
52 }
53 Ok(CommitId(out))
54 }
55}
56
57fn hex_digit(nibble: u8) -> char {
58 match nibble {
59 0..=9 => (b'0' + nibble) as char,
60 _ => (b'a' + nibble - 10) as char,
61 }
62}
63
64fn hex_value(c: u8) -> Option<u8> {
65 match c {
66 b'0'..=b'9' => Some(c - b'0'),
67 b'a'..=b'f' => Some(c - b'a' + 10),
68 b'A'..=b'F' => Some(c - b'A' + 10),
69 _ => None,
70 }
71}
72
73impl fmt::Display for CommitId {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 f.write_str(&self.to_hex())
76 }
77}
78
79impl fmt::Debug for CommitId {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 write!(f, "CommitId({})", self.to_hex())
82 }
83}