iscc-lib 0.4.0

High-performance Rust implementation of ISO 24138:2024 (ISCC)
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
//! Streaming hash types for incremental ISCC code generation.
//!
//! Provides `DataHasher` and `InstanceHasher` — streaming counterparts to
//! `gen_data_code_v0` and `gen_instance_code_v0`. Both follow the
//! `new() → update(&[u8]) → finalize()` pattern for incremental processing
//! of large files without loading entire contents into memory.

use crate::types::{DataCodeResult, InstanceCodeResult};
use crate::{IsccResult, cdc, codec, minhash};

/// Streaming Instance-Code generator.
///
/// Incrementally hashes data with BLAKE3 to produce an ISCC Instance-Code
/// identical to `gen_instance_code_v0` for the same byte stream.
pub struct InstanceHasher {
    hasher: blake3::Hasher,
    filesize: u64,
}

impl InstanceHasher {
    /// Create a new `InstanceHasher`.
    pub fn new() -> Self {
        Self {
            hasher: blake3::Hasher::new(),
            filesize: 0,
        }
    }

    /// Push data into the hasher.
    pub fn update(&mut self, data: &[u8]) {
        self.filesize += data.len() as u64;
        self.hasher.update(data);
    }

    /// Consume the hasher and produce an Instance-Code result.
    ///
    /// Equivalent to calling `gen_instance_code_v0` with the concatenation
    /// of all data passed to `update`.
    pub fn finalize(self, bits: u32) -> IsccResult<InstanceCodeResult> {
        let digest = self.hasher.finalize();
        let datahash = format!("1e20{}", hex::encode(digest.as_bytes()));
        let component = codec::encode_component(
            codec::MainType::Instance,
            codec::SubType::None,
            codec::Version::V0,
            bits,
            digest.as_bytes(),
        )?;
        Ok(InstanceCodeResult {
            iscc: format!("ISCC:{component}"),
            datahash,
            filesize: self.filesize,
        })
    }
}

impl Default for InstanceHasher {
    /// Create a new `InstanceHasher` (delegates to `new()`).
    fn default() -> Self {
        Self::new()
    }
}

/// Streaming Data-Code generator.
///
/// Incrementally processes data with content-defined chunking (CDC) and
/// MinHash to produce an ISCC Data-Code identical to `gen_data_code_v0`
/// for the same byte stream. Uses a persistent internal buffer to avoid
/// per-call heap allocations.
pub struct DataHasher {
    chunk_features: Vec<u32>,
    buf: Vec<u8>,
}

impl DataHasher {
    /// Create a new `DataHasher`.
    pub fn new() -> Self {
        Self {
            chunk_features: Vec::new(),
            buf: Vec::new(),
        }
    }

    /// Push data into the hasher.
    ///
    /// Appends data to the internal buffer (which starts with the retained
    /// tail from the previous call), runs CDC, hashes all complete chunks,
    /// and shifts the last chunk (tail) to the front of the buffer for the
    /// next call. The buffer is reused across calls to avoid allocations.
    pub fn update(&mut self, data: &[u8]) {
        self.buf.extend_from_slice(data);

        let chunks = cdc::alg_cdc_chunks_unchecked(&self.buf, false, cdc::DATA_AVG_CHUNK_SIZE);

        // Process all chunks except the last (which becomes the new tail).
        // This mirrors the Python `push()` method's `prev_chunk` pattern.
        let mut prev_chunk: Option<&[u8]> = None;
        for chunk in &chunks {
            if let Some(pc) = prev_chunk {
                self.chunk_features.push(xxhash_rust::xxh32::xxh32(pc, 0));
            }
            prev_chunk = Some(chunk);
        }

        // Extract tail length before dropping borrows on self.buf
        let tail_len = prev_chunk.map_or(0, |c| c.len());
        drop(chunks);

        // Shift tail to front of buffer, reusing existing capacity
        let tail_start = self.buf.len() - tail_len;
        self.buf.copy_within(tail_start.., 0);
        self.buf.truncate(tail_len);
    }

    /// Consume the hasher and produce a Data-Code result.
    ///
    /// Equivalent to calling `gen_data_code_v0` with the concatenation
    /// of all data passed to `update`.
    pub fn finalize(mut self, bits: u32) -> IsccResult<DataCodeResult> {
        if !self.buf.is_empty() {
            self.chunk_features
                .push(xxhash_rust::xxh32::xxh32(&self.buf, 0));
        } else if self.chunk_features.is_empty() {
            // Empty input: ensure at least one feature
            self.chunk_features.push(xxhash_rust::xxh32::xxh32(b"", 0));
        }

        let digest = minhash::alg_minhash_256(&self.chunk_features);
        let component = codec::encode_component(
            codec::MainType::Data,
            codec::SubType::None,
            codec::Version::V0,
            bits,
            &digest,
        )?;

        Ok(DataCodeResult {
            iscc: format!("ISCC:{component}"),
        })
    }
}

impl Default for DataHasher {
    /// Create a new `DataHasher` (delegates to `new()`).
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{gen_data_code_v0, gen_instance_code_v0};

    // ---- InstanceHasher tests ----

    #[test]
    fn test_instance_hasher_empty() {
        let ih = InstanceHasher::new();
        let streaming = ih.finalize(64).unwrap();
        let oneshot = gen_instance_code_v0(b"", 64).unwrap();
        assert_eq!(streaming.iscc, oneshot.iscc);
        assert_eq!(streaming.datahash, oneshot.datahash);
        assert_eq!(streaming.filesize, oneshot.filesize);
        assert_eq!(streaming.filesize, 0);
    }

    #[test]
    fn test_instance_hasher_small_data() {
        let data = b"Hello, ISCC World!";
        let mut ih = InstanceHasher::new();
        ih.update(data);
        let streaming = ih.finalize(64).unwrap();
        let oneshot = gen_instance_code_v0(data, 64).unwrap();
        assert_eq!(streaming.iscc, oneshot.iscc);
        assert_eq!(streaming.datahash, oneshot.datahash);
        assert_eq!(streaming.filesize, oneshot.filesize);
    }

    #[test]
    fn test_instance_hasher_multi_chunk() {
        let data = b"The quick brown fox jumps over the lazy dog";
        let mut ih = InstanceHasher::new();
        ih.update(&data[..10]);
        ih.update(&data[10..25]);
        ih.update(&data[25..]);
        let streaming = ih.finalize(64).unwrap();
        let oneshot = gen_instance_code_v0(data, 64).unwrap();
        assert_eq!(streaming.iscc, oneshot.iscc);
        assert_eq!(streaming.datahash, oneshot.datahash);
        assert_eq!(streaming.filesize, oneshot.filesize);
    }

    #[test]
    fn test_instance_hasher_byte_at_a_time() {
        let data = b"streaming byte by byte";
        let mut ih = InstanceHasher::new();
        for &b in data.iter() {
            ih.update(&[b]);
        }
        let streaming = ih.finalize(128).unwrap();
        let oneshot = gen_instance_code_v0(data, 128).unwrap();
        assert_eq!(streaming.iscc, oneshot.iscc);
        assert_eq!(streaming.datahash, oneshot.datahash);
        assert_eq!(streaming.filesize, oneshot.filesize);
    }

    #[test]
    fn test_instance_hasher_default() {
        let ih = InstanceHasher::default();
        let streaming = ih.finalize(64).unwrap();
        let oneshot = gen_instance_code_v0(b"", 64).unwrap();
        assert_eq!(streaming.iscc, oneshot.iscc);
    }

    #[test]
    fn test_instance_hasher_various_bits() {
        let data = b"test various bit widths";
        for bits in [64, 128, 256] {
            let mut ih = InstanceHasher::new();
            ih.update(data);
            let streaming = ih.finalize(bits).unwrap();
            let oneshot = gen_instance_code_v0(data, bits).unwrap();
            assert_eq!(streaming.iscc, oneshot.iscc, "bits={bits}");
            assert_eq!(streaming.datahash, oneshot.datahash, "bits={bits}");
        }
    }

    #[test]
    fn test_instance_hasher_conformance() {
        let json_str = include_str!("../tests/data.json");
        let data: serde_json::Value = serde_json::from_str(json_str).unwrap();
        let section = &data["gen_instance_code_v0"];
        let cases = section.as_object().unwrap();

        for (name, tc) in cases {
            let inputs = tc["inputs"].as_array().unwrap();
            let stream_str = inputs[0].as_str().unwrap();
            let bits = inputs[1].as_u64().unwrap() as u32;

            let hex_data = stream_str
                .strip_prefix("stream:")
                .unwrap_or_else(|| panic!("expected 'stream:' prefix in test case {name}"));
            let input_bytes = hex::decode(hex_data)
                .unwrap_or_else(|e| panic!("invalid hex in test case {name}: {e}"));

            // One-shot reference
            let oneshot = gen_instance_code_v0(&input_bytes, bits)
                .unwrap_or_else(|e| panic!("gen_instance_code_v0 failed for {name}: {e}"));

            // Streaming — single update
            let mut ih = InstanceHasher::new();
            ih.update(&input_bytes);
            let streaming = ih
                .finalize(bits)
                .unwrap_or_else(|e| panic!("InstanceHasher failed for {name}: {e}"));

            assert_eq!(
                streaming.iscc, oneshot.iscc,
                "ISCC mismatch in test case {name}"
            );
            assert_eq!(
                streaming.datahash, oneshot.datahash,
                "datahash mismatch in test case {name}"
            );
            assert_eq!(
                streaming.filesize, oneshot.filesize,
                "filesize mismatch in test case {name}"
            );

            // Streaming — multi-chunk (split into 256-byte chunks)
            let mut ih2 = InstanceHasher::new();
            for chunk in input_bytes.chunks(256) {
                ih2.update(chunk);
            }
            let streaming2 = ih2
                .finalize(bits)
                .unwrap_or_else(|e| panic!("InstanceHasher multi-chunk failed for {name}: {e}"));

            assert_eq!(
                streaming2.iscc, oneshot.iscc,
                "multi-chunk ISCC mismatch in test case {name}"
            );
            assert_eq!(
                streaming2.datahash, oneshot.datahash,
                "multi-chunk datahash mismatch in test case {name}"
            );
        }
    }

    // ---- DataHasher tests ----

    #[test]
    fn test_data_hasher_empty() {
        let dh = DataHasher::new();
        let streaming = dh.finalize(64).unwrap();
        let oneshot = gen_data_code_v0(b"", 64).unwrap();
        assert_eq!(streaming.iscc, oneshot.iscc);
    }

    #[test]
    fn test_data_hasher_small_data() {
        let data = b"Hello, ISCC World!";
        let mut dh = DataHasher::new();
        dh.update(data);
        let streaming = dh.finalize(64).unwrap();
        let oneshot = gen_data_code_v0(data, 64).unwrap();
        assert_eq!(streaming.iscc, oneshot.iscc);
    }

    #[test]
    fn test_data_hasher_multi_chunk_small() {
        let data = b"The quick brown fox jumps over the lazy dog";
        let mut dh = DataHasher::new();
        dh.update(&data[..10]);
        dh.update(&data[10..25]);
        dh.update(&data[25..]);
        let streaming = dh.finalize(64).unwrap();
        let oneshot = gen_data_code_v0(data, 64).unwrap();
        assert_eq!(streaming.iscc, oneshot.iscc);
    }

    #[test]
    fn test_data_hasher_byte_at_a_time() {
        // Small data that fits within a single CDC chunk
        let data = b"streaming byte by byte";
        let mut dh = DataHasher::new();
        for &b in data.iter() {
            dh.update(&[b]);
        }
        let streaming = dh.finalize(64).unwrap();
        let oneshot = gen_data_code_v0(data, 64).unwrap();
        assert_eq!(streaming.iscc, oneshot.iscc);
    }

    #[test]
    fn test_data_hasher_large_data_multi_chunk() {
        // Generate data large enough to produce multiple CDC chunks
        let data: Vec<u8> = (0..10_000).map(|i| (i % 256) as u8).collect();
        for chunk_size in [1, 256, 1024, 4096] {
            let mut dh = DataHasher::new();
            for chunk in data.chunks(chunk_size) {
                dh.update(chunk);
            }
            let streaming = dh.finalize(64).unwrap();
            let oneshot = gen_data_code_v0(&data, 64).unwrap();
            assert_eq!(
                streaming.iscc, oneshot.iscc,
                "chunk_size={chunk_size} mismatch"
            );
        }
    }

    #[test]
    fn test_data_hasher_default() {
        let dh = DataHasher::default();
        let streaming = dh.finalize(64).unwrap();
        let oneshot = gen_data_code_v0(b"", 64).unwrap();
        assert_eq!(streaming.iscc, oneshot.iscc);
    }

    #[test]
    fn test_data_hasher_various_bits() {
        let data = b"test various bit widths for data code";
        for bits in [64, 128, 256] {
            let mut dh = DataHasher::new();
            dh.update(data);
            let streaming = dh.finalize(bits).unwrap();
            let oneshot = gen_data_code_v0(data, bits).unwrap();
            assert_eq!(streaming.iscc, oneshot.iscc, "bits={bits}");
        }
    }

    #[test]
    fn test_data_hasher_conformance() {
        let json_str = include_str!("../tests/data.json");
        let data: serde_json::Value = serde_json::from_str(json_str).unwrap();
        let section = &data["gen_data_code_v0"];
        let cases = section.as_object().unwrap();

        for (name, tc) in cases {
            let inputs = tc["inputs"].as_array().unwrap();
            let stream_str = inputs[0].as_str().unwrap();
            let bits = inputs[1].as_u64().unwrap() as u32;

            let hex_data = stream_str
                .strip_prefix("stream:")
                .unwrap_or_else(|| panic!("expected 'stream:' prefix in test case {name}"));
            let input_bytes = hex::decode(hex_data)
                .unwrap_or_else(|e| panic!("invalid hex in test case {name}: {e}"));

            // One-shot reference
            let oneshot = gen_data_code_v0(&input_bytes, bits)
                .unwrap_or_else(|e| panic!("gen_data_code_v0 failed for {name}: {e}"));

            // Streaming — single update
            let mut dh = DataHasher::new();
            dh.update(&input_bytes);
            let streaming = dh
                .finalize(bits)
                .unwrap_or_else(|e| panic!("DataHasher failed for {name}: {e}"));

            assert_eq!(
                streaming.iscc, oneshot.iscc,
                "ISCC mismatch in test case {name}"
            );

            // Streaming — 256-byte chunks
            let mut dh2 = DataHasher::new();
            for chunk in input_bytes.chunks(256) {
                dh2.update(chunk);
            }
            let streaming2 = dh2
                .finalize(bits)
                .unwrap_or_else(|e| panic!("DataHasher multi-chunk failed for {name}: {e}"));

            assert_eq!(
                streaming2.iscc, oneshot.iscc,
                "multi-chunk ISCC mismatch in test case {name}"
            );

            // Streaming — 1-byte chunks (stress test)
            let mut dh3 = DataHasher::new();
            for &b in &input_bytes {
                dh3.update(&[b]);
            }
            let streaming3 = dh3
                .finalize(bits)
                .unwrap_or_else(|e| panic!("DataHasher byte-at-a-time failed for {name}: {e}"));

            assert_eq!(
                streaming3.iscc, oneshot.iscc,
                "byte-at-a-time ISCC mismatch in test case {name}"
            );
        }
    }
}