Skip to main content

ostrya_core/
objname.rs

1//! An object name: a checksum paired with its object type.
2//!
3//! Reachability traversal, prune, and fsck work over sets of object names, so
4//! the two coordinates that identify a loose object travel together. The string
5//! form is `<hexchecksum>.<typestr>` (the tool's object reference), where the
6//! type string is mode-independent -- a content object is `file` even in
7//! archive mode, where its loose path carries the `z` suffix.
8
9use crate::checksum::Checksum;
10use crate::loosepath::loose_path;
11use crate::mode::RepoMode;
12use crate::objtype::ObjectType;
13
14/// A checksum together with the object type it identifies.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub struct ObjectName {
17    /// The object's SHA-256 identity.
18    pub checksum: Checksum,
19    /// The object type.
20    pub ty: ObjectType,
21}
22
23impl ObjectName {
24    /// Pair a checksum with its type.
25    pub fn new(checksum: Checksum, ty: ObjectType) -> ObjectName {
26        ObjectName { checksum, ty }
27    }
28
29    /// The loose path of this object relative to `objects/`, for the given
30    /// repository mode.
31    pub fn loose_path(&self, mode: RepoMode) -> String {
32        loose_path(&self.checksum, self.ty, mode)
33    }
34}
35
36impl std::fmt::Display for ObjectName {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        write!(f, "{}.{}", self.checksum.to_hex(), self.ty.type_str())
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45
46    #[test]
47    fn string_form_uses_the_mode_independent_type() {
48        let c =
49            Checksum::from_hex("b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89")
50                .unwrap();
51        // A content object is `.file` in the string form regardless of mode.
52        assert_eq!(
53            ObjectName::new(c, ObjectType::File).to_string(),
54            "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89.file"
55        );
56        assert_eq!(
57            ObjectName::new(c, ObjectType::DirTree).to_string(),
58            "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89.dirtree"
59        );
60        // The loose path is mode-aware: archive content carries the z suffix.
61        assert_eq!(
62            ObjectName::new(c, ObjectType::File).loose_path(RepoMode::Archive),
63            "b3/c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89.filez"
64        );
65    }
66}