crates/repo/src/oid.rs 3.9 KiB raw
1
//! Object identifier parsing and formatting.
2
3
use std::str::FromStr;
4
use std::{fmt, str};
5
6
use serde::de::{Deserialize, Scalar, Visitor};
7
use serde::ser::{Fragment, Serialize};
8
9
/// Number of bytes in a SHA-1 object digest.
10
const SHA1_LEN: usize = 20;
11
/// Number of bytes in a SHA-256 object digest.
12
const SHA256_LEN: usize = 32;
13
/// Number of leading hash characters shown as an abbreviated object id.
14
const SHORT_LEN: usize = 9;
15
16
/// Object identifier as it appears in a Git diff header or rev-parse output.
17
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
18
pub enum Oid {
19
    /// A SHA-1 hash digest.
20
    Sha1([u8; SHA1_LEN]),
21
    /// A SHA-256 hash digest.
22
    Sha256([u8; SHA256_LEN]),
23
}
24
25
impl Oid {
26
    /// Returns the abbreviated object id used in compact displays.
27
    pub fn short(&self) -> String {
28
        self.to_string()[..SHORT_LEN].to_owned()
29
    }
30
31
    /// Returns whether every byte in the object identifier is zero.
32
    pub fn is_zero(&self) -> bool {
33
        match self {
34
            Self::Sha1(bytes) => bytes.iter().all(|byte| *byte == 0),
35
            Self::Sha256(bytes) => bytes.iter().all(|byte| *byte == 0),
36
        }
37
    }
38
}
39
40
impl FromStr for Oid {
41
    type Err = OidError;
42
43
    fn from_str(input: &str) -> Result<Self, Self::Err> {
44
        match input.len() {
45
            40 => {
46
                let mut bytes = [0; SHA1_LEN];
47
                parse_hex(input, &mut bytes)?;
48
                Ok(Self::Sha1(bytes))
49
            }
50
            64 => {
51
                let mut bytes = [0; SHA256_LEN];
52
                parse_hex(input, &mut bytes)?;
53
                Ok(Self::Sha256(bytes))
54
            }
55
            _ => Err(OidError),
56
        }
57
    }
58
}
59
60
impl Serialize for Oid {
61
    fn begin(&self) -> Fragment<'_> {
62
        Fragment::Str(self.to_string().into())
63
    }
64
}
65
66
/// Visitor that parses an object identifier from its hexadecimal string form.
67
pub struct OidVisitor<'a> {
68
    /// Output slot the parsed object identifier is written into.
69
    out: &'a mut Option<Oid>,
70
}
71
72
impl Visitor for OidVisitor<'_> {
73
    fn scalar(&mut self, s: &Scalar) -> serde::Result<()> {
74
        let Scalar::Str(value) = s else {
75
            return Err(serde::Error);
76
        };
77
        *self.out = Some(value.parse().map_err(|_| serde::Error)?);
78
        Ok(())
79
    }
80
}
81
82
impl Deserialize for Oid {
83
    type Visitor<'a> = OidVisitor<'a>;
84
85
    fn begin(out: &mut Option<Self>) -> Self::Visitor<'_> {
86
        OidVisitor { out }
87
    }
88
}
89
90
impl TryFrom<&[u8]> for Oid {
91
    type Error = OidError;
92
93
    fn try_from(input: &[u8]) -> Result<Self, Self::Error> {
94
        let input = str::from_utf8(input).map_err(|_| OidError)?;
95
        input.trim().parse()
96
    }
97
}
98
99
impl fmt::Display for Oid {
100
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101
        let bytes: &[u8] = match self {
102
            Self::Sha1(bytes) => bytes,
103
            Self::Sha256(bytes) => bytes,
104
        };
105
        for byte in bytes {
106
            write!(f, "{byte:02x}")?;
107
        }
108
        Ok(())
109
    }
110
}
111
112
/// Error returned when an object identifier is malformed.
113
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
114
pub struct OidError;
115
116
impl fmt::Display for OidError {
117
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118
        f.write_str("object id must be non-empty hexadecimal text")
119
    }
120
}
121
122
impl std::error::Error for OidError {}
123
124
/// Parses a hexadecimal digest string into `out`.
125
fn parse_hex(input: &str, out: &mut [u8]) -> Result<(), OidError> {
126
    for (index, chunk) in input.as_bytes().chunks_exact(2).enumerate() {
127
        let high = hex_val(chunk[0])?;
128
        let low = hex_val(chunk[1])?;
129
        out[index] = (high << 4) | low;
130
    }
131
    Ok(())
132
}
133
134
/// Returns the numeric value of one ASCII hex digit.
135
fn hex_val(byte: u8) -> Result<u8, OidError> {
136
    match byte {
137
        b'0'..=b'9' => Ok(byte - b'0'),
138
        b'a'..=b'f' => Ok(byte - b'a' + 10),
139
        b'A'..=b'F' => Ok(byte - b'A' + 10),
140
        _ => Err(OidError),
141
    }
142
}