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.
@@ -0,0 +1,158 @@
1
+ //! Strict base32 decoding (decisions.md 2026-11-18, "Base32 decoding stays strict").
2
+ //!
3
+ //! The reference implementation accepts `=` padding and non-zero unused
4
+ //! trailing bits; iscc-lib deliberately rejects both so every ISCC has exactly
5
+ //! one string form. These tests pin that behaviour so a "match the reference"
6
+ //! change cannot relax it unnoticed. Each failure test feeds one bad input and
7
+ //! asserts the error comes from the base32 decoder, not an earlier check.
8
+
9
+ use iscc_lib::codec::decode_base32;
10
+ use iscc_lib::{encode_seq, iscc_decode};
11
+
12
+ /// Non-canonical ISCC strings: two spare-bit aliases and one padded form.
13
+ const REJECTS: [&str; 3] = [
14
+ "ISCC:GAAAAAAAAB",
15
+ "ISCC:KUAK3LB55M3HQ5QVHLT5QBPWPCNGJ",
16
+ "ISCC:GAAAAAAAAA======",
17
+ ];
18
+
19
+ /// Assert that `result` is an error whose message names the base32 decoder.
20
+ fn assert_base32_error<T: std::fmt::Debug>(input: &str, result: iscc_lib::IsccResult<T>) {
21
+ let err = result.expect_err(&format!("{input:?} must be rejected"));
22
+ let msg = err.to_string();
23
+ assert!(
24
+ msg.contains("base32 decode error"),
25
+ "{input:?}: expected a base32 decode error, got {msg:?}"
26
+ );
27
+ }
28
+
29
+ /// Every non-canonical ISCC string fails in the base32 decoder.
30
+ #[test]
31
+ fn test_iscc_decode_rejects_non_canonical_base32() {
32
+ for input in REJECTS {
33
+ assert_base32_error(input, iscc_decode(input));
34
+ }
35
+ }
36
+
37
+ /// Spare-bit aliases fail specifically on their non-zero trailing bits.
38
+ #[test]
39
+ fn test_iscc_decode_rejects_spare_bits_reason() {
40
+ let msg = iscc_decode("ISCC:GAAAAAAAAB").unwrap_err().to_string();
41
+ assert!(msg.contains("trailing bits"), "got {msg:?}");
42
+ let msg = iscc_decode("ISCC:KUAK3LB55M3HQ5QVHLT5QBPWPCNGJ")
43
+ .unwrap_err()
44
+ .to_string();
45
+ assert!(msg.contains("trailing bits"), "got {msg:?}");
46
+ }
47
+
48
+ /// `=` padding fails as an invalid symbol, not as a length or header error.
49
+ #[test]
50
+ fn test_iscc_decode_rejects_padding_reason() {
51
+ let msg = iscc_decode("ISCC:GAAAAAAAAA======")
52
+ .unwrap_err()
53
+ .to_string();
54
+ assert!(msg.contains("invalid symbol"), "got {msg:?}");
55
+ }
56
+
57
+ /// The bare decoder rejects spare bits, padding and an interior newline.
58
+ #[test]
59
+ fn test_decode_base32_rejects_non_canonical_bare() {
60
+ for input in ["GAAAAAAAAB", "GAAAAAAAAA======", "GAAA\nAAAAAA"] {
61
+ assert_base32_error(input, decode_base32(input));
62
+ }
63
+ }
64
+
65
+ /// The canonical form of the `GAAAAAAAAB` alias decodes.
66
+ #[test]
67
+ fn test_iscc_decode_accepts_canonical_data_code() {
68
+ let (mt, st, vs, li, digest) = iscc_decode("ISCC:GAAAAAAAAA").unwrap();
69
+ assert_eq!((mt, st, vs, li), (3, 0, 0, 0));
70
+ assert_eq!(digest, vec![0u8; 4]);
71
+ }
72
+
73
+ /// The canonical form of the `…CNGJ` alias decodes.
74
+ #[test]
75
+ fn test_iscc_decode_accepts_canonical_sum_code() {
76
+ let (mt, st, vs, li, digest) = iscc_decode("ISCC:KUAK3LB55M3HQ5QVHLT5QBPWPCNGI").unwrap();
77
+ assert_eq!((mt, st, vs, li), (5, 5, 0, 0));
78
+ assert_eq!(
79
+ digest,
80
+ vec![
81
+ 173, 172, 61, 235, 54, 120, 118, 21, 58, 231, 216, 5, 246, 120, 154, 100
82
+ ]
83
+ );
84
+ }
85
+
86
+ /// Canonical input decodes regardless of letter case.
87
+ #[test]
88
+ fn test_decode_base32_accepts_canonical_any_case() {
89
+ assert_eq!(
90
+ decode_base32("GAAAAAAAAA").unwrap(),
91
+ vec![0x30, 0, 0, 0, 0, 0]
92
+ );
93
+ assert_eq!(
94
+ decode_base32("gaaaaaaaaa").unwrap(),
95
+ vec![0x30, 0, 0, 0, 0, 0]
96
+ );
97
+ }
98
+
99
+ /// Non-ASCII case-fold aliases paired with their canonical ASCII twins.
100
+ ///
101
+ /// Unicode upper-casing maps `ı`→`I`, `ſ`→`S`, `ß`→`SS` and `fi`→`FI`; the
102
+ /// reference's ASCII-only base32 decoder rejects all four characters. Each
103
+ /// alias char sits after the two-character prefix so the prefix check passes.
104
+ const CASE_FOLD_ALIASES: [(&str, &str); 4] = [
105
+ (
106
+ "ISCC:KUAK3LB55M3HQ5QVHLT5QBPWPCNGı",
107
+ "ISCC:KUAK3LB55M3HQ5QVHLT5QBPWPCNGI",
108
+ ),
109
+ ("ISCC:GAAWDLQNG6ßDPF2", "ISCC:GAAWDLQNG6SSDPF2"),
110
+ ("ISCC:GAAT5fiNQWRC4HQV", "ISCC:GAAT5FINQWRC4HQV"),
111
+ ("ISCC:GAAWDLQNG6ſSDPF2", "ISCC:GAAWDLQNG6SSDPF2"),
112
+ ];
113
+
114
+ /// `iscc_decode` rejects each non-ASCII case-fold alias in the base32 decoder.
115
+ #[test]
116
+ fn test_iscc_decode_rejects_non_ascii_case_fold_aliases() {
117
+ for (alias, _) in CASE_FOLD_ALIASES {
118
+ assert_base32_error(alias, iscc_decode(alias));
119
+ }
120
+ }
121
+
122
+ /// The canonical ASCII twin of each case-fold alias decodes.
123
+ #[test]
124
+ fn test_iscc_decode_accepts_case_fold_twins() {
125
+ for (_, twin) in CASE_FOLD_ALIASES {
126
+ assert!(iscc_decode(twin).is_ok(), "{twin:?} must decode");
127
+ }
128
+ }
129
+
130
+ /// The bare decoder rejects the non-ASCII characters themselves.
131
+ #[test]
132
+ fn test_decode_base32_rejects_non_ascii_case_fold_bare() {
133
+ for input in ["GAAWDLQNG6ſSDPF2", "KUAK3LB55M3HQ5QVHLT5QBPWPCNGı"] {
134
+ assert_base32_error(input, decode_base32(input));
135
+ }
136
+ }
137
+
138
+ /// `encode_seq` rejects a lowercase unit carrying a `ſ` alias.
139
+ #[test]
140
+ fn test_encode_seq_rejects_long_s_alias() {
141
+ let input = "gaawdlqng6ſsdpf2";
142
+ assert_base32_error(input, encode_seq(&[input]));
143
+ }
144
+
145
+ /// `encode_seq` rejects a lowercase unit carrying a `ı` alias.
146
+ #[test]
147
+ fn test_encode_seq_rejects_dotless_i_alias() {
148
+ let input = "gaat5fınqwrc4hqv";
149
+ assert_base32_error(input, encode_seq(&[input]));
150
+ }
151
+
152
+ /// `encode_seq` accepts the lowercase ASCII twins of both aliased units.
153
+ #[test]
154
+ fn test_encode_seq_accepts_lowercase_ascii_twins() {
155
+ for input in ["gaawdlqng6ssdpf2", "gaat5finqwrc4hqv"] {
156
+ assert!(encode_seq(&[input]).is_ok(), "{input:?} must encode");
157
+ }
158
+ }
@@ -0,0 +1,157 @@
1
+ //! Integration tests for the public text utility API.
2
+ //!
3
+ //! Verifies that `text_clean`, `text_remove_newlines`, `text_trim`, and
4
+ //! `text_collapse` are accessible from the crate root and produce correct
5
+ //! results for a variety of inputs.
6
+
7
+ // ---- text_clean tests ----
8
+
9
+ #[cfg(feature = "text-processing")]
10
+ #[test]
11
+ fn test_text_clean_nfkc_normalization() {
12
+ // Fullwidth "A" (U+FF21) normalizes to ASCII "A" under NFKC
13
+ assert_eq!(iscc_lib::text_clean("A"), "A");
14
+ }
15
+
16
+ #[cfg(feature = "text-processing")]
17
+ #[test]
18
+ fn test_text_clean_removes_control_chars_keeps_newlines() {
19
+ // Tab (U+0009) is a control char and should be removed
20
+ assert_eq!(iscc_lib::text_clean("hello\tworld"), "helloworld");
21
+ // Newline should be preserved
22
+ assert_eq!(iscc_lib::text_clean("hello\nworld"), "hello\nworld");
23
+ }
24
+
25
+ #[cfg(feature = "text-processing")]
26
+ #[test]
27
+ fn test_text_clean_collapses_consecutive_empty_lines() {
28
+ // Three consecutive newlines → at most one empty line between content
29
+ assert_eq!(iscc_lib::text_clean("a\n\n\nb"), "a\n\nb");
30
+ // Four consecutive newlines → still one empty line
31
+ assert_eq!(iscc_lib::text_clean("a\n\n\n\nb"), "a\n\nb");
32
+ }
33
+
34
+ #[cfg(feature = "text-processing")]
35
+ #[test]
36
+ fn test_text_clean_crlf_normalization() {
37
+ assert_eq!(iscc_lib::text_clean("a\r\nb"), "a\nb");
38
+ }
39
+
40
+ #[cfg(feature = "text-processing")]
41
+ #[test]
42
+ fn test_text_clean_strips_whitespace() {
43
+ assert_eq!(iscc_lib::text_clean(" hello "), "hello");
44
+ }
45
+
46
+ #[cfg(feature = "text-processing")]
47
+ #[test]
48
+ fn test_text_clean_empty_input() {
49
+ assert_eq!(iscc_lib::text_clean(""), "");
50
+ }
51
+
52
+ // ---- text_remove_newlines tests ----
53
+
54
+ #[test]
55
+ fn test_text_remove_newlines_multiline() {
56
+ assert_eq!(
57
+ iscc_lib::text_remove_newlines("line one\nline two\nline three"),
58
+ "line one line two line three"
59
+ );
60
+ }
61
+
62
+ #[test]
63
+ fn test_text_remove_newlines_collapses_spaces() {
64
+ assert_eq!(iscc_lib::text_remove_newlines("a b c"), "a b c");
65
+ }
66
+
67
+ #[test]
68
+ fn test_text_remove_newlines_strips_edges() {
69
+ assert_eq!(iscc_lib::text_remove_newlines(" hello "), "hello");
70
+ }
71
+
72
+ #[test]
73
+ fn test_text_remove_newlines_empty_input() {
74
+ assert_eq!(iscc_lib::text_remove_newlines(""), "");
75
+ }
76
+
77
+ // ---- text_trim tests ----
78
+
79
+ #[test]
80
+ fn test_text_trim_shorter_than_limit() {
81
+ assert_eq!(iscc_lib::text_trim("hello", 100), "hello");
82
+ }
83
+
84
+ #[test]
85
+ fn test_text_trim_exact_length() {
86
+ assert_eq!(iscc_lib::text_trim("hello", 5), "hello");
87
+ }
88
+
89
+ #[test]
90
+ fn test_text_trim_truncation() {
91
+ assert_eq!(iscc_lib::text_trim("hello world", 5), "hello");
92
+ }
93
+
94
+ #[test]
95
+ fn test_text_trim_utf8_boundary() {
96
+ // "é" is 2 bytes in UTF-8 (C3 A9); truncating at 1 byte drops it
97
+ assert_eq!(iscc_lib::text_trim("é", 1), "");
98
+ // "café" — 'c','a','f' are 1 byte each, 'é' is 2 bytes = 5 bytes total
99
+ // Trimming to 4 bytes drops the incomplete 'é'
100
+ assert_eq!(iscc_lib::text_trim("café", 4), "caf");
101
+ }
102
+
103
+ #[test]
104
+ fn test_text_trim_strips_whitespace() {
105
+ assert_eq!(iscc_lib::text_trim("hello ", 6), "hello");
106
+ }
107
+
108
+ // ---- text_collapse tests ----
109
+
110
+ #[cfg(feature = "text-processing")]
111
+ #[test]
112
+ fn test_text_collapse_lowercasing() {
113
+ assert_eq!(iscc_lib::text_collapse("HELLO"), "hello");
114
+ }
115
+
116
+ #[cfg(feature = "text-processing")]
117
+ #[test]
118
+ fn test_text_collapse_whitespace_removal() {
119
+ assert_eq!(iscc_lib::text_collapse("a b c"), "abc");
120
+ }
121
+
122
+ #[cfg(feature = "text-processing")]
123
+ #[test]
124
+ fn test_text_collapse_punctuation_removal() {
125
+ assert_eq!(iscc_lib::text_collapse("hello, world!"), "helloworld");
126
+ }
127
+
128
+ #[cfg(feature = "text-processing")]
129
+ #[test]
130
+ fn test_text_collapse_diacritics_removal() {
131
+ // NFD decomposes accented chars, then M-category marks are filtered
132
+ assert_eq!(iscc_lib::text_collapse("café"), "cafe");
133
+ assert_eq!(iscc_lib::text_collapse("naïve"), "naive");
134
+ }
135
+
136
+ #[cfg(feature = "text-processing")]
137
+ #[test]
138
+ fn test_text_collapse_empty_input() {
139
+ assert_eq!(iscc_lib::text_collapse(""), "");
140
+ }
141
+
142
+ // ---- Public API access via crate root ----
143
+
144
+ #[test]
145
+ fn test_crate_root_imports() {
146
+ // Verify ungated functions are callable via iscc_lib::<fn>
147
+ let _ = iscc_lib::text_remove_newlines("test");
148
+ let _ = iscc_lib::text_trim("test", 10);
149
+ }
150
+
151
+ #[cfg(feature = "text-processing")]
152
+ #[test]
153
+ fn test_crate_root_imports_text_processing() {
154
+ // Verify text-processing-gated functions are callable via iscc_lib::<fn>
155
+ let _ = iscc_lib::text_clean("test");
156
+ let _ = iscc_lib::text_collapse("test");
157
+ }
@@ -2,5 +2,5 @@
2
2
 
3
3
  # Version constant for the iscc-lib gem (synced from root Cargo.toml).
4
4
  module IsccLib
5
- VERSION = "0.7.0"
5
+ VERSION = "0.8.0"
6
6
  end
data/src/lib.rs CHANGED
@@ -4,12 +4,13 @@
4
4
  //! under the `IsccLib` module. The pure Ruby wrapper in `lib/iscc_lib.rb`
5
5
  //! provides idiomatic result classes and keyword arguments.
6
6
  //!
7
- //! Symbols (33 of 33):
7
+ //! Symbols (35 of 35):
8
8
  //! - `gen_meta_code_v0`, `gen_text_code_v0`, `gen_image_code_v0`, `gen_audio_code_v0`
9
9
  //! - `gen_video_code_v0`, `gen_mixed_code_v0`, `gen_data_code_v0`
10
10
  //! - `gen_instance_code_v0`, `gen_iscc_code_v0`, `gen_sum_code_v0`, `gen_iscc_id_v1`
11
11
  //! - `text_clean`, `text_remove_newlines`, `text_trim`, `text_collapse`
12
12
  //! - `encode_base64`, `iscc_decompose`, `encode_component`, `iscc_decode`
13
+ //! - `encode_seq`, `decode_seq`
13
14
  //! - `json_to_data_url`, `conformance_selftest`
14
15
  //! - `sliding_window`, `alg_simhash`, `alg_minhash_256`, `alg_cdc_chunks`,
15
16
  //! `soft_hash_video_v0`
@@ -18,7 +19,8 @@
18
19
  //! IO_READ_SIZE, TEXT_NGRAM_SIZE
19
20
 
20
21
  use magnus::{
21
- Error, Integer, RArray, RHash, RString, Ruby, TryConvert, function, method, prelude::*,
22
+ Error, Integer, RArray, RHash, RString, Ruby, TryConvert, Value, function, method, prelude::*,
23
+ try_convert::TryConvertOwned,
22
24
  };
23
25
  use std::cell::RefCell;
24
26
 
@@ -28,6 +30,60 @@ fn to_magnus_err(e: iscc_lib::IsccError) -> Error {
28
30
  Error::new(ruby.exception_runtime_error(), e.to_string())
29
31
  }
30
32
 
33
+ /// Convert a Ruby Array into a `Vec<T>` via `RArray::into_iter`.
34
+ ///
35
+ /// `into_iter` walks a hidden copy of the array (frozen arrays are walked in
36
+ /// place, as they cannot change), so an element conversion (`to_str`/`to_int`)
37
+ /// that mutates the caller's array cannot invalidate the walk. Magnus' own
38
+ /// `Vec<T>` conversion walks a borrowed slice and segfaults in that case.
39
+ /// The `TryConvertOwned` bound keeps Ruby handles (which the GC cannot see
40
+ /// inside a Rust `Vec`) out of the result. Element errors are Magnus' own:
41
+ /// `TypeError` for an element with no implicit conversion to `T`, `RangeError`
42
+ /// for an integer outside `T`. Integer elements convert through `to_int`, so a
43
+ /// Float (or any object with `to_int`) is accepted and truncated toward zero.
44
+ /// Never use it with `T = i32`: Magnus' `i32` conversion truncates negative
45
+ /// Bignums on 64-bit Ruby, so `i32` elements go through [`array_to_i32_vec`].
46
+ fn array_to_vec<T: TryConvertOwned>(ary: RArray) -> Result<Vec<T>, Error> {
47
+ ary.into_iter().map(TryConvert::try_convert).collect()
48
+ }
49
+
50
+ /// Convert a Ruby Array of integers into a `Vec<i32>`.
51
+ ///
52
+ /// Converts each element to `i64` through [`array_to_vec`] (Magnus truncates
53
+ /// a Float or other `to_int` object toward zero, raises `TypeError` for an
54
+ /// element without `to_int` and `RangeError` outside `i64`), then narrows
55
+ /// it with `i32::try_from`, raising `RangeError` for anything outside `i32`.
56
+ /// Magnus' own `RBignum::to_i32` checks only the upper bound, so a negative
57
+ /// Bignum between `-(2**63)` and `-(2**62) - 1` would be silently truncated.
58
+ fn array_to_i32_vec(ary: RArray) -> Result<Vec<i32>, Error> {
59
+ array_to_vec::<i64>(ary)?
60
+ .into_iter()
61
+ .map(narrow_to_i32)
62
+ .collect()
63
+ }
64
+
65
+ /// Narrow an `i64` to `i32`, raising `RangeError` when it does not fit.
66
+ fn narrow_to_i32(value: i64) -> Result<i32, Error> {
67
+ i32::try_from(value).map_err(|_| {
68
+ let ruby = Ruby::get().expect("called from Ruby");
69
+ Error::new(
70
+ ruby.exception_range_error(),
71
+ format!("integer {value} out of range for `i32`"),
72
+ )
73
+ })
74
+ }
75
+
76
+ /// Convert a Ruby Array of Arrays of integers into frame signatures.
77
+ ///
78
+ /// Each frame is coerced with `RArray::try_convert` (raises `TypeError` for a
79
+ /// non-Array) and converted through [`array_to_i32_vec`].
80
+ fn frames_to_vec(frame_sigs: RArray) -> Result<Vec<Vec<i32>>, Error> {
81
+ frame_sigs
82
+ .into_iter()
83
+ .map(|frame| array_to_i32_vec(RArray::try_convert(frame)?))
84
+ .collect()
85
+ }
86
+
31
87
  /// Generate a Meta-Code from name and optional metadata.
32
88
  ///
33
89
  /// Returns a Ruby Hash with keys: `iscc`, `name`, `metahash`, and optionally
@@ -85,7 +141,8 @@ fn gen_image_code_v0(pixels: RString, bits: u32) -> Result<RHash, Error> {
85
141
  ///
86
142
  /// Accepts a Ruby Array of integers (i32 Chromaprint fingerprints).
87
143
  /// Returns a Ruby Hash with key: `iscc`.
88
- fn gen_audio_code_v0(cv: Vec<i32>, bits: u32) -> Result<RHash, Error> {
144
+ fn gen_audio_code_v0(cv: RArray, bits: u32) -> Result<RHash, Error> {
145
+ let cv = array_to_i32_vec(cv)?;
89
146
  let r = iscc_lib::gen_audio_code_v0(&cv, bits).map_err(to_magnus_err)?;
90
147
  let ruby = Ruby::get().expect("called from Ruby");
91
148
  let hash = ruby.hash_new();
@@ -98,13 +155,7 @@ fn gen_audio_code_v0(cv: Vec<i32>, bits: u32) -> Result<RHash, Error> {
98
155
  /// Accepts a Ruby Array of Arrays of integers (nested `i32` frame signatures).
99
156
  /// Returns a Ruby Hash with key: `iscc`.
100
157
  fn gen_video_code_v0(frame_sigs: RArray, bits: u32) -> Result<RHash, Error> {
101
- let frames: Vec<Vec<i32>> = frame_sigs
102
- .into_iter()
103
- .map(|frame| {
104
- let arr: Vec<i32> = TryConvert::try_convert(frame)?;
105
- Ok(arr)
106
- })
107
- .collect::<Result<Vec<_>, Error>>()?;
158
+ let frames = frames_to_vec(frame_sigs)?;
108
159
  let r = iscc_lib::gen_video_code_v0(&frames, bits).map_err(to_magnus_err)?;
109
160
  let ruby = Ruby::get().expect("called from Ruby");
110
161
  let hash = ruby.hash_new();
@@ -116,7 +167,8 @@ fn gen_video_code_v0(frame_sigs: RArray, bits: u32) -> Result<RHash, Error> {
116
167
  ///
117
168
  /// Accepts a Ruby Array of ISCC unit strings.
118
169
  /// Returns a Ruby Hash with keys: `iscc`, `parts`.
119
- fn gen_mixed_code_v0(codes: Vec<String>, bits: u32) -> Result<RHash, Error> {
170
+ fn gen_mixed_code_v0(codes: RArray, bits: u32) -> Result<RHash, Error> {
171
+ let codes: Vec<String> = array_to_vec(codes)?;
120
172
  let refs: Vec<&str> = codes.iter().map(|s| s.as_str()).collect();
121
173
  let r = iscc_lib::gen_mixed_code_v0(&refs, bits).map_err(to_magnus_err)?;
122
174
  let ruby = Ruby::get().expect("called from Ruby");
@@ -162,7 +214,8 @@ fn gen_instance_code_v0(data: RString, bits: u32) -> Result<RHash, Error> {
162
214
  ///
163
215
  /// Accepts a Ruby Array of ISCC unit strings and a wide flag.
164
216
  /// Returns a Ruby Hash with key: `iscc`.
165
- fn gen_iscc_code_v0(codes: Vec<String>, wide: bool) -> Result<RHash, Error> {
217
+ fn gen_iscc_code_v0(codes: RArray, wide: bool) -> Result<RHash, Error> {
218
+ let codes: Vec<String> = array_to_vec(codes)?;
166
219
  let refs: Vec<&str> = codes.iter().map(|s| s.as_str()).collect();
167
220
  let r = iscc_lib::gen_iscc_code_v0(&refs, wide).map_err(to_magnus_err)?;
168
221
  let ruby = Ruby::get().expect("called from Ruby");
@@ -321,6 +374,29 @@ fn iscc_decode(iscc: String) -> Result<RArray, Error> {
321
374
  Ok(arr)
322
375
  }
323
376
 
377
+ /// Encode an ordered list of ISCC-UNIT strings as a binary ISCC-SEQ (IEP-0020).
378
+ ///
379
+ /// Accepts a Ruby Array of ISCC-UNIT strings and returns a binary
380
+ /// (ASCII-8BIT) Ruby String. Raises `RuntimeError` on invalid input.
381
+ fn encode_seq(units: RArray) -> Result<RString, Error> {
382
+ let units: Vec<String> = array_to_vec(units)?;
383
+ let refs: Vec<&str> = units.iter().map(|s| s.as_str()).collect();
384
+ let bytes = iscc_lib::encode_seq(&refs).map_err(to_magnus_err)?;
385
+ let ruby = Ruby::get().expect("called from Ruby");
386
+ Ok(ruby.str_from_slice(&bytes))
387
+ }
388
+
389
+ /// Decode a binary ISCC-SEQ (IEP-0020) into its ISCC-UNIT strings.
390
+ ///
391
+ /// Returns a Ruby Array of `ISCC:`-prefixed unit strings in sequence order.
392
+ /// Raises `RuntimeError` on empty, truncated, or malformed data.
393
+ fn decode_seq(data: RString) -> Result<Vec<String>, Error> {
394
+ // Safety: we copy the bytes immediately and do not hold the slice
395
+ // across any Ruby API calls.
396
+ let bytes = unsafe { data.as_slice() }.to_vec();
397
+ iscc_lib::decode_seq(&bytes).map_err(to_magnus_err)
398
+ }
399
+
324
400
  /// Convert a JSON string into a `data:` URL with JCS canonicalization.
325
401
  ///
326
402
  /// Uses `application/ld+json` media type when the JSON contains an `@context`
@@ -365,11 +441,12 @@ fn alg_simhash(hash_digests: RArray) -> Result<RString, Error> {
365
441
 
366
442
  /// Compute a 256-bit MinHash digest from 32-bit integer features.
367
443
  ///
368
- /// Returns a 32-byte binary String.
369
- fn alg_minhash_256(features: Vec<u32>) -> RString {
370
- let result = iscc_lib::alg_minhash_256(&features);
444
+ /// Returns a 32-byte binary String. Raises on an empty Array.
445
+ fn alg_minhash_256(features: RArray) -> Result<RString, Error> {
446
+ let features: Vec<u32> = array_to_vec(features)?;
447
+ let result = iscc_lib::alg_minhash_256(&features).map_err(to_magnus_err)?;
371
448
  let ruby = Ruby::get().expect("called from Ruby");
372
- ruby.str_from_slice(&result)
449
+ Ok(ruby.str_from_slice(&result))
373
450
  }
374
451
 
375
452
  /// Split data into content-defined chunks using gear rolling hash.
@@ -394,13 +471,7 @@ fn alg_cdc_chunks(data: RString, utf32: bool, avg_chunk_size: u32) -> Result<RAr
394
471
  /// Accepts a Ruby Array of Arrays of integers (nested `i32` frame signatures)
395
472
  /// and a bit length. Returns a binary String of length `bits / 8`.
396
473
  fn soft_hash_video_v0(frame_sigs: RArray, bits: u32) -> Result<RString, Error> {
397
- let frames: Vec<Vec<i32>> = frame_sigs
398
- .into_iter()
399
- .map(|frame| {
400
- let arr: Vec<i32> = TryConvert::try_convert(frame)?;
401
- Ok(arr)
402
- })
403
- .collect::<Result<Vec<_>, Error>>()?;
474
+ let frames = frames_to_vec(frame_sigs)?;
404
475
  let result = iscc_lib::soft_hash_video_v0(&frames, bits).map_err(to_magnus_err)?;
405
476
  let ruby = Ruby::get().expect("called from Ruby");
406
477
  Ok(ruby.str_from_slice(&result))
@@ -446,7 +517,11 @@ impl RbDataHasher {
446
517
  ///
447
518
  /// Returns an `RHash` with key `"iscc"`. Raises `RuntimeError` if
448
519
  /// called more than once.
449
- fn finalize(&self, bits: u32) -> Result<RHash, Error> {
520
+ ///
521
+ /// `bits` is converted (Ruby's implicit `to_int`) only after the inner
522
+ /// hasher is taken, so the first call consumes the hasher even when it
523
+ /// raises on its argument.
524
+ fn finalize(&self, bits: Value) -> Result<RHash, Error> {
450
525
  let ruby = Ruby::get().expect("called from Ruby");
451
526
  let hasher = self.inner.borrow_mut().take().ok_or_else(|| {
452
527
  Error::new(
@@ -454,6 +529,7 @@ impl RbDataHasher {
454
529
  "DataHasher already finalized",
455
530
  )
456
531
  })?;
532
+ let bits = u32::try_convert(bits)?;
457
533
  let r = hasher.finalize(bits).map_err(to_magnus_err)?;
458
534
  let hash = ruby.hash_new();
459
535
  hash.aset("iscc", r.iscc)?;
@@ -501,7 +577,11 @@ impl RbInstanceHasher {
501
577
  ///
502
578
  /// Returns an `RHash` with keys `"iscc"`, `"datahash"`, `"filesize"`.
503
579
  /// Raises `RuntimeError` if called more than once.
504
- fn finalize(&self, bits: u32) -> Result<RHash, Error> {
580
+ ///
581
+ /// `bits` is converted (Ruby's implicit `to_int`) only after the inner
582
+ /// hasher is taken, so the first call consumes the hasher even when it
583
+ /// raises on its argument.
584
+ fn finalize(&self, bits: Value) -> Result<RHash, Error> {
505
585
  let ruby = Ruby::get().expect("called from Ruby");
506
586
  let hasher = self.inner.borrow_mut().take().ok_or_else(|| {
507
587
  Error::new(
@@ -509,6 +589,7 @@ impl RbInstanceHasher {
509
589
  "InstanceHasher already finalized",
510
590
  )
511
591
  })?;
592
+ let bits = u32::try_convert(bits)?;
512
593
  let r = hasher.finalize(bits).map_err(to_magnus_err)?;
513
594
  let hash = ruby.hash_new();
514
595
  hash.aset("iscc", r.iscc)?;
@@ -547,6 +628,8 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
547
628
  module.define_module_function("iscc_decompose", function!(iscc_decompose, 1))?;
548
629
  module.define_module_function("encode_component", function!(encode_component, 5))?;
549
630
  module.define_module_function("iscc_decode", function!(iscc_decode, 1))?;
631
+ module.define_module_function("encode_seq", function!(encode_seq, 1))?;
632
+ module.define_module_function("decode_seq", function!(decode_seq, 1))?;
550
633
  module.define_module_function("json_to_data_url", function!(json_to_data_url, 1))?;
551
634
  module.define_module_function("conformance_selftest", function!(conformance_selftest, 0))?;
552
635
 
metadata CHANGED
@@ -1,15 +1,29 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: iscc-lib
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.7.0
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Titusz Pan
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-17 00:00:00.000000000 Z
12
- dependencies: []
11
+ date: 2026-11-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rb_sys
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.9'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.9'
13
27
  description: High-performance Ruby bindings for ISO 24138:2024 (ISCC). Native Rust
14
28
  extension via Magnus for content identification and matching.
15
29
  email:
@@ -19,9 +33,34 @@ extensions:
19
33
  - extconf.rb
20
34
  extra_rdoc_files: []
21
35
  files:
36
+ - Cargo.lock
22
37
  - Cargo.toml
23
38
  - LICENSE
24
39
  - README.md
40
+ - core/CLAUDE.md
41
+ - core/Cargo.lock
42
+ - core/Cargo.toml
43
+ - core/README.md
44
+ - core/benches/benchmarks.rs
45
+ - core/benches/iai_benches.rs
46
+ - core/src/cdc.rs
47
+ - core/src/codec.rs
48
+ - core/src/conformance.rs
49
+ - core/src/dct.rs
50
+ - core/src/lib.rs
51
+ - core/src/minhash.rs
52
+ - core/src/simhash.rs
53
+ - core/src/streaming.rs
54
+ - core/src/types.rs
55
+ - core/src/utils.rs
56
+ - core/src/wtahash.rs
57
+ - core/src/xxh32.rs
58
+ - core/tests/codec_clean.rs
59
+ - core/tests/data.json
60
+ - core/tests/test_algorithm_primitives.rs
61
+ - core/tests/test_seq.rs
62
+ - core/tests/test_strict_base32.rs
63
+ - core/tests/test_text_utils.rs
25
64
  - extconf.rb
26
65
  - lib/iscc_lib.rb
27
66
  - lib/iscc_lib/version.rb
@@ -42,7 +81,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
42
81
  requirements:
43
82
  - - ">="
44
83
  - !ruby/object:Gem::Version
45
- version: 3.1.0
84
+ version: 3.3.0
46
85
  required_rubygems_version: !ruby/object:Gem::Requirement
47
86
  requirements:
48
87
  - - ">="