Skip to main content

xet_data/processing/
xet_file.rs

1use serde::{Deserialize, Serialize};
2use xet_core_structures::merklehash::{DataHashHexParseError, 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)]
7pub struct XetFileInfo {
8    /// The Merkle hash of the file
9    pub hash: String,
10
11    /// The size of the file, if known.
12    #[serde(default, skip_serializing_if = "Option::is_none")]
13    pub file_size: Option<u64>,
14
15    /// The SHA-256 hash of the file, if available.
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub sha256: Option<String>,
18}
19
20impl XetFileInfo {
21    /// Creates a new `XetFileInfo` instance with a known size.
22    ///
23    /// # Arguments
24    ///
25    /// * `hash` - The Xet hash of the file. This is a Merkle hash string.
26    /// * `file_size` - The size of the file.
27    pub fn new(hash: String, file_size: u64) -> Self {
28        Self {
29            hash,
30            file_size: Some(file_size),
31            sha256: None,
32        }
33    }
34
35    /// Creates a new `XetFileInfo` instance with a SHA-256 hash and known size.
36    pub fn new_with_sha256(hash: String, file_size: u64, sha256: String) -> Self {
37        Self {
38            hash,
39            file_size: Some(file_size),
40            sha256: Some(sha256),
41        }
42    }
43
44    /// Creates a new `XetFileInfo` with only a hash and no known size.
45    pub fn new_hash_only(hash: String) -> Self {
46        Self {
47            hash,
48            file_size: None,
49            sha256: None,
50        }
51    }
52
53    /// Returns the Merkle hash of the file.
54    pub fn hash(&self) -> &str {
55        &self.hash
56    }
57
58    /// Returns the parsed merkle hash of the file.
59    pub fn merkle_hash(&self) -> std::result::Result<MerkleHash, DataHashHexParseError> {
60        MerkleHash::from_hex(&self.hash).log_error("Error parsing hash value for file info")
61    }
62
63    /// Returns the size of the file, if known.
64    pub fn file_size(&self) -> Option<u64> {
65        self.file_size
66    }
67
68    /// Returns the SHA-256 hash of the file, if available.
69    pub fn sha256(&self) -> Option<&str> {
70        self.sha256.as_deref()
71    }
72
73    pub fn as_pointer_file(&self) -> std::result::Result<String, serde_json::Error> {
74        serde_json::to_string(self)
75    }
76}