Skip to main content

zff/header/chunk_map/
mod.rs

1//! Module for chunk map functionality in zff.
2//!
3//! Chunk maps store metadata about chunks in a zff container, enabling efficient
4//! random access and deduplication. This module provides different types of chunk maps
5//! for various metadata aspects.
6//!
7//! # Submodules
8//!
9//! - [`chunk_header`]: Chunk header map (stores chunk headers by chunk number)
10//! - [`chunk_same_bytes`]: Same bytes map (tracks chunks filled with a single repeated byte)
11//! - [`chunk_deduplication`]: Deduplication map (tracks duplicate chunks to save space)
12//!
13//! # Types
14//!
15//! - [`ChunkMaps`]: Container for all chunk map types
16//! - [`ChunkMapType`]: Enum identifying the type of chunk map
17//! - [`ChunkMap`]: Trait defining common chunk map operations
18
19// - STD
20use std::borrow::Borrow;
21use std::collections::BTreeMap;
22use std::fmt;
23use std::io::Read;
24
25// - internal
26use crate::helper::read_exact_buffer;
27#[cfg(feature = "serde")]
28use crate::helper::string_to_str;
29use crate::{helper::decode_header_content_len, prelude::*};
30
31// - external
32#[cfg(feature = "serde")]
33use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct};
34
35// - modules
36mod chunk_deduplication;
37mod chunk_header;
38mod chunk_same_bytes;
39
40// - re-exports
41pub use chunk_deduplication::*;
42pub use chunk_header::*;
43pub use chunk_same_bytes::*;
44
45#[repr(C)]
46#[derive(Debug)]
47/// The appropriate Chunkmap type.
48pub enum ChunkMapType {
49    /// The header map.
50    HeaderMap = 0,
51    /// The sambebytes map.
52    SamebytesMap = 1,
53    /// The deduplication map.
54    DeduplicationMap = 2,
55}
56
57impl fmt::Display for ChunkMapType {
58    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59        let value = match self {
60            ChunkMapType::HeaderMap => "HeaderMap",
61            ChunkMapType::SamebytesMap => "SamebytesMap",
62            ChunkMapType::DeduplicationMap => "DeduplicationMap",
63        };
64        write!(f, "{value}")
65    }
66}
67
68/// The ChunkMaps struct contains all chunk maps.
69#[derive(Debug, Clone, PartialEq, Eq, Default)]
70#[cfg_attr(feature = "serde", derive(Deserialize))]
71pub struct ChunkMaps {
72    /// The offset map.
73    pub header_map: ChunkHeaderMap,
74    /// The same bytes map.
75    pub same_bytes_map: ChunkSamebytesMap,
76    /// The deduplication map.
77    pub duplicate_chunks: ChunkDeduplicationMap,
78}
79
80impl ChunkMaps {
81    /// Generates a new map
82    pub fn new(
83        header_map: ChunkHeaderMap,
84        same_bytes_map: ChunkSamebytesMap,
85        duplicate_chunks: ChunkDeduplicationMap,
86    ) -> Self {
87        Self {
88            header_map,
89            same_bytes_map,
90            duplicate_chunks,
91        }
92    }
93
94    /// checks if all maps are empty.
95    pub fn is_empty(&self) -> bool {
96        self.header_map.chunkmap().is_empty()
97            && self.same_bytes_map.chunkmap().is_empty()
98            && self.duplicate_chunks.chunkmap().is_empty()
99    }
100
101    /// sets the appropriate object number
102    pub fn set_object_number(&mut self, object_number: u64) {
103        self.header_map.set_object_number(object_number);
104        self.same_bytes_map.set_object_number(object_number);
105        self.duplicate_chunks.set_object_number(object_number);
106    }
107}
108
109#[cfg(feature = "serde")]
110impl Serialize for ChunkMaps {
111    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
112    where
113        S: Serializer,
114    {
115        let mut state = serializer.serialize_struct("ChunkMaps", 6)?;
116        if !self.header_map.is_empty() {
117            state.serialize_field(string_to_str(self.header_map.to_string()), &self.header_map)?;
118        }
119        if !self.same_bytes_map.is_empty() {
120            state.serialize_field(
121                string_to_str(self.same_bytes_map.to_string()),
122                &self.same_bytes_map,
123            )?;
124        }
125        if !self.duplicate_chunks.is_empty() {
126            state.serialize_field(
127                string_to_str(self.duplicate_chunks.to_string()),
128                &self.duplicate_chunks,
129            )?;
130        }
131        state.end()
132    }
133}
134
135/// The ChunkMap trait specifies common interface for various types of chunk maps.
136///
137/// The chunk maps are used to store information about chunks in the file.
138/// The information is stored in the form of a map, where the key is the chunk offset
139/// and the value is the chunk information.
140///
141/// The chunk maps are used to optimize the file reading.
142pub trait ChunkMap {
143    /// The type of the value stored in the map.
144    type Value;
145
146    /// returns a new chunk map with the given values.
147    fn new(object_number: u64, chunkmap: BTreeMap<u64, Self::Value>) -> Self;
148
149    /// returns a new, empty chunk map with the given values.
150    fn new_empty(object_number: u64) -> Self;
151
152    /// Returns the inner map and replaces it with an empty map.
153    fn flush(&mut self) -> BTreeMap<u64, Self::Value>;
154
155    /// Tries to add a chunk entry.  
156    /// Returns true, if the chunk no / value pair was added to the map.  
157    /// Returns false, if the map is full (in this case, the pair was **not** added to the map).
158    fn add_chunk_entry(&mut self, chunk_no: u64, value: Self::Value) -> bool;
159
160    /// Checks if the map is full (returns true if, returns false if not).
161    fn is_full(&self) -> bool;
162
163    /// Checks if the inner map is empty
164    fn is_empty(&self) -> bool;
165
166    /// The encoded size of this map.
167    fn current_size(&self) -> usize;
168
169    /// Reset the target size to the given value.
170    fn set_target_size(&mut self, target_size: usize);
171
172    /// Returns a reference to the inner map
173    fn chunkmap(&self) -> &BTreeMap<u64, Self::Value>;
174
175    /// Appends another chunkmap to this map
176    fn append(&mut self, map: Self);
177
178    /// Returns the corresponding object number of the inner map
179    fn object_number(&self) -> u64;
180
181    /// Sets the appropriate object number
182    fn set_object_number(&mut self, object_number: u64);
183
184    /// Returns the apprpropriate (encrypted) structure data
185    fn inner_structure_data<D: Read>(data: &mut D) -> Result<ChunkMapInnerStructureData>
186    where
187        Self: HeaderCoding,
188    {
189        if !Self::check_identifier(data) {
190            return Err(ZffError::new(
191                ZffErrorKind::Invalid,
192                ERROR_HEADER_DECODER_MISMATCH_IDENTIFIER,
193            ));
194        }
195        let header_length = Self::decode_header_length(data)?;
196        let version = u8::decode_directly(data)?;
197        if version != Self::version() {
198            return Err(ZffError::new(
199                ZffErrorKind::Unsupported,
200                format!("{ERROR_UNSUPPORTED_VERSION}{version}"),
201            ));
202        }
203        let object_number = u64::decode_directly(data)?;
204        let structure_content_length =
205            decode_header_content_len(header_length, 1 + object_number.encoded_size())?;
206        let structure_content = read_exact_buffer(data, structure_content_length)?;
207        Ok(ChunkMapInnerStructureData::new(
208            object_number,
209            structure_content,
210        ))
211    }
212
213    /// Decrypts and decodes the chunk map by using the given key from given offset.
214    fn decrypt_and_decode_at<K, A, D>(
215        key: K,
216        encryption_algorithm: A,
217        data: &D,
218        chunk_no: u64,
219        offset: u64,
220    ) -> Result<Self>
221    where
222        K: AsRef<[u8]>,
223        A: Borrow<EncryptionAlgorithm>,
224        D: ReadAt + ?Sized,
225        Self: Sized + HeaderCoding,
226    {
227        let mut cursor = ReadAtCursor::new(data, offset);
228        Self::decrypt_and_decode(key, encryption_algorithm, &mut cursor, chunk_no)
229    }
230
231    /// Decrypts and decodes the chunk map by using the given key.
232    fn decrypt_and_decode<K, A, D>(
233        key: K,
234        encryption_algorithm: A,
235        data: &mut D,
236        chunk_no: u64,
237    ) -> Result<Self>
238    where
239        K: AsRef<[u8]>,
240        A: Borrow<EncryptionAlgorithm>,
241        D: Read,
242        Self: Sized + HeaderCoding;
243
244    /// Encodes the inner map
245    fn encode_map(&self) -> Vec<u8>;
246
247    /// Encrypts the inner encoded map
248    fn encrypt_encoded_map<K, A>(
249        &self,
250        key: K,
251        encryption_algorithm: A,
252        chunk_no: u64,
253    ) -> Result<Vec<u8>>
254    where
255        K: AsRef<[u8]>,
256        A: Borrow<EncryptionAlgorithm>,
257        Self: HeaderCoding;
258
259    /// Encodes and encrypts the appropriate chunk map
260    fn encode_and_encrypt<K, A>(
261        &self,
262        key: K,
263        encryption_algorithm: A,
264        chunk_no: u64,
265    ) -> Result<Vec<u8>>
266    where
267        K: AsRef<[u8]>,
268        A: Borrow<EncryptionAlgorithm>,
269        Self: HeaderCoding,
270    {
271        let mut vec = Vec::new();
272        let encrypted_map = self.encrypt_encoded_map(key, encryption_algorithm, chunk_no)?;
273        let identifier = Self::identifier();
274        let encoded_header_length = (DEFAULT_LENGTH_HEADER_IDENTIFIER
275            + DEFAULT_LENGTH_VALUE_HEADER_LENGTH
276            + encrypted_map.len()) as u64; //4 bytes identifier + 8 bytes for length + length itself
277        vec.extend_from_slice(&identifier.to_be_bytes());
278        vec.extend_from_slice(&encoded_header_length.to_le_bytes());
279        vec.extend_from_slice(&encrypted_map);
280
281        Ok(vec)
282    }
283}
284
285/// Structure data for chunk map inner structure.
286/// This structure is used to store the structure data for chunk map inner structure.
287#[derive(Debug, Clone, PartialEq, Eq, Hash)]
288pub struct ChunkMapInnerStructureData {
289    /// Object number for chunk map inner structure.
290    pub object_number: u64,
291    /// Structure data for chunk map inner structure.
292    pub structure_data: Vec<u8>,
293}
294
295impl ChunkMapInnerStructureData {
296    /// Creates a new chunk map inner structure data.
297    pub fn new(object_number: u64, structure_data: Vec<u8>) -> Self {
298        Self {
299            object_number,
300            structure_data,
301        }
302    }
303}