gix_actor/
identity.rs

1use bstr::ByteSlice;
2use winnow::{error::StrContext, prelude::*};
3
4use crate::{signature::decode, Identity, IdentityRef};
5
6impl<'a> IdentityRef<'a> {
7    /// Deserialize an identity from the given `data`.
8    pub fn from_bytes<E>(mut data: &'a [u8]) -> Result<Self, winnow::error::ErrMode<E>>
9    where
10        E: winnow::error::ParserError<&'a [u8]> + winnow::error::AddContext<&'a [u8], StrContext>,
11    {
12        decode::identity.parse_next(&mut data)
13    }
14
15    /// Create an owned instance from this shared one.
16    pub fn to_owned(&self) -> Identity {
17        Identity {
18            name: self.name.to_owned(),
19            email: self.email.to_owned(),
20        }
21    }
22
23    /// Trim whitespace surrounding the name and email and return a new identity.
24    pub fn trim(&self) -> IdentityRef<'a> {
25        IdentityRef {
26            name: self.name.trim().as_bstr(),
27            email: self.email.trim().as_bstr(),
28        }
29    }
30}
31
32mod write {
33    use crate::{signature::write::validated_token, Identity, IdentityRef};
34
35    /// Output
36    impl Identity {
37        /// Serialize this instance to `out` in the git serialization format for signatures (but without timestamp).
38        pub fn write_to(&self, out: &mut dyn std::io::Write) -> std::io::Result<()> {
39            self.to_ref().write_to(out)
40        }
41    }
42
43    impl IdentityRef<'_> {
44        /// Serialize this instance to `out` in the git serialization format for signatures (but without timestamp).
45        pub fn write_to(&self, out: &mut dyn std::io::Write) -> std::io::Result<()> {
46            out.write_all(validated_token(self.name)?)?;
47            out.write_all(b" ")?;
48            out.write_all(b"<")?;
49            out.write_all(validated_token(self.email)?)?;
50            out.write_all(b">")
51        }
52    }
53}
54
55mod impls {
56    use crate::{Identity, IdentityRef};
57
58    impl Identity {
59        /// Borrow this instance as immutable
60        pub fn to_ref(&self) -> IdentityRef<'_> {
61            IdentityRef {
62                name: self.name.as_ref(),
63                email: self.email.as_ref(),
64            }
65        }
66    }
67
68    impl From<IdentityRef<'_>> for Identity {
69        fn from(other: IdentityRef<'_>) -> Identity {
70            let IdentityRef { name, email } = other;
71            Identity {
72                name: name.to_owned(),
73                email: email.to_owned(),
74            }
75        }
76    }
77
78    impl<'a> From<&'a Identity> for IdentityRef<'a> {
79        fn from(other: &'a Identity) -> IdentityRef<'a> {
80            other.to_ref()
81        }
82    }
83}