Skip to main content

gix_object/
kind.rs

1use crate::Kind;
2use gix_error::{Result, bail};
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]) -> Result<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            _ => {
16                bail!(gix_error::validation("Unknown object kind").with_input(s));
17            }
18        })
19    }
20}
21
22/// Access
23impl Kind {
24    /// Return the name of `self` for use in serialized loose git objects.
25    pub fn as_bytes(&self) -> &[u8] {
26        match self {
27            Kind::Tree => b"tree",
28            Kind::Commit => b"commit",
29            Kind::Blob => b"blob",
30            Kind::Tag => b"tag",
31        }
32    }
33
34    /// Returns `true` if this instance is representing a commit.
35    pub fn is_commit(&self) -> bool {
36        matches!(self, Kind::Commit)
37    }
38
39    /// Returns `true` if this instance is representing a tree.
40    pub fn is_tree(&self) -> bool {
41        matches!(self, Kind::Tree)
42    }
43
44    /// Returns `true` if this instance is representing a tag.
45    pub fn is_tag(&self) -> bool {
46        matches!(self, Kind::Tag)
47    }
48
49    /// Returns `true` if this instance is representing a blob.
50    pub fn is_blob(&self) -> bool {
51        matches!(self, Kind::Blob)
52    }
53}
54
55impl std::fmt::Display for Kind {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.write_str(std::str::from_utf8(self.as_bytes()).expect("Converting Kind name to utf8"))
58    }
59}