copia 0.1.3

Pure Rust rsync-style delta synchronization library
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
//! Strong hash implementation using BLAKE3.
//!
//! BLAKE3 provides cryptographic verification of block matches after
//! the rolling checksum identifies potential candidates.

use std::io::Read;

use serde::{Deserialize, Serialize};

/// Strong cryptographic hash for block verification.
///
/// Uses BLAKE3 for 256-bit security with high performance.
/// BLAKE3 is significantly faster than SHA-256 while providing
/// equivalent security guarantees.
///
/// # Example
///
/// ```rust
/// use copia::StrongHash;
///
/// let hash1 = StrongHash::compute(b"hello world");
/// let hash2 = StrongHash::compute(b"hello world");
/// assert_eq!(hash1, hash2);
///
/// let hash3 = StrongHash::compute(b"different data");
/// assert_ne!(hash1, hash3);
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct StrongHash([u8; 32]);

impl StrongHash {
    /// Compute BLAKE3 hash of data.
    ///
    /// # Arguments
    ///
    /// * `data` - Byte slice to hash
    ///
    /// # Example
    ///
    /// ```rust
    /// use copia::StrongHash;
    ///
    /// let hash = StrongHash::compute(b"test data");
    /// ```
    #[must_use]
    pub fn compute(data: &[u8]) -> Self {
        let hash = blake3::hash(data);
        Self(*hash.as_bytes())
    }

    /// Compute hash from a reader with streaming interface.
    ///
    /// This is useful for large files that shouldn't be loaded entirely
    /// into memory.
    ///
    /// # Arguments
    ///
    /// * `reader` - Any type implementing `Read`
    ///
    /// # Errors
    ///
    /// Returns an I/O error if reading fails.
    ///
    /// # Example
    ///
    /// ```rust
    /// use copia::StrongHash;
    /// use std::io::Cursor;
    ///
    /// let data = b"streaming data";
    /// let mut cursor = Cursor::new(data);
    /// let hash = StrongHash::compute_streaming(&mut cursor).unwrap();
    /// ```
    pub fn compute_streaming<R: Read>(reader: &mut R) -> std::io::Result<Self> {
        let mut hasher = blake3::Hasher::new();
        let mut buffer = [0u8; 8192];

        loop {
            let n = reader.read(&mut buffer)?;
            if n == 0 {
                break;
            }
            hasher.update(&buffer[..n]);
        }

        Ok(Self(*hasher.finalize().as_bytes()))
    }

    /// Create a `StrongHash` from raw bytes.
    ///
    /// # Arguments
    ///
    /// * `bytes` - 32-byte array
    #[must_use]
    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }

    /// Get the raw bytes of the hash.
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Get a truncated view of the hash.
    ///
    /// Useful for memory-efficient signature tables where full
    /// 32-byte hashes aren't necessary.
    ///
    /// # Arguments
    ///
    /// * `len` - Number of bytes to return (clamped to 32)
    #[must_use]
    pub fn truncated(&self, len: usize) -> &[u8] {
        &self.0[..len.min(32)]
    }

    /// Check equality of truncated hashes.
    ///
    /// # Arguments
    ///
    /// * `other` - Other hash to compare
    /// * `len` - Number of bytes to compare
    #[must_use]
    pub fn eq_truncated(&self, other: &Self, len: usize) -> bool {
        self.truncated(len) == other.truncated(len)
    }

    /// Constant-time equality comparison.
    ///
    /// Prevents timing attacks when comparing hashes in security-sensitive contexts.
    #[must_use]
    pub fn ct_eq(&self, other: &Self) -> bool {
        // XOR all bytes and OR results together
        // If any byte differs, result will be non-zero
        let mut result = 0u8;
        for (a, b) in self.0.iter().zip(other.0.iter()) {
            result |= a ^ b;
        }
        result == 0
    }

    /// Create a zero hash (for testing/initialization).
    #[must_use]
    pub const fn zero() -> Self {
        Self([0u8; 32])
    }
}

impl std::fmt::Debug for StrongHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "StrongHash({:016x}...)",
            u64::from_be_bytes(self.0[..8].try_into().unwrap_or([0u8; 8]))
        )
    }
}

impl std::fmt::Display for StrongHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for byte in &self.0 {
            write!(f, "{byte:02x}")?;
        }
        Ok(())
    }
}

impl Default for StrongHash {
    fn default() -> Self {
        Self::zero()
    }
}

impl AsRef<[u8]> for StrongHash {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    // ==========================================================================
    // UNIT TESTS - Basic functionality
    // ==========================================================================

    #[test]
    fn compute_empty() {
        let hash = StrongHash::compute(b"");
        // BLAKE3 has a well-defined hash for empty input
        assert_ne!(hash, StrongHash::zero());
    }

    #[test]
    fn compute_single_byte() {
        let hash = StrongHash::compute(b"a");
        assert_ne!(hash, StrongHash::zero());
        assert_ne!(hash, StrongHash::compute(b""));
    }

    #[test]
    fn compute_deterministic() {
        let data = b"test data for hashing";
        let hash1 = StrongHash::compute(data);
        let hash2 = StrongHash::compute(data);
        assert_eq!(hash1, hash2);
    }

    #[test]
    fn compute_different_data() {
        let hash1 = StrongHash::compute(b"hello");
        let hash2 = StrongHash::compute(b"world");
        assert_ne!(hash1, hash2);
    }

    #[test]
    fn compute_case_sensitive() {
        let hash1 = StrongHash::compute(b"Hello");
        let hash2 = StrongHash::compute(b"hello");
        assert_ne!(hash1, hash2);
    }

    // ==========================================================================
    // STREAMING TESTS
    // ==========================================================================

    #[test]
    fn streaming_matches_direct() {
        let data = b"test data for streaming hash computation";
        let direct = StrongHash::compute(data);

        let mut cursor = Cursor::new(data);
        let streaming = StrongHash::compute_streaming(&mut cursor).unwrap();

        assert_eq!(direct, streaming);
    }

    #[test]
    fn streaming_empty() {
        let data: &[u8] = b"";
        let direct = StrongHash::compute(data);

        let mut cursor = Cursor::new(data);
        let streaming = StrongHash::compute_streaming(&mut cursor).unwrap();

        assert_eq!(direct, streaming);
    }

    #[test]
    fn streaming_large_data() {
        let data = vec![42u8; 100_000];
        let direct = StrongHash::compute(&data);

        let mut cursor = Cursor::new(&data);
        let streaming = StrongHash::compute_streaming(&mut cursor).unwrap();

        assert_eq!(direct, streaming);
    }

    // ==========================================================================
    // TRUNCATION TESTS
    // ==========================================================================

    #[test]
    fn truncated_returns_prefix() {
        let hash = StrongHash::compute(b"test");
        let full = hash.as_bytes();
        let truncated = hash.truncated(8);

        assert_eq!(truncated.len(), 8);
        assert_eq!(truncated, &full[..8]);
    }

    #[test]
    fn truncated_clamps_to_32() {
        let hash = StrongHash::compute(b"test");
        let truncated = hash.truncated(100);
        assert_eq!(truncated.len(), 32);
    }

    #[test]
    fn truncated_zero() {
        let hash = StrongHash::compute(b"test");
        let truncated = hash.truncated(0);
        assert!(truncated.is_empty());
    }

    #[test]
    fn eq_truncated_equal() {
        let hash1 = StrongHash::compute(b"test");
        let hash2 = StrongHash::compute(b"test");
        assert!(hash1.eq_truncated(&hash2, 8));
        assert!(hash1.eq_truncated(&hash2, 32));
    }

    #[test]
    fn eq_truncated_different() {
        let hash1 = StrongHash::compute(b"test1");
        let hash2 = StrongHash::compute(b"test2");
        assert!(!hash1.eq_truncated(&hash2, 8));
    }

    // ==========================================================================
    // CONSTANT TIME COMPARISON
    // ==========================================================================

    #[test]
    fn ct_eq_equal() {
        let hash1 = StrongHash::compute(b"test");
        let hash2 = StrongHash::compute(b"test");
        assert!(hash1.ct_eq(&hash2));
    }

    #[test]
    fn ct_eq_different() {
        let hash1 = StrongHash::compute(b"test1");
        let hash2 = StrongHash::compute(b"test2");
        assert!(!hash1.ct_eq(&hash2));
    }

    #[test]
    fn ct_eq_matches_regular_eq() {
        let hash1 = StrongHash::compute(b"same data");
        let hash2 = StrongHash::compute(b"same data");
        let hash3 = StrongHash::compute(b"different");

        assert_eq!(hash1 == hash2, hash1.ct_eq(&hash2));
        assert_eq!(hash1 == hash3, hash1.ct_eq(&hash3));
    }

    // ==========================================================================
    // CONSTRUCTORS AND CONVERSIONS
    // ==========================================================================

    #[test]
    fn from_bytes() {
        let bytes = [42u8; 32];
        let hash = StrongHash::from_bytes(bytes);
        assert_eq!(*hash.as_bytes(), bytes);
    }

    #[test]
    fn zero() {
        let hash = StrongHash::zero();
        assert_eq!(*hash.as_bytes(), [0u8; 32]);
    }

    #[test]
    fn default_is_zero() {
        assert_eq!(StrongHash::default(), StrongHash::zero());
    }

    #[test]
    fn as_ref() {
        let hash = StrongHash::compute(b"test");
        let bytes: &[u8] = hash.as_ref();
        assert_eq!(bytes.len(), 32);
        assert_eq!(bytes, hash.as_bytes());
    }

    // ==========================================================================
    // DISPLAY AND DEBUG
    // ==========================================================================

    #[test]
    fn display_format() {
        let hash = StrongHash::compute(b"test");
        let display = format!("{hash}");
        assert_eq!(display.len(), 64); // 32 bytes * 2 hex chars
        assert!(display.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn debug_format() {
        let hash = StrongHash::compute(b"test");
        let debug = format!("{hash:?}");
        assert!(debug.starts_with("StrongHash("));
        assert!(debug.contains("..."));
    }

    // ==========================================================================
    // HASHING (as HashMap key)
    // ==========================================================================

    #[test]
    fn hashable() {
        use std::collections::HashSet;

        let mut set = HashSet::new();
        let hash1 = StrongHash::compute(b"test1");
        let hash2 = StrongHash::compute(b"test2");
        let hash3 = StrongHash::compute(b"test1"); // Same as hash1

        set.insert(hash1);
        set.insert(hash2);
        set.insert(hash3);

        assert_eq!(set.len(), 2); // hash1 and hash3 are equal
    }

    // ==========================================================================
    // SERDE SERIALIZATION
    // ==========================================================================

    #[test]
    fn serde_roundtrip() {
        let original = StrongHash::compute(b"test data");
        let serialized = bincode::serialize(&original).unwrap();
        let deserialized: StrongHash = bincode::deserialize(&serialized).unwrap();
        assert_eq!(original, deserialized);
    }

    #[test]
    fn serde_size() {
        let hash = StrongHash::compute(b"test");
        let serialized = bincode::serialize(&hash).unwrap();
        // Should be exactly 32 bytes (no overhead with bincode)
        assert_eq!(serialized.len(), 32);
    }

    // ==========================================================================
    // EDGE CASES
    // ==========================================================================

    #[test]
    fn binary_data() {
        let data: Vec<u8> = (0..=255).collect();
        let hash = StrongHash::compute(&data);
        assert_ne!(hash, StrongHash::zero());
    }

    #[test]
    fn large_data() {
        let data = vec![0xABu8; 1_000_000];
        let hash = StrongHash::compute(&data);
        assert_ne!(hash, StrongHash::zero());
    }

    #[test]
    fn null_bytes() {
        let hash1 = StrongHash::compute(&[0u8; 10]);
        let hash2 = StrongHash::compute(&[0u8; 11]);
        assert_ne!(hash1, hash2); // Different lengths should produce different hashes
    }

    // ==========================================================================
    // CLONE AND COPY
    // ==========================================================================

    #[test]
    fn clone_equals_original() {
        let original = StrongHash::compute(b"test");
        let cloned = original;
        assert_eq!(original, cloned);
    }

    #[test]
    fn copy_semantics() {
        let original = StrongHash::compute(b"test");
        let copied = original; // Copy, not move
        assert_eq!(original, copied);
        // Both should still be usable
        let _ = original.as_bytes();
        let _ = copied.as_bytes();
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        /// Hash computation is deterministic
        #[test]
        fn deterministic(data in prop::collection::vec(any::<u8>(), 0..1000)) {
            let hash1 = StrongHash::compute(&data);
            let hash2 = StrongHash::compute(&data);
            prop_assert_eq!(hash1, hash2);
        }

        /// Different data (usually) produces different hashes
        #[test]
        fn collision_resistant(
            data1 in prop::collection::vec(any::<u8>(), 1..100),
            data2 in prop::collection::vec(any::<u8>(), 1..100)
        ) {
            if data1 != data2 {
                let hash1 = StrongHash::compute(&data1);
                let hash2 = StrongHash::compute(&data2);
                // With 256-bit hashes, collisions are astronomically unlikely
                prop_assert_ne!(hash1, hash2);
            }
        }

        /// Streaming and direct produce same result
        #[test]
        fn streaming_equivalence(data in prop::collection::vec(any::<u8>(), 0..10000)) {
            let direct = StrongHash::compute(&data);
            let mut cursor = std::io::Cursor::new(&data);
            let streaming = StrongHash::compute_streaming(&mut cursor).unwrap();
            prop_assert_eq!(direct, streaming);
        }

        /// Truncation returns correct prefix
        #[test]
        fn truncation_correct(
            data in prop::collection::vec(any::<u8>(), 1..100),
            len in 0usize..40
        ) {
            let hash = StrongHash::compute(&data);
            let truncated = hash.truncated(len);
            let expected_len = len.min(32);
            prop_assert_eq!(truncated.len(), expected_len);
            prop_assert_eq!(truncated, &hash.as_bytes()[..expected_len]);
        }

        /// ct_eq matches regular equality
        #[test]
        fn ct_eq_matches_eq(
            data1 in prop::collection::vec(any::<u8>(), 0..100),
            data2 in prop::collection::vec(any::<u8>(), 0..100)
        ) {
            let hash1 = StrongHash::compute(&data1);
            let hash2 = StrongHash::compute(&data2);
            prop_assert_eq!(hash1 == hash2, hash1.ct_eq(&hash2));
        }

        /// Serde roundtrip preserves data
        #[test]
        fn serde_roundtrip_preserves(data in prop::collection::vec(any::<u8>(), 0..100)) {
            let original = StrongHash::compute(&data);
            let serialized = bincode::serialize(&original).unwrap();
            let deserialized: StrongHash = bincode::deserialize(&serialized).unwrap();
            prop_assert_eq!(original, deserialized);
        }
    }
}