libvctrl_core 2.0.2

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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! 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 such as
//! [`Blob`](libvctrl_handler::Blob), [`Tree`](libvctrl_handler::Tree),
//! [`Commit`](libvctrl_handler::Commit), and [`Tag`](libvctrl_handler::Tag).
//!
//! # Design Rationale
//!
//! The decoder is built with security and robustness as first-class concerns.
//!
//! - **Defensive parsing**: Every slice access is preceded by a bounds check
//!   against the available data length. If data is truncated or malformed,
//!   the decoder gracefully returns
//!   [`VctrlError::CorruptedData`](libvctrl_handler::VctrlError::CorruptedData)
//!   instead of panicking.
//! - **Denial-of-service prevention**: Before allocating memory for
//!   variable-length fields such as blob data or commit messages, the decoder
//!   validates the declared length against system limits
//!   ([`MAX_BLOB_SIZE`](libvctrl_handler::MAX_BLOB_SIZE),
//!   [`MAX_MESSAGE_LENGTH`](libvctrl_handler::MAX_MESSAGE_LENGTH),
//!   [`MAX_TREE_ENTRIES`](libvctrl_handler::MAX_TREE_ENTRIES)). This prevents
//!   a malicious payload from requesting an enormous allocation and crashing
//!   the host process.
//! - **Strict UTF-8 validation**: All string fields are validated using
//!   [`std::str::from_utf8`]. Invalid UTF-8 sequences are rejected as
//!   corruption rather than being silently accepted.
//! - **Version checking**: The first byte of every serialized payload is
//!   compared against the expected format version. This allows the wire
//!   format to evolve while ensuring incompatible data is rejected early
//!   and clearly.
//!
//! # Binary Format Overview
//!
//! All integers are little-endian. Strings and variable-length byte arrays
//! are length-prefixed. The exact layout for each object type is documented
//! on the corresponding decode method.
//!
//! # Internal Mechanism
//!
//! The decoder operates by maintaining a cursor position 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.
//!
//! # Safety and Panic-Freedom
//!
//! The decoder is explicitly designed to be panic-free for arbitrary input.
//! All arithmetic is checked or bounded, and no unchecked indexing is used.
//! This property is critical when parsing untrusted data received from a
//! network or filesystem.
//!
//! # Examples
//!
//! Decoding a `Blob` from a byte vector:
//!
//! ```
//! use libvctrl_handler::{Blob, Decoder, Encoder};
//! use libvctrl_core::codec::{BinaryDecoder, BinaryEncoder};
//!
//! 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);
//! ```

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. The current version is
/// 2, indicating the second revision of the binary format.
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). This is the inverse
/// operation of the encoder: raw bytes are converted back into strongly
/// typed, validated objects.
///
/// # Design Rationale
///
/// The decoder is a stateless unit struct. It holds no internal buffers or
/// configuration, which provides several advantages:
///
/// - **Cheap instantiation**: A zero-sized type can be created without heap
///   allocation or initialization cost.
/// - **Concurrent use**: Because there is no mutable state, the same decoder
///   instance can be safely used from multiple threads or reused repeatedly
///   without side effects.
/// - **Predictability**: Decoding does not depend on any external state,
///   making the operation deterministic and easy to test.
///
/// # 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.
///
/// # Error Handling
///
/// All decode methods return
/// [`Result<_, VctrlError>`](libvctrl_handler::VctrlError). The most common
/// error variant is
/// [`VctrlError::CorruptedData`](libvctrl_handler::VctrlError::CorruptedData),
/// which indicates malformed or truncated input. Some methods may also return
/// [`VctrlError::SerializationError`](libvctrl_handler::VctrlError::SerializationError)
/// for limit violations, or pass through validation errors from object
/// constructors such as [`VctrlError::InvalidName`](libvctrl_handler::VctrlError::InvalidName).
///
/// # Examples
///
/// Decoding a `Blob` from a byte vector:
///
/// ```
/// use libvctrl_handler::{Blob, Decoder, Encoder};
/// use libvctrl_core::codec::{BinaryDecoder, BinaryEncoder};
///
/// 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.
    ///
    /// # Purpose
    ///
    /// 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.
    ///
    /// # Design Rationale
    ///
    /// Centralizing version checks avoids duplicating the same logic in each
    /// decode method. It also provides a single place to adjust if the
    /// versioning strategy changes, such as supporting multiple versions.
    ///
    /// # 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.
    ///
    /// # Purpose
    ///
    /// Reconstructs a [`Blob`](libvctrl_handler::Blob) from its binary
    /// representation. The resulting blob contains the exact byte content
    /// that was originally encoded.
    ///
    /// # 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`.
    ///
    /// # Security
    ///
    /// The declared `data_len` is validated against
    /// [`MAX_BLOB_SIZE`](libvctrl_handler::MAX_BLOB_SIZE) before any
    /// allocation is attempted, preventing memory exhaustion attacks.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_handler::{Blob, Decoder, Encoder};
    /// use libvctrl_core::codec::{BinaryDecoder, BinaryEncoder};
    ///
    /// 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.
    ///
    /// # Purpose
    ///
    /// Reconstructs a [`Tree`](libvctrl_handler::Tree) from its binary
    /// representation. The tree's entries must be sorted and valid; these
    /// invariants are enforced by [`Tree::new`](libvctrl_handler::Tree::new).
    ///
    /// # Format
    ///
    /// Expects the format produced by
    /// [`BinaryEncoder::encode_tree`](crate::codec::BinaryEncoder::encode_tree):
    ///
    /// 1. `VERSION` (1 byte)
    /// 2. `entry_count` (4 bytes, u32 LE)
    /// 3. For each entry:
    ///    a. `name_len` (1 byte, u8)
    ///    b. `name` (`name_len` bytes, UTF-8)
    ///    c. `kind` (1 byte: 0=Blob, 1=Executable, 2=Symlink, 3=Tree, 4=Submodule)
    ///    d. `hash` (64 bytes)
    ///
    /// # Errors
    ///
    /// Returns [`VctrlError::CorruptedData`] if the data is truncated, the
    /// entry count exceeds
    /// [`MAX_TREE_ENTRIES`](libvctrl_handler::MAX_TREE_ENTRIES), the UTF-8
    /// name is invalid, or an entry kind byte is unknown.
    ///
    /// # Security
    ///
    /// The entry count is validated against
    /// [`MAX_TREE_ENTRIES`](libvctrl_handler::MAX_TREE_ENTRIES) before any
    /// vector allocation, preventing memory exhaustion. Each entry's name
    /// length is bounds-checked before reading.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_handler::{Decoder, Encoder, EntryKind, Hash, Tree, TreeEntry};
    /// use libvctrl_core::codec::{BinaryDecoder, BinaryEncoder};
    ///
    /// 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.
    ///
    /// # Purpose
    ///
    /// Reconstructs a [`Commit`](libvctrl_handler::Commit) from its binary
    /// representation, including tree hash, parent hashes, author and
    /// committer identities, message, and metadata.
    ///
    /// # Format
    ///
    /// Expects the format produced by
    /// [`BinaryEncoder::encode_commit`](crate::codec::BinaryEncoder::encode_commit):
    ///
    /// 1. `VERSION` (1 byte)
    /// 2. `tree_hash` (64 bytes)
    /// 3. `parent_count` (1 byte)
    /// 4. `parent_hashes` (64 bytes * `parent_count`)
    /// 5. `author_name_len` (1 byte) + `author_name`
    /// 6. `author_email_len` (1 byte) + `author_email`
    /// 7. `committer_name_len` (1 byte) + `committer_name`
    /// 8. `committer_email_len` (1 byte) + `committer_email`
    /// 9. `msg_len` (4 bytes, u32 LE) + `msg`
    /// 10. `timestamp` (8 bytes, i64 LE)
    /// 11. `timezone_offset` (2 bytes, i16 LE)
    /// 12. `encoding_len` (1 byte) + `encoding`
    ///
    /// # Errors
    ///
    /// Returns [`VctrlError::CorruptedData`] if the data is truncated, the
    /// message length exceeds
    /// [`MAX_MESSAGE_LENGTH`](libvctrl_handler::MAX_MESSAGE_LENGTH), or any
    /// string field contains invalid UTF-8. Returns
    /// [`VctrlError::InvalidName`](libvctrl_handler::VctrlError::InvalidName)
    /// or [`VctrlError::InvalidEmail`](libvctrl_handler::VctrlError::InvalidEmail)
    /// if author/committer identity validation fails.
    ///
    /// # Security
    ///
    /// The message length is validated against
    /// [`MAX_MESSAGE_LENGTH`](libvctrl_handler::MAX_MESSAGE_LENGTH) before
    /// allocation. All variable-length fields are bounds-checked before
    /// reading.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_handler::{Commit, CommitMeta, Decoder, Encoder, Hash, UserID};
    /// use libvctrl_core::codec::{BinaryDecoder, BinaryEncoder};
    ///
    /// 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.
    ///
    /// # Purpose
    ///
    /// Reconstructs a [`Tag`](libvctrl_handler::Tag) from its binary
    /// representation, including name, target hash, optional tagger identity,
    /// message, and metadata.
    ///
    /// # Format
    ///
    /// Expects the format produced by
    /// [`BinaryEncoder::encode_tag`](crate::codec::BinaryEncoder::encode_tag):
    ///
    /// 1. `VERSION` (1 byte)
    /// 2. `name_len` (1 byte) + `name`
    /// 3. `target_hash` (64 bytes)
    /// 4. `has_tagger` (1 byte: 0=false, 1=true)
    /// 5. If `has_tagger` is 1:
    ///    a. `tagger_name_len` (1 byte) + `tagger_name`
    ///    b. `tagger_email_len` (1 byte) + `tagger_email`
    /// 6. `msg_len` (4 bytes, u32 LE) + `msg`
    /// 7. `timestamp` (8 bytes, i64 LE)
    /// 8. `timezone_offset` (2 bytes, i16 LE)
    /// 9. `encoding_len` (1 byte) + `encoding`
    ///
    /// # 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`](libvctrl_handler::VctrlError::SerializationError)
    /// if the message length exceeds
    /// [`MAX_MESSAGE_LENGTH`](libvctrl_handler::MAX_MESSAGE_LENGTH).
    ///
    /// # Security
    ///
    /// The message length is validated against
    /// [`MAX_MESSAGE_LENGTH`](libvctrl_handler::MAX_MESSAGE_LENGTH) before
    /// allocation. All variable-length fields are bounds-checked before
    /// reading.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_handler::{Decoder, Encoder, Hash, Tag, UserID};
    /// use libvctrl_core::codec::{BinaryDecoder, BinaryEncoder};
    ///
    /// 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)
    }
}