Skip to main content

gix_object/
kind.rs

1use crate::Kind;
2use gix_error::ExnMessageResult;
3
4/// Initialization
5impl Kind {
6    /// Parse a `Kind` from its serialized loose git objects.
7    /// Invalid kind bytes are stored as `input` in [`gix_error::Message::values`].
8    /// After [wrapping](gix_error::Error::from_error()), inspect them with [metadata](gix_error::Error::metadata()).
9    pub fn from_bytes(s: &[u8]) -> ExnMessageResult<Kind> {
10        Ok(match s {
11            b"tree" => Kind::Tree,
12            b"blob" => Kind::Blob,
13            b"commit" => Kind::Commit,
14            b"tag" => Kind::Tag,
15            _ => return Err(gix_error::validation("Unknown object kind").with("input", s).into()),
16        })
17    }
18}
19
20/// Access
21impl Kind {
22    /// Return the name of `self` for use in serialized loose git objects.
23    pub fn as_bytes(&self) -> &[u8] {
24        match self {
25            Kind::Tree => b"tree",
26            Kind::Commit => b"commit",
27            Kind::Blob => b"blob",
28            Kind::Tag => b"tag",
29        }
30    }
31
32    /// Returns `true` if this instance is representing a commit.
33    pub fn is_commit(&self) -> bool {
34        matches!(self, Kind::Commit)
35    }
36
37    /// Returns `true` if this instance is representing a tree.
38    pub fn is_tree(&self) -> bool {
39        matches!(self, Kind::Tree)
40    }
41
42    /// Returns `true` if this instance is representing a tag.
43    pub fn is_tag(&self) -> bool {
44        matches!(self, Kind::Tag)
45    }
46
47    /// Returns `true` if this instance is representing a blob.
48    pub fn is_blob(&self) -> bool {
49        matches!(self, Kind::Blob)
50    }
51}
52
53impl std::fmt::Display for Kind {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        f.write_str(std::str::from_utf8(self.as_bytes()).expect("Converting Kind name to utf8"))
56    }
57}