libvctrl_core 2.0.1

Reference implementations of the libvctrl contracts (in-memory store, SHA-512 hasher, binary codec)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Binary deserialization format decoder for `libvctrl_core`.
//!
//! # Purpose
//! This module provides the [`BinaryDecoder`], a concrete implementation of the
//! [`Decoder`](libvctrl_handler::Decoder) trait. It deserializes raw bytes
//! produced by the [`BinaryEncoder`](crate::codec::BinaryEncoder) back into
//! in-memory version control objects.
//!
//! # Design rationale
//! - **Defensive Parsing**: The decoder is designed to be completely panic-free.
//!   Every slice access is preceded by a bounds check against the available data
//!   length. If data is truncated or malformed, it gracefully returns a
//!   [`VctrlError::CorruptedData`] error.
//! - **Denial-of-Service Prevention**: Before allocating memory for variable-length
//!   fields (like blob data or messages), the decoder validates the requested
//!   length against system limits ([`MAX_BLOB_SIZE`](libvctrl_handler::MAX_BLOB_SIZE),
//!   [`MAX_MESSAGE_LENGTH`](libvctrl_handler::MAX_MESSAGE_LENGTH)). This prevents
//!   a malicious payload from requesting gigabytes of memory and crashing the host.
//! - **Strict UTF-8 Validation**: All string fields are strictly validated using
//!   [`str::from_utf8`]. Invalid UTF-8 sequences result in a corruption error.
//! - **Version Checking**: The first byte of every payload is checked against the
//!   expected version, ensuring that incompatible data formats are rejected early.

use libvctrl_handler::{
    Blob, Commit, CommitMeta, Decoder, EntryKind, Hash, MAX_BLOB_SIZE, MAX_MESSAGE_LENGTH,
    MAX_TREE_ENTRIES, Tag, Tree, TreeEntry, UserID, VctrlError,
};
use std::str;

/// The expected binary format version number.
///
/// # Purpose
/// This constant is checked against the first byte of every serialized payload.
/// If the versions do not match, the decoder rejects the data.
///
/// # Design rationale
/// Bumping this version allows breaking changes to the wire format in the
/// future. A decoder reading an unexpected version can fail gracefully
/// instead of attempting to parse incompatible data.
const EXPECTED_VERSION: u8 = 2;

/// A binary decoder that deserializes version control objects from a compact byte format.
///
/// # Purpose
/// Implements the [`Decoder`](libvctrl_handler::Decoder) trait to parse the
/// binary representation generated by [`BinaryEncoder`](crate::codec::BinaryEncoder).
///
/// # Design rationale
/// The decoder is a stateless unit struct, allowing it to be instantiated
/// cheaply and used concurrently or repeatedly without side effects.
///
/// # Internal mechanism
/// The decoder operates by maintaining a cursor (`pos`) over the input byte
/// slice. It reads length prefixes, advances the cursor, and extracts slices.
/// Where exact sizes are known, it uses `try_into().unwrap()` safely because
/// preceding bounds checks guarantee the slice has the correct number of bytes.
///
/// # Examples
///
/// Decoding a `Blob` from a byte vector:
///
/// ```
/// use libvctrl_handler::{Blob, Encoder, Decoder};
/// use libvctrl_core::codec::{BinaryEncoder, BinaryDecoder};
///
/// let original_blob = Blob::new(b"hello".to_vec());
/// let bytes = BinaryEncoder.encode_blob(&original_blob).unwrap();
///
/// let decoder = BinaryDecoder;
/// let decoded_blob = decoder.decode_blob(&bytes).unwrap();
/// assert_eq!(decoded_blob, original_blob);
/// ```
pub struct BinaryDecoder;

impl BinaryDecoder {
    /// Checks if the first byte of the data slice matches the expected format version.
    ///
    /// # Design rationale
    /// This helper centralizes version validation. It ensures that the payload
    /// is non-empty and that the version byte matches [`EXPECTED_VERSION`]. If
    /// successful, it returns a slice pointing to the data *after* the version
    /// byte, simplifying subsequent parsing logic.
    ///
    /// # Errors
    /// Returns [`VctrlError::CorruptedData`] if the slice is empty or if the
    /// version byte does not match [`EXPECTED_VERSION`].
    fn check_version(data: &[u8]) -> Result<&[u8], VctrlError> {
        if data.is_empty() {
            return Err(VctrlError::CorruptedData("missing version byte".into()));
        }
        if data[0] != EXPECTED_VERSION {
            return Err(VctrlError::CorruptedData(format!(
                "unsupported version: {} (expected {})",
                data[0], EXPECTED_VERSION
            )));
        }
        Ok(&data[1..])
    }
}

impl Decoder for BinaryDecoder {
    /// Decodes a [`Blob`](libvctrl_handler::Blob) from a byte slice.
    ///
    /// # Format
    /// Expects the format produced by
    /// [`BinaryEncoder::encode_blob`](crate::codec::BinaryEncoder::encode_blob):
    /// 1. `VERSION` (1 byte)
    /// 2. `data_len` (8 bytes, u64 LE)
    /// 3. `data` (`data_len` bytes)
    ///
    /// # Errors
    /// Returns [`VctrlError::CorruptedData`] if:
    /// - The data is too short to contain the version or length prefix.
    /// - The `data_len` exceeds [`MAX_BLOB_SIZE`](libvctrl_handler::MAX_BLOB_SIZE).
    /// - The actual number of remaining bytes does not match `data_len`.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_handler::{Blob, Encoder, Decoder};
    /// use libvctrl_core::codec::{BinaryEncoder, BinaryDecoder};
    ///
    /// let original = Blob::new(b"data".to_vec());
    /// let bytes = BinaryEncoder.encode_blob(&original).unwrap();
    /// let decoded = BinaryDecoder.decode_blob(&bytes).unwrap();
    /// assert_eq!(decoded, original);
    /// ```
    fn decode_blob(&self, data: &[u8]) -> Result<Blob, VctrlError> {
        let data = Self::check_version(data)?;
        if data.len() < 8 {
            return Err(VctrlError::CorruptedData(
                "blob too short for length prefix".into(),
            ));
        }
        let len_bytes: [u8; 8] = data[..8].try_into().unwrap();
        let data_len = usize::try_from(u64::from_le_bytes(len_bytes))
            .map_err(|_| VctrlError::CorruptedData("blob length out of range".into()))?;
        if data_len > usize::try_from(MAX_BLOB_SIZE).expect("MAX_BLOB_SIZE too large") {
            return Err(VctrlError::CorruptedData("blob exceeds size limit".into()));
        }
        if data.len() != 8 + data_len {
            return Err(VctrlError::CorruptedData("blob length mismatch".into()));
        }
        Ok(Blob::new(data[8..].to_vec()))
    }

    /// Decodes a [`Tree`](libvctrl_handler::Tree) from a byte slice.
    ///
    /// # Format
    /// Expects the format produced by
    /// [`BinaryEncoder::encode_tree`](crate::codec::BinaryEncoder::encode_tree).
    ///
    /// # Errors
    /// Returns [`VctrlError::CorruptedData`] if the data is truncated, the entry
    /// count exceeds the limit, the UTF-8 name is invalid, or the hash is malformed.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_handler::{Encoder, Decoder, EntryKind, Hash, Tree, TreeEntry};
    /// use libvctrl_core::codec::{BinaryEncoder, BinaryDecoder};
    ///
    /// let hash = Hash::from_bytes(&[1; 64]).unwrap();
    /// let entry = TreeEntry::new("file.txt".to_string(), EntryKind::Blob, hash).unwrap();
    /// let original = Tree::new(vec![entry]).unwrap();
    ///
    /// let bytes = BinaryEncoder.encode_tree(&original).unwrap();
    /// let decoded = BinaryDecoder.decode_tree(&bytes).unwrap();
    /// assert_eq!(decoded, original);
    /// ```
    fn decode_tree(&self, data: &[u8]) -> Result<Tree, VctrlError> {
        let data = Self::check_version(data)?;
        if data.len() < 4 {
            return Err(VctrlError::CorruptedData("tree too short".into()));
        }
        let count_bytes: [u8; 4] = data[..4].try_into().unwrap();
        let count = u32::from_le_bytes(count_bytes) as usize;
        if count > usize::try_from(MAX_TREE_ENTRIES).expect("MAX_TREE_ENTRIES too large") {
            return Err(VctrlError::CorruptedData(
                "tree entry count exceeds limit".into(),
            ));
        }
        let mut pos = 4;
        let mut entries = Vec::with_capacity(count);
        for _ in 0..count {
            if pos >= data.len() {
                return Err(VctrlError::CorruptedData("unexpected end of tree".into()));
            }
            let name_len = data[pos] as usize;
            pos += 1;
            if pos + name_len > data.len() {
                return Err(VctrlError::CorruptedData("name exceeds data".into()));
            }
            let name = str::from_utf8(&data[pos..pos + name_len])
                .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in name".into()))?
                .to_string();
            pos += name_len;
            if pos >= data.len() {
                return Err(VctrlError::CorruptedData("missing kind".into()));
            }
            let kind = match data[pos] {
                0 => EntryKind::Blob,
                1 => EntryKind::Executable,
                2 => EntryKind::Symlink,
                3 => EntryKind::Tree,
                4 => EntryKind::Submodule,
                _ => return Err(VctrlError::CorruptedData("unknown entry kind".into())),
            };
            pos += 1;
            if pos + 64 > data.len() {
                return Err(VctrlError::CorruptedData("hash truncated".into()));
            }
            let hash = Hash::from_bytes(&data[pos..pos + 64])?;
            pos += 64;
            entries.push(TreeEntry::new(name, kind, hash)?);
        }
        Tree::new(entries)
    }

    /// Decodes a [`Commit`](libvctrl_handler::Commit) from a byte slice.
    ///
    /// # Format
    /// Expects the format produced by
    /// [`BinaryEncoder::encode_commit`](crate::codec::BinaryEncoder::encode_commit).
    ///
    /// # Errors
    /// Returns [`VctrlError::CorruptedData`] if the data is truncated, the
    /// message length exceeds the limit, or any string field contains invalid UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_handler::{Commit, CommitMeta, Encoder, Decoder, Hash, UserID};
    /// use libvctrl_core::codec::{BinaryEncoder, BinaryDecoder};
    ///
    /// let tree = Hash::from_bytes(&[2; 64]).unwrap();
    /// let user = UserID::new("Alice".to_string(), "a@b.com".to_string()).unwrap();
    /// let meta = CommitMeta { timestamp: 100, timezone_offset: 60, encoding: Some("UTF-8".to_string()) };
    /// let original = Commit::with_meta(tree, Vec::new(), user.clone(), user, "msg".to_string(), meta);
    ///
    /// let bytes = BinaryEncoder.encode_commit(&original).unwrap();
    /// let decoded = BinaryDecoder.decode_commit(&bytes).unwrap();
    /// assert_eq!(decoded, original);
    /// ```
    #[allow(clippy::too_many_lines)]
    fn decode_commit(&self, data: &[u8]) -> Result<Commit, VctrlError> {
        let data = Self::check_version(data)?;
        if data.len() < 64 + 1 {
            return Err(VctrlError::CorruptedData("commit too short".into()));
        }
        let tree = Hash::from_bytes(&data[..64])?;
        let parent_count = data[64] as usize;
        let mut pos = 65;
        let mut parents = Vec::with_capacity(parent_count);
        for _ in 0..parent_count {
            if pos + 64 > data.len() {
                return Err(VctrlError::CorruptedData("parent hash truncated".into()));
            }
            parents.push(Hash::from_bytes(&data[pos..pos + 64])?);
            pos += 64;
        }
        if pos >= data.len() {
            return Err(VctrlError::CorruptedData("missing author name".into()));
        }
        let author_name_len = data[pos] as usize;
        pos += 1;
        if pos + author_name_len > data.len() {
            return Err(VctrlError::CorruptedData("author name truncated".into()));
        }
        let author_name = str::from_utf8(&data[pos..pos + author_name_len])
            .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in author name".into()))?
            .to_string();
        pos += author_name_len;
        if pos >= data.len() {
            return Err(VctrlError::CorruptedData("missing author email".into()));
        }
        let author_email_len = data[pos] as usize;
        pos += 1;
        if pos + author_email_len > data.len() {
            return Err(VctrlError::CorruptedData("author email truncated".into()));
        }
        let author_email = str::from_utf8(&data[pos..pos + author_email_len])
            .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in author email".into()))?
            .to_string();
        pos += author_email_len;
        let author = UserID::new(author_name, author_email)?;
        if pos >= data.len() {
            return Err(VctrlError::CorruptedData("missing committer name".into()));
        }
        let committer_name_len = data[pos] as usize;
        pos += 1;
        if pos + committer_name_len > data.len() {
            return Err(VctrlError::CorruptedData("committer name truncated".into()));
        }
        let committer_name = str::from_utf8(&data[pos..pos + committer_name_len])
            .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in committer name".into()))?
            .to_string();
        pos += committer_name_len;
        if pos >= data.len() {
            return Err(VctrlError::CorruptedData("missing committer email".into()));
        }
        let committer_email_len = data[pos] as usize;
        pos += 1;
        if pos + committer_email_len > data.len() {
            return Err(VctrlError::CorruptedData(
                "committer email truncated".into(),
            ));
        }
        let committer_email = str::from_utf8(&data[pos..pos + committer_email_len])
            .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in committer email".into()))?
            .to_string();
        pos += committer_email_len;
        let committer = UserID::new(committer_name, committer_email)?;
        if pos + 4 > data.len() {
            return Err(VctrlError::CorruptedData("missing message length".into()));
        }
        let msg_len_bytes: [u8; 4] = data[pos..pos + 4].try_into().unwrap();
        let msg_len = u32::from_le_bytes(msg_len_bytes) as usize;
        pos += 4;
        if msg_len > usize::try_from(MAX_MESSAGE_LENGTH).expect("MAX_MESSAGE_LENGTH too large") {
            return Err(VctrlError::CorruptedData(
                "commit message exceeds size limit".into(),
            ));
        }
        if pos + msg_len > data.len() {
            return Err(VctrlError::CorruptedData("message truncated".into()));
        }
        let message = str::from_utf8(&data[pos..pos + msg_len])
            .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in message".into()))?
            .to_string();
        pos += msg_len;

        if pos + 8 > data.len() {
            return Err(VctrlError::CorruptedData("missing timestamp".into()));
        }
        let timestamp = i64::from_le_bytes(data[pos..pos + 8].try_into().unwrap());
        pos += 8;
        if pos + 2 > data.len() {
            return Err(VctrlError::CorruptedData("missing timezone offset".into()));
        }
        let timezone_offset = i16::from_le_bytes(data[pos..pos + 2].try_into().unwrap());
        pos += 2;
        if pos >= data.len() {
            return Err(VctrlError::CorruptedData("missing encoding length".into()));
        }
        let encoding_len = data[pos] as usize;
        pos += 1;
        let encoding = if encoding_len > 0 {
            if pos + encoding_len > data.len() {
                return Err(VctrlError::CorruptedData("encoding truncated".into()));
            }
            let enc = str::from_utf8(&data[pos..pos + encoding_len])
                .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in encoding".into()))?
                .to_string();
            Some(enc)
        } else {
            None
        };
        let meta = CommitMeta {
            timestamp,
            timezone_offset,
            encoding,
        };
        Ok(Commit::with_meta(
            tree, parents, author, committer, message, meta,
        ))
    }

    /// Decodes a [`Tag`](libvctrl_handler::Tag) from a byte slice.
    ///
    /// # Format
    /// Expects the format produced by
    /// [`BinaryEncoder::encode_tag`](crate::codec::BinaryEncoder::encode_tag).
    ///
    /// # Errors
    /// Returns [`VctrlError::CorruptedData`] if the data is truncated, the tagger
    /// presence byte is invalid, or any string field contains invalid UTF-8.
    /// Returns [`VctrlError::SerializationError`] if the message length exceeds
    /// the system limit.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_handler::{Encoder, Decoder, Hash, Tag, UserID};
    /// use libvctrl_core::codec::{BinaryEncoder, BinaryDecoder};
    ///
    /// let target = Hash::from_bytes(&[3; 64]).unwrap();
    /// let tagger = UserID::new("Bob".to_string(), "b@c.com".to_string()).unwrap();
    /// let original = Tag::new("v1.0".to_string(), target, Some(tagger), "rel".to_string()).unwrap();
    ///
    /// let bytes = BinaryEncoder.encode_tag(&original).unwrap();
    /// let decoded = BinaryDecoder.decode_tag(&bytes).unwrap();
    /// assert_eq!(decoded, original);
    /// ```
    #[allow(clippy::too_many_lines)]
    fn decode_tag(&self, data: &[u8]) -> Result<Tag, VctrlError> {
        let data = Self::check_version(data)?;
        if data.is_empty() {
            return Err(VctrlError::CorruptedData("tag too short".into()));
        }
        let name_len = data[0] as usize;
        let mut pos = 1;
        if pos + name_len > data.len() {
            return Err(VctrlError::CorruptedData("tag name truncated".into()));
        }
        let name = str::from_utf8(&data[pos..pos + name_len])
            .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in tag name".into()))?
            .to_string();
        pos += name_len;
        if pos + 64 > data.len() {
            return Err(VctrlError::CorruptedData("target hash truncated".into()));
        }
        let target = Hash::from_bytes(&data[pos..pos + 64])?;
        pos += 64;
        if pos >= data.len() {
            return Err(VctrlError::CorruptedData(
                "missing tagger presence byte".into(),
            ));
        }
        let has_tagger = match data[pos] {
            0 => false,
            1 => true,
            _ => {
                return Err(VctrlError::CorruptedData(
                    "invalid tagger presence byte".into(),
                ));
            }
        };
        pos += 1;
        let tagger = if has_tagger {
            if pos >= data.len() {
                return Err(VctrlError::CorruptedData("missing tagger name".into()));
            }
            let tagger_name_len = data[pos] as usize;
            pos += 1;
            if pos + tagger_name_len > data.len() {
                return Err(VctrlError::CorruptedData("tagger name truncated".into()));
            }
            let tagger_name = str::from_utf8(&data[pos..pos + tagger_name_len])
                .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in tagger name".into()))?
                .to_string();
            pos += tagger_name_len;
            if pos >= data.len() {
                return Err(VctrlError::CorruptedData("missing tagger email".into()));
            }
            let tagger_email_len = data[pos] as usize;
            pos += 1;
            if pos + tagger_email_len > data.len() {
                return Err(VctrlError::CorruptedData("tagger email truncated".into()));
            }
            let tagger_email = str::from_utf8(&data[pos..pos + tagger_email_len])
                .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in tagger email".into()))?
                .to_string();
            pos += tagger_email_len;
            Some(UserID::new(tagger_name, tagger_email)?)
        } else {
            None
        };
        if pos + 4 > data.len() {
            return Err(VctrlError::CorruptedData("missing message length".into()));
        }
        let msg_len_bytes: [u8; 4] = data[pos..pos + 4].try_into().unwrap();
        let msg_len = u32::from_le_bytes(msg_len_bytes) as usize;
        pos += 4;
        if msg_len > usize::try_from(MAX_MESSAGE_LENGTH).expect("MAX_MESSAGE_LENGTH too large") {
            return Err(VctrlError::SerializationError(
                "tag message exceeds size limit".into(),
            ));
        }
        if pos + msg_len > data.len() {
            return Err(VctrlError::CorruptedData("message truncated".into()));
        }
        let message = str::from_utf8(&data[pos..pos + msg_len])
            .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in message".into()))?
            .to_string();
        pos += msg_len;

        if pos + 8 > data.len() {
            return Err(VctrlError::CorruptedData("missing timestamp".into()));
        }
        let timestamp = i64::from_le_bytes(data[pos..pos + 8].try_into().unwrap());
        pos += 8;
        if pos + 2 > data.len() {
            return Err(VctrlError::CorruptedData("missing timezone offset".into()));
        }
        let timezone_offset = i16::from_le_bytes(data[pos..pos + 2].try_into().unwrap());
        pos += 2;
        if pos >= data.len() {
            return Err(VctrlError::CorruptedData("missing encoding length".into()));
        }
        let encoding_len = data[pos] as usize;
        pos += 1;
        let encoding = if encoding_len > 0 {
            if pos + encoding_len > data.len() {
                return Err(VctrlError::CorruptedData("encoding truncated".into()));
            }
            let enc = str::from_utf8(&data[pos..pos + encoding_len])
                .map_err(|_| VctrlError::CorruptedData("invalid UTF-8 in encoding".into()))?
                .to_string();
            Some(enc)
        } else {
            None
        };
        let meta = CommitMeta {
            timestamp,
            timezone_offset,
            encoding,
        };
        Tag::with_meta(name, target, tagger, message, meta)
    }
}