git_internal/internal/object/blob.rs
1//! In Git, a blob (binary large object) is a type of Git object that stores the contents of a file.
2//! A blob object contains the binary data of a file, but does not contain any metadata such as
3//! the file name or permissions. The structure of a Git blob object is as follows:
4//!
5//! ```bash
6//! blob <content-length>\0<content>
7//! ```
8//!
9//! - `blob` is the object type, indicating that this is a blob object.
10//! - `<content-length>` is the length of the content in bytes, encoded as a string of decimal digits.
11//! - `\0` is a null byte, which separates the header from the content.
12//! - `<content>` is the binary data of the file, represented as a sequence of bytes.
13//!
14//! We can create a Git blob object for this file by running the following command:
15//!
16//! ```bash
17//! $ echo "Hello, world!" | git hash-object -w --stdin
18//! ```
19//!
20//! This will output an SHA-1/ SHA-256 hash, which is the ID of the newly created blob object.
21//! The contents of the blob object would look something like this:
22//!
23//! ```bash
24//! blob 13\0Hello, world!
25//! ```
26//! Git uses blobs to store the contents of files in a repository. Each version of a file is
27//! represented by a separate blob object, which can be linked together using Git's commit and tree
28//! objects to form a version history of the repository.
29//!
30use std::fmt::Display;
31
32use crate::{
33 errors::GitError,
34 hash::{HashKind, ObjectHash},
35 internal::object::{ObjectTrait, types::ObjectType},
36};
37
38/// **The Blob Object**
39#[derive(Eq, Debug, Clone)]
40pub struct Blob {
41 pub id: ObjectHash,
42 pub data: Vec<u8>,
43}
44
45impl PartialEq for Blob {
46 /// The Blob object is equal to another Blob object if their IDs are equal.
47 fn eq(&self, other: &Self) -> bool {
48 self.id == other.id
49 }
50}
51
52impl Display for Blob {
53 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
54 writeln!(f, "Type: Blob").unwrap();
55 writeln!(f, "Size: {}", self.data.len())
56 }
57}
58
59impl ObjectTrait for Blob {
60 /// Creates a new object from a byte slice.
61 fn from_bytes(data: &[u8], hash: ObjectHash) -> Result<Self, GitError>
62 where
63 Self: Sized,
64 {
65 Ok(Blob {
66 id: hash,
67 data: data.to_vec(),
68 })
69 }
70
71 /// Returns the Blob type
72 fn get_type(&self) -> ObjectType {
73 ObjectType::Blob
74 }
75
76 fn get_size(&self) -> usize {
77 self.data.len()
78 }
79
80 fn to_data(&self) -> Result<Vec<u8>, GitError> {
81 Ok(self.data.clone())
82 }
83}
84
85impl Blob {
86 /// Create a new Blob from content bytes, hashing with an explicit repository `kind`.
87 ///
88 /// Does not consult the thread-local [`HashKind`]. Fails closed (never
89 /// panics) if the ID cannot be computed.
90 pub fn from_content_bytes_with_kind(
91 kind: HashKind,
92 content: Vec<u8>,
93 ) -> Result<Self, GitError> {
94 let id = ObjectHash::from_type_and_data_for_kind(kind, ObjectType::Blob, &content)?;
95 Ok(Blob { id, data: content })
96 }
97
98 /// Create a new Blob from a content string, hashing with an explicit repository `kind`.
99 pub fn from_content_with_kind(kind: HashKind, content: &str) -> Result<Self, GitError> {
100 Self::from_content_bytes_with_kind(kind, content.as_bytes().to_vec())
101 }
102
103 /// Create a new Blob object from the given content string.
104 /// - This is a convenience method for creating a Blob from a string.
105 /// - It converts the string to bytes and then calls `from_content_bytes`.
106 /// - Uses the thread-local [`HashKind`]; see [`Blob::from_content_with_kind`].
107 pub fn from_content(content: &str) -> Self {
108 let content = content.as_bytes().to_vec();
109 Blob::from_content_bytes(content)
110 }
111
112 /// Create a new Blob object from the given content bytes.
113 /// - some file content can't be represented as a string (UTF-8), so we need to use bytes.
114 /// - Uses the thread-local [`HashKind`]; see [`Blob::from_content_bytes_with_kind`].
115 pub fn from_content_bytes(content: Vec<u8>) -> Self {
116 Blob {
117 // Calculate the hash from the type and content
118 id: ObjectHash::from_type_and_data(ObjectType::Blob, &content),
119 data: content,
120 }
121 }
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127 use crate::{
128 hash::{HashKind, set_hash_kind_for_test},
129 internal::object::ObjectTrait,
130 };
131
132 /// Test creating a Blob from content string
133 #[test]
134 fn test_blob_from_content() {
135 let _guard = set_hash_kind_for_test(HashKind::Sha1);
136 let content = "Hello, world!";
137 let blob = Blob::from_content(content);
138 assert_eq!(
139 blob.id.to_string(),
140 "5dd01c177f5d7d1be5346a5bc18a569a7410c2ef"
141 );
142 let hash_from_trait = blob.object_hash().unwrap();
143 assert_eq!(hash_from_trait.to_string(), blob.id.to_string());
144 }
145
146 /// Test creating a Blob from content string using SHA-256 hash algorithm.
147 #[test]
148 fn test_blob_from_content_sha256() {
149 let _guard = set_hash_kind_for_test(HashKind::Sha256);
150 let content = "Hello, world!";
151 let blob = Blob::from_content(content);
152 assert_eq!(
153 blob.id.to_string(),
154 "178b5fbed164aee269fee7323badf7269cca0eed0875717b0d2d4f9819164c3f"
155 );
156 }
157}