iscc-lib 0.6.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/types.rs ADDED
@@ -0,0 +1,116 @@
1
+ //! Structured result types for ISCC code generation functions.
2
+ //!
3
+ //! Each `gen_*_v0` function returns a dedicated result struct carrying the ISCC
4
+ //! code string plus any additional fields (metahash, name, characters, etc.)
5
+ //! that match the `iscc-core` Python reference implementation's dict returns.
6
+
7
+ /// Result of [`gen_meta_code_v0`](crate::gen_meta_code_v0).
8
+ #[derive(Debug, Clone, PartialEq, Eq)]
9
+ #[non_exhaustive]
10
+ pub struct MetaCodeResult {
11
+ /// ISCC code string (e.g., `"ISCC:AAAZXZ6OU74YAZIM"`).
12
+ pub iscc: String,
13
+ /// Normalized name after cleaning, newline removal, and trimming.
14
+ pub name: String,
15
+ /// Normalized description (present only when description was non-empty).
16
+ pub description: Option<String>,
17
+ /// Metadata as a Data-URL string (present only when meta was provided).
18
+ pub meta: Option<String>,
19
+ /// Hex-encoded BLAKE3 multihash (`"1e20..."`) of the metadata payload.
20
+ pub metahash: String,
21
+ }
22
+
23
+ /// Result of [`gen_text_code_v0`](crate::gen_text_code_v0).
24
+ #[derive(Debug, Clone, PartialEq, Eq)]
25
+ #[non_exhaustive]
26
+ pub struct TextCodeResult {
27
+ /// ISCC code string.
28
+ pub iscc: String,
29
+ /// Character count after `text_collapse`.
30
+ pub characters: usize,
31
+ }
32
+
33
+ /// Result of [`gen_image_code_v0`](crate::gen_image_code_v0).
34
+ #[derive(Debug, Clone, PartialEq, Eq)]
35
+ #[non_exhaustive]
36
+ pub struct ImageCodeResult {
37
+ /// ISCC code string.
38
+ pub iscc: String,
39
+ }
40
+
41
+ /// Result of [`gen_audio_code_v0`](crate::gen_audio_code_v0).
42
+ #[derive(Debug, Clone, PartialEq, Eq)]
43
+ #[non_exhaustive]
44
+ pub struct AudioCodeResult {
45
+ /// ISCC code string.
46
+ pub iscc: String,
47
+ }
48
+
49
+ /// Result of [`gen_video_code_v0`](crate::gen_video_code_v0).
50
+ #[derive(Debug, Clone, PartialEq, Eq)]
51
+ #[non_exhaustive]
52
+ pub struct VideoCodeResult {
53
+ /// ISCC code string.
54
+ pub iscc: String,
55
+ }
56
+
57
+ /// Result of [`gen_mixed_code_v0`](crate::gen_mixed_code_v0).
58
+ #[derive(Debug, Clone, PartialEq, Eq)]
59
+ #[non_exhaustive]
60
+ pub struct MixedCodeResult {
61
+ /// ISCC code string.
62
+ pub iscc: String,
63
+ /// Input Content-Code strings (passed through unchanged).
64
+ pub parts: Vec<String>,
65
+ }
66
+
67
+ /// Result of [`gen_data_code_v0`](crate::gen_data_code_v0).
68
+ #[derive(Debug, Clone, PartialEq, Eq)]
69
+ #[non_exhaustive]
70
+ pub struct DataCodeResult {
71
+ /// ISCC code string.
72
+ pub iscc: String,
73
+ }
74
+
75
+ /// Result of [`gen_instance_code_v0`](crate::gen_instance_code_v0).
76
+ #[derive(Debug, Clone, PartialEq, Eq)]
77
+ #[non_exhaustive]
78
+ pub struct InstanceCodeResult {
79
+ /// ISCC code string.
80
+ pub iscc: String,
81
+ /// Hex-encoded BLAKE3 multihash (`"1e20..."`) of the input data.
82
+ pub datahash: String,
83
+ /// Byte length of the input data.
84
+ pub filesize: u64,
85
+ }
86
+
87
+ /// Result of [`gen_iscc_code_v0`](crate::gen_iscc_code_v0).
88
+ #[derive(Debug, Clone, PartialEq, Eq)]
89
+ #[non_exhaustive]
90
+ pub struct IsccCodeResult {
91
+ /// ISCC code string.
92
+ pub iscc: String,
93
+ }
94
+
95
+ /// Result of [`gen_iscc_id_v1`](crate::gen_iscc_id_v1).
96
+ #[derive(Debug, Clone, PartialEq, Eq)]
97
+ #[non_exhaustive]
98
+ pub struct IsccIdResult {
99
+ /// ISCC-IDv1 string (e.g., `"ISCC:MAIGHFECJMOPMIAB"`).
100
+ pub iscc: String,
101
+ }
102
+
103
+ /// Result of [`gen_sum_code_v0`](crate::gen_sum_code_v0).
104
+ #[derive(Debug, Clone, PartialEq, Eq)]
105
+ #[non_exhaustive]
106
+ pub struct SumCodeResult {
107
+ /// Composite ISCC-CODE string (e.g., `"ISCC:KUA..."`).
108
+ pub iscc: String,
109
+ /// Hex-encoded BLAKE3 multihash (`"1e20..."`) of the file.
110
+ pub datahash: String,
111
+ /// Byte length of the file.
112
+ pub filesize: u64,
113
+ /// Individual `[Data-Code, Instance-Code]` ISCC strings at the requested bit precision.
114
+ /// Present only when `add_units` is `true`.
115
+ pub units: Option<Vec<String>>,
116
+ }
data/core/src/utils.rs ADDED
@@ -0,0 +1,361 @@
1
+ //! Text normalization and hashing utilities for ISCC code generation.
2
+ //!
3
+ //! Provides text cleaning, trimming, collapsing, and BLAKE3 multihash functions
4
+ //! ported from `iscc-core` `code_meta.py` and `utils.py`.
5
+
6
+ use crate::codec::is_py_strip_char;
7
+ #[cfg(feature = "text-processing")]
8
+ use unicode_general_category::{GeneralCategory, get_general_category};
9
+ #[cfg(feature = "text-processing")]
10
+ use unicode_normalization::UnicodeNormalization;
11
+
12
+ /// Characters treated as newlines (preserved during control-char removal).
13
+ #[cfg(feature = "text-processing")]
14
+ const NEWLINES: &[char] = &[
15
+ '\u{000A}', // LINE FEED
16
+ '\u{000B}', // VERTICAL TAB
17
+ '\u{000C}', // FORM FEED
18
+ '\u{000D}', // CARRIAGE RETURN
19
+ '\u{0085}', // NEXT LINE
20
+ '\u{2028}', // LINE SEPARATOR
21
+ '\u{2029}', // PARAGRAPH SEPARATOR
22
+ ];
23
+
24
+ /// Check if a character belongs to a Unicode "C" (control/format/etc) category.
25
+ #[cfg(feature = "text-processing")]
26
+ fn is_c_category(c: char) -> bool {
27
+ matches!(
28
+ get_general_category(c),
29
+ GeneralCategory::Control
30
+ | GeneralCategory::Format
31
+ | GeneralCategory::Unassigned
32
+ | GeneralCategory::PrivateUse
33
+ | GeneralCategory::Surrogate
34
+ )
35
+ }
36
+
37
+ /// Check if a character belongs to Unicode "C", "M", or "P" categories.
38
+ #[cfg(feature = "text-processing")]
39
+ fn is_cmp_category(c: char) -> bool {
40
+ matches!(
41
+ get_general_category(c),
42
+ // C: Control categories
43
+ GeneralCategory::Control
44
+ | GeneralCategory::Format
45
+ | GeneralCategory::Unassigned
46
+ | GeneralCategory::PrivateUse
47
+ | GeneralCategory::Surrogate
48
+ // M: Mark categories
49
+ | GeneralCategory::NonspacingMark
50
+ | GeneralCategory::SpacingMark
51
+ | GeneralCategory::EnclosingMark
52
+ // P: Punctuation categories
53
+ | GeneralCategory::ConnectorPunctuation
54
+ | GeneralCategory::DashPunctuation
55
+ | GeneralCategory::OpenPunctuation
56
+ | GeneralCategory::ClosePunctuation
57
+ | GeneralCategory::InitialPunctuation
58
+ | GeneralCategory::FinalPunctuation
59
+ | GeneralCategory::OtherPunctuation
60
+ )
61
+ }
62
+
63
+ /// Clean and normalize text for display.
64
+ ///
65
+ /// Applies NFKC normalization, removes control characters (except newlines),
66
+ /// normalizes `\r\n` to `\n`, collapses consecutive empty lines to at most one,
67
+ /// and strips leading/trailing whitespace. Mirrors the reference `text_clean`
68
+ /// step for step; Unicode data comes from the tables the dependencies ship.
69
+ #[cfg(feature = "text-processing")]
70
+ pub fn text_clean(text: &str) -> String {
71
+ // 1. NFKC normalize
72
+ let text: String = text.nfkc().collect();
73
+
74
+ // 2. Remove control chars except newlines, normalizing all newlines to \n
75
+ let mut cleaned = String::with_capacity(text.len());
76
+ let mut chars = text.chars().peekable();
77
+ while let Some(c) = chars.next() {
78
+ if NEWLINES.contains(&c) {
79
+ // Handle \r\n as a single newline
80
+ if c == '\r' && chars.peek() == Some(&'\n') {
81
+ chars.next();
82
+ }
83
+ cleaned.push('\n');
84
+ } else if is_c_category(c) {
85
+ // Skip control characters
86
+ } else {
87
+ cleaned.push(c);
88
+ }
89
+ }
90
+
91
+ // 3. Split on \n, collapse consecutive empty/whitespace-only lines
92
+ let mut result_lines: Vec<&str> = Vec::new();
93
+ let mut prev_empty = false;
94
+ for line in cleaned.split('\n') {
95
+ let is_empty = line.trim().is_empty();
96
+ if is_empty {
97
+ if prev_empty {
98
+ continue;
99
+ }
100
+ prev_empty = true;
101
+ } else {
102
+ prev_empty = false;
103
+ }
104
+ result_lines.push(line);
105
+ }
106
+
107
+ // 4. Join with \n and strip leading/trailing whitespace
108
+ result_lines.join("\n").trim().to_string()
109
+ }
110
+
111
+ /// Remove newlines and collapse whitespace to single spaces.
112
+ ///
113
+ /// Converts multi-line text into a single normalized line by splitting on
114
+ /// Python `str.split()` whitespace (see `is_py_strip_char`) and joining with a single space.
115
+ pub fn text_remove_newlines(text: &str) -> String {
116
+ text.split(is_py_strip_char)
117
+ .filter(|s| !s.is_empty())
118
+ .collect::<Vec<_>>()
119
+ .join(" ")
120
+ }
121
+
122
+ /// Trim text so its UTF-8 encoded size does not exceed `nbytes`.
123
+ ///
124
+ /// Finds the largest valid UTF-8 prefix within `nbytes`, then strips
125
+ /// leading/trailing Python `str.strip()` whitespace from the result. Multi-byte characters
126
+ /// that would be split are dropped entirely.
127
+ pub fn text_trim(text: &str, nbytes: usize) -> String {
128
+ if text.len() <= nbytes {
129
+ return text.trim_matches(is_py_strip_char).to_string();
130
+ }
131
+ let bytes = &text.as_bytes()[..nbytes];
132
+ let s = match std::str::from_utf8(bytes) {
133
+ Ok(s) => s,
134
+ Err(e) => &text[..e.valid_up_to()],
135
+ };
136
+ s.trim_matches(is_py_strip_char).to_string()
137
+ }
138
+
139
+ /// Normalize and simplify text for similarity hashing.
140
+ ///
141
+ /// Applies NFD normalization, lowercasing, removes whitespace and characters in
142
+ /// Unicode categories C (control), M (mark), and P (punctuation), then
143
+ /// recombines with NFKC normalization. Mirrors the reference `text_collapse`
144
+ /// step for step; Unicode data comes from the tables the dependencies ship.
145
+ #[cfg(feature = "text-processing")]
146
+ pub fn text_collapse(text: &str) -> String {
147
+ // 1. NFD normalize, then lowercase
148
+ let nfd_lower = text.nfd().collect::<String>().to_lowercase();
149
+
150
+ // 2. Filter: keep chars that are NOT whitespace AND NOT in C/M/P categories
151
+ let filtered: String = nfd_lower
152
+ .chars()
153
+ .filter(|&c| !c.is_whitespace() && !is_cmp_category(c))
154
+ .collect();
155
+
156
+ // 3. NFKC normalize the filtered result
157
+ filtered.nfkc().collect()
158
+ }
159
+
160
+ /// Compute a BLAKE3 hash with multihash prefix.
161
+ ///
162
+ /// Returns a hex-encoded string with the BLAKE3 multicodec prefix (0x1e)
163
+ /// and digest length (0x20 = 32 bytes). Only Meta-Code hashes raw bytes here;
164
+ /// callers that already hold a digest use `blake3_multihash_hex`.
165
+ #[cfg(any(feature = "meta-code", test))]
166
+ pub(crate) fn multi_hash_blake3(data: &[u8]) -> String {
167
+ blake3_multihash_hex(&blake3::hash(data))
168
+ }
169
+
170
+ /// Format an existing BLAKE3 digest as a hex-encoded multihash.
171
+ ///
172
+ /// Prepends the BLAKE3 multicodec prefix (0x1e) and digest length
173
+ /// (0x20 = 32 bytes) to the digest and hex-encodes the result.
174
+ pub(crate) fn blake3_multihash_hex(digest: &blake3::Hash) -> String {
175
+ let mut result = Vec::with_capacity(34);
176
+ result.push(0x1e); // BLAKE3 multicodec
177
+ result.push(0x20); // 32 bytes length
178
+ result.extend_from_slice(digest.as_bytes());
179
+ hex::encode(result)
180
+ }
181
+
182
+ #[cfg(test)]
183
+ mod tests {
184
+ use super::*;
185
+
186
+ // ---- text_clean tests ----
187
+
188
+ #[cfg(feature = "text-processing")]
189
+ #[test]
190
+ fn test_text_clean_nfkc_normalization() {
191
+ // ℍ (U+210D) should normalize to H under NFKC
192
+ assert!(text_clean("ℍ").contains('H'));
193
+ }
194
+
195
+ #[cfg(feature = "text-processing")]
196
+ #[test]
197
+ fn test_text_clean_removes_control_chars() {
198
+ assert_eq!(text_clean("hello\tworld"), "helloworld");
199
+ }
200
+
201
+ #[cfg(feature = "text-processing")]
202
+ #[test]
203
+ fn test_text_clean_preserves_newlines() {
204
+ assert_eq!(text_clean("hello\nworld"), "hello\nworld");
205
+ }
206
+
207
+ #[cfg(feature = "text-processing")]
208
+ #[test]
209
+ fn test_text_clean_collapses_empty_lines() {
210
+ assert_eq!(text_clean("a\n\n\nb"), "a\n\nb");
211
+ }
212
+
213
+ #[cfg(feature = "text-processing")]
214
+ #[test]
215
+ fn test_text_clean_strips_whitespace() {
216
+ assert_eq!(text_clean(" hello "), "hello");
217
+ }
218
+
219
+ #[cfg(feature = "text-processing")]
220
+ #[test]
221
+ fn test_text_clean_handles_crlf() {
222
+ assert_eq!(text_clean("a\r\nb"), "a\nb");
223
+ }
224
+
225
+ #[cfg(feature = "text-processing")]
226
+ #[test]
227
+ fn test_text_clean_empty() {
228
+ assert_eq!(text_clean(""), "");
229
+ }
230
+
231
+ // ---- text_remove_newlines tests ----
232
+
233
+ #[test]
234
+ fn test_text_remove_newlines() {
235
+ assert_eq!(text_remove_newlines("hello\nworld"), "hello world");
236
+ }
237
+
238
+ #[test]
239
+ fn test_text_remove_newlines_collapses_spaces() {
240
+ assert_eq!(text_remove_newlines("a b c"), "a b c");
241
+ }
242
+
243
+ #[test]
244
+ fn test_text_remove_newlines_splits_on_info_separators() {
245
+ assert_eq!(text_remove_newlines("\x1eab\x1fcd\x1e"), "ab cd");
246
+ for sep in ['\x1c', '\x1d', '\x1e', '\x1f'] {
247
+ // leading, interior (single and run) and trailing positions
248
+ let text = format!("{sep}a{sep}b{sep}{sep}c{sep}");
249
+ assert_eq!(text_remove_newlines(&text), "a b c");
250
+ }
251
+ }
252
+
253
+ #[test]
254
+ fn test_text_remove_newlines_keeps_zero_width_space() {
255
+ assert_eq!(text_remove_newlines("a\u{200b}b"), "a\u{200b}b");
256
+ }
257
+
258
+ // ---- text_trim tests ----
259
+
260
+ #[test]
261
+ fn test_text_trim_no_truncation() {
262
+ assert_eq!(text_trim("hello", 10), "hello");
263
+ }
264
+
265
+ #[test]
266
+ fn test_text_trim_exact() {
267
+ assert_eq!(text_trim("hello", 5), "hello");
268
+ }
269
+
270
+ #[test]
271
+ fn test_text_trim_truncates() {
272
+ assert_eq!(text_trim("hello world", 5), "hello");
273
+ }
274
+
275
+ #[test]
276
+ fn test_text_trim_unicode_boundary() {
277
+ // "é" is 2 bytes in UTF-8 (C3 A9). Truncating at 1 byte should drop it.
278
+ assert_eq!(text_trim("é", 1), "");
279
+ }
280
+
281
+ #[test]
282
+ fn test_text_trim_strips() {
283
+ assert_eq!(text_trim("hello ", 6), "hello");
284
+ }
285
+
286
+ #[test]
287
+ fn test_text_trim_short_path_strips_info_separators() {
288
+ // nbytes >= len: only the outer U+001C..U+001F are stripped, the inner one stays
289
+ let text = "\x1eab\x1fcd\x1e";
290
+ assert_eq!(text_trim(text, 64), "ab\x1fcd");
291
+ assert_eq!(text_trim(text, text.len()), "ab\x1fcd");
292
+ for sep in ['\x1c', '\x1d', '\x1e', '\x1f'] {
293
+ assert_eq!(text_trim(&format!("{sep}ab{sep}"), 64), "ab");
294
+ }
295
+ }
296
+
297
+ #[test]
298
+ fn test_text_trim_truncation_strips_separator_at_cut_edge() {
299
+ // The cut lands right after the separators, so they become trailing
300
+ for sep in ['\x1c', '\x1d', '\x1e', '\x1f'] {
301
+ let text = format!("{sep}ab{sep}{sep}cd");
302
+ let nbytes = format!("{sep}ab{sep}{sep}").len();
303
+ assert_eq!(text_trim(&text, nbytes), "ab");
304
+ }
305
+ // Multi-byte strip member (U+3000, 3 bytes) at the cut edge, whole and split
306
+ let text = "ab\u{3000}cd";
307
+ assert_eq!(text_trim(text, "ab\u{3000}".len()), "ab");
308
+ assert_eq!(text_trim(text, "ab\u{3000}".len() - 1), "ab");
309
+ }
310
+
311
+ #[test]
312
+ fn test_text_trim_keeps_zero_width_space() {
313
+ // U+200B is not in Python's strip set and must survive trimming
314
+ assert_eq!(text_trim("\u{200b}ab\u{200b}", 64), "\u{200b}ab\u{200b}");
315
+ }
316
+
317
+ // ---- text_collapse tests ----
318
+
319
+ #[cfg(feature = "text-processing")]
320
+ #[test]
321
+ fn test_text_collapse_basic() {
322
+ assert_eq!(text_collapse("Hello World"), "helloworld");
323
+ }
324
+
325
+ #[cfg(feature = "text-processing")]
326
+ #[test]
327
+ fn test_text_collapse_strips_accents() {
328
+ // NFD decomposes accented chars, then M-category marks are filtered
329
+ assert_eq!(text_collapse("café"), "cafe");
330
+ }
331
+
332
+ #[cfg(feature = "text-processing")]
333
+ #[test]
334
+ fn test_text_collapse_strips_punctuation() {
335
+ assert_eq!(text_collapse("hello, world!"), "helloworld");
336
+ }
337
+
338
+ #[cfg(feature = "text-processing")]
339
+ #[test]
340
+ fn test_text_collapse_empty() {
341
+ assert_eq!(text_collapse(""), "");
342
+ }
343
+
344
+ // ---- multi_hash_blake3 tests ----
345
+
346
+ #[test]
347
+ fn test_multi_hash_blake3_empty() {
348
+ assert_eq!(
349
+ multi_hash_blake3(b""),
350
+ "1e20af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"
351
+ );
352
+ }
353
+
354
+ #[test]
355
+ fn test_multi_hash_blake3_hello_world() {
356
+ assert_eq!(
357
+ multi_hash_blake3(b"hello world"),
358
+ "1e20d74981efa70a0c880b8d8c1985d075dbcbf679b99a5f9914e5aaf96b831a9e24"
359
+ );
360
+ }
361
+ }