iscc-lib 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/core/src/codec.rs ADDED
@@ -0,0 +1,2074 @@
1
+ //! ISCC codec: type enums, header encoding/decoding, base32, and component encoding.
2
+ //!
3
+ //! Provides the foundational encoding primitives that all `gen_*_v0` functions
4
+ //! depend on to produce ISCC-encoded output strings. This is a Tier 2 module —
5
+ //! available to Rust consumers but not exposed through FFI bindings.
6
+
7
+ use crate::{IsccError, IsccResult};
8
+ use std::borrow::Cow;
9
+
10
+ // ---- Type Enums ----
11
+
12
+ /// ISCC MainType identifier.
13
+ ///
14
+ /// Integer values match the `iscc-core` Python reference (MT enum).
15
+ #[repr(u8)]
16
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
17
+ pub enum MainType {
18
+ Meta = 0,
19
+ Semantic = 1,
20
+ Content = 2,
21
+ Data = 3,
22
+ Instance = 4,
23
+ Iscc = 5,
24
+ Id = 6,
25
+ Flake = 7,
26
+ }
27
+
28
+ impl TryFrom<u8> for MainType {
29
+ type Error = IsccError;
30
+
31
+ fn try_from(value: u8) -> Result<Self, Self::Error> {
32
+ match value {
33
+ 0 => Ok(Self::Meta),
34
+ 1 => Ok(Self::Semantic),
35
+ 2 => Ok(Self::Content),
36
+ 3 => Ok(Self::Data),
37
+ 4 => Ok(Self::Instance),
38
+ 5 => Ok(Self::Iscc),
39
+ 6 => Ok(Self::Id),
40
+ 7 => Ok(Self::Flake),
41
+ _ => Err(IsccError::InvalidInput(format!(
42
+ "invalid MainType: {value}"
43
+ ))),
44
+ }
45
+ }
46
+ }
47
+
48
+ /// ISCC SubType identifier.
49
+ ///
50
+ /// A unified enum covering all subtype contexts (ST, ST_CC, ST_ISCC).
51
+ /// The interpretation depends on the MainType context. Integer values
52
+ /// match the `iscc-core` Python reference.
53
+ #[repr(u8)]
54
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
55
+ pub enum SubType {
56
+ /// No specific subtype (general) / Text content (ST_CC context).
57
+ None = 0,
58
+ /// Image content.
59
+ Image = 1,
60
+ /// Audio content.
61
+ Audio = 2,
62
+ /// Video content.
63
+ Video = 3,
64
+ /// Mixed content.
65
+ Mixed = 4,
66
+ /// ISCC composite summary (only 2 mandatory units, no optional).
67
+ Sum = 5,
68
+ /// ISCC no specific content type (3+ units, mixed subtypes).
69
+ IsccNone = 6,
70
+ /// ISCC wide mode (256-bit Data+Instance composite).
71
+ Wide = 7,
72
+ }
73
+
74
+ impl SubType {
75
+ /// Alias for `None` (value 0) in Content-Code / Semantic-Code context.
76
+ pub const TEXT: Self = Self::None;
77
+ }
78
+
79
+ impl TryFrom<u8> for SubType {
80
+ type Error = IsccError;
81
+
82
+ fn try_from(value: u8) -> Result<Self, Self::Error> {
83
+ match value {
84
+ 0 => Ok(Self::None),
85
+ 1 => Ok(Self::Image),
86
+ 2 => Ok(Self::Audio),
87
+ 3 => Ok(Self::Video),
88
+ 4 => Ok(Self::Mixed),
89
+ 5 => Ok(Self::Sum),
90
+ 6 => Ok(Self::IsccNone),
91
+ 7 => Ok(Self::Wide),
92
+ _ => Err(IsccError::InvalidInput(format!("invalid SubType: {value}"))),
93
+ }
94
+ }
95
+ }
96
+
97
+ /// ISCC version identifier.
98
+ ///
99
+ /// `V1` exists only for the experimental ISCC-IDv1 (MainType `Id`); every other
100
+ /// MainType permits only `V0`. This enum is `#[non_exhaustive]` so future
101
+ /// versions can be added without a further SemVer-major break.
102
+ #[repr(u8)]
103
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
104
+ #[non_exhaustive]
105
+ pub enum Version {
106
+ V0 = 0,
107
+ V1 = 1,
108
+ }
109
+
110
+ impl TryFrom<u8> for Version {
111
+ type Error = IsccError;
112
+
113
+ fn try_from(value: u8) -> Result<Self, Self::Error> {
114
+ match value {
115
+ 0 => Ok(Self::V0),
116
+ 1 => Ok(Self::V1),
117
+ _ => Err(IsccError::InvalidInput(format!("invalid Version: {value}"))),
118
+ }
119
+ }
120
+ }
121
+
122
+ /// Validate a MainType/Version combination.
123
+ ///
124
+ /// Version 1 is accepted only for MainType `Id` (the experimental ISCC-IDv1);
125
+ /// every other MainType permits only Version 0. This is the MainType-aware gate
126
+ /// the context-free `Version::try_from` cannot express: `try_from` maps the raw
127
+ /// nibble, while this function rejects a Version-1 header on any non-`Id` type.
128
+ fn validate_version(mtype: MainType, version: Version) -> IsccResult<()> {
129
+ match (mtype, version) {
130
+ (_, Version::V0) | (MainType::Id, Version::V1) => Ok(()),
131
+ (_, other) => Err(IsccError::InvalidInput(format!(
132
+ "invalid Version: {} for MainType {mtype:?}",
133
+ other as u8
134
+ ))),
135
+ }
136
+ }
137
+
138
+ // ---- Bit Manipulation Helpers ----
139
+
140
+ /// Read bit at position `bit_pos` from byte slice (MSB-first ordering).
141
+ fn get_bit(data: &[u8], bit_pos: usize) -> bool {
142
+ let byte_idx = bit_pos / 8;
143
+ let bit_idx = 7 - (bit_pos % 8);
144
+ (data[byte_idx] >> bit_idx) & 1 == 1
145
+ }
146
+
147
+ /// Extract `count` bits starting at `bit_pos` as a u32 (MSB-first).
148
+ fn extract_bits(data: &[u8], bit_pos: usize, count: usize) -> u32 {
149
+ let mut value = 0u32;
150
+ for i in 0..count {
151
+ value = (value << 1) | u32::from(get_bit(data, bit_pos + i));
152
+ }
153
+ value
154
+ }
155
+
156
+ /// Convert a bit slice (big-endian, MSB first) to a u32.
157
+ #[cfg(test)]
158
+ fn bits_to_u32(bits: &[bool]) -> u32 {
159
+ bits.iter().fold(0u32, |acc, &b| (acc << 1) | u32::from(b))
160
+ }
161
+
162
+ /// Convert bytes to a bit vector (big-endian, MSB first).
163
+ #[cfg(test)]
164
+ fn bytes_to_bits(bytes: &[u8]) -> Vec<bool> {
165
+ bytes
166
+ .iter()
167
+ .flat_map(|&byte| (0..8).rev().map(move |i| (byte >> i) & 1 == 1))
168
+ .collect()
169
+ }
170
+
171
+ /// Convert a bit vector to bytes, padding with zero bits on the right.
172
+ fn bits_to_bytes(bits: &[bool]) -> Vec<u8> {
173
+ bits.chunks(8)
174
+ .map(|chunk| {
175
+ chunk.iter().enumerate().fold(
176
+ 0u8,
177
+ |byte, (i, &bit)| if bit { byte | (1 << (7 - i)) } else { byte },
178
+ )
179
+ })
180
+ .collect()
181
+ }
182
+
183
+ // ---- Varnibble Encoding ----
184
+
185
+ /// Encode an integer as a variable-length nibble (varnibble) bit sequence.
186
+ ///
187
+ /// Encoding scheme:
188
+ /// - `0xxx` (4 bits, 1 nibble): values 0–7
189
+ /// - `10xxxxxx` (8 bits, 2 nibbles): values 8–71
190
+ /// - `110xxxxxxxxx` (12 bits, 3 nibbles): values 72–583
191
+ /// - `1110xxxxxxxxxxxx` (16 bits, 4 nibbles): values 584–4679
192
+ fn encode_varnibble(value: u32) -> IsccResult<Vec<bool>> {
193
+ match value {
194
+ 0..=7 => {
195
+ // 4 bits: value fits directly (leading 0 implicit in 4-bit encoding)
196
+ Ok((0..4).rev().map(|i| (value >> i) & 1 == 1).collect())
197
+ }
198
+ 8..=71 => {
199
+ // 8 bits: prefix 10 + 6 data bits for (value - 8)
200
+ let v = value - 8;
201
+ let mut bits = vec![true, false];
202
+ bits.extend((0..6).rev().map(|i| (v >> i) & 1 == 1));
203
+ Ok(bits)
204
+ }
205
+ 72..=583 => {
206
+ // 12 bits: prefix 110 + 9 data bits for (value - 72)
207
+ let v = value - 72;
208
+ let mut bits = vec![true, true, false];
209
+ bits.extend((0..9).rev().map(|i| (v >> i) & 1 == 1));
210
+ Ok(bits)
211
+ }
212
+ 584..=4679 => {
213
+ // 16 bits: prefix 1110 + 12 data bits for (value - 584)
214
+ let v = value - 584;
215
+ let mut bits = vec![true, true, true, false];
216
+ bits.extend((0..12).rev().map(|i| (v >> i) & 1 == 1));
217
+ Ok(bits)
218
+ }
219
+ _ => Err(IsccError::InvalidInput(format!(
220
+ "varnibble value out of range (0-4679): {value}"
221
+ ))),
222
+ }
223
+ }
224
+
225
+ /// Decode the first varnibble from a byte slice at the given bit position.
226
+ ///
227
+ /// Operates directly on `&[u8]` with bitwise extraction, avoiding any
228
+ /// intermediate `Vec<bool>` allocation. Returns the decoded integer and
229
+ /// the number of bits consumed.
230
+ fn decode_varnibble_from_bytes(data: &[u8], bit_pos: usize) -> IsccResult<(u32, usize)> {
231
+ let available = data.len() * 8 - bit_pos;
232
+ if available < 4 {
233
+ return Err(IsccError::InvalidInput(
234
+ "insufficient bits for varnibble".into(),
235
+ ));
236
+ }
237
+
238
+ if !get_bit(data, bit_pos) {
239
+ // 0xxx — 4 bits, values 0–7
240
+ Ok((extract_bits(data, bit_pos, 4), 4))
241
+ } else if available >= 8 && !get_bit(data, bit_pos + 1) {
242
+ // 10xxxxxx — 8 bits, values 8–71
243
+ Ok((extract_bits(data, bit_pos + 2, 6) + 8, 8))
244
+ } else if available >= 12 && !get_bit(data, bit_pos + 2) {
245
+ // 110xxxxxxxxx — 12 bits, values 72–583
246
+ Ok((extract_bits(data, bit_pos + 3, 9) + 72, 12))
247
+ } else if available >= 16 && !get_bit(data, bit_pos + 3) {
248
+ // 1110xxxxxxxxxxxx — 16 bits, values 584–4679
249
+ Ok((extract_bits(data, bit_pos + 4, 12) + 584, 16))
250
+ } else {
251
+ Err(IsccError::InvalidInput(
252
+ "invalid varnibble prefix or insufficient bits".into(),
253
+ ))
254
+ }
255
+ }
256
+
257
+ // ---- Header Encoding ----
258
+
259
+ /// Encode four raw header integers as padded varnibble bytes.
260
+ ///
261
+ /// Performs no MainType/SubType/Version semantics — only the varnibble range
262
+ /// check (0–4679). Pads an odd nibble count with a zero nibble on the right.
263
+ fn encode_header_raw(mtype: u32, stype: u32, version: u32, length: u32) -> IsccResult<Vec<u8>> {
264
+ let mut bits = Vec::new();
265
+ bits.extend(encode_varnibble(mtype)?);
266
+ bits.extend(encode_varnibble(stype)?);
267
+ bits.extend(encode_varnibble(version)?);
268
+ bits.extend(encode_varnibble(length)?);
269
+
270
+ // Pad to byte boundary with zero bits (equivalent to bitarray.fill())
271
+ let remainder = bits.len() % 8;
272
+ if remainder != 0 {
273
+ bits.resize(bits.len() + (8 - remainder), false);
274
+ }
275
+
276
+ Ok(bits_to_bytes(&bits))
277
+ }
278
+
279
+ /// Decode four raw header integers from bytes without type validation.
280
+ ///
281
+ /// Returns `(mtype, stype, version, length, tail_start)` where `tail_start` is
282
+ /// the byte offset of the data following the header. A 4-bit zero padding
283
+ /// nibble after a non-byte-aligned header is skipped; a non-zero nibble is not
284
+ /// (callers needing canonical headers re-encode and compare).
285
+ #[inline]
286
+ fn decode_header_raw(data: &[u8]) -> IsccResult<(u32, u32, u32, u32, usize)> {
287
+ let mut bit_pos = 0;
288
+
289
+ let (mtype, consumed) = decode_varnibble_from_bytes(data, bit_pos)?;
290
+ bit_pos += consumed;
291
+
292
+ let (stype, consumed) = decode_varnibble_from_bytes(data, bit_pos)?;
293
+ bit_pos += consumed;
294
+
295
+ let (version, consumed) = decode_varnibble_from_bytes(data, bit_pos)?;
296
+ bit_pos += consumed;
297
+
298
+ let (length, consumed) = decode_varnibble_from_bytes(data, bit_pos)?;
299
+ bit_pos += consumed;
300
+
301
+ // Strip 4-bit zero padding if header bits are not byte-aligned.
302
+ // Since each varnibble is a multiple of 4 bits, misalignment is always 4 bits.
303
+ if bit_pos % 8 != 0 && bit_pos + 4 <= data.len() * 8 && extract_bits(data, bit_pos, 4) == 0 {
304
+ bit_pos += 4;
305
+ }
306
+
307
+ Ok((mtype, stype, version, length, bit_pos.div_ceil(8)))
308
+ }
309
+
310
+ /// Encode ISCC header fields into bytes.
311
+ ///
312
+ /// Concatenates varnibble-encoded MainType, SubType, Version, and length,
313
+ /// then pads to byte boundary with zero bits on the right.
314
+ /// Result is 2 bytes minimum (typical case), up to 8 bytes maximum.
315
+ pub fn encode_header(
316
+ mtype: MainType,
317
+ stype: SubType,
318
+ version: Version,
319
+ length: u32,
320
+ ) -> IsccResult<Vec<u8>> {
321
+ validate_version(mtype, version)?;
322
+ encode_header_raw(mtype as u32, stype as u32, version as u32, length)
323
+ }
324
+
325
+ /// Decode ISCC header from bytes.
326
+ ///
327
+ /// Operates directly on `&[u8]` with bitwise extraction, avoiding any
328
+ /// intermediate `Vec<bool>` allocation. Returns `(MainType, SubType,
329
+ /// Version, length, tail_bytes)` where `tail_bytes` contains any
330
+ /// remaining data after the header.
331
+ pub fn decode_header(data: &[u8]) -> IsccResult<(MainType, SubType, Version, u32, Vec<u8>)> {
332
+ let (mtype_val, stype_val, version_val, length, tail_byte_start) = decode_header_raw(data)?;
333
+
334
+ let tail = if tail_byte_start < data.len() {
335
+ data[tail_byte_start..].to_vec()
336
+ } else {
337
+ vec![]
338
+ };
339
+
340
+ // Range-check each varnibble before narrowing so a multi-nibble value that
341
+ // does not fit in a u8 is rejected instead of wrapping (e.g. 262 -> 6 = Id).
342
+ let mtype_u8 = u8::try_from(mtype_val)
343
+ .map_err(|_| IsccError::InvalidInput(format!("invalid MainType: {mtype_val}")))?;
344
+ let stype_u8 = u8::try_from(stype_val)
345
+ .map_err(|_| IsccError::InvalidInput(format!("invalid SubType: {stype_val}")))?;
346
+ let version_u8 = u8::try_from(version_val)
347
+ .map_err(|_| IsccError::InvalidInput(format!("invalid Version: {version_val}")))?;
348
+
349
+ let mtype = MainType::try_from(mtype_u8)?;
350
+ let stype = SubType::try_from(stype_u8)?;
351
+ let version = Version::try_from(version_u8)?;
352
+ validate_version(mtype, version)?;
353
+
354
+ Ok((mtype, stype, version, length, tail))
355
+ }
356
+
357
+ // ---- Length Encoding ----
358
+
359
+ /// Bit lengths of an ISCC-ID: the ID values of iscc-core's `LN` enum (no 88).
360
+ const ID_BIT_LENGTHS: [u32; 4] = [64, 72, 80, 96];
361
+
362
+ /// Encode bit length to header length field value.
363
+ ///
364
+ /// Semantics depend on MainType:
365
+ /// - META/SEMANTIC/CONTENT/DATA/INSTANCE/FLAKE: `(bit_length / 32) - 1`, for a
366
+ /// multiple of 32 from 32 to 256 (an ISCC-UNIT is at most 256 bits)
367
+ /// - ISCC: pass-through (0–7, unit composition flags)
368
+ /// - ID: `(bit_length - 64) / 8`, for 64, 72, 80 or 96 (an 88-bit ID would not
369
+ /// decode on iscc-core)
370
+ pub fn encode_length(mtype: MainType, length: u32) -> IsccResult<u32> {
371
+ match mtype {
372
+ MainType::Meta
373
+ | MainType::Semantic
374
+ | MainType::Content
375
+ | MainType::Data
376
+ | MainType::Instance
377
+ | MainType::Flake => {
378
+ if (32..=256).contains(&length) && length % 32 == 0 {
379
+ Ok(length / 32 - 1)
380
+ } else {
381
+ Err(IsccError::InvalidInput(format!(
382
+ "invalid length {length} for {mtype:?} (must be a multiple of 32 from 32 to 256)"
383
+ )))
384
+ }
385
+ }
386
+ MainType::Iscc => {
387
+ if length <= 7 {
388
+ Ok(length)
389
+ } else {
390
+ Err(IsccError::InvalidInput(format!(
391
+ "invalid length {length} for ISCC (must be 0-7)"
392
+ )))
393
+ }
394
+ }
395
+ MainType::Id => {
396
+ if ID_BIT_LENGTHS.contains(&length) {
397
+ Ok((length - 64) / 8)
398
+ } else {
399
+ Err(IsccError::InvalidInput(format!(
400
+ "invalid length {length} for ID (must be 64, 72, 80 or 96)"
401
+ )))
402
+ }
403
+ }
404
+ }
405
+ }
406
+
407
+ /// Decode header length field to actual bit length.
408
+ ///
409
+ /// Inverse of `encode_length`. Returns the number of bits in the digest.
410
+ /// - META/SEMANTIC/CONTENT/DATA/INSTANCE/FLAKE: `(length + 1) * 32`
411
+ /// - ISCC + Wide: 256
412
+ /// - ISCC + other: `popcount(length) * 64 + 128`
413
+ /// - ID: `length * 8 + 64`
414
+ ///
415
+ /// The length field is not range-checked: a META..FLAKE index above 7 decodes
416
+ /// to more than 256 bits, which is not a valid ISCC-UNIT (an ISCC-UNIT is at
417
+ /// most 256 bits). The crate's own decoders apply that rule.
418
+ pub fn decode_length(mtype: MainType, length: u32, stype: SubType) -> u32 {
419
+ match mtype {
420
+ MainType::Meta
421
+ | MainType::Semantic
422
+ | MainType::Content
423
+ | MainType::Data
424
+ | MainType::Instance
425
+ | MainType::Flake => (length + 1) * 32,
426
+ MainType::Iscc => {
427
+ if stype == SubType::Wide {
428
+ 256
429
+ } else {
430
+ length.count_ones() * 64 + 128
431
+ }
432
+ }
433
+ MainType::Id => length * 8 + 64,
434
+ }
435
+ }
436
+
437
+ /// Decode a header length field to the bit length of a valid ISCC header.
438
+ ///
439
+ /// Same result as [`decode_length`], but a length that iscc-core's `LN` lookup
440
+ /// rejects is an error: a META..FLAKE length index above 7 (more than 256 bits)
441
+ /// and an ID length other than 64, 72, 80 or 96 bits. ISCC lengths decode
442
+ /// unchanged.
443
+ pub(crate) fn unit_bit_length(mtype: MainType, length: u32, stype: SubType) -> IsccResult<u32> {
444
+ let bits = decode_length(mtype, length, stype);
445
+ match mtype {
446
+ MainType::Iscc => Ok(bits),
447
+ MainType::Id if !ID_BIT_LENGTHS.contains(&bits) => Err(IsccError::InvalidInput(format!(
448
+ "invalid length {bits} bits for ID (must be 64, 72, 80 or 96)"
449
+ ))),
450
+ MainType::Id => Ok(bits),
451
+ _ if bits > 256 => Err(IsccError::InvalidInput(format!(
452
+ "invalid length {bits} bits for {mtype:?} (an ISCC-UNIT is at most 256 bits)"
453
+ ))),
454
+ _ => Ok(bits),
455
+ }
456
+ }
457
+
458
+ // ---- Unit Encoding ----
459
+
460
+ /// Encode optional ISCC-UNIT MainTypes as a unit combination index (0–7).
461
+ ///
462
+ /// Maps the optional units (Meta, Semantic, Content) present in a composite
463
+ /// ISCC-CODE to a bitfield index. Data and Instance are mandatory and must
464
+ /// not be included. The bitfield pattern is:
465
+ /// bit 0 = Content, bit 1 = Semantic, bit 2 = Meta.
466
+ pub fn encode_units(main_types: &[MainType]) -> IsccResult<u32> {
467
+ let mut result = 0u32;
468
+ for &mt in main_types {
469
+ match mt {
470
+ MainType::Content => result |= 1,
471
+ MainType::Semantic => result |= 2,
472
+ MainType::Meta => result |= 4,
473
+ _ => {
474
+ return Err(IsccError::InvalidInput(format!(
475
+ "{mt:?} is not a valid optional unit type"
476
+ )));
477
+ }
478
+ }
479
+ }
480
+ Ok(result)
481
+ }
482
+
483
+ /// Decode a unit combination index (0–7) to a sorted list of optional MainTypes.
484
+ ///
485
+ /// Inverse of `encode_units`. Decodes the 3-bit bitfield:
486
+ /// bit 0 = Content, bit 1 = Semantic, bit 2 = Meta. Results are returned
487
+ /// in MainType discriminant order (Meta, Semantic, Content) so they are
488
+ /// automatically sorted.
489
+ pub fn decode_units(unit_id: u32) -> IsccResult<Vec<MainType>> {
490
+ if unit_id > 7 {
491
+ return Err(IsccError::InvalidInput(format!(
492
+ "invalid unit_id: {unit_id} (must be 0-7)"
493
+ )));
494
+ }
495
+ let mut result = Vec::new();
496
+ if unit_id & 4 != 0 {
497
+ result.push(MainType::Meta);
498
+ }
499
+ if unit_id & 2 != 0 {
500
+ result.push(MainType::Semantic);
501
+ }
502
+ if unit_id & 1 != 0 {
503
+ result.push(MainType::Content);
504
+ }
505
+ Ok(result)
506
+ }
507
+
508
+ // ---- Prefix Validation ----
509
+
510
+ /// Valid two-character ISCC prefixes, mirroring `iscc_core.constants.PREFIXES`.
511
+ /// Note: `MA` and `ME` are ambiguous between ID-V0 and ID-V1.
512
+ pub(crate) const PREFIXES: [&str; 26] = [
513
+ "AA", // META-NONE
514
+ "CA", // SEMANTIC-TEXT
515
+ "CE", // SEMANTIC-IMAGE
516
+ "CI", // SEMANTIC-AUDIO
517
+ "CM", // SEMANTIC-VIDEO
518
+ "CQ", // SEMANTIC-MIXED
519
+ "EA", // CONTENT-TEXT
520
+ "EE", // CONTENT-IMAGE
521
+ "EI", // CONTENT-AUDIO
522
+ "EM", // CONTENT-VIDEO
523
+ "EQ", // CONTENT-MIXED
524
+ "GA", // DATA-NONE
525
+ "IA", // INSTANCE-NONE
526
+ "KA", // ISCC-TEXT
527
+ "KE", // ISCC-IMAGE
528
+ "KI", // ISCC-AUDIO
529
+ "KM", // ISCC-VIDEO
530
+ "KQ", // ISCC-MIXED
531
+ "KU", // ISCC-SUM
532
+ "KY", // ISCC-NONE
533
+ "K4", // ISCC-WIDE
534
+ "MA", // ID-PRIVATE-V0 / ID-REALM_0-V1 (ambiguous)
535
+ "ME", // ID-BITCOIN-V0 / ID-REALM_1-V1 (ambiguous)
536
+ "MI", // ID-ETHEREUM-V0
537
+ "MM", // ID-POLYGON-V0
538
+ "OA", // FLAKE-NONE
539
+ ];
540
+
541
+ // ---- Base32 Encoding ----
542
+
543
+ /// Encode bytes as base32 (RFC 4648, uppercase, no padding).
544
+ pub fn encode_base32(data: &[u8]) -> String {
545
+ data_encoding::BASE32_NOPAD.encode(data)
546
+ }
547
+
548
+ /// Decode base32 string to bytes (ASCII case-insensitive, no padding expected).
549
+ pub fn decode_base32(code: &str) -> IsccResult<Vec<u8>> {
550
+ let upper = code.to_ascii_uppercase();
551
+ data_encoding::BASE32_NOPAD
552
+ .decode(upper.as_bytes())
553
+ .map_err(|e| IsccError::InvalidInput(format!("base32 decode error: {e}")))
554
+ }
555
+
556
+ // ---- Base64 Encoding ----
557
+
558
+ /// Encode bytes as base64url (RFC 4648 §5, no padding).
559
+ pub fn encode_base64(data: &[u8]) -> String {
560
+ data_encoding::BASE64URL_NOPAD.encode(data)
561
+ }
562
+
563
+ // ---- Component Encoding ----
564
+
565
+ /// Encode an ISCC-UNIT with header and body as a base32 string.
566
+ ///
567
+ /// Produces the base32-encoded string (without "ISCC:" prefix). Callers
568
+ /// add the prefix when constructing the final ISCC string.
569
+ ///
570
+ /// Note: ISCC-CODEs (MainType::Iscc) are not encoded via this function —
571
+ /// `gen_iscc_code_v0` constructs the composite header directly.
572
+ pub fn encode_component(
573
+ mtype: MainType,
574
+ stype: SubType,
575
+ version: Version,
576
+ bit_length: u32,
577
+ digest: &[u8],
578
+ ) -> IsccResult<String> {
579
+ if mtype == MainType::Iscc {
580
+ return Err(IsccError::InvalidInput(
581
+ "ISCC MainType is not a unit; use gen_iscc_code_v0 instead".into(),
582
+ ));
583
+ }
584
+
585
+ let encoded_length = encode_length(mtype, bit_length)?;
586
+ let nbytes = (bit_length / 8) as usize;
587
+ let header = encode_header(mtype, stype, version, encoded_length)?;
588
+ let body = &digest[..nbytes.min(digest.len())];
589
+
590
+ let mut component = header;
591
+ component.extend_from_slice(body);
592
+
593
+ Ok(encode_base32(&component))
594
+ }
595
+
596
+ /// Return whether Python's `str.strip()` (no arguments) removes `c`.
597
+ ///
598
+ /// Python's whitespace set is Rust's `char::is_whitespace` set plus the four
599
+ /// information separators U+001C..=U+001F, which `str::trim` keeps. Trimming
600
+ /// with this predicate keeps cleaned input aligned with `iscc_core.codec.iscc_clean`.
601
+ pub(crate) fn is_py_strip_char(c: char) -> bool {
602
+ c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
603
+ }
604
+
605
+ /// Clean up an ISCC string to its bare base32 form.
606
+ ///
607
+ /// Mirrors `iscc_core.codec.iscc_clean`: trims surrounding whitespace (the
608
+ /// `str.strip()` set, see [`is_py_strip_char`]), removes an
609
+ /// optional scheme prefix (matched case-insensitively against `iscc`), and strips
610
+ /// the hyphen group separators of the canonical display form (e.g.
611
+ /// `ISCC:KACY-PXW4-…`). A single-part input whose first character is a multibase
612
+ /// prefix (`f`, `b`, `v`, `z`, `u`) keeps its dashes intact, since `-` may be
613
+ /// significant in multibase-encoded data.
614
+ ///
615
+ /// Returns the cleaned code with no scheme prefix and no dashes.
616
+ ///
617
+ /// # Errors
618
+ ///
619
+ /// Returns `IsccError::InvalidInput` when a two-part input uses a scheme other
620
+ /// than `iscc` (case-insensitive), when the input contains more than one colon,
621
+ /// or when the cleaned result is empty (mirrors the reference erroring on empty
622
+ /// input; `decode_base32("")` returns `Ok(empty)`, so an empty code would
623
+ /// otherwise be silently accepted as a zero-unit ISCC).
624
+ pub(crate) fn iscc_clean(iscc: &str) -> IsccResult<Cow<'_, str>> {
625
+ let trimmed = iscc.trim_matches(is_py_strip_char);
626
+ let cleaned: Cow<'_, str> = match trimmed.split_once(':') {
627
+ None => {
628
+ // Single part, no scheme prefix. Preserve dashes for multibase-encoded
629
+ // inputs; strip them otherwise. Borrow when nothing needs removing.
630
+ let is_multibase = matches!(
631
+ trimmed.as_bytes().first(),
632
+ Some(b'f' | b'b' | b'v' | b'z' | b'u')
633
+ );
634
+ if is_multibase || !trimmed.contains('-') {
635
+ Cow::Borrowed(trimmed)
636
+ } else {
637
+ Cow::Owned(trimmed.replace('-', ""))
638
+ }
639
+ }
640
+ Some((scheme, rest)) => {
641
+ let scheme = scheme.trim_matches(is_py_strip_char);
642
+ let code = rest.trim_matches(is_py_strip_char);
643
+ // A second colon means the string is malformed (more than one part).
644
+ if code.contains(':') {
645
+ return Err(IsccError::InvalidInput(format!(
646
+ "Malformed ISCC string: {iscc}"
647
+ )));
648
+ }
649
+ if !scheme.eq_ignore_ascii_case("iscc") {
650
+ return Err(IsccError::InvalidInput(format!("Invalid scheme: {scheme}")));
651
+ }
652
+ if code.contains('-') {
653
+ Cow::Owned(code.replace('-', ""))
654
+ } else {
655
+ Cow::Borrowed(code)
656
+ }
657
+ }
658
+ };
659
+
660
+ if cleaned.is_empty() {
661
+ return Err(IsccError::InvalidInput("Empty ISCC string".to_string()));
662
+ }
663
+
664
+ Ok(cleaned)
665
+ }
666
+
667
+ /// Decompose a composite ISCC-CODE or ISCC sequence into individual ISCC-UNITs.
668
+ ///
669
+ /// Accepts a normalized ISCC-CODE or the base32 form of concatenated ISCC-UNIT
670
+ /// bytes. The second form is the display form of an ISCC-SEQ (IEP-0020): `ISCC:`
671
+ /// followed by the base32 encoding of the ISCC-SEQ bytes (see [`encode_seq`]).
672
+ /// Concatenating ISCC-UNIT *strings*, with or without hyphens, yields such a
673
+ /// string only for 64-bit units, whose 10-byte encoding is exactly 16 base32
674
+ /// characters; longer units misalign the bit stream.
675
+ ///
676
+ /// The input is cleaned via [`iscc_clean`] (scheme prefix, dashes, whitespace)
677
+ /// before decoding. Returns a list of base32-encoded ISCC-UNIT strings (without
678
+ /// "ISCC:" prefix).
679
+ ///
680
+ /// This is the lenient reader for ISCC strings. Use [`decode_seq`] to strictly
681
+ /// decode ISCC-SEQ byte strings (IEP-0020), e.g. C2PA soft binding values.
682
+ pub fn iscc_decompose(iscc_code: &str) -> IsccResult<Vec<String>> {
683
+ let clean = iscc_clean(iscc_code)?;
684
+ let mut raw_code = decode_base32(&clean)?;
685
+ let mut components = Vec::new();
686
+
687
+ while !raw_code.is_empty() {
688
+ let (mt, st, vs, ln, body) = decode_header(&raw_code)?;
689
+
690
+ // Standard ISCC-UNIT with tail continuation
691
+ if mt != MainType::Iscc {
692
+ let ln_bits = unit_bit_length(mt, ln, st)?;
693
+ let nbytes = (ln_bits / 8) as usize;
694
+ if body.len() < nbytes {
695
+ return Err(IsccError::InvalidInput(format!(
696
+ "truncated ISCC body: expected {nbytes} bytes, got {}",
697
+ body.len()
698
+ )));
699
+ }
700
+ let code = encode_component(mt, st, vs, ln_bits, &body[..nbytes])?;
701
+ components.push(code);
702
+ raw_code = body[nbytes..].to_vec();
703
+ continue;
704
+ }
705
+
706
+ // ISCC-CODE: decode into constituent units
707
+ let main_types = decode_units(ln)?;
708
+
709
+ // Wide mode: 128-bit Data-Code + 128-bit Instance-Code
710
+ if st == SubType::Wide {
711
+ if body.len() < 32 {
712
+ return Err(IsccError::InvalidInput(format!(
713
+ "truncated ISCC body: expected 32 bytes, got {}",
714
+ body.len()
715
+ )));
716
+ }
717
+ let data_code = encode_component(MainType::Data, SubType::None, vs, 128, &body[..16])?;
718
+ let instance_code =
719
+ encode_component(MainType::Instance, SubType::None, vs, 128, &body[16..32])?;
720
+ components.push(data_code);
721
+ components.push(instance_code);
722
+ break;
723
+ }
724
+
725
+ // Non-wide ISCC-CODE: total body = dynamic units × 8 + Data 8 + Instance 8
726
+ let expected_body = main_types.len() * 8 + 16;
727
+ if body.len() < expected_body {
728
+ return Err(IsccError::InvalidInput(format!(
729
+ "truncated ISCC body: expected {expected_body} bytes, got {}",
730
+ body.len()
731
+ )));
732
+ }
733
+
734
+ // Rebuild dynamic units (Meta, Semantic, Content)
735
+ for (idx, &mtype) in main_types.iter().enumerate() {
736
+ let stype = if mtype == MainType::Meta {
737
+ SubType::None
738
+ } else {
739
+ st
740
+ };
741
+ let code = encode_component(mtype, stype, vs, 64, &body[idx * 8..])?;
742
+ components.push(code);
743
+ }
744
+
745
+ // Rebuild static units (Data-Code, Instance-Code)
746
+ let data_code = encode_component(
747
+ MainType::Data,
748
+ SubType::None,
749
+ vs,
750
+ 64,
751
+ &body[body.len() - 16..body.len() - 8],
752
+ )?;
753
+ let instance_code = encode_component(
754
+ MainType::Instance,
755
+ SubType::None,
756
+ vs,
757
+ 64,
758
+ &body[body.len() - 8..],
759
+ )?;
760
+ components.push(data_code);
761
+ components.push(instance_code);
762
+ break;
763
+ }
764
+
765
+ Ok(components)
766
+ }
767
+
768
+ // ---- ISCC-SEQ (IEP-0020) ----
769
+
770
+ /// MainTypes permitted in an ISCC-SEQ (IEP-0020): META, SEMANTIC, CONTENT, DATA, INSTANCE.
771
+ ///
772
+ /// ISCC-CODE, ID and FLAKE units are rejected by [`read_unit`], [`encode_seq`]
773
+ /// and [`decode_seq`].
774
+ pub const SEQ_MAINTYPES: &[MainType] = &[
775
+ MainType::Meta,
776
+ MainType::Semantic,
777
+ MainType::Content,
778
+ MainType::Data,
779
+ MainType::Instance,
780
+ ];
781
+
782
+ /// Upper bound of an encoded ISCC-HEADER in bytes (four 16-bit varnibbles).
783
+ const HEADER_MAX: usize = 8;
784
+
785
+ /// Read one strictly encoded ISCC-UNIT from an ISCC-SEQ byte string (IEP-0020).
786
+ ///
787
+ /// Validates the ISCC-UNIT starting at `offset` and returns the offset where it
788
+ /// ends (the start of the next unit), which allows sequential decoding of an
789
+ /// ISCC-SEQ. Mirrors `iscc_core.codec.read_unit`. Unknown SubType and Version
790
+ /// values are accepted.
791
+ ///
792
+ /// # Errors
793
+ ///
794
+ /// Returns `IsccError::InvalidInput` (checked in this order) if the header is
795
+ /// incomplete (including `offset >= data.len()`), the header is non-canonical
796
+ /// (e.g. a non-zero padding nibble), the MainType is not in [`SEQ_MAINTYPES`],
797
+ /// the Length field is above 7, or the body runs past the end of `data`.
798
+ pub fn read_unit(data: &[u8], offset: usize) -> IsccResult<usize> {
799
+ // An out-of-range offset yields an empty window, which fails as a malformed
800
+ // header (as in the reference) instead of panicking on the slice.
801
+ let rest = data.get(offset..).unwrap_or(&[]);
802
+ let window = &rest[..rest.len().min(HEADER_MAX)];
803
+ let (mt, st, vs, ln, _) = decode_header_raw(window).map_err(|e| {
804
+ IsccError::InvalidInput(format!("Malformed ISCC-HEADER at offset {offset}: {e}"))
805
+ })?;
806
+ let header = encode_header_raw(mt, st, vs, ln)?;
807
+ if !window.starts_with(&header) {
808
+ return Err(IsccError::InvalidInput(format!(
809
+ "Non-canonical ISCC-HEADER at offset {offset}"
810
+ )));
811
+ }
812
+ if !SEQ_MAINTYPES.iter().any(|&m| m as u32 == mt) {
813
+ return Err(IsccError::InvalidInput(format!(
814
+ "MainType {mt} is not permitted in an ISCC-SEQ (offset {offset})"
815
+ )));
816
+ }
817
+ if ln > 7 {
818
+ return Err(IsccError::InvalidInput(format!(
819
+ "Unsupported Length field {ln} at offset {offset}"
820
+ )));
821
+ }
822
+ let end = offset + header.len() + 4 * (ln as usize + 1);
823
+ if end > data.len() {
824
+ return Err(IsccError::InvalidInput(format!(
825
+ "Truncated ISCC-UNIT at offset {offset}"
826
+ )));
827
+ }
828
+ Ok(end)
829
+ }
830
+
831
+ /// Encode ISCC-UNIT strings as an ISCC-SEQ byte string (IEP-0020).
832
+ ///
833
+ /// Returns the concatenation of the header and body bytes of each unit, in the
834
+ /// given order (never sorted, deduplicated or dropped). Unit strings may omit
835
+ /// the `ISCC:` prefix and may be lowercase or contain hyphens. Mirrors
836
+ /// `iscc_core.codec.encode_seq`.
837
+ ///
838
+ /// Any 32 to 256-bit unit of any SubType and Version is accepted. A C2PA
839
+ /// `io.iscc.v0` soft binding value additionally requires Version 0 units with
840
+ /// 256-bit bodies; callers producing such values must enforce that.
841
+ ///
842
+ /// # Errors
843
+ ///
844
+ /// Returns `IsccError::InvalidInput` if `units` is empty, or a unit is empty,
845
+ /// malformed, multiformat-encoded, of a MainType outside [`SEQ_MAINTYPES`]
846
+ /// (ISCC-CODE, ID, FLAKE), or carries trailing data (e.g. several units in one
847
+ /// string).
848
+ pub fn encode_seq(units: &[&str]) -> IsccResult<Vec<u8>> {
849
+ if units.is_empty() {
850
+ return Err(IsccError::InvalidInput(
851
+ "ISCC-SEQ requires at least one ISCC-UNIT".into(),
852
+ ));
853
+ }
854
+ let mut seq = Vec::new();
855
+ for unit in units {
856
+ if unit.trim_matches(is_py_strip_char).is_empty() {
857
+ return Err(IsccError::InvalidInput(
858
+ "ISCC-UNIT must not be empty".into(),
859
+ ));
860
+ }
861
+ // ASCII-uppercase first: iscc_clean keeps hyphens in bare strings that start with
862
+ // a multibase prefix character, and bare lowercase units with SubType >= 8
863
+ // start with "b" or "f".
864
+ let upper = unit.to_ascii_uppercase();
865
+ let raw = decode_base32(&iscc_clean(&upper)?)?;
866
+ if read_unit(&raw, 0)? != raw.len() {
867
+ return Err(IsccError::InvalidInput(format!(
868
+ "Trailing data in ISCC-UNIT {unit:?}"
869
+ )));
870
+ }
871
+ seq.extend_from_slice(&raw);
872
+ }
873
+ Ok(seq)
874
+ }
875
+
876
+ /// Decode an ISCC-SEQ byte string to canonical ISCC-UNIT strings (IEP-0020).
877
+ ///
878
+ /// Strict byte-level reader: applies every [`read_unit`] rule to each unit and
879
+ /// rejects trailing bytes. Unknown SubType and Version values are preserved.
880
+ /// Returns `ISCC:`-prefixed unit strings in wire order; [`encode_seq`] of the
881
+ /// result reproduces `data`. Mirrors `iscc_core.codec.decode_seq`.
882
+ ///
883
+ /// # Errors
884
+ ///
885
+ /// Returns `IsccError::InvalidInput` if `data` is empty or any unit is
886
+ /// malformed (see [`read_unit`]).
887
+ pub fn decode_seq(data: &[u8]) -> IsccResult<Vec<String>> {
888
+ if data.is_empty() {
889
+ return Err(IsccError::InvalidInput("Empty ISCC-SEQ".into()));
890
+ }
891
+ let mut units = Vec::new();
892
+ let mut offset = 0;
893
+ while offset < data.len() {
894
+ let end = read_unit(data, offset)?;
895
+ units.push(format!("ISCC:{}", encode_base32(&data[offset..end])));
896
+ offset = end;
897
+ }
898
+ Ok(units)
899
+ }
900
+
901
+ #[cfg(test)]
902
+ mod tests {
903
+ use super::*;
904
+
905
+ // ---- iscc_clean tests ----
906
+
907
+ #[test]
908
+ fn test_iscc_clean_strips_scheme_and_dashes() {
909
+ // Canonical display form: scheme prefix + hyphen groups.
910
+ assert_eq!(
911
+ iscc_clean("ISCC:KACY-PXW4-45FT-YNJ3").unwrap(),
912
+ "KACYPXW445FTYNJ3"
913
+ );
914
+ }
915
+
916
+ #[test]
917
+ fn test_iscc_clean_case_insensitive_scheme() {
918
+ assert_eq!(
919
+ iscc_clean("iscc:KACYPXW445FTYNJ3").unwrap(),
920
+ "KACYPXW445FTYNJ3"
921
+ );
922
+ assert_eq!(
923
+ iscc_clean("Iscc:KACYPXW445FTYNJ3").unwrap(),
924
+ "KACYPXW445FTYNJ3"
925
+ );
926
+ }
927
+
928
+ #[test]
929
+ fn test_is_py_strip_char_matches_rust_whitespace_plus_separators() {
930
+ for c in char::MIN..=char::MAX {
931
+ let expected = c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c);
932
+ assert_eq!(is_py_strip_char(c), expected, "{c:?}");
933
+ }
934
+ assert!(!is_py_strip_char('\u{200b}'));
935
+ }
936
+
937
+ #[test]
938
+ fn test_iscc_clean_trims_whitespace() {
939
+ assert_eq!(iscc_clean(" ISCC: KACY-PXW4 ").unwrap(), "KACYPXW4");
940
+ }
941
+
942
+ #[test]
943
+ fn test_iscc_clean_no_prefix() {
944
+ assert_eq!(
945
+ iscc_clean("KACY-PXW4-45FT-YNJ3").unwrap(),
946
+ "KACYPXW445FTYNJ3"
947
+ );
948
+ }
949
+
950
+ #[test]
951
+ fn test_iscc_clean_preserves_multibase_dashes() {
952
+ // A multibase-prefixed input (starts with 'u') must keep its dashes intact.
953
+ assert_eq!(iscc_clean("uABC-DEF").unwrap(), "uABC-DEF");
954
+ // Every multibase prefix is preserved verbatim.
955
+ for prefix in ['f', 'b', 'v', 'z', 'u'] {
956
+ let input = format!("{prefix}AA-BB");
957
+ assert_eq!(iscc_clean(&input).unwrap(), input);
958
+ }
959
+ }
960
+
961
+ #[test]
962
+ fn test_iscc_clean_rejects_bad_scheme() {
963
+ assert!(matches!(
964
+ iscc_clean("http:KACYPXW445FTYNJ3"),
965
+ Err(IsccError::InvalidInput(_))
966
+ ));
967
+ }
968
+
969
+ #[test]
970
+ fn test_iscc_clean_rejects_extra_colon() {
971
+ assert!(matches!(
972
+ iscc_clean("ISCC:KACY:PXW4"),
973
+ Err(IsccError::InvalidInput(_))
974
+ ));
975
+ }
976
+
977
+ // ---- Varnibble roundtrip tests ----
978
+
979
+ #[test]
980
+ fn test_varnibble_roundtrip() {
981
+ let test_values = [0, 1, 7, 8, 71, 72, 583, 584, 4679];
982
+ for &value in &test_values {
983
+ let bits = encode_varnibble(value).unwrap();
984
+ let bytes = bits_to_bytes(&bits);
985
+ let (decoded, consumed) = decode_varnibble_from_bytes(&bytes, 0).unwrap();
986
+ assert_eq!(decoded, value, "roundtrip failed for value {value}");
987
+ assert_eq!(consumed, bits.len(), "consumed mismatch for value {value}");
988
+ }
989
+ }
990
+
991
+ #[test]
992
+ fn test_varnibble_bit_lengths() {
993
+ // 0-7: 4 bits (1 nibble)
994
+ assert_eq!(encode_varnibble(0).unwrap().len(), 4);
995
+ assert_eq!(encode_varnibble(7).unwrap().len(), 4);
996
+ // 8-71: 8 bits (2 nibbles)
997
+ assert_eq!(encode_varnibble(8).unwrap().len(), 8);
998
+ assert_eq!(encode_varnibble(71).unwrap().len(), 8);
999
+ // 72-583: 12 bits (3 nibbles)
1000
+ assert_eq!(encode_varnibble(72).unwrap().len(), 12);
1001
+ assert_eq!(encode_varnibble(583).unwrap().len(), 12);
1002
+ // 584-4679: 16 bits (4 nibbles)
1003
+ assert_eq!(encode_varnibble(584).unwrap().len(), 16);
1004
+ assert_eq!(encode_varnibble(4679).unwrap().len(), 16);
1005
+ }
1006
+
1007
+ #[test]
1008
+ fn test_varnibble_out_of_range() {
1009
+ assert!(encode_varnibble(4680).is_err());
1010
+ }
1011
+
1012
+ #[test]
1013
+ fn test_varnibble_boundary_values() {
1014
+ // Verify exact bit patterns at boundaries
1015
+ let bits_0 = encode_varnibble(0).unwrap();
1016
+ assert_eq!(bits_0, vec![false, false, false, false]); // 0000
1017
+
1018
+ let bits_7 = encode_varnibble(7).unwrap();
1019
+ assert_eq!(bits_7, vec![false, true, true, true]); // 0111
1020
+
1021
+ let bits_8 = encode_varnibble(8).unwrap();
1022
+ assert_eq!(
1023
+ bits_8,
1024
+ vec![true, false, false, false, false, false, false, false]
1025
+ ); // 10 000000
1026
+ }
1027
+
1028
+ // ---- Bitwise extraction tests ----
1029
+
1030
+ #[test]
1031
+ fn test_extract_bits_basic() {
1032
+ // 0xA5 = 1010_0101 in binary
1033
+ let data = [0xA5u8];
1034
+ assert_eq!(extract_bits(&data, 0, 4), 0b1010); // first nibble
1035
+ assert_eq!(extract_bits(&data, 4, 4), 0b0101); // second nibble
1036
+ assert_eq!(extract_bits(&data, 0, 8), 0xA5); // full byte
1037
+ assert_eq!(extract_bits(&data, 1, 3), 0b010); // bits 1-3
1038
+ assert_eq!(extract_bits(&data, 0, 1), 1); // MSB
1039
+ assert_eq!(extract_bits(&data, 7, 1), 1); // LSB
1040
+
1041
+ // Multi-byte: 0xFF 0x00 = 1111_1111 0000_0000
1042
+ let data2 = [0xFF, 0x00];
1043
+ assert_eq!(extract_bits(&data2, 0, 8), 0xFF);
1044
+ assert_eq!(extract_bits(&data2, 8, 8), 0x00);
1045
+ assert_eq!(extract_bits(&data2, 4, 8), 0xF0); // crossing byte boundary
1046
+ assert_eq!(extract_bits(&data2, 6, 4), 0b1100); // crossing byte boundary
1047
+ }
1048
+
1049
+ #[test]
1050
+ fn test_decode_varnibble_from_bytes_boundary_values() {
1051
+ // Test decoding at non-zero bit offsets within a byte slice.
1052
+ // Encode two varnibbles into a single byte sequence and decode both.
1053
+
1054
+ // varnibble(3) = 0011 (4 bits) + varnibble(8) = 10_000000 (8 bits) = 12 bits
1055
+ let bits_3 = encode_varnibble(3).unwrap();
1056
+ let bits_8 = encode_varnibble(8).unwrap();
1057
+ let mut combined_bits = bits_3.clone();
1058
+ combined_bits.extend(&bits_8);
1059
+ let bytes = bits_to_bytes(&combined_bits);
1060
+
1061
+ // Decode first varnibble at bit 0
1062
+ let (val1, consumed1) = decode_varnibble_from_bytes(&bytes, 0).unwrap();
1063
+ assert_eq!(val1, 3);
1064
+ assert_eq!(consumed1, 4);
1065
+
1066
+ // Decode second varnibble at bit 4 (non-zero offset)
1067
+ let (val2, consumed2) = decode_varnibble_from_bytes(&bytes, 4).unwrap();
1068
+ assert_eq!(val2, 8);
1069
+ assert_eq!(consumed2, 8);
1070
+
1071
+ // Test with a 3-nibble value at offset
1072
+ // varnibble(0) = 0000 (4 bits) + varnibble(72) = 110_000000000 (12 bits)
1073
+ let bits_0 = encode_varnibble(0).unwrap();
1074
+ let bits_72 = encode_varnibble(72).unwrap();
1075
+ let mut combined2 = bits_0;
1076
+ combined2.extend(&bits_72);
1077
+ let bytes2 = bits_to_bytes(&combined2);
1078
+
1079
+ let (val3, consumed3) = decode_varnibble_from_bytes(&bytes2, 4).unwrap();
1080
+ assert_eq!(val3, 72);
1081
+ assert_eq!(consumed3, 12);
1082
+
1083
+ // Test insufficient bits at offset
1084
+ let single_byte = [0x00u8];
1085
+ let result = decode_varnibble_from_bytes(&single_byte, 6);
1086
+ assert!(result.is_err(), "should fail with only 2 bits available");
1087
+ }
1088
+
1089
+ // ---- Header encoding tests ----
1090
+
1091
+ #[test]
1092
+ fn test_encode_header_meta_v0() {
1093
+ // encode_header(META=0, NONE=0, V0=0, length=1) → 2 bytes
1094
+ let header = encode_header(MainType::Meta, SubType::None, Version::V0, 1).unwrap();
1095
+ assert_eq!(header, vec![0x00, 0x01]);
1096
+ }
1097
+
1098
+ #[test]
1099
+ fn test_encode_header_with_padding() {
1100
+ // encode_header(META=0, NONE=0, V0=0, length=8)
1101
+ // varnibble(0)=4b + varnibble(0)=4b + varnibble(0)=4b + varnibble(8)=8b = 20 bits
1102
+ // Padded to 24 bits = 3 bytes
1103
+ let header = encode_header(MainType::Meta, SubType::None, Version::V0, 8).unwrap();
1104
+ assert_eq!(header.len(), 3);
1105
+ // bits: 0000 0000 0000 10|000000 0000
1106
+ // ^^^^ ^^^^ ^^^^ ^^^^^^^^ ^^^^(pad)
1107
+ assert_eq!(header, vec![0x00, 0x08, 0x00]);
1108
+ }
1109
+
1110
+ #[test]
1111
+ fn test_encode_header_data_type() {
1112
+ // DATA=3, NONE=0, V0=0, length=1
1113
+ let header = encode_header(MainType::Data, SubType::None, Version::V0, 1).unwrap();
1114
+ // varnibble(3)=0011, varnibble(0)=0000, varnibble(0)=0000, varnibble(1)=0001
1115
+ // bits: 0011 0000 0000 0001
1116
+ assert_eq!(header, vec![0x30, 0x01]);
1117
+ }
1118
+
1119
+ #[test]
1120
+ fn test_encode_header_instance_type() {
1121
+ // INSTANCE=4, NONE=0, V0=0, length=1
1122
+ let header = encode_header(MainType::Instance, SubType::None, Version::V0, 1).unwrap();
1123
+ // varnibble(4)=0100, varnibble(0)=0000, varnibble(0)=0000, varnibble(1)=0001
1124
+ // bits: 0100 0000 0000 0001
1125
+ assert_eq!(header, vec![0x40, 0x01]);
1126
+ }
1127
+
1128
+ #[test]
1129
+ fn test_decode_header_roundtrip_all_main_types() {
1130
+ let main_types = [
1131
+ MainType::Meta,
1132
+ MainType::Semantic,
1133
+ MainType::Content,
1134
+ MainType::Data,
1135
+ MainType::Instance,
1136
+ MainType::Iscc,
1137
+ MainType::Id,
1138
+ MainType::Flake,
1139
+ ];
1140
+
1141
+ for &mtype in &main_types {
1142
+ let header = encode_header(mtype, SubType::None, Version::V0, 1).unwrap();
1143
+ let (dec_mtype, dec_stype, dec_version, dec_length, tail) =
1144
+ decode_header(&header).unwrap();
1145
+ assert_eq!(dec_mtype, mtype, "MainType mismatch for {mtype:?}");
1146
+ assert_eq!(dec_stype, SubType::None);
1147
+ assert_eq!(dec_version, Version::V0);
1148
+ assert_eq!(dec_length, 1);
1149
+ assert!(tail.is_empty(), "unexpected tail for {mtype:?}");
1150
+ }
1151
+ }
1152
+
1153
+ #[test]
1154
+ fn test_decode_header_with_tail() {
1155
+ // Simulate header + 8 bytes body
1156
+ let header = encode_header(MainType::Meta, SubType::None, Version::V0, 1).unwrap();
1157
+ let body = vec![0xAA, 0xBB, 0xCC, 0xDD, 0x11, 0x22, 0x33, 0x44];
1158
+ let mut data = header;
1159
+ data.extend_from_slice(&body);
1160
+
1161
+ let (mtype, stype, version, length, tail) = decode_header(&data).unwrap();
1162
+ assert_eq!(mtype, MainType::Meta);
1163
+ assert_eq!(stype, SubType::None);
1164
+ assert_eq!(version, Version::V0);
1165
+ assert_eq!(length, 1);
1166
+ assert_eq!(tail, body);
1167
+ }
1168
+
1169
+ #[test]
1170
+ fn test_decode_header_with_padding_and_tail() {
1171
+ // Header with padding (3 bytes) + body
1172
+ let header = encode_header(MainType::Meta, SubType::None, Version::V0, 8).unwrap();
1173
+ assert_eq!(header.len(), 3); // 20 bits padded to 24
1174
+
1175
+ let body = vec![0xFF, 0xEE];
1176
+ let mut data = header;
1177
+ data.extend_from_slice(&body);
1178
+
1179
+ let (mtype, _stype, _version, length, tail) = decode_header(&data).unwrap();
1180
+ assert_eq!(mtype, MainType::Meta);
1181
+ assert_eq!(length, 8);
1182
+ assert_eq!(tail, body);
1183
+ }
1184
+
1185
+ #[test]
1186
+ fn test_decode_header_subtypes() {
1187
+ // Test with non-zero subtype
1188
+ let header = encode_header(MainType::Content, SubType::Image, Version::V0, 1).unwrap();
1189
+ let (mtype, stype, version, length, _tail) = decode_header(&header).unwrap();
1190
+ assert_eq!(mtype, MainType::Content);
1191
+ assert_eq!(stype, SubType::Image);
1192
+ assert_eq!(version, Version::V0);
1193
+ assert_eq!(length, 1);
1194
+ }
1195
+
1196
+ // ---- Length encoding tests ----
1197
+
1198
+ #[test]
1199
+ fn test_encode_length_standard_types() {
1200
+ // (bit_length / 32) - 1
1201
+ assert_eq!(encode_length(MainType::Meta, 32).unwrap(), 0);
1202
+ assert_eq!(encode_length(MainType::Meta, 64).unwrap(), 1);
1203
+ assert_eq!(encode_length(MainType::Meta, 96).unwrap(), 2);
1204
+ assert_eq!(encode_length(MainType::Meta, 128).unwrap(), 3);
1205
+ assert_eq!(encode_length(MainType::Meta, 256).unwrap(), 7);
1206
+ assert_eq!(encode_length(MainType::Data, 64).unwrap(), 1);
1207
+ assert_eq!(encode_length(MainType::Instance, 64).unwrap(), 1);
1208
+ }
1209
+
1210
+ #[test]
1211
+ fn test_encode_length_iscc() {
1212
+ // Pass-through for ISCC (0-7)
1213
+ for i in 0..=7 {
1214
+ assert_eq!(encode_length(MainType::Iscc, i).unwrap(), i);
1215
+ }
1216
+ assert!(encode_length(MainType::Iscc, 8).is_err());
1217
+ }
1218
+
1219
+ #[test]
1220
+ fn test_encode_length_id() {
1221
+ // (bit_length - 64) / 8
1222
+ assert_eq!(encode_length(MainType::Id, 64).unwrap(), 0);
1223
+ assert_eq!(encode_length(MainType::Id, 72).unwrap(), 1);
1224
+ assert_eq!(encode_length(MainType::Id, 80).unwrap(), 2);
1225
+ assert_eq!(encode_length(MainType::Id, 96).unwrap(), 4);
1226
+ // iscc-core's LN has no 88, so its decoder rejects an 88-bit ID
1227
+ assert!(encode_length(MainType::Id, 88).is_err());
1228
+ }
1229
+
1230
+ #[test]
1231
+ fn test_encode_length_invalid() {
1232
+ // Not a multiple of 32
1233
+ assert!(encode_length(MainType::Meta, 48).is_err());
1234
+ // Too small
1235
+ assert!(encode_length(MainType::Meta, 0).is_err());
1236
+ // Above 256 bits
1237
+ assert!(encode_length(MainType::Meta, 288).is_err());
1238
+ assert!(encode_length(MainType::Data, 512).is_err());
1239
+ // ID out of range
1240
+ assert!(encode_length(MainType::Id, 63).is_err());
1241
+ assert!(encode_length(MainType::Id, 97).is_err());
1242
+ }
1243
+
1244
+ #[test]
1245
+ fn test_decode_length_standard_types() {
1246
+ // (length + 1) * 32
1247
+ assert_eq!(decode_length(MainType::Meta, 0, SubType::None), 32);
1248
+ assert_eq!(decode_length(MainType::Meta, 1, SubType::None), 64);
1249
+ assert_eq!(decode_length(MainType::Meta, 7, SubType::None), 256);
1250
+ assert_eq!(decode_length(MainType::Data, 1, SubType::None), 64);
1251
+ }
1252
+
1253
+ #[test]
1254
+ fn test_decode_length_iscc() {
1255
+ // Wide → 256
1256
+ assert_eq!(decode_length(MainType::Iscc, 0, SubType::Wide), 256);
1257
+ // Non-wide → popcount(length) * 64 + 128
1258
+ assert_eq!(decode_length(MainType::Iscc, 0, SubType::Sum), 128); // 0 optional units
1259
+ assert_eq!(decode_length(MainType::Iscc, 1, SubType::None), 192); // 1 optional unit
1260
+ assert_eq!(decode_length(MainType::Iscc, 3, SubType::None), 256); // 2 optional units
1261
+ assert_eq!(decode_length(MainType::Iscc, 7, SubType::None), 320); // 3 optional units
1262
+ }
1263
+
1264
+ #[test]
1265
+ fn test_decode_length_id() {
1266
+ // length * 8 + 64
1267
+ assert_eq!(decode_length(MainType::Id, 0, SubType::None), 64);
1268
+ assert_eq!(decode_length(MainType::Id, 1, SubType::None), 72);
1269
+ assert_eq!(decode_length(MainType::Id, 4, SubType::None), 96);
1270
+ }
1271
+
1272
+ #[test]
1273
+ fn test_unit_bit_length_above_256() {
1274
+ // Length index 7 is 256 bits, the longest ISCC-UNIT
1275
+ assert_eq!(
1276
+ unit_bit_length(MainType::Meta, 7, SubType::None).unwrap(),
1277
+ 256
1278
+ );
1279
+ assert_eq!(
1280
+ unit_bit_length(MainType::Flake, 7, SubType::None).unwrap(),
1281
+ 256
1282
+ );
1283
+ // Length index 8 would be 288 bits
1284
+ let err = unit_bit_length(MainType::Meta, 8, SubType::None).unwrap_err();
1285
+ assert!(err.to_string().contains("256"), "unexpected error: {err}");
1286
+ assert!(unit_bit_length(MainType::Instance, 8, SubType::None).is_err());
1287
+ // ISCC lengths are unchanged
1288
+ assert_eq!(
1289
+ unit_bit_length(MainType::Iscc, 7, SubType::None).unwrap(),
1290
+ 320
1291
+ );
1292
+ }
1293
+
1294
+ #[test]
1295
+ fn test_unit_bit_length_id() {
1296
+ // Length indexes 0, 1, 2 and 4 are the ID lengths of iscc-core's LN
1297
+ for (index, bits) in [(0, 64), (1, 72), (2, 80), (4, 96)] {
1298
+ assert_eq!(
1299
+ unit_bit_length(MainType::Id, index, SubType::None).unwrap(),
1300
+ bits
1301
+ );
1302
+ }
1303
+ // Index 3 (88 bits) and index 5 (104 bits) are not
1304
+ for index in [3, 5] {
1305
+ let err = unit_bit_length(MainType::Id, index, SubType::None).unwrap_err();
1306
+ assert!(err.to_string().contains("ID"), "unexpected error: {err}");
1307
+ }
1308
+ }
1309
+
1310
+ #[test]
1311
+ fn test_iscc_decompose_above_256() {
1312
+ let mut raw = encode_header(MainType::Meta, SubType::None, Version::V0, 8).unwrap();
1313
+ raw.extend_from_slice(&[0u8; 36]);
1314
+ let err = iscc_decompose(&encode_base32(&raw)).unwrap_err();
1315
+ assert!(err.to_string().contains("256"), "unexpected error: {err}");
1316
+ }
1317
+
1318
+ #[test]
1319
+ fn test_encode_decode_length_roundtrip() {
1320
+ for &mtype in &[
1321
+ MainType::Meta,
1322
+ MainType::Data,
1323
+ MainType::Instance,
1324
+ MainType::Content,
1325
+ ] {
1326
+ for bit_length in (32..=256).step_by(32) {
1327
+ let encoded = encode_length(mtype, bit_length).unwrap();
1328
+ let decoded = decode_length(mtype, encoded, SubType::None);
1329
+ assert_eq!(
1330
+ decoded, bit_length,
1331
+ "roundtrip failed for {mtype:?} bit_length={bit_length}"
1332
+ );
1333
+ }
1334
+ }
1335
+ }
1336
+
1337
+ // ---- Base32 tests ----
1338
+
1339
+ #[test]
1340
+ fn test_base32_roundtrip() {
1341
+ let test_data: &[&[u8]] = &[
1342
+ &[0x00],
1343
+ &[0xFF],
1344
+ &[0x00, 0x01, 0x02, 0x03],
1345
+ &[0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE],
1346
+ &[0; 10],
1347
+ &[0xFF; 10],
1348
+ ];
1349
+
1350
+ for data in test_data {
1351
+ let encoded = encode_base32(data);
1352
+ let decoded = decode_base32(&encoded).unwrap();
1353
+ assert_eq!(&decoded, data, "base32 roundtrip failed for {data:?}");
1354
+ }
1355
+ }
1356
+
1357
+ #[test]
1358
+ fn test_base32_no_padding() {
1359
+ let encoded = encode_base32(&[0x00, 0x01]);
1360
+ assert!(!encoded.contains('='), "base32 should not contain padding");
1361
+ }
1362
+
1363
+ #[test]
1364
+ fn test_base32_case_insensitive_decode() {
1365
+ let data = vec![0xDE, 0xAD, 0xBE, 0xEF];
1366
+ let encoded = encode_base32(&data);
1367
+ let lower = encoded.to_lowercase();
1368
+ let decoded = decode_base32(&lower).unwrap();
1369
+ assert_eq!(decoded, data);
1370
+ }
1371
+
1372
+ // ---- Base64 encoding tests ----
1373
+
1374
+ #[test]
1375
+ fn test_encode_base64_empty() {
1376
+ assert_eq!(encode_base64(&[]), "");
1377
+ }
1378
+
1379
+ #[test]
1380
+ fn test_encode_base64_known_value() {
1381
+ // Python: base64.urlsafe_b64encode(bytes([0,1,2,3])).decode().rstrip("=") == "AAECAw"
1382
+ assert_eq!(encode_base64(&[0, 1, 2, 3]), "AAECAw");
1383
+ }
1384
+
1385
+ #[test]
1386
+ fn test_encode_base64_roundtrip() {
1387
+ let data: &[&[u8]] = &[
1388
+ &[0xFF],
1389
+ &[0xDE, 0xAD, 0xBE, 0xEF],
1390
+ &[0; 10],
1391
+ &[0xFF; 10],
1392
+ b"Hello World",
1393
+ ];
1394
+ for input in data {
1395
+ let encoded = encode_base64(input);
1396
+ let decoded = data_encoding::BASE64URL_NOPAD
1397
+ .decode(encoded.as_bytes())
1398
+ .unwrap();
1399
+ assert_eq!(&decoded, input, "base64 roundtrip failed for {input:?}");
1400
+ }
1401
+ }
1402
+
1403
+ #[test]
1404
+ fn test_encode_base64_no_padding() {
1405
+ // Various lengths that would normally produce padding
1406
+ for len in 1..=10 {
1407
+ let data = vec![0xABu8; len];
1408
+ let encoded = encode_base64(&data);
1409
+ assert!(
1410
+ !encoded.contains('='),
1411
+ "base64 output must not contain padding for len={len}"
1412
+ );
1413
+ }
1414
+ }
1415
+
1416
+ // ---- encode_component tests ----
1417
+
1418
+ #[test]
1419
+ fn test_encode_component_meta_known_vector() {
1420
+ // gen_meta_code_v0("Hello World") → "ISCC:AAAWKLHFPV6OPKDG"
1421
+ // Decode the known output to extract the digest, then re-encode
1422
+ let known_code = "AAAWKLHFPV6OPKDG";
1423
+ let raw = decode_base32(known_code).unwrap();
1424
+ assert_eq!(raw.len(), 10); // 2 header bytes + 8 digest bytes
1425
+
1426
+ // Verify header decodes correctly
1427
+ let (mtype, stype, version, length, tail) = decode_header(&raw).unwrap();
1428
+ assert_eq!(mtype, MainType::Meta);
1429
+ assert_eq!(stype, SubType::None);
1430
+ assert_eq!(version, Version::V0);
1431
+ assert_eq!(length, 1); // encode_length(META, 64) = 1
1432
+ assert_eq!(tail.len(), 8); // 64-bit digest
1433
+
1434
+ // Re-encode from extracted digest
1435
+ let result =
1436
+ encode_component(MainType::Meta, SubType::None, Version::V0, 64, &tail).unwrap();
1437
+ assert_eq!(result, known_code);
1438
+ }
1439
+
1440
+ #[test]
1441
+ fn test_encode_component_rejects_iscc_maintype() {
1442
+ assert!(
1443
+ encode_component(MainType::Iscc, SubType::Sum, Version::V0, 128, &[0; 16],).is_err()
1444
+ );
1445
+ }
1446
+
1447
+ #[test]
1448
+ fn test_encode_component_data_type() {
1449
+ // Encode a Data-Code component and verify roundtrip
1450
+ let digest = [0xAA; 32];
1451
+ let code =
1452
+ encode_component(MainType::Data, SubType::None, Version::V0, 64, &digest).unwrap();
1453
+
1454
+ // Decode and verify
1455
+ let raw = decode_base32(&code).unwrap();
1456
+ let (mtype, stype, version, length, tail) = decode_header(&raw).unwrap();
1457
+ assert_eq!(mtype, MainType::Data);
1458
+ assert_eq!(stype, SubType::None);
1459
+ assert_eq!(version, Version::V0);
1460
+ assert_eq!(length, 1); // encode_length(DATA, 64) = 1
1461
+ assert_eq!(tail, &digest[..8]); // 64 bits = 8 bytes
1462
+ }
1463
+
1464
+ #[test]
1465
+ fn test_encode_component_content_image() {
1466
+ let digest = [0x55; 16];
1467
+ let code =
1468
+ encode_component(MainType::Content, SubType::Image, Version::V0, 128, &digest).unwrap();
1469
+
1470
+ let raw = decode_base32(&code).unwrap();
1471
+ let (mtype, stype, _version, length, tail) = decode_header(&raw).unwrap();
1472
+ assert_eq!(mtype, MainType::Content);
1473
+ assert_eq!(stype, SubType::Image);
1474
+ assert_eq!(length, 3); // encode_length(CONTENT, 128) = 3
1475
+ assert_eq!(tail, &digest[..]); // 128 bits = 16 bytes
1476
+ }
1477
+
1478
+ // ---- TryFrom tests ----
1479
+
1480
+ #[test]
1481
+ fn test_maintype_try_from() {
1482
+ for v in 0..=7u8 {
1483
+ assert!(MainType::try_from(v).is_ok());
1484
+ }
1485
+ assert!(MainType::try_from(8).is_err());
1486
+ }
1487
+
1488
+ #[test]
1489
+ fn test_subtype_try_from() {
1490
+ for v in 0..=7u8 {
1491
+ assert!(SubType::try_from(v).is_ok());
1492
+ }
1493
+ assert!(SubType::try_from(8).is_err());
1494
+ }
1495
+
1496
+ #[test]
1497
+ fn test_version_try_from() {
1498
+ assert_eq!(Version::try_from(0).unwrap(), Version::V0);
1499
+ assert_eq!(Version::try_from(1).unwrap(), Version::V1);
1500
+ assert!(Version::try_from(2).is_err());
1501
+ }
1502
+
1503
+ // ---- ISCC-IDv1 Version 1 acceptance tests ----
1504
+
1505
+ #[test]
1506
+ fn test_iscc_decode_idv1_realm0() {
1507
+ // Reference: iscc_core.iscc_decode("ISCC:MAIGHFECJMOPMIAB")
1508
+ // -> (6, 0, 1, 0, b'c\x94\x82K\x1c\xf6 \x01')
1509
+ let expected_body = vec![0x63, 0x94, 0x82, 0x4b, 0x1c, 0xf6, 0x20, 0x01];
1510
+ let with_prefix = crate::iscc_decode("ISCC:MAIGHFECJMOPMIAB").unwrap();
1511
+ assert_eq!(with_prefix, (6, 0, 1, 0, expected_body.clone()));
1512
+ // Same result via the bare (no-prefix) form.
1513
+ let no_prefix = crate::iscc_decode("MAIGHFECJMOPMIAB").unwrap();
1514
+ assert_eq!(no_prefix, (6, 0, 1, 0, expected_body));
1515
+ }
1516
+
1517
+ #[test]
1518
+ fn test_decompose_idv1_accepts_version1() {
1519
+ // A single ISCC-IDv1 unit must decompose without "invalid Version: 1".
1520
+ let result = iscc_decompose("ISCC:MAIGHFECJMOPMIAB").unwrap();
1521
+ assert_eq!(result, vec!["MAIGHFECJMOPMIAB"]);
1522
+ }
1523
+
1524
+ #[test]
1525
+ fn test_decode_header_idv1_version1() {
1526
+ // Header 0x6010 = MainType Id (6), realm 0, Version 1, length 0.
1527
+ let raw = decode_base32("MAIGHFECJMOPMIAB").unwrap();
1528
+ let (mtype, stype, version, length, tail) = decode_header(&raw).unwrap();
1529
+ assert_eq!(mtype, MainType::Id);
1530
+ assert_eq!(stype, SubType::None); // realm 0 travels as the nibble 0
1531
+ assert_eq!(version, Version::V1);
1532
+ assert_eq!(length, 0);
1533
+ assert_eq!(tail.len(), 8);
1534
+ }
1535
+
1536
+ #[test]
1537
+ fn test_encode_decode_header_idv1_roundtrip() {
1538
+ // Realm 1 (operational) travels as the SubType nibble 1 (cosmetically Image).
1539
+ let header = encode_header(MainType::Id, SubType::Image, Version::V1, 0).unwrap();
1540
+ let (mtype, stype, version, length, _tail) = decode_header(&header).unwrap();
1541
+ assert_eq!(mtype, MainType::Id);
1542
+ assert_eq!(stype, SubType::Image);
1543
+ assert_eq!(version, Version::V1);
1544
+ assert_eq!(length, 0);
1545
+ }
1546
+
1547
+ #[test]
1548
+ fn test_encode_header_rejects_version1_for_non_id() {
1549
+ // Version 1 is only valid for MainType Id; a Meta header must reject it.
1550
+ let result = encode_header(MainType::Meta, SubType::None, Version::V1, 1);
1551
+ assert!(result.is_err());
1552
+ assert!(result.unwrap_err().to_string().contains("invalid Version"));
1553
+ }
1554
+
1555
+ #[test]
1556
+ fn test_decode_header_rejects_version1_for_non_id() {
1557
+ // Craft a Meta header (MainType 0) with version nibble 1 and length 1.
1558
+ // varnibble(0)=0000 mtype, varnibble(0)=0000 stype, varnibble(1)=0001 version,
1559
+ // varnibble(1)=0001 length -> bits 0000 0000 0001 0001 = 0x00 0x11
1560
+ let raw = [0x00u8, 0x11u8];
1561
+ let result = decode_header(&raw);
1562
+ assert!(result.is_err());
1563
+ assert!(result.unwrap_err().to_string().contains("invalid Version"));
1564
+ }
1565
+
1566
+ #[test]
1567
+ fn test_decode_header_rejects_truncated_varnibble_fields() {
1568
+ // "MDFZAAAAAAAAAAAAAA" decodes to a header whose multi-nibble fields
1569
+ // overflow a u8 (version 257, MainType 262). Before the range check these
1570
+ // wrapped (257 -> 1, 262 -> 6 = Id) and canonicalized to a valid ISCC.
1571
+ assert!(crate::iscc_decode("MDFZAAAAAAAAAAAAAA").is_err());
1572
+ assert!(iscc_decompose("MDFZAAAAAAAAAAAAAA").is_err());
1573
+ }
1574
+
1575
+ #[test]
1576
+ fn test_iscc_decode_rejects_version1_for_non_id() {
1577
+ // The Tier 1 iscc_decode must also reject a non-Id Version-1 header.
1578
+ let iscc = encode_base32(&[0x00u8, 0x11u8]);
1579
+ let result = crate::iscc_decode(&iscc);
1580
+ assert!(result.is_err());
1581
+ assert!(result.unwrap_err().to_string().contains("invalid Version"));
1582
+ }
1583
+
1584
+ #[test]
1585
+ fn test_subtype_text_alias() {
1586
+ assert_eq!(SubType::TEXT, SubType::None);
1587
+ assert_eq!(SubType::TEXT as u8, 0);
1588
+ }
1589
+
1590
+ // ---- Bit helper tests ----
1591
+
1592
+ #[test]
1593
+ fn test_bits_to_u32() {
1594
+ assert_eq!(bits_to_u32(&[false, false, false, false]), 0);
1595
+ assert_eq!(bits_to_u32(&[false, true, true, true]), 7);
1596
+ assert_eq!(bits_to_u32(&[true, false, false, false]), 8);
1597
+ assert_eq!(bits_to_u32(&[true, true, true, true]), 15);
1598
+ }
1599
+
1600
+ #[test]
1601
+ fn test_bytes_bits_roundtrip() {
1602
+ let data = vec![0x00, 0x01, 0xFF, 0xAB];
1603
+ let bits = bytes_to_bits(&data);
1604
+ assert_eq!(bits.len(), 32);
1605
+ let bytes = bits_to_bytes(&bits);
1606
+ assert_eq!(bytes, data);
1607
+ }
1608
+
1609
+ // ---- encode_units tests ----
1610
+
1611
+ #[test]
1612
+ fn test_encode_units_empty() {
1613
+ assert_eq!(encode_units(&[]).unwrap(), 0);
1614
+ }
1615
+
1616
+ #[test]
1617
+ fn test_encode_units_content_only() {
1618
+ assert_eq!(encode_units(&[MainType::Content]).unwrap(), 1);
1619
+ }
1620
+
1621
+ #[test]
1622
+ fn test_encode_units_semantic_only() {
1623
+ assert_eq!(encode_units(&[MainType::Semantic]).unwrap(), 2);
1624
+ }
1625
+
1626
+ #[test]
1627
+ fn test_encode_units_semantic_content() {
1628
+ assert_eq!(
1629
+ encode_units(&[MainType::Semantic, MainType::Content]).unwrap(),
1630
+ 3
1631
+ );
1632
+ }
1633
+
1634
+ #[test]
1635
+ fn test_encode_units_meta_only() {
1636
+ assert_eq!(encode_units(&[MainType::Meta]).unwrap(), 4);
1637
+ }
1638
+
1639
+ #[test]
1640
+ fn test_encode_units_meta_content() {
1641
+ assert_eq!(
1642
+ encode_units(&[MainType::Meta, MainType::Content]).unwrap(),
1643
+ 5
1644
+ );
1645
+ }
1646
+
1647
+ #[test]
1648
+ fn test_encode_units_meta_semantic() {
1649
+ assert_eq!(
1650
+ encode_units(&[MainType::Meta, MainType::Semantic]).unwrap(),
1651
+ 6
1652
+ );
1653
+ }
1654
+
1655
+ #[test]
1656
+ fn test_encode_units_all_optional() {
1657
+ assert_eq!(
1658
+ encode_units(&[MainType::Meta, MainType::Semantic, MainType::Content]).unwrap(),
1659
+ 7
1660
+ );
1661
+ }
1662
+
1663
+ #[test]
1664
+ fn test_encode_units_rejects_data() {
1665
+ assert!(encode_units(&[MainType::Data]).is_err());
1666
+ }
1667
+
1668
+ #[test]
1669
+ fn test_encode_units_rejects_instance() {
1670
+ assert!(encode_units(&[MainType::Instance]).is_err());
1671
+ }
1672
+
1673
+ #[test]
1674
+ fn test_encode_units_rejects_iscc() {
1675
+ assert!(encode_units(&[MainType::Iscc]).is_err());
1676
+ }
1677
+
1678
+ // ---- decode_units tests ----
1679
+
1680
+ #[test]
1681
+ fn test_decode_units_empty() {
1682
+ assert_eq!(decode_units(0).unwrap(), vec![]);
1683
+ }
1684
+
1685
+ #[test]
1686
+ fn test_decode_units_content() {
1687
+ assert_eq!(decode_units(1).unwrap(), vec![MainType::Content]);
1688
+ }
1689
+
1690
+ #[test]
1691
+ fn test_decode_units_semantic() {
1692
+ assert_eq!(decode_units(2).unwrap(), vec![MainType::Semantic]);
1693
+ }
1694
+
1695
+ #[test]
1696
+ fn test_decode_units_semantic_content() {
1697
+ assert_eq!(
1698
+ decode_units(3).unwrap(),
1699
+ vec![MainType::Semantic, MainType::Content]
1700
+ );
1701
+ }
1702
+
1703
+ #[test]
1704
+ fn test_decode_units_meta() {
1705
+ assert_eq!(decode_units(4).unwrap(), vec![MainType::Meta]);
1706
+ }
1707
+
1708
+ #[test]
1709
+ fn test_decode_units_meta_content() {
1710
+ assert_eq!(
1711
+ decode_units(5).unwrap(),
1712
+ vec![MainType::Meta, MainType::Content]
1713
+ );
1714
+ }
1715
+
1716
+ #[test]
1717
+ fn test_decode_units_meta_semantic() {
1718
+ assert_eq!(
1719
+ decode_units(6).unwrap(),
1720
+ vec![MainType::Meta, MainType::Semantic]
1721
+ );
1722
+ }
1723
+
1724
+ #[test]
1725
+ fn test_decode_units_all() {
1726
+ assert_eq!(
1727
+ decode_units(7).unwrap(),
1728
+ vec![MainType::Meta, MainType::Semantic, MainType::Content]
1729
+ );
1730
+ }
1731
+
1732
+ #[test]
1733
+ fn test_decode_units_invalid() {
1734
+ assert!(decode_units(8).is_err());
1735
+ assert!(decode_units(255).is_err());
1736
+ }
1737
+
1738
+ #[test]
1739
+ fn test_decode_units_roundtrip_with_encode_units() {
1740
+ for unit_id in 0..=7u32 {
1741
+ let types = decode_units(unit_id).unwrap();
1742
+ let encoded = encode_units(&types).unwrap();
1743
+ assert_eq!(encoded, unit_id, "roundtrip failed for unit_id={unit_id}");
1744
+ }
1745
+ }
1746
+
1747
+ // ---- iscc_decompose tests ----
1748
+
1749
+ #[test]
1750
+ fn test_decompose_single_meta_unit() {
1751
+ // A single Meta-Code unit passes through unchanged
1752
+ let result = iscc_decompose("AAAYPXW445FTYNJ3").unwrap();
1753
+ assert_eq!(result, vec!["AAAYPXW445FTYNJ3"]);
1754
+ }
1755
+
1756
+ #[test]
1757
+ fn test_decompose_single_unit_with_prefix() {
1758
+ // Accepts "ISCC:" prefix and returns without prefix
1759
+ let result = iscc_decompose("ISCC:AAAYPXW445FTYNJ3").unwrap();
1760
+ assert_eq!(result, vec!["AAAYPXW445FTYNJ3"]);
1761
+ }
1762
+
1763
+ #[test]
1764
+ fn test_decompose_single_unit_maintype() {
1765
+ // Verify the decomposed unit decodes to the expected MainType
1766
+ let result = iscc_decompose("AAAYPXW445FTYNJ3").unwrap();
1767
+ assert_eq!(result.len(), 1);
1768
+ let raw = decode_base32(&result[0]).unwrap();
1769
+ let (mt, _, _, _, _) = decode_header(&raw).unwrap();
1770
+ assert_eq!(mt, MainType::Meta);
1771
+ }
1772
+
1773
+ #[test]
1774
+ fn test_decompose_standard_iscc_code() {
1775
+ // test_0000_standard: Meta + Content(Text) + Data + Instance → composite
1776
+ let codes = [
1777
+ "AAAYPXW445FTYNJ3",
1778
+ "EAARMJLTQCUWAND2",
1779
+ "GABVVC5DMJJGYKZ4ZBYVNYABFFYXG",
1780
+ "IADWIK7A7JTUAQ2D6QARX7OBEIK3OOUAM42LOBLCZ4ZOGDLRHMDL6TQ",
1781
+ ];
1782
+ let composite = crate::gen_iscc_code_v0(
1783
+ &codes.iter().map(|s| *s as &str).collect::<Vec<&str>>(),
1784
+ false,
1785
+ )
1786
+ .unwrap();
1787
+
1788
+ let decomposed = iscc_decompose(&composite.iscc).unwrap();
1789
+
1790
+ // Should produce 4 units: Meta, Content, Data, Instance
1791
+ assert_eq!(decomposed.len(), 4);
1792
+
1793
+ // Verify MainTypes in order
1794
+ let main_types: Vec<MainType> = decomposed
1795
+ .iter()
1796
+ .map(|code| {
1797
+ let raw = decode_base32(code).unwrap();
1798
+ let (mt, _, _, _, _) = decode_header(&raw).unwrap();
1799
+ mt
1800
+ })
1801
+ .collect();
1802
+ assert_eq!(
1803
+ main_types,
1804
+ vec![
1805
+ MainType::Meta,
1806
+ MainType::Content,
1807
+ MainType::Data,
1808
+ MainType::Instance
1809
+ ]
1810
+ );
1811
+
1812
+ // Data and Instance are always the last two
1813
+ let raw_data = decode_base32(&decomposed[2]).unwrap();
1814
+ let (mt_d, _, _, _, _) = decode_header(&raw_data).unwrap();
1815
+ assert_eq!(mt_d, MainType::Data);
1816
+
1817
+ let raw_inst = decode_base32(&decomposed[3]).unwrap();
1818
+ let (mt_i, _, _, _, _) = decode_header(&raw_inst).unwrap();
1819
+ assert_eq!(mt_i, MainType::Instance);
1820
+ }
1821
+
1822
+ #[test]
1823
+ fn test_decompose_no_meta() {
1824
+ // test_0001_no_meta: Content(Text) + Data + Instance → composite (no Meta)
1825
+ let codes = [
1826
+ "EAARMJLTQCUWAND2",
1827
+ "GABVVC5DMJJGYKZ4ZBYVNYABFFYXG",
1828
+ "IADWIK7A7JTUAQ2D6QARX7OBEIK3OOUAM42LOBLCZ4ZOGDLRHMDL6TQ",
1829
+ ];
1830
+ let composite = crate::gen_iscc_code_v0(
1831
+ &codes.iter().map(|s| *s as &str).collect::<Vec<&str>>(),
1832
+ false,
1833
+ )
1834
+ .unwrap();
1835
+
1836
+ let decomposed = iscc_decompose(&composite.iscc).unwrap();
1837
+
1838
+ // Should produce 3 units: Content, Data, Instance (no Meta)
1839
+ assert_eq!(decomposed.len(), 3);
1840
+
1841
+ let main_types: Vec<MainType> = decomposed
1842
+ .iter()
1843
+ .map(|code| {
1844
+ let raw = decode_base32(code).unwrap();
1845
+ let (mt, _, _, _, _) = decode_header(&raw).unwrap();
1846
+ mt
1847
+ })
1848
+ .collect();
1849
+ assert_eq!(
1850
+ main_types,
1851
+ vec![MainType::Content, MainType::Data, MainType::Instance]
1852
+ );
1853
+ }
1854
+
1855
+ #[test]
1856
+ fn test_decompose_sum_only() {
1857
+ // test_0002: Data + Instance only (Sum SubType)
1858
+ let codes = [
1859
+ "GABVVC5DMJJGYKZ4ZBYVNYABFFYXG",
1860
+ "IADWIK7A7JTUAQ2D6QARX7OBEIK3OOUAM42LOBLCZ4ZOGDLRHMDL6TQ",
1861
+ ];
1862
+ let composite = crate::gen_iscc_code_v0(
1863
+ &codes.iter().map(|s| *s as &str).collect::<Vec<&str>>(),
1864
+ false,
1865
+ )
1866
+ .unwrap();
1867
+
1868
+ let decomposed = iscc_decompose(&composite.iscc).unwrap();
1869
+
1870
+ // Should produce 2 units: Data, Instance
1871
+ assert_eq!(decomposed.len(), 2);
1872
+
1873
+ let main_types: Vec<MainType> = decomposed
1874
+ .iter()
1875
+ .map(|code| {
1876
+ let raw = decode_base32(code).unwrap();
1877
+ let (mt, _, _, _, _) = decode_header(&raw).unwrap();
1878
+ mt
1879
+ })
1880
+ .collect();
1881
+ assert_eq!(main_types, vec![MainType::Data, MainType::Instance]);
1882
+ }
1883
+
1884
+ #[test]
1885
+ fn test_decompose_conformance_roundtrip() {
1886
+ // Use gen_iscc_code_v0 conformance vectors to verify decompose
1887
+ let data = crate::conformance::test_data().unwrap();
1888
+ let cases = crate::conformance::cases(&data, "gen_iscc_code_v0").unwrap();
1889
+
1890
+ for (tc_name, tc) in cases {
1891
+ let expected_iscc = crate::conformance::expected_iscc(tc).unwrap();
1892
+ let input_codes = crate::conformance::iscc_inputs(tc)
1893
+ .unwrap_or_else(|| panic!("unparsable inputs in {tc_name}"));
1894
+
1895
+ let decomposed = iscc_decompose(&expected_iscc).unwrap();
1896
+
1897
+ // Each decomposed code decodes to a valid MainType
1898
+ for code in &decomposed {
1899
+ let raw = decode_base32(code).unwrap();
1900
+ let (mt, _, _, _, _) = decode_header(&raw).unwrap();
1901
+ assert_ne!(
1902
+ mt,
1903
+ MainType::Iscc,
1904
+ "decomposed unit should not be ISCC in {tc_name}"
1905
+ );
1906
+ }
1907
+
1908
+ // Data and Instance are always the last two units
1909
+ let last_two: Vec<MainType> = decomposed[decomposed.len() - 2..]
1910
+ .iter()
1911
+ .map(|code| {
1912
+ let raw = decode_base32(code).unwrap();
1913
+ let (mt, _, _, _, _) = decode_header(&raw).unwrap();
1914
+ mt
1915
+ })
1916
+ .collect();
1917
+ assert_eq!(
1918
+ last_two,
1919
+ vec![MainType::Data, MainType::Instance],
1920
+ "last two units must be Data+Instance in {tc_name}"
1921
+ );
1922
+
1923
+ // Number of decomposed units matches number of input codes
1924
+ assert_eq!(
1925
+ decomposed.len(),
1926
+ input_codes.len(),
1927
+ "decomposed unit count mismatch in {tc_name}"
1928
+ );
1929
+ }
1930
+ }
1931
+
1932
+ // ---- iscc_decompose truncation tests ----
1933
+
1934
+ /// Build a truncated ISCC string: valid header for given params, but fewer body bytes than needed.
1935
+ ///
1936
+ /// For ISCC MainType, `length_field` is the raw unit_id (0-7).
1937
+ /// For other MainTypes, `length_field` is the raw header length field value.
1938
+ fn make_truncated_iscc(
1939
+ mtype: MainType,
1940
+ stype: SubType,
1941
+ length_field: u32,
1942
+ body_len: usize,
1943
+ ) -> String {
1944
+ let header = encode_header(mtype, stype, Version::V0, length_field).unwrap();
1945
+ let mut raw = header;
1946
+ raw.extend(vec![0xABu8; body_len]);
1947
+ encode_base32(&raw)
1948
+ }
1949
+
1950
+ #[test]
1951
+ fn test_decompose_truncated_standard_unit() {
1952
+ // Meta-Code header for 64 bits (8 bytes expected), but only 4 body bytes provided.
1953
+ // encode_length(Meta, 64) = 64/32 - 1 = 1
1954
+ let length_field = encode_length(MainType::Meta, 64).unwrap();
1955
+ let iscc = make_truncated_iscc(MainType::Meta, SubType::None, length_field, 4);
1956
+ let result = iscc_decompose(&iscc);
1957
+ assert!(
1958
+ result.is_err(),
1959
+ "expected error for truncated standard unit"
1960
+ );
1961
+ let err = result.unwrap_err().to_string();
1962
+ assert!(
1963
+ err.contains("truncated ISCC body"),
1964
+ "error should mention truncation: {err}"
1965
+ );
1966
+ }
1967
+
1968
+ #[test]
1969
+ fn test_decompose_truncated_wide_mode() {
1970
+ // ISCC-CODE Wide header expects 32 body bytes, provide only 16.
1971
+ // For Wide ISCC-CODE, length field is unit_id (0 = no optional units)
1972
+ let iscc = make_truncated_iscc(MainType::Iscc, SubType::Wide, 0, 16);
1973
+ let result = iscc_decompose(&iscc);
1974
+ assert!(result.is_err(), "expected error for truncated wide mode");
1975
+ let err = result.unwrap_err().to_string();
1976
+ assert!(
1977
+ err.contains("truncated ISCC body"),
1978
+ "error should mention truncation: {err}"
1979
+ );
1980
+ }
1981
+
1982
+ #[test]
1983
+ fn test_decompose_truncated_dynamic_units() {
1984
+ // ISCC-CODE with Meta+Content (unit_id=5, bit0=Content+bit2=Meta)
1985
+ // Dynamic units: 2 × 8 = 16 bytes, static: 16 bytes, total: 32 bytes needed
1986
+ // Provide only 8 body bytes (enough for 1 dynamic unit, not all)
1987
+ let unit_id = 5; // Meta + Content
1988
+ let iscc = make_truncated_iscc(MainType::Iscc, SubType::None, unit_id, 8);
1989
+ let result = iscc_decompose(&iscc);
1990
+ assert!(
1991
+ result.is_err(),
1992
+ "expected error for truncated dynamic units"
1993
+ );
1994
+ let err = result.unwrap_err().to_string();
1995
+ assert!(
1996
+ err.contains("truncated ISCC body"),
1997
+ "error should mention truncation: {err}"
1998
+ );
1999
+ }
2000
+
2001
+ #[test]
2002
+ fn test_decompose_truncated_static_units() {
2003
+ // ISCC-CODE with Content only (unit_id=1)
2004
+ // Dynamic: 1 × 8 = 8, static: 16, total: 24 bytes needed
2005
+ // Provide only 16 body bytes (dynamic ok, but static Data+Instance missing)
2006
+ let unit_id = 1; // Content only
2007
+ let iscc = make_truncated_iscc(MainType::Iscc, SubType::None, unit_id, 16);
2008
+ let result = iscc_decompose(&iscc);
2009
+ assert!(result.is_err(), "expected error for truncated static units");
2010
+ let err = result.unwrap_err().to_string();
2011
+ assert!(
2012
+ err.contains("truncated ISCC body"),
2013
+ "error should mention truncation: {err}"
2014
+ );
2015
+ }
2016
+
2017
+ #[test]
2018
+ fn test_decompose_empty_body() {
2019
+ // Meta-Code header for 64 bits but zero body bytes
2020
+ let length_field = encode_length(MainType::Meta, 64).unwrap();
2021
+ let iscc = make_truncated_iscc(MainType::Meta, SubType::None, length_field, 0);
2022
+ let result = iscc_decompose(&iscc);
2023
+ assert!(result.is_err(), "expected error for empty body");
2024
+ let err = result.unwrap_err().to_string();
2025
+ assert!(
2026
+ err.contains("truncated ISCC body"),
2027
+ "error should mention truncation: {err}"
2028
+ );
2029
+ }
2030
+
2031
+ #[test]
2032
+ fn test_decompose_valid_still_works() {
2033
+ // A valid ISCC-CODE should still decompose correctly (regression guard)
2034
+ // Build: Meta(64) + Content-Text(64) + Data(64) + Instance(64)
2035
+ let meta_body = [0x11u8; 8];
2036
+ let content_body = [0x22u8; 8];
2037
+ let data_body = [0x33u8; 8];
2038
+ let instance_body = [0x44u8; 8];
2039
+
2040
+ let meta_code =
2041
+ encode_component(MainType::Meta, SubType::None, Version::V0, 64, &meta_body).unwrap();
2042
+ let content_code = encode_component(
2043
+ MainType::Content,
2044
+ SubType::None,
2045
+ Version::V0,
2046
+ 64,
2047
+ &content_body,
2048
+ )
2049
+ .unwrap();
2050
+ let data_code =
2051
+ encode_component(MainType::Data, SubType::None, Version::V0, 64, &data_body).unwrap();
2052
+ let instance_code = encode_component(
2053
+ MainType::Instance,
2054
+ SubType::None,
2055
+ Version::V0,
2056
+ 64,
2057
+ &instance_body,
2058
+ )
2059
+ .unwrap();
2060
+
2061
+ // Concatenate as a sequence of ISCC-UNITs (not a single ISCC-CODE)
2062
+ let sequence = format!("{meta_code}{content_code}{data_code}{instance_code}");
2063
+ let raw = decode_base32(&sequence).unwrap();
2064
+ let full_iscc = encode_base32(&raw);
2065
+
2066
+ let result = iscc_decompose(&full_iscc);
2067
+ assert!(
2068
+ result.is_ok(),
2069
+ "valid ISCC sequence should decompose: {result:?}"
2070
+ );
2071
+ let units = result.unwrap();
2072
+ assert_eq!(units.len(), 4, "should decompose into 4 units");
2073
+ }
2074
+ }