Skip to main content

xet_data/processing/
xet_file.rs

1use serde::{Deserialize, Serialize};
2use xet_core_structures::merklehash::{DataHashError, MerkleHash};
3use xet_runtime::error_printer::ErrorPrinter;
4
5/// A struct that wraps a the Xet file information.
6#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
7#[cfg_attr(feature = "python", pyo3::pyclass(get_all, from_py_object))]
8pub struct XetFileInfo {
9    /// The Merkle hash of the file
10    pub hash: String,
11
12    /// The size of the file, if known.
13    #[serde(default, skip_serializing_if = "Option::is_none")]
14    pub file_size: Option<u64>,
15
16    /// The SHA-256 hash of the file, if available.
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub sha256: Option<String>,
19}
20
21#[cfg_attr(feature = "python", pyo3::pymethods)]
22impl XetFileInfo {
23    /// Python constructor: ``XetFileInfo(hash, file_size=None)``
24    #[cfg(feature = "python")]
25    #[new]
26    #[pyo3(signature = (hash, file_size=None))]
27    fn py_new(hash: String, file_size: Option<u64>) -> Self {
28        Self {
29            hash,
30            file_size,
31            sha256: None,
32        }
33    }
34}
35
36impl XetFileInfo {
37    /// Creates a new `XetFileInfo` instance with a known size.
38    ///
39    /// # Arguments
40    ///
41    /// * `hash` - The Xet hash of the file. This is a Merkle hash string.
42    /// * `file_size` - The size of the file.
43    pub fn new(hash: String, file_size: u64) -> Self {
44        Self {
45            hash,
46            file_size: Some(file_size),
47            sha256: None,
48        }
49    }
50
51    /// Creates a new `XetFileInfo` instance with a SHA-256 hash and known size.
52    pub fn new_with_sha256(hash: String, file_size: u64, sha256: String) -> Self {
53        Self {
54            hash,
55            file_size: Some(file_size),
56            sha256: Some(sha256),
57        }
58    }
59
60    /// Creates a new `XetFileInfo` with only a hash and no known size.
61    pub fn new_hash_only(hash: String) -> Self {
62        Self {
63            hash,
64            file_size: None,
65            sha256: None,
66        }
67    }
68
69    /// Returns the Merkle hash of the file.
70    pub fn hash(&self) -> &str {
71        &self.hash
72    }
73
74    /// Returns the parsed merkle hash of the file.
75    pub fn merkle_hash(&self) -> std::result::Result<MerkleHash, DataHashError> {
76        MerkleHash::from_hex(&self.hash).log_error("Error parsing hash value for file info")
77    }
78
79    /// Returns the size of the file, if known.
80    pub fn file_size(&self) -> Option<u64> {
81        self.file_size
82    }
83
84    /// Returns the SHA-256 hash of the file, if available.
85    pub fn sha256(&self) -> Option<&str> {
86        self.sha256.as_deref()
87    }
88
89    pub fn as_pointer_file(&self) -> std::result::Result<String, serde_json::Error> {
90        serde_json::to_string(self)
91    }
92}