Skip to main content

radicle_git_ext/
oid.rs

1use std::{
2    convert::TryFrom,
3    fmt::{self, Display},
4    ops::Deref,
5    str::FromStr,
6};
7
8/// Serializable [`git2::Oid`]
9#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
10pub struct Oid(git2::Oid);
11
12impl Oid {
13    pub fn from_str_ext(s: &str, format: git2::ObjectFormat) -> Result<Self, git2::Error> {
14        Ok(Self(git2::Oid::from_str_ext(s, format)?))
15    }
16}
17
18#[cfg(feature = "serde")]
19mod serde_impls {
20    use super::*;
21    use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
22
23    impl Serialize for Oid {
24        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
25        where
26            S: Serializer,
27        {
28            self.0.to_string().serialize(serializer)
29        }
30    }
31
32    impl<'de> Deserialize<'de> for Oid {
33        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
34        where
35            D: Deserializer<'de>,
36        {
37            struct OidVisitor;
38
39            impl Visitor<'_> for OidVisitor {
40                type Value = Oid;
41
42                fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
43                    write!(f, "a hexidecimal git2::Oid")
44                }
45
46                fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
47                where
48                    E: serde::de::Error,
49                {
50                    s.parse().map_err(serde::de::Error::custom)
51                }
52            }
53
54            deserializer.deserialize_str(OidVisitor)
55        }
56    }
57}
58
59impl Deref for Oid {
60    type Target = git2::Oid;
61
62    fn deref(&self) -> &Self::Target {
63        &self.0
64    }
65}
66
67impl AsRef<git2::Oid> for Oid {
68    fn as_ref(&self) -> &git2::Oid {
69        self
70    }
71}
72
73impl AsRef<[u8]> for Oid {
74    fn as_ref(&self) -> &[u8] {
75        self.as_bytes()
76    }
77}
78
79impl From<git2::Oid> for Oid {
80    fn from(oid: git2::Oid) -> Self {
81        Self(oid)
82    }
83}
84
85impl From<Oid> for git2::Oid {
86    fn from(oid: Oid) -> Self {
87        oid.0
88    }
89}
90
91impl Display for Oid {
92    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93        self.0.fmt(f)
94    }
95}
96
97impl TryFrom<&str> for Oid {
98    type Error = git2::Error;
99
100    fn try_from(s: &str) -> Result<Self, Self::Error> {
101        s.parse().map(Self)
102    }
103}
104
105impl FromStr for Oid {
106    type Err = git2::Error;
107
108    fn from_str(s: &str) -> Result<Self, Self::Err> {
109        Self::try_from(s)
110    }
111}
112
113impl TryFrom<&[u8]> for Oid {
114    type Error = git2::Error;
115
116    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
117        git2::Oid::from_bytes(bytes).map(Self)
118    }
119}