iscc-lib 0.0.2__tar.gz → 0.0.3__tar.gz

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.
Files changed (31) hide show
  1. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/Cargo.lock +6 -6
  2. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/Cargo.toml +1 -1
  3. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/PKG-INFO +1 -1
  4. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/CLAUDE.md +22 -18
  5. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/src/lib.rs +439 -3
  6. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-py/src/lib.rs +48 -0
  7. iscc_lib-0.0.3/crates/iscc-py/uv.lock +7 -0
  8. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/python/iscc_lib/__init__.py +87 -2
  9. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/python/iscc_lib/_lowlevel.pyi +58 -0
  10. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/README.md +0 -0
  11. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/Cargo.toml +0 -0
  12. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/README.md +0 -0
  13. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/benches/benchmarks.rs +0 -0
  14. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/src/cdc.rs +0 -0
  15. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/src/codec.rs +0 -0
  16. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/src/conformance.rs +0 -0
  17. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/src/dct.rs +0 -0
  18. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/src/minhash.rs +0 -0
  19. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/src/simhash.rs +0 -0
  20. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/src/streaming.rs +0 -0
  21. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/src/types.rs +0 -0
  22. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/src/utils.rs +0 -0
  23. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/src/wtahash.rs +0 -0
  24. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/tests/data.json +0 -0
  25. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/tests/test_algorithm_primitives.rs +0 -0
  26. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-lib/tests/test_text_utils.rs +0 -0
  27. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-py/CLAUDE.md +0 -0
  28. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-py/Cargo.toml +0 -0
  29. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/crates/iscc-py/README.md +0 -0
  30. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/pyproject.toml +0 -0
  31. {iscc_lib-0.0.2 → iscc_lib-0.0.3}/python/iscc_lib/py.typed +0 -0
@@ -453,14 +453,14 @@ dependencies = [
453
453
 
454
454
  [[package]]
455
455
  name = "iscc-ffi"
456
- version = "0.0.2"
456
+ version = "0.0.3"
457
457
  dependencies = [
458
458
  "iscc-lib",
459
459
  ]
460
460
 
461
461
  [[package]]
462
462
  name = "iscc-jni"
463
- version = "0.0.2"
463
+ version = "0.0.3"
464
464
  dependencies = [
465
465
  "iscc-lib",
466
466
  "jni",
@@ -468,7 +468,7 @@ dependencies = [
468
468
 
469
469
  [[package]]
470
470
  name = "iscc-lib"
471
- version = "0.0.2"
471
+ version = "0.0.3"
472
472
  dependencies = [
473
473
  "blake3",
474
474
  "criterion",
@@ -485,7 +485,7 @@ dependencies = [
485
485
 
486
486
  [[package]]
487
487
  name = "iscc-napi"
488
- version = "0.0.2"
488
+ version = "0.0.3"
489
489
  dependencies = [
490
490
  "iscc-lib",
491
491
  "napi",
@@ -495,7 +495,7 @@ dependencies = [
495
495
 
496
496
  [[package]]
497
497
  name = "iscc-py"
498
- version = "0.0.2"
498
+ version = "0.0.3"
499
499
  dependencies = [
500
500
  "iscc-lib",
501
501
  "pyo3",
@@ -503,7 +503,7 @@ dependencies = [
503
503
 
504
504
  [[package]]
505
505
  name = "iscc-wasm"
506
- version = "0.0.2"
506
+ version = "0.0.3"
507
507
  dependencies = [
508
508
  "hex",
509
509
  "iscc-lib",
@@ -3,7 +3,7 @@ resolver = "2"
3
3
  members = ["crates/iscc-lib", "crates/iscc-py"]
4
4
 
5
5
  [workspace.package]
6
- version = "0.0.2"
6
+ version = "0.0.3"
7
7
  edition = "2024"
8
8
  rust-version = "1.85"
9
9
  authors = ["Titusz Pan <tp@py7.de>"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: iscc-lib
3
- Version: 0.0.2
3
+ Version: 0.0.3
4
4
  Classifier: Development Status :: 2 - Pre-Alpha
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: Apache Software License
@@ -5,30 +5,30 @@ Pure Rust implementation of ISO 24138:2024 (ISCC) -- the hub of the hub-and-spok
5
5
  ## Crate Role
6
6
 
7
7
  - This is the **core crate** that all binding crates (`iscc-py`, `iscc-napi`, `iscc-wasm`,
8
- `iscc-ffi`) depend on
8
+ `iscc-ffi`, `iscc-jni`) depend on
9
9
  - Must remain **pure Rust** -- zero binding dependencies (no PyO3, napi, wasm-bindgen)
10
10
  - Publishable to crates.io as `iscc-lib`
11
11
  - All ISCC algorithm logic lives here; binding crates only translate the API
12
12
 
13
13
  ## Module Layout
14
14
 
15
- | Module | Visibility | Purpose |
16
- | ---------------- | ------------ | ---------------------------------------------------------------------------------------------------------------- |
17
- | `lib.rs` | public | Crate root: re-exports, `IsccError`/`IsccResult`, all 9 `gen_*_v0` functions |
18
- | `types.rs` | `pub` | Result structs (`MetaCodeResult`, `TextCodeResult`, etc.) |
19
- | `codec.rs` | `pub` | Tier 2: `MainType`/`SubType`/`Version` enums, header encode/decode, base32, `encode_component`, `iscc_decompose` |
20
- | `streaming.rs` | `pub` | `DataHasher` and `InstanceHasher` streaming types |
21
- | `conformance.rs` | `pub` | `conformance_selftest()` -- runtime conformance checker |
22
- | `utils.rs` | `pub` | `text_clean`, `text_remove_newlines`, `text_trim`, `text_collapse`, `multi_hash_blake3` (pub(crate)) |
23
- | `cdc.rs` | `pub` | Content-defined chunking (`alg_cdc_chunks`) |
24
- | `minhash.rs` | `pub` | MinHash algorithm (`alg_minhash_256`) |
25
- | `simhash.rs` | `pub` | SimHash and sliding window (`alg_simhash`, `sliding_window`) |
26
- | `dct.rs` | `pub(crate)` | Discrete Cosine Transform for image hashing |
27
- | `wtahash.rs` | `pub(crate)` | Winner-Take-All hash for video fingerprinting |
15
+ | Module | Visibility | Purpose |
16
+ | ---------------- | ------------ | ---------------------------------------------------------------------------------------------------- |
17
+ | `lib.rs` | public | Crate root: re-exports, `IsccError`/`IsccResult`, all 9 `gen_*_v0` functions |
18
+ | `types.rs` | `pub` | Result structs (`MetaCodeResult`, `TextCodeResult`, etc.) |
19
+ | `codec.rs` | `pub` | Tier 2: `MainType`/`SubType`/`Version` enums, header encode/decode, base32, `iscc_decompose` |
20
+ | `streaming.rs` | `pub` | `DataHasher` and `InstanceHasher` streaming types |
21
+ | `conformance.rs` | `pub` | `conformance_selftest()` -- runtime conformance checker |
22
+ | `utils.rs` | `pub` | `text_clean`, `text_remove_newlines`, `text_trim`, `text_collapse`, `multi_hash_blake3` (pub(crate)) |
23
+ | `cdc.rs` | `pub` | Content-defined chunking (`alg_cdc_chunks`) |
24
+ | `minhash.rs` | `pub` | MinHash algorithm (`alg_minhash_256`) |
25
+ | `simhash.rs` | `pub` | SimHash and sliding window (`alg_simhash`, `sliding_window`) |
26
+ | `dct.rs` | `pub(crate)` | Discrete Cosine Transform for image hashing |
27
+ | `wtahash.rs` | `pub(crate)` | Winner-Take-All hash for video fingerprinting |
28
28
 
29
29
  ## API Tier Rules
30
30
 
31
- **Tier 1 -- public API, bound in all languages (22 symbols at crate root):**
31
+ **Tier 1 -- public API, bound in all languages (30 symbols at crate root):**
32
32
 
33
33
  - 9 gen functions: `gen_meta_code_v0`, `gen_text_code_v0`, `gen_image_code_v0`, `gen_audio_code_v0`,
34
34
  `gen_video_code_v0`, `gen_mixed_code_v0`, `gen_data_code_v0`, `gen_instance_code_v0`,
@@ -36,8 +36,10 @@ Pure Rust implementation of ISO 24138:2024 (ISCC) -- the hub of the hub-and-spok
36
36
  - 4 text utilities: `text_clean`, `text_remove_newlines`, `text_trim`, `text_collapse`
37
37
  - 4 algorithm primitives: `sliding_window`, `alg_minhash_256`, `alg_cdc_chunks`, `alg_simhash`
38
38
  - 1 soft hash: `soft_hash_video_v0`
39
- - 1 encoding utility: `encode_base64`
40
- - 1 codec operation: `iscc_decompose`
39
+ - 2 encoding utilities: `encode_base64`, `json_to_data_url`
40
+ - 3 codec operations: `iscc_decompose`, `encode_component`, `iscc_decode`
41
+ - 4 algorithm constants: `META_TRIM_NAME`, `META_TRIM_DESCRIPTION`, `IO_READ_SIZE`,
42
+ `TEXT_NGRAM_SIZE`
41
43
  - 2 streaming types: `DataHasher`, `InstanceHasher`
42
44
  - 1 diagnostic: `conformance_selftest`
43
45
 
@@ -45,7 +47,7 @@ Pure Rust implementation of ISO 24138:2024 (ISCC) -- the hub of the hub-and-spok
45
47
 
46
48
  - `MainType`, `SubType`, `Version` enums
47
49
  - `encode_header`, `decode_header`, `encode_base32`, `decode_base32`
48
- - `encode_component`, `encode_length`, `decode_length`, `encode_units`, `decode_units`
50
+ - `encode_length`, `decode_length`, `encode_units`, `decode_units`
49
51
 
50
52
  **Internal -- `pub(crate)` or private, free to change:**
51
53
 
@@ -118,6 +120,8 @@ cargo bench -p iscc-lib # Criterion benchmarks
118
120
  - `unicode-general-category` -- Unicode category classification for text filtering
119
121
  - `thiserror` -- error derive macro
120
122
  - `serde_json` -- JSON parsing for meta processing and conformance vectors
123
+ - `serde_json_canonicalizer` -- RFC 8785 (JCS) compliant JSON serialization for metadata
124
+ canonicalization
121
125
  - `serde` + `criterion` -- dev-dependencies only
122
126
 
123
127
  ## Common Pitfalls
@@ -25,6 +25,18 @@ pub use streaming::{DataHasher, InstanceHasher};
25
25
  pub use types::*;
26
26
  pub use utils::{text_clean, text_collapse, text_remove_newlines, text_trim};
27
27
 
28
+ /// Max UTF-8 byte length for name metadata trimming.
29
+ pub const META_TRIM_NAME: usize = 128;
30
+
31
+ /// Max UTF-8 byte length for description metadata trimming.
32
+ pub const META_TRIM_DESCRIPTION: usize = 4096;
33
+
34
+ /// Buffer size in bytes for streaming file reads (4 MB).
35
+ pub const IO_READ_SIZE: usize = 4_194_304;
36
+
37
+ /// Character n-gram width for text content features.
38
+ pub const TEXT_NGRAM_SIZE: usize = 13;
39
+
28
40
  /// Error type for ISCC operations.
29
41
  #[derive(Debug, thiserror::Error)]
30
42
  pub enum IsccError {
@@ -151,6 +163,109 @@ fn build_meta_data_url(json_bytes: &[u8], json_value: &serde_json::Value) -> Str
151
163
  format!("data:{media_type};base64,{b64}")
152
164
  }
153
165
 
166
+ /// Encode a raw digest into an ISCC unit string.
167
+ ///
168
+ /// Takes integer type identifiers (matching `MainType`, `SubType`, `Version` enum values)
169
+ /// and a raw digest, returns a base32-encoded ISCC unit string.
170
+ ///
171
+ /// # Errors
172
+ ///
173
+ /// Returns `IsccError::InvalidInput` if enum values are out of range, if `mtype` is
174
+ /// `MainType::Iscc` (5), or if `digest.len() < bit_length / 8`.
175
+ pub fn encode_component(
176
+ mtype: u8,
177
+ stype: u8,
178
+ version: u8,
179
+ bit_length: u32,
180
+ digest: &[u8],
181
+ ) -> IsccResult<String> {
182
+ let mt = codec::MainType::try_from(mtype)?;
183
+ let st = codec::SubType::try_from(stype)?;
184
+ let vs = codec::Version::try_from(version)?;
185
+ let needed = (bit_length / 8) as usize;
186
+ if digest.len() < needed {
187
+ return Err(IsccError::InvalidInput(format!(
188
+ "digest length {} < bit_length/8 ({})",
189
+ digest.len(),
190
+ needed
191
+ )));
192
+ }
193
+ codec::encode_component(mt, st, vs, bit_length, digest)
194
+ }
195
+
196
+ /// Decode an ISCC unit string into its header components and raw digest.
197
+ ///
198
+ /// Inverse of [`encode_component`]. Strips an optional `"ISCC:"` prefix and
199
+ /// dashes, base32-decodes the string, parses the variable-length header, and
200
+ /// returns the digest truncated to exactly the encoded bit-length.
201
+ ///
202
+ /// Returns `(maintype, subtype, version, length_index, digest)` where the
203
+ /// integer fields match [`codec::MainType`], [`codec::SubType`], and
204
+ /// [`codec::Version`] enum values.
205
+ ///
206
+ /// # Errors
207
+ ///
208
+ /// Returns `IsccError::InvalidInput` on invalid base32 input, malformed
209
+ /// header, or if the decoded body is shorter than the expected digest length.
210
+ pub fn iscc_decode(iscc: &str) -> IsccResult<(u8, u8, u8, u8, Vec<u8>)> {
211
+ // Strip optional "ISCC:" prefix (case-sensitive, matching iscc_decompose)
212
+ let clean = iscc.strip_prefix("ISCC:").unwrap_or(iscc);
213
+ // Remove dashes (matching iscc_clean behavior for base32 input)
214
+ let clean = clean.replace('-', "");
215
+ let raw = codec::decode_base32(&clean)?;
216
+ let (mt, st, vs, length_index, tail) = codec::decode_header(&raw)?;
217
+ let bit_length = codec::decode_length(mt, length_index, st);
218
+ let nbytes = (bit_length / 8) as usize;
219
+ if tail.len() < nbytes {
220
+ return Err(IsccError::InvalidInput(format!(
221
+ "decoded body too short: expected {nbytes} digest bytes, got {}",
222
+ tail.len()
223
+ )));
224
+ }
225
+ Ok((
226
+ mt as u8,
227
+ st as u8,
228
+ vs as u8,
229
+ length_index as u8,
230
+ tail[..nbytes].to_vec(),
231
+ ))
232
+ }
233
+
234
+ /// Convert a JSON string into a `data:` URL with JCS canonicalization.
235
+ ///
236
+ /// Parses the JSON, re-serializes to [RFC 8785 (JCS)](https://www.rfc-editor.org/rfc/rfc8785)
237
+ /// canonical form, base64-encodes the result, and wraps it in a `data:` URL.
238
+ /// Uses `application/ld+json` media type when the JSON contains an `@context`
239
+ /// key, otherwise `application/json`.
240
+ ///
241
+ /// This enables all language bindings to support dict/object meta parameters
242
+ /// by serializing to JSON once (language-specific) then delegating encoding
243
+ /// to Rust.
244
+ ///
245
+ /// # Errors
246
+ ///
247
+ /// Returns [`IsccError::InvalidInput`] if `json` is not valid JSON or if
248
+ /// JCS canonicalization fails.
249
+ ///
250
+ /// # Examples
251
+ ///
252
+ /// ```
253
+ /// # use iscc_lib::json_to_data_url;
254
+ /// let url = json_to_data_url(r#"{"key": "value"}"#).unwrap();
255
+ /// assert!(url.starts_with("data:application/json;base64,"));
256
+ ///
257
+ /// let ld_url = json_to_data_url(r#"{"@context": "https://schema.org"}"#).unwrap();
258
+ /// assert!(ld_url.starts_with("data:application/ld+json;base64,"));
259
+ /// ```
260
+ pub fn json_to_data_url(json: &str) -> IsccResult<String> {
261
+ let parsed: serde_json::Value = serde_json::from_str(json)
262
+ .map_err(|e| IsccError::InvalidInput(format!("invalid JSON: {e}")))?;
263
+ let mut canonical_bytes = Vec::new();
264
+ serde_json_canonicalizer::to_writer(&parsed, &mut canonical_bytes)
265
+ .map_err(|e| IsccError::InvalidInput(format!("JSON canonicalization failed: {e}")))?;
266
+ Ok(build_meta_data_url(&canonical_bytes, &parsed))
267
+ }
268
+
154
269
  /// Generate a Meta-Code from name and optional metadata.
155
270
  ///
156
271
  /// Produces an ISCC Meta-Code by hashing the provided name, description,
@@ -167,7 +282,7 @@ pub fn gen_meta_code_v0(
167
282
  // Normalize name: clean → remove newlines → trim to 128 bytes
168
283
  let name = utils::text_clean(name);
169
284
  let name = utils::text_remove_newlines(&name);
170
- let name = utils::text_trim(&name, 128);
285
+ let name = utils::text_trim(&name, META_TRIM_NAME);
171
286
 
172
287
  if name.is_empty() {
173
288
  return Err(IsccError::InvalidInput(
@@ -178,7 +293,7 @@ pub fn gen_meta_code_v0(
178
293
  // Normalize description: clean → trim to 4096 bytes
179
294
  let desc_str = description.unwrap_or("");
180
295
  let desc_clean = utils::text_clean(desc_str);
181
- let desc_clean = utils::text_trim(&desc_clean, 4096);
296
+ let desc_clean = utils::text_trim(&desc_clean, META_TRIM_DESCRIPTION);
182
297
 
183
298
  // Resolve meta payload bytes (if meta is provided)
184
299
  let meta_payload: Option<Vec<u8>> = match meta {
@@ -267,7 +382,7 @@ pub fn gen_meta_code_v0(
267
382
  /// Generates character n-grams with a sliding window of width 13,
268
383
  /// hashes each with xxh32, then applies MinHash to produce a 32-byte digest.
269
384
  fn soft_hash_text_v0(text: &str) -> Vec<u8> {
270
- let ngrams = simhash::sliding_window_strs(text, 13);
385
+ let ngrams = simhash::sliding_window_strs(text, TEXT_NGRAM_SIZE);
271
386
  let features: Vec<u32> = ngrams
272
387
  .iter()
273
388
  .map(|ng| xxhash_rust::xxh32::xxh32(ng.as_bytes(), 0))
@@ -1561,4 +1676,325 @@ mod tests {
1561
1676
  "empty bytes should produce same digest as name-only (no interleaving)"
1562
1677
  );
1563
1678
  }
1679
+
1680
+ // ---- Algorithm constants tests ----
1681
+
1682
+ #[test]
1683
+ fn test_meta_trim_name_value() {
1684
+ assert_eq!(META_TRIM_NAME, 128);
1685
+ }
1686
+
1687
+ #[test]
1688
+ fn test_meta_trim_description_value() {
1689
+ assert_eq!(META_TRIM_DESCRIPTION, 4096);
1690
+ }
1691
+
1692
+ #[test]
1693
+ fn test_io_read_size_value() {
1694
+ assert_eq!(IO_READ_SIZE, 4_194_304);
1695
+ }
1696
+
1697
+ #[test]
1698
+ fn test_text_ngram_size_value() {
1699
+ assert_eq!(TEXT_NGRAM_SIZE, 13);
1700
+ }
1701
+
1702
+ // ---- encode_component Tier 1 wrapper tests ----
1703
+
1704
+ /// Encode a known digest and verify the output matches the codec version.
1705
+ #[test]
1706
+ fn test_encode_component_matches_codec() {
1707
+ let digest = [0xABu8; 8];
1708
+ let tier1 = encode_component(3, 0, 0, 64, &digest).unwrap();
1709
+ let tier2 = codec::encode_component(
1710
+ codec::MainType::Data,
1711
+ codec::SubType::None,
1712
+ codec::Version::V0,
1713
+ 64,
1714
+ &digest,
1715
+ )
1716
+ .unwrap();
1717
+ assert_eq!(tier1, tier2);
1718
+ }
1719
+
1720
+ /// Round-trip: encode a digest and verify the result is a valid ISCC unit.
1721
+ #[test]
1722
+ fn test_encode_component_round_trip() {
1723
+ let digest = [0x42u8; 32];
1724
+ let result = encode_component(0, 0, 0, 64, &digest).unwrap();
1725
+ // Meta-Code with 64-bit digest should start with "AA"
1726
+ assert!(!result.is_empty());
1727
+ }
1728
+
1729
+ /// Reject MainType::Iscc (value 5).
1730
+ #[test]
1731
+ fn test_encode_component_rejects_iscc() {
1732
+ let result = encode_component(5, 0, 0, 64, &[0u8; 8]);
1733
+ assert!(result.is_err());
1734
+ }
1735
+
1736
+ /// Reject digest shorter than bit_length / 8.
1737
+ #[test]
1738
+ fn test_encode_component_rejects_short_digest() {
1739
+ let result = encode_component(0, 0, 0, 64, &[0u8; 4]);
1740
+ assert!(result.is_err());
1741
+ let err = result.unwrap_err().to_string();
1742
+ assert!(
1743
+ err.contains("digest length 4 < bit_length/8 (8)"),
1744
+ "unexpected error: {err}"
1745
+ );
1746
+ }
1747
+
1748
+ /// Reject invalid MainType value.
1749
+ #[test]
1750
+ fn test_encode_component_rejects_invalid_mtype() {
1751
+ let result = encode_component(99, 0, 0, 64, &[0u8; 8]);
1752
+ assert!(result.is_err());
1753
+ }
1754
+
1755
+ /// Reject invalid SubType value.
1756
+ #[test]
1757
+ fn test_encode_component_rejects_invalid_stype() {
1758
+ let result = encode_component(0, 99, 0, 64, &[0u8; 8]);
1759
+ assert!(result.is_err());
1760
+ }
1761
+
1762
+ /// Reject invalid Version value.
1763
+ #[test]
1764
+ fn test_encode_component_rejects_invalid_version() {
1765
+ let result = encode_component(0, 0, 99, 64, &[0u8; 8]);
1766
+ assert!(result.is_err());
1767
+ }
1768
+
1769
+ // ---- iscc_decode tests ----
1770
+
1771
+ /// Round-trip: encode a Meta-Code digest, decode back, verify all fields match.
1772
+ #[test]
1773
+ fn test_iscc_decode_round_trip_meta() {
1774
+ let digest = [0xaa_u8; 8];
1775
+ let encoded = encode_component(0, 0, 0, 64, &digest).unwrap();
1776
+ let (mt, st, vs, li, decoded_digest) = iscc_decode(&encoded).unwrap();
1777
+ assert_eq!(mt, 0, "MainType::Meta");
1778
+ assert_eq!(st, 0, "SubType::None");
1779
+ assert_eq!(vs, 0, "Version::V0");
1780
+ // encode_length(Meta, 64) → 64/32 - 1 = 1
1781
+ assert_eq!(li, 1, "length_index");
1782
+ assert_eq!(decoded_digest, digest.to_vec());
1783
+ }
1784
+
1785
+ /// Round-trip with Content-Code (MainType=2, SubType::TEXT=0).
1786
+ #[test]
1787
+ fn test_iscc_decode_round_trip_content() {
1788
+ let digest = [0xbb_u8; 8];
1789
+ let encoded = encode_component(2, 0, 0, 64, &digest).unwrap();
1790
+ let (mt, st, vs, _li, decoded_digest) = iscc_decode(&encoded).unwrap();
1791
+ assert_eq!(mt, 2, "MainType::Content");
1792
+ assert_eq!(st, 0, "SubType::TEXT");
1793
+ assert_eq!(vs, 0, "Version::V0");
1794
+ assert_eq!(decoded_digest, digest.to_vec());
1795
+ }
1796
+
1797
+ /// Round-trip with Data-Code (MainType=3).
1798
+ #[test]
1799
+ fn test_iscc_decode_round_trip_data() {
1800
+ let digest = [0xcc_u8; 8];
1801
+ let encoded = encode_component(3, 0, 0, 64, &digest).unwrap();
1802
+ let (mt, _st, _vs, _li, decoded_digest) = iscc_decode(&encoded).unwrap();
1803
+ assert_eq!(mt, 3, "MainType::Data");
1804
+ assert_eq!(decoded_digest, digest.to_vec());
1805
+ }
1806
+
1807
+ /// Round-trip with Instance-Code (MainType=4).
1808
+ #[test]
1809
+ fn test_iscc_decode_round_trip_instance() {
1810
+ let digest = [0xdd_u8; 8];
1811
+ let encoded = encode_component(4, 0, 0, 64, &digest).unwrap();
1812
+ let (mt, _st, _vs, _li, decoded_digest) = iscc_decode(&encoded).unwrap();
1813
+ assert_eq!(mt, 4, "MainType::Instance");
1814
+ assert_eq!(decoded_digest, digest.to_vec());
1815
+ }
1816
+
1817
+ /// Decode with "ISCC:" prefix produces the same result.
1818
+ #[test]
1819
+ fn test_iscc_decode_with_prefix() {
1820
+ let digest = [0xaa_u8; 8];
1821
+ let encoded = encode_component(0, 0, 0, 64, &digest).unwrap();
1822
+ let with_prefix = format!("ISCC:{encoded}");
1823
+ let (mt, st, vs, li, decoded_digest) = iscc_decode(&with_prefix).unwrap();
1824
+ assert_eq!(mt, 0);
1825
+ assert_eq!(st, 0);
1826
+ assert_eq!(vs, 0);
1827
+ assert_eq!(li, 1);
1828
+ assert_eq!(decoded_digest, digest.to_vec());
1829
+ }
1830
+
1831
+ /// Decode with dashes inserted in the string.
1832
+ #[test]
1833
+ fn test_iscc_decode_with_dashes() {
1834
+ let digest = [0xaa_u8; 8];
1835
+ let encoded = encode_component(0, 0, 0, 64, &digest).unwrap();
1836
+ // Insert dashes at arbitrary positions
1837
+ let with_dashes = format!("{}-{}-{}", &encoded[..4], &encoded[4..8], &encoded[8..]);
1838
+ let (mt, st, vs, li, decoded_digest) = iscc_decode(&with_dashes).unwrap();
1839
+ assert_eq!(mt, 0);
1840
+ assert_eq!(st, 0);
1841
+ assert_eq!(vs, 0);
1842
+ assert_eq!(li, 1);
1843
+ assert_eq!(decoded_digest, digest.to_vec());
1844
+ }
1845
+
1846
+ /// Error on invalid base32 characters.
1847
+ #[test]
1848
+ fn test_iscc_decode_invalid_base32() {
1849
+ let result = iscc_decode("!!!INVALID!!!");
1850
+ assert!(result.is_err());
1851
+ let err = result.unwrap_err().to_string();
1852
+ assert!(err.contains("base32"), "expected base32 error: {err}");
1853
+ }
1854
+
1855
+ /// Known value from conformance vectors: Meta-Code "ISCC:AAAZXZ6OU74YAZIM".
1856
+ /// MainType=Meta(0), SubType=None(0), Version=V0(0), 64-bit digest.
1857
+ #[test]
1858
+ fn test_iscc_decode_known_meta_code() {
1859
+ let (mt, st, vs, li, digest) = iscc_decode("ISCC:AAAZXZ6OU74YAZIM").unwrap();
1860
+ assert_eq!(mt, 0, "MainType::Meta");
1861
+ assert_eq!(st, 0, "SubType::None");
1862
+ assert_eq!(vs, 0, "Version::V0");
1863
+ assert_eq!(li, 1, "length_index for 64-bit");
1864
+ assert_eq!(digest.len(), 8, "64-bit = 8 bytes");
1865
+ }
1866
+
1867
+ /// Known value from conformance vectors: Instance-Code "ISCC:IAA26E2JXH27TING".
1868
+ /// MainType=Instance(4), SubType=None(0), Version=V0(0), 64-bit digest.
1869
+ #[test]
1870
+ fn test_iscc_decode_known_instance_code() {
1871
+ let (mt, st, vs, li, digest) = iscc_decode("ISCC:IAA26E2JXH27TING").unwrap();
1872
+ assert_eq!(mt, 4, "MainType::Instance");
1873
+ assert_eq!(st, 0, "SubType::None");
1874
+ assert_eq!(vs, 0, "Version::V0");
1875
+ assert_eq!(li, 1, "length_index for 64-bit");
1876
+ assert_eq!(digest.len(), 8, "64-bit = 8 bytes");
1877
+ }
1878
+
1879
+ /// Known value: Data-Code "ISCC:GAAXL2XYM5BQIAZ3".
1880
+ /// MainType=Data(3), SubType=None(0), Version=V0(0), 64-bit digest.
1881
+ #[test]
1882
+ fn test_iscc_decode_known_data_code() {
1883
+ let (mt, st, vs, _li, digest) = iscc_decode("ISCC:GAAXL2XYM5BQIAZ3").unwrap();
1884
+ assert_eq!(mt, 3, "MainType::Data");
1885
+ assert_eq!(st, 0, "SubType::None");
1886
+ assert_eq!(vs, 0, "Version::V0");
1887
+ assert_eq!(digest.len(), 8, "64-bit = 8 bytes");
1888
+ }
1889
+
1890
+ /// Verification criterion: round-trip with specific known values.
1891
+ /// encode_component(0, 0, 0, 64, &[0xaa;8]) → iscc_decode → (0, 0, 0, 1, vec![0xaa;8])
1892
+ #[test]
1893
+ fn test_iscc_decode_verification_round_trip() {
1894
+ let digest = [0xaa_u8; 8];
1895
+ let encoded = encode_component(0, 0, 0, 64, &digest).unwrap();
1896
+ let result = iscc_decode(&encoded).unwrap();
1897
+ assert_eq!(result, (0, 0, 0, 1, vec![0xaa; 8]));
1898
+ }
1899
+
1900
+ /// Error on truncated input where body is shorter than expected digest length.
1901
+ #[test]
1902
+ fn test_iscc_decode_truncated_input() {
1903
+ // Encode a valid 256-bit Meta-Code, then truncate the base32 string
1904
+ let digest = [0xff_u8; 32];
1905
+ let encoded = encode_component(0, 0, 0, 256, &digest).unwrap();
1906
+ // Truncate to just the header portion (first few chars)
1907
+ let truncated = &encoded[..6];
1908
+ let result = iscc_decode(truncated);
1909
+ assert!(result.is_err(), "should fail on truncated input");
1910
+ }
1911
+
1912
+ // --- json_to_data_url tests ---
1913
+
1914
+ /// Basic JSON object produces a data URL with application/json media type.
1915
+ #[test]
1916
+ fn test_json_to_data_url_basic() {
1917
+ let url = json_to_data_url(r#"{"key": "value"}"#).unwrap();
1918
+ assert!(
1919
+ url.starts_with("data:application/json;base64,"),
1920
+ "expected application/json prefix, got: {url}"
1921
+ );
1922
+ }
1923
+
1924
+ /// JSON with `@context` key uses application/ld+json media type.
1925
+ #[test]
1926
+ fn test_json_to_data_url_ld_json() {
1927
+ let url = json_to_data_url(r#"{"@context": "https://schema.org"}"#).unwrap();
1928
+ assert!(
1929
+ url.starts_with("data:application/ld+json;base64,"),
1930
+ "expected application/ld+json prefix, got: {url}"
1931
+ );
1932
+ }
1933
+
1934
+ /// JCS canonicalization reorders keys alphabetically.
1935
+ #[test]
1936
+ fn test_json_to_data_url_jcs_ordering() {
1937
+ let url = json_to_data_url(r#"{"b":1,"a":2}"#).unwrap();
1938
+ // Extract and decode the base64 payload
1939
+ let b64 = url.split_once(',').unwrap().1;
1940
+ let decoded = data_encoding::BASE64.decode(b64.as_bytes()).unwrap();
1941
+ let canonical = std::str::from_utf8(&decoded).unwrap();
1942
+ assert_eq!(canonical, r#"{"a":2,"b":1}"#, "JCS should sort keys");
1943
+ }
1944
+
1945
+ /// Round-trip: json_to_data_url output fed into decode_data_url recovers
1946
+ /// the JCS-canonical bytes.
1947
+ #[test]
1948
+ fn test_json_to_data_url_round_trip() {
1949
+ let input = r#"{"hello": "world", "num": 42}"#;
1950
+ let url = json_to_data_url(input).unwrap();
1951
+ let decoded_bytes = decode_data_url(&url).unwrap();
1952
+ // The decoded bytes should be JCS-canonical JSON
1953
+ let canonical: serde_json::Value =
1954
+ serde_json::from_slice(&decoded_bytes).expect("decoded bytes should be valid JSON");
1955
+ let original: serde_json::Value = serde_json::from_str(input).unwrap();
1956
+ assert_eq!(canonical, original, "round-trip preserves JSON semantics");
1957
+ }
1958
+
1959
+ /// Invalid JSON string returns an error.
1960
+ #[test]
1961
+ fn test_json_to_data_url_invalid_json() {
1962
+ let result = json_to_data_url("not json");
1963
+ assert!(result.is_err(), "should reject invalid JSON");
1964
+ let err = result.unwrap_err().to_string();
1965
+ assert!(
1966
+ err.contains("invalid JSON"),
1967
+ "expected 'invalid JSON' in error: {err}"
1968
+ );
1969
+ }
1970
+
1971
+ /// Compatibility with conformance vector test_0016_meta_data_url.
1972
+ ///
1973
+ /// The conformance vector's meta field is:
1974
+ /// data:application/json;charset=utf-8;base64,eyJzb21lIjogIm9iamVjdCJ9
1975
+ /// which encodes `{"some": "object"}` (with space after colon).
1976
+ ///
1977
+ /// Our function differs in two ways:
1978
+ /// 1. No `charset=utf-8` parameter (matching Python's DataURL.from_byte_data)
1979
+ /// 2. JCS canonicalization removes whitespace: `{"some":"object"}` (no space)
1980
+ ///
1981
+ /// We verify: (a) correct media type prefix, and (b) decoded payload equals
1982
+ /// JCS-canonical form of the same JSON input.
1983
+ #[test]
1984
+ fn test_json_to_data_url_conformance_0016() {
1985
+ let url = json_to_data_url(r#"{"some": "object"}"#).unwrap();
1986
+ // (a) Correct media type prefix (no charset, no @context → application/json)
1987
+ assert!(
1988
+ url.starts_with("data:application/json;base64,"),
1989
+ "expected application/json prefix"
1990
+ );
1991
+ // (b) Decoded payload is JCS-canonical (no whitespace)
1992
+ let b64 = url.split_once(',').unwrap().1;
1993
+ let decoded = data_encoding::BASE64.decode(b64.as_bytes()).unwrap();
1994
+ let canonical = std::str::from_utf8(&decoded).unwrap();
1995
+ assert_eq!(
1996
+ canonical, r#"{"some":"object"}"#,
1997
+ "JCS removes whitespace from JSON"
1998
+ );
1999
+ }
1564
2000
  }
@@ -391,6 +391,47 @@ fn iscc_decompose(iscc_code: &str) -> PyResult<Vec<String>> {
391
391
  iscc_lib::iscc_decompose(iscc_code).map_err(|e| PyValueError::new_err(e.to_string()))
392
392
  }
393
393
 
394
+ /// Encode raw digest components into a base32 ISCC unit string.
395
+ ///
396
+ /// Takes integer type identifiers and a raw digest, returns a base32-encoded
397
+ /// ISCC unit string (without "ISCC:" prefix).
398
+ #[pyfunction]
399
+ #[pyo3(signature = (mtype, stype, version, bit_length, digest))]
400
+ fn encode_component(
401
+ mtype: u8,
402
+ stype: u8,
403
+ version: u8,
404
+ bit_length: u32,
405
+ digest: &[u8],
406
+ ) -> PyResult<String> {
407
+ iscc_lib::encode_component(mtype, stype, version, bit_length, digest)
408
+ .map_err(|e| PyValueError::new_err(e.to_string()))
409
+ }
410
+
411
+ /// Decode an ISCC unit string into header components and raw digest.
412
+ ///
413
+ /// Returns a tuple of `(maintype, subtype, version, length_index, digest)`
414
+ /// where digest is the raw bytes truncated to the encoded bit-length.
415
+ #[pyfunction]
416
+ #[pyo3(signature = (iscc))]
417
+ fn iscc_decode(py: Python<'_>, iscc: &str) -> PyResult<PyObject> {
418
+ let (mt, st, vs, li, digest) =
419
+ iscc_lib::iscc_decode(iscc).map_err(|e| PyValueError::new_err(e.to_string()))?;
420
+ Ok((mt, st, vs, li, PyBytes::new(py, &digest))
421
+ .into_pyobject(py)?
422
+ .into())
423
+ }
424
+
425
+ /// Convert a JSON string into a `data:` URL with JCS canonicalization.
426
+ ///
427
+ /// Uses `application/ld+json` media type when the JSON contains an `@context`
428
+ /// key, otherwise `application/json`.
429
+ #[pyfunction]
430
+ #[pyo3(signature = (json))]
431
+ fn json_to_data_url(json: &str) -> PyResult<String> {
432
+ iscc_lib::json_to_data_url(json).map_err(|e| PyValueError::new_err(e.to_string()))
433
+ }
434
+
394
435
  /// Generate sliding window n-grams from a string.
395
436
  ///
396
437
  /// Returns overlapping substrings of `width` Unicode characters, advancing
@@ -560,6 +601,13 @@ fn iscc_lowlevel(m: &Bound<'_, PyModule>) -> PyResult<()> {
560
601
  m.add_function(wrap_pyfunction!(text_collapse, m)?)?;
561
602
  m.add_function(wrap_pyfunction!(encode_base64, m)?)?;
562
603
  m.add_function(wrap_pyfunction!(iscc_decompose, m)?)?;
604
+ m.add_function(wrap_pyfunction!(encode_component, m)?)?;
605
+ m.add_function(wrap_pyfunction!(iscc_decode, m)?)?;
606
+ m.add_function(wrap_pyfunction!(json_to_data_url, m)?)?;
607
+ m.add("META_TRIM_NAME", iscc_lib::META_TRIM_NAME)?;
608
+ m.add("META_TRIM_DESCRIPTION", iscc_lib::META_TRIM_DESCRIPTION)?;
609
+ m.add("IO_READ_SIZE", iscc_lib::IO_READ_SIZE)?;
610
+ m.add("TEXT_NGRAM_SIZE", iscc_lib::TEXT_NGRAM_SIZE)?;
563
611
  m.add_function(wrap_pyfunction!(sliding_window, m)?)?;
564
612
  m.add_function(wrap_pyfunction!(alg_simhash, m)?)?;
565
613
  m.add_function(wrap_pyfunction!(alg_minhash_256, m)?)?;
@@ -0,0 +1,7 @@
1
+ version = 1
2
+ revision = 3
3
+ requires-python = ">=3.10"
4
+
5
+ [[package]]
6
+ name = "iscc-lib"
7
+ source = { editable = "." }
@@ -2,13 +2,20 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import enum
6
+ import json as _json
5
7
  from collections.abc import Sequence
6
8
  from importlib.metadata import version
9
+ from types import SimpleNamespace
7
10
  from typing import BinaryIO
8
11
 
9
12
  __version__ = version("iscc-lib")
10
13
 
11
14
  from iscc_lib._lowlevel import (
15
+ IO_READ_SIZE as IO_READ_SIZE,
16
+ META_TRIM_DESCRIPTION as META_TRIM_DESCRIPTION,
17
+ META_TRIM_NAME as META_TRIM_NAME,
18
+ TEXT_NGRAM_SIZE as TEXT_NGRAM_SIZE,
12
19
  DataHasher as _DataHasher,
13
20
  InstanceHasher as _InstanceHasher,
14
21
  alg_cdc_chunks as alg_cdc_chunks,
@@ -16,6 +23,7 @@ from iscc_lib._lowlevel import (
16
23
  alg_simhash as alg_simhash,
17
24
  conformance_selftest as conformance_selftest,
18
25
  encode_base64 as encode_base64,
26
+ encode_component as encode_component,
19
27
  gen_audio_code_v0 as _gen_audio_code_v0,
20
28
  gen_data_code_v0 as _gen_data_code_v0,
21
29
  gen_image_code_v0 as _gen_image_code_v0,
@@ -25,7 +33,9 @@ from iscc_lib._lowlevel import (
25
33
  gen_mixed_code_v0 as _gen_mixed_code_v0,
26
34
  gen_text_code_v0 as _gen_text_code_v0,
27
35
  gen_video_code_v0 as _gen_video_code_v0,
36
+ iscc_decode as _iscc_decode,
28
37
  iscc_decompose as iscc_decompose,
38
+ json_to_data_url as json_to_data_url,
29
39
  sliding_window as sliding_window,
30
40
  soft_hash_video_v0 as soft_hash_video_v0,
31
41
  text_clean as text_clean,
@@ -34,6 +44,62 @@ from iscc_lib._lowlevel import (
34
44
  text_trim as text_trim,
35
45
  )
36
46
 
47
+
48
+ # ── Type Enums ──────────────────────────────────────────────────────────────
49
+
50
+
51
+ class MT(enum.IntEnum):
52
+ """ISCC MainType identifiers."""
53
+
54
+ META = 0
55
+ SEMANTIC = 1
56
+ CONTENT = 2
57
+ DATA = 3
58
+ INSTANCE = 4
59
+ ISCC = 5
60
+ ID = 6
61
+ FLAKE = 7
62
+
63
+
64
+ class ST(enum.IntEnum):
65
+ """ISCC SubType identifiers."""
66
+
67
+ NONE = 0
68
+ IMAGE = 1
69
+ AUDIO = 2
70
+ VIDEO = 3
71
+ MIXED = 4
72
+ SUM = 5
73
+ ISCC_NONE = 6
74
+ WIDE = 7
75
+ TEXT = 0 # Alias — IntEnum allows duplicate values as aliases
76
+
77
+
78
+ class VS(enum.IntEnum):
79
+ """ISCC Version identifiers."""
80
+
81
+ V0 = 0
82
+
83
+
84
+ # ── Algorithm configuration namespace ───────────────────────────────────────
85
+
86
+ core_opts = SimpleNamespace(
87
+ meta_trim_name=META_TRIM_NAME,
88
+ meta_trim_description=META_TRIM_DESCRIPTION,
89
+ io_read_size=IO_READ_SIZE,
90
+ text_ngram_size=TEXT_NGRAM_SIZE,
91
+ )
92
+
93
+
94
+ # ── Codec helpers ───────────────────────────────────────────────────────────
95
+
96
+
97
+ def iscc_decode(iscc: str) -> tuple[MT, ST, VS, int, bytes]:
98
+ """Decode an ISCC unit string into header components and raw digest."""
99
+ mt, st, vs, length, digest = _iscc_decode(iscc)
100
+ return MT(mt), ST(st), VS(vs), length, digest
101
+
102
+
37
103
  _CHUNK_SIZE = 65536 # 64 KiB read chunks
38
104
 
39
105
 
@@ -118,10 +184,14 @@ class IsccCodeResult(IsccResult):
118
184
  def gen_meta_code_v0(
119
185
  name: str,
120
186
  description: str | None = None,
121
- meta: str | None = None,
187
+ meta: str | dict | None = None,
122
188
  bits: int = 64,
123
189
  ) -> MetaCodeResult:
124
190
  """Generate an ISCC Meta-Code from content metadata."""
191
+ if isinstance(meta, dict):
192
+ meta = json_to_data_url(
193
+ _json.dumps(meta, separators=(",", ":"), ensure_ascii=False)
194
+ )
125
195
  return MetaCodeResult(_gen_meta_code_v0(name, description, meta, bits))
126
196
 
127
197
 
@@ -130,8 +200,12 @@ def gen_text_code_v0(text: str, bits: int = 64) -> TextCodeResult:
130
200
  return TextCodeResult(_gen_text_code_v0(text, bits))
131
201
 
132
202
 
133
- def gen_image_code_v0(pixels: bytes, bits: int = 64) -> ImageCodeResult:
203
+ def gen_image_code_v0(
204
+ pixels: bytes | bytearray | memoryview | Sequence[int], bits: int = 64
205
+ ) -> ImageCodeResult:
134
206
  """Generate an ISCC Image-Code from pixel data."""
207
+ if not isinstance(pixels, bytes):
208
+ pixels = bytes(pixels)
135
209
  return ImageCodeResult(_gen_image_code_v0(pixels, bits))
136
210
 
137
211
 
@@ -250,6 +324,13 @@ class InstanceHasher:
250
324
 
251
325
  __all__ = [
252
326
  "__version__",
327
+ "IO_READ_SIZE",
328
+ "META_TRIM_DESCRIPTION",
329
+ "META_TRIM_NAME",
330
+ "MT",
331
+ "ST",
332
+ "TEXT_NGRAM_SIZE",
333
+ "VS",
253
334
  "IsccResult",
254
335
  "AudioCodeResult",
255
336
  "DataCodeResult",
@@ -266,7 +347,9 @@ __all__ = [
266
347
  "alg_minhash_256",
267
348
  "alg_simhash",
268
349
  "conformance_selftest",
350
+ "core_opts",
269
351
  "encode_base64",
352
+ "encode_component",
270
353
  "gen_audio_code_v0",
271
354
  "gen_data_code_v0",
272
355
  "gen_image_code_v0",
@@ -276,7 +359,9 @@ __all__ = [
276
359
  "gen_mixed_code_v0",
277
360
  "gen_text_code_v0",
278
361
  "gen_video_code_v0",
362
+ "iscc_decode",
279
363
  "iscc_decompose",
364
+ "json_to_data_url",
280
365
  "sliding_window",
281
366
  "soft_hash_video_v0",
282
367
  "text_clean",
@@ -3,6 +3,64 @@
3
3
  from collections.abc import Sequence
4
4
  from typing import Any
5
5
 
6
+ META_TRIM_NAME: int
7
+ """Max UTF-8 byte length for name metadata trimming (128)."""
8
+
9
+ META_TRIM_DESCRIPTION: int
10
+ """Max UTF-8 byte length for description metadata trimming (4096)."""
11
+
12
+ IO_READ_SIZE: int
13
+ """Buffer size in bytes for streaming file reads (4,194,304 = 4 MB)."""
14
+
15
+ TEXT_NGRAM_SIZE: int
16
+ """Character n-gram width for text content features (13)."""
17
+
18
+ def encode_component(
19
+ mtype: int, stype: int, version: int, bit_length: int, digest: bytes
20
+ ) -> str:
21
+ """Encode raw digest components into a base32 ISCC unit string.
22
+
23
+ Takes integer type identifiers (matching ``MainType``, ``SubType``,
24
+ ``Version`` enum values) and a raw digest, returns a base32-encoded
25
+ ISCC unit string (without ``"ISCC:"`` prefix).
26
+
27
+ :param mtype: Main type identifier (0–6).
28
+ :param stype: Sub type identifier (0–7).
29
+ :param version: Version identifier (0).
30
+ :param bit_length: Bit length of the code body (multiple of 32).
31
+ :param digest: Raw digest bytes (at least ``bit_length // 8`` bytes).
32
+ :return: Base32-encoded ISCC unit string.
33
+ :raises ValueError: If enum values are out of range or digest is too short.
34
+ """
35
+ ...
36
+
37
+ def iscc_decode(iscc: str) -> tuple[int, int, int, int, bytes]:
38
+ """Decode an ISCC unit string into header components and raw digest.
39
+
40
+ Inverse of :func:`encode_component`. Strips an optional ``"ISCC:"``
41
+ prefix and dashes, base32-decodes the string, parses the header, and
42
+ returns the digest truncated to exactly the encoded bit-length.
43
+
44
+ :param iscc: ISCC unit string (with or without ``"ISCC:"`` prefix).
45
+ :return: Tuple of ``(maintype, subtype, version, length_index, digest)``.
46
+ :raises ValueError: If the input is not a valid ISCC string.
47
+ """
48
+ ...
49
+
50
+ def json_to_data_url(json: str) -> str:
51
+ """Convert a JSON string into a ``data:`` URL with JCS canonicalization.
52
+
53
+ Parses the JSON, re-serializes to RFC 8785 (JCS) canonical form,
54
+ base64-encodes the result, and wraps it in a ``data:`` URL. Uses
55
+ ``application/ld+json`` media type when the JSON contains an ``@context``
56
+ key, otherwise ``application/json``.
57
+
58
+ :param json: JSON string to convert.
59
+ :return: Data URL string.
60
+ :raises ValueError: If ``json`` is not valid JSON.
61
+ """
62
+ ...
63
+
6
64
  def conformance_selftest() -> bool:
7
65
  """Run all conformance tests against vendored test vectors.
8
66
 
File without changes
File without changes