1use std::str::FromStr;
2
3use crate::{oid, Kind, ObjectId};
4
5impl TryFrom<u8> for Kind {
6 type Error = u8;
7
8 fn try_from(value: u8) -> Result<Self, Self::Error> {
9 Ok(match value {
10 1 => Kind::Sha1,
11 unknown => return Err(unknown),
12 })
13 }
14}
15
16impl FromStr for Kind {
17 type Err = String;
18
19 fn from_str(s: &str) -> Result<Self, Self::Err> {
20 Ok(match s {
21 "sha1" | "SHA1" => Kind::Sha1,
22 other => return Err(other.into()),
23 })
24 }
25}
26
27impl std::fmt::Display for Kind {
28 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 match self {
30 Kind::Sha1 => f.write_str("SHA1"),
31 }
32 }
33}
34
35impl Kind {
36 #[inline]
38 pub const fn shortest() -> Self {
39 Self::Sha1
40 }
41
42 #[inline]
44 pub const fn longest() -> Self {
45 Self::Sha1
46 }
47
48 #[inline]
50 pub const fn hex_buf() -> [u8; Kind::longest().len_in_hex()] {
51 [0u8; Kind::longest().len_in_hex()]
52 }
53
54 #[inline]
56 pub const fn buf() -> [u8; Kind::longest().len_in_bytes()] {
57 [0u8; Kind::longest().len_in_bytes()]
58 }
59
60 #[inline]
62 pub const fn len_in_hex(&self) -> usize {
63 match self {
64 Kind::Sha1 => 40,
65 }
66 }
67 #[inline]
69 pub const fn len_in_bytes(&self) -> usize {
70 match self {
71 Kind::Sha1 => 20,
72 }
73 }
74
75 #[inline]
78 pub const fn from_hex_len(hex_len: usize) -> Option<Self> {
79 Some(match hex_len {
80 0..=40 => Kind::Sha1,
81 _ => return None,
82 })
83 }
84
85 #[inline]
94 pub(crate) fn from_len_in_bytes(bytes: usize) -> Self {
95 match bytes {
96 20 => Kind::Sha1,
97 _ => panic!("BUG: must be called only with valid hash lengths produced by len_in_bytes()"),
98 }
99 }
100
101 #[inline]
103 pub fn null_ref(&self) -> &'static oid {
104 match self {
105 Kind::Sha1 => oid::null_sha1(),
106 }
107 }
108
109 #[inline]
111 pub const fn null(&self) -> ObjectId {
112 match self {
113 Kind::Sha1 => ObjectId::null_sha1(),
114 }
115 }
116}