//! Object identifier parsing and formatting. use std::str::FromStr; use std::{fmt, str}; use serde::de::{Deserialize, Scalar, Visitor}; use serde::ser::{Fragment, Serialize}; /// Number of bytes in a SHA-1 object digest. const SHA1_LEN: usize = 20; /// Number of bytes in a SHA-256 object digest. const SHA256_LEN: usize = 32; /// Number of leading hash characters shown as an abbreviated object id. const SHORT_LEN: usize = 9; /// Object identifier as it appears in a Git diff header or rev-parse output. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum Oid { /// A SHA-1 hash digest. Sha1([u8; SHA1_LEN]), /// A SHA-256 hash digest. Sha256([u8; SHA256_LEN]), } impl Oid { /// Returns the abbreviated object id used in compact displays. pub fn short(&self) -> String { self.to_string()[..SHORT_LEN].to_owned() } /// Returns whether every byte in the object identifier is zero. pub fn is_zero(&self) -> bool { match self { Self::Sha1(bytes) => bytes.iter().all(|byte| *byte == 0), Self::Sha256(bytes) => bytes.iter().all(|byte| *byte == 0), } } } impl FromStr for Oid { type Err = OidError; fn from_str(input: &str) -> Result { match input.len() { 40 => { let mut bytes = [0; SHA1_LEN]; parse_hex(input, &mut bytes)?; Ok(Self::Sha1(bytes)) } 64 => { let mut bytes = [0; SHA256_LEN]; parse_hex(input, &mut bytes)?; Ok(Self::Sha256(bytes)) } _ => Err(OidError), } } } impl Serialize for Oid { fn begin(&self) -> Fragment<'_> { Fragment::Str(self.to_string().into()) } } /// Visitor that parses an object identifier from its hexadecimal string form. pub struct OidVisitor<'a> { /// Output slot the parsed object identifier is written into. out: &'a mut Option, } impl Visitor for OidVisitor<'_> { fn scalar(&mut self, s: &Scalar) -> serde::Result<()> { let Scalar::Str(value) = s else { return Err(serde::Error); }; *self.out = Some(value.parse().map_err(|_| serde::Error)?); Ok(()) } } impl Deserialize for Oid { type Visitor<'a> = OidVisitor<'a>; fn begin(out: &mut Option) -> Self::Visitor<'_> { OidVisitor { out } } } impl TryFrom<&[u8]> for Oid { type Error = OidError; fn try_from(input: &[u8]) -> Result { let input = str::from_utf8(input).map_err(|_| OidError)?; input.trim().parse() } } impl fmt::Display for Oid { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let bytes: &[u8] = match self { Self::Sha1(bytes) => bytes, Self::Sha256(bytes) => bytes, }; for byte in bytes { write!(f, "{byte:02x}")?; } Ok(()) } } /// Error returned when an object identifier is malformed. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct OidError; impl fmt::Display for OidError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("object id must be non-empty hexadecimal text") } } impl std::error::Error for OidError {} /// Parses a hexadecimal digest string into `out`. fn parse_hex(input: &str, out: &mut [u8]) -> Result<(), OidError> { for (index, chunk) in input.as_bytes().chunks_exact(2).enumerate() { let high = hex_val(chunk[0])?; let low = hex_val(chunk[1])?; out[index] = (high << 4) | low; } Ok(()) } /// Returns the numeric value of one ASCII hex digit. fn hex_val(byte: u8) -> Result { match byte { b'0'..=b'9' => Ok(byte - b'0'), b'a'..=b'f' => Ok(byte - b'a' + 10), b'A'..=b'F' => Ok(byte - b'A' + 10), _ => Err(OidError), } }