gix_object/
kind.rs

1use std::fmt;
2
3use crate::Kind;
4
5/// The Error used in [`Kind::from_bytes()`].
6#[derive(Debug, Clone, thiserror::Error)]
7#[allow(missing_docs)]
8pub enum Error {
9    #[error("Unknown object kind: {kind:?}")]
10    InvalidObjectKind { kind: bstr::BString },
11}
12
13/// Initialization
14impl Kind {
15    /// Parse a `Kind` from its serialized loose git objects.
16    pub fn from_bytes(s: &[u8]) -> Result<Kind, Error> {
17        Ok(match s {
18            b"tree" => Kind::Tree,
19            b"blob" => Kind::Blob,
20            b"commit" => Kind::Commit,
21            b"tag" => Kind::Tag,
22            _ => return Err(Error::InvalidObjectKind { kind: s.into() }),
23        })
24    }
25}
26
27/// Access
28impl Kind {
29    /// Return the name of `self` for use in serialized loose git objects.
30    pub fn as_bytes(&self) -> &[u8] {
31        match self {
32            Kind::Tree => b"tree",
33            Kind::Commit => b"commit",
34            Kind::Blob => b"blob",
35            Kind::Tag => b"tag",
36        }
37    }
38
39    /// Returns `true` if this instance is representing a commit.
40    pub fn is_commit(&self) -> bool {
41        matches!(self, Kind::Commit)
42    }
43
44    /// Returns `true` if this instance is representing a tree.
45    pub fn is_tree(&self) -> bool {
46        matches!(self, Kind::Tree)
47    }
48
49    /// Returns `true` if this instance is representing a tag.
50    pub fn is_tag(&self) -> bool {
51        matches!(self, Kind::Tag)
52    }
53
54    /// Returns `true` if this instance is representing a blob.
55    pub fn is_blob(&self) -> bool {
56        matches!(self, Kind::Blob)
57    }
58}
59
60impl fmt::Display for Kind {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.write_str(std::str::from_utf8(self.as_bytes()).expect("Converting Kind name to utf8"))
63    }
64}