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.
@@ -0,0 +1,754 @@
1
+ //! Conformance selftest for ISO 24138:2024 (ISCC).
2
+ //!
3
+ //! Runs gen functions and the ISCC-SEQ codec (`encode_seq` / `decode_seq`)
4
+ //! against vendored conformance vectors from `data.json` and reports
5
+ //! pass/fail. Code types whose feature flags are disabled are skipped (not
6
+ //! failed). With all features enabled, all 9 gen functions are tested; the
7
+ //! ISCC-SEQ sections run under every feature set. An application claiming ISCC
8
+ //! conformance MUST pass all tests in this suite.
9
+
10
+ #[cfg(feature = "meta-code")]
11
+ use crate::gen_meta_code_v0;
12
+ #[cfg(feature = "text-processing")]
13
+ use crate::gen_text_code_v0;
14
+ use crate::{
15
+ IsccResult, decode_seq, encode_seq, gen_audio_code_v0, gen_data_code_v0, gen_image_code_v0,
16
+ gen_instance_code_v0, gen_iscc_code_v0, gen_mixed_code_v0, gen_video_code_v0,
17
+ };
18
+ use serde_json::{Map, Value};
19
+ use std::fmt::Debug;
20
+
21
+ /// Embedded conformance test vectors (compile-time).
22
+ const TEST_DATA: &str = include_str!("../tests/data.json");
23
+
24
+ /// Outcome of one parsed conformance case: `Err` holds the failure description.
25
+ type Verdict = Result<(), String>;
26
+
27
+ /// Parse one case, call the function under test and judge its result.
28
+ ///
29
+ /// `None` means the case's inputs or expected outputs could not be parsed.
30
+ type CaseCheck = fn(&Value) -> Option<Verdict>;
31
+
32
+ /// Every `data.json` section, each with the check that runs one of its cases.
33
+ ///
34
+ /// This table is the only list of sections: `conformance_selftest` runs every
35
+ /// row, and a test compares the row names with the `data.json` keys. Rows whose
36
+ /// feature flag is disabled are left out, so their sections are skipped.
37
+ const SECTIONS: &[(&str, CaseCheck)] = &[
38
+ #[cfg(feature = "meta-code")]
39
+ ("gen_meta_code_v0", meta_case),
40
+ #[cfg(feature = "text-processing")]
41
+ ("gen_text_code_v0", text_case),
42
+ ("gen_image_code_v0", image_case),
43
+ ("gen_audio_code_v0", audio_case),
44
+ ("gen_video_code_v0", video_case),
45
+ ("gen_mixed_code_v0", mixed_case),
46
+ ("gen_data_code_v0", data_case),
47
+ ("gen_instance_code_v0", instance_case),
48
+ ("gen_iscc_code_v0", iscc_case),
49
+ ("encode_seq", encode_seq_case),
50
+ ("decode_seq", decode_seq_case),
51
+ ];
52
+
53
+ /// Run conformance tests against vendored test vectors.
54
+ ///
55
+ /// Tests each `gen_*_v0` section (comparing the result's `.iscc` field) and the
56
+ /// `encode_seq` / `decode_seq` sections (comparing bytes / unit lists) against
57
+ /// the expected outputs. Code types whose feature flags are disabled are
58
+ /// skipped. Returns `true` if all enabled tests pass, `false` if any
59
+ /// mismatch or error occurs. Does not panic — logs failures via `eprintln!`
60
+ /// and continues through all test cases.
61
+ pub fn conformance_selftest() -> bool {
62
+ let data = match test_data() {
63
+ Ok(v) => v,
64
+ Err(e) => {
65
+ eprintln!("FAILED: could not parse conformance data: {e}");
66
+ return false;
67
+ }
68
+ };
69
+ if let Err(e) = check_sections(&data) {
70
+ eprintln!("FAILED: {e}");
71
+ return false;
72
+ }
73
+
74
+ let mut passed = true;
75
+ for &(name, check) in SECTIONS {
76
+ passed &= run_section(&data, name, check);
77
+ }
78
+ passed
79
+ }
80
+
81
+ /// Parse the embedded conformance vectors.
82
+ pub(crate) fn test_data() -> serde_json::Result<Value> {
83
+ serde_json::from_str(TEST_DATA)
84
+ }
85
+
86
+ /// Check that every top-level key except `_metadata` maps to an object of case objects.
87
+ ///
88
+ /// Returns a message naming the first key that does not.
89
+ fn check_sections(data: &Value) -> Result<(), String> {
90
+ let sections = data
91
+ .as_object()
92
+ .ok_or("conformance data is not an object")?;
93
+ let bad = sections.iter().find(|(key, section)| {
94
+ *key != "_metadata"
95
+ && !section
96
+ .as_object()
97
+ .is_some_and(|cases| cases.values().all(Value::is_object))
98
+ });
99
+ match bad {
100
+ Some((key, _)) => Err(format!("section {key} is not an object of cases")),
101
+ None => Ok(()),
102
+ }
103
+ }
104
+
105
+ /// Return the cases of one `data.json` section, keyed by case name.
106
+ pub(crate) fn cases<'a>(data: &'a Value, section: &str) -> Option<&'a Map<String, Value>> {
107
+ data[section].as_object()
108
+ }
109
+
110
+ /// Run every case of one `data.json` section and report each failure.
111
+ ///
112
+ /// Returns `false` if the section is missing or any case fails.
113
+ fn run_section(data: &Value, func_name: &str, check: CaseCheck) -> bool {
114
+ let Some(section) = cases(data, func_name) else {
115
+ eprintln!("FAILED: {func_name} section missing from conformance data");
116
+ return false;
117
+ };
118
+
119
+ let mut passed = true;
120
+ for (tc_name, tc) in section {
121
+ passed &= report_case(func_name, tc_name, check(tc));
122
+ }
123
+ passed
124
+ }
125
+
126
+ /// Report the outcome of one conformance case; returns whether it passed.
127
+ fn report_case(func_name: &str, tc_name: &str, verdict: Option<Verdict>) -> bool {
128
+ match verdict {
129
+ None => {
130
+ eprintln!("FAILED: {func_name}.{tc_name} — could not parse test inputs");
131
+ false
132
+ }
133
+ Some(Ok(())) => true,
134
+ Some(Err(reason)) => {
135
+ eprintln!("FAILED: {func_name}.{tc_name} — {reason}");
136
+ false
137
+ }
138
+ }
139
+ }
140
+
141
+ /// Judge a function result against the expected output.
142
+ fn judge<T: PartialEq + Debug>(result: IsccResult<T>, expected: T) -> Verdict {
143
+ match result {
144
+ Ok(actual) if actual == expected => Ok(()),
145
+ Ok(actual) => Err(format!("expected {expected:?}, got {actual:?}")),
146
+ Err(e) => Err(format!("error: {e}")),
147
+ }
148
+ }
149
+
150
+ /// Read the expected `.iscc` output of a `gen_*_v0` case.
151
+ pub(crate) fn expected_iscc(tc: &Value) -> Option<String> {
152
+ tc["outputs"]["iscc"].as_str().map(String::from)
153
+ }
154
+
155
+ /// Return the positional `inputs` list of a case.
156
+ fn inputs(tc: &Value) -> Option<&[Value]> {
157
+ tc["inputs"].as_array().map(Vec::as_slice)
158
+ }
159
+
160
+ /// Read the `bits` argument at position `index` of an inputs list.
161
+ ///
162
+ /// Returns `None` unless the value is an integer in `u32` range.
163
+ fn bits_at(inputs: &[Value], index: usize) -> Option<u32> {
164
+ u32::try_from(inputs.get(index)?.as_u64()?).ok()
165
+ }
166
+
167
+ /// Read a JSON array of integers as `i32` values.
168
+ ///
169
+ /// Returns `None` if any entry is not an integer in `i32` range.
170
+ fn i32_entries(value: &Value) -> Option<Vec<i32>> {
171
+ value
172
+ .as_array()?
173
+ .iter()
174
+ .map(|v| i32::try_from(v.as_i64()?).ok())
175
+ .collect()
176
+ }
177
+
178
+ /// Read a JSON array of strings; `None` if it is not an array or any entry is not a string.
179
+ fn string_entries(value: &Value) -> Option<Vec<&str>> {
180
+ value.as_array()?.iter().map(Value::as_str).collect()
181
+ }
182
+
183
+ /// Decode a `"stream:<hex>"` value into bytes.
184
+ fn decode_stream(s: &str) -> Option<Vec<u8>> {
185
+ let hex_data = s.strip_prefix("stream:")?;
186
+ hex::decode(hex_data).ok()
187
+ }
188
+
189
+ /// Parsed inputs of a `gen_meta_code_v0` case.
190
+ #[cfg(feature = "meta-code")]
191
+ pub(crate) struct MetaInputs<'a> {
192
+ /// The `name` argument.
193
+ pub(crate) name: &'a str,
194
+ /// The `description` argument (`None` for an empty string).
195
+ pub(crate) description: Option<&'a str>,
196
+ /// The `meta` argument: a data URL as given, or a JSON object serialized.
197
+ pub(crate) meta: Option<String>,
198
+ /// The `bits` argument.
199
+ pub(crate) bits: u32,
200
+ }
201
+
202
+ /// Convert a vector's `meta` value into the `meta` argument.
203
+ ///
204
+ /// `null` is no meta (`Some(None)`), a string is a data URL as given and an
205
+ /// object is serialized. Any other JSON type is rejected (`None`).
206
+ #[cfg(feature = "meta-code")]
207
+ fn meta_arg(value: &Value) -> Option<Option<String>> {
208
+ match value {
209
+ Value::Null => Some(None),
210
+ Value::String(s) => Some(Some(s.clone())),
211
+ Value::Object(_) => serde_json::to_string(value).ok().map(Some),
212
+ _ => None,
213
+ }
214
+ }
215
+
216
+ /// Parse the inputs `[name, description, meta, bits]` of a `gen_meta_code_v0` case.
217
+ #[cfg(feature = "meta-code")]
218
+ pub(crate) fn meta_inputs(tc: &Value) -> Option<MetaInputs<'_>> {
219
+ let inputs = inputs(tc)?;
220
+ let name = inputs.first()?.as_str()?;
221
+ let description = inputs.get(1)?.as_str()?;
222
+ let meta = meta_arg(inputs.get(2)?)?;
223
+ let bits = bits_at(inputs, 3)?;
224
+ Some(MetaInputs {
225
+ name,
226
+ description: (!description.is_empty()).then_some(description),
227
+ meta,
228
+ bits,
229
+ })
230
+ }
231
+
232
+ /// Parse the inputs `[text, bits]` of a `gen_text_code_v0` case.
233
+ #[cfg(feature = "text-processing")]
234
+ pub(crate) fn text_inputs(tc: &Value) -> Option<(&str, u32)> {
235
+ let inputs = inputs(tc)?;
236
+ Some((inputs.first()?.as_str()?, bits_at(inputs, 1)?))
237
+ }
238
+
239
+ /// Parse the inputs `[pixels, bits]` of a `gen_image_code_v0` case.
240
+ pub(crate) fn image_inputs(tc: &Value) -> Option<(Vec<u8>, u32)> {
241
+ let inputs = inputs(tc)?;
242
+ let pixels = inputs
243
+ .first()?
244
+ .as_array()?
245
+ .iter()
246
+ .map(|v| u8::try_from(v.as_u64()?).ok())
247
+ .collect::<Option<Vec<u8>>>()?;
248
+ Some((pixels, bits_at(inputs, 1)?))
249
+ }
250
+
251
+ /// Parse the inputs `[cv, bits]` of a `gen_audio_code_v0` case.
252
+ fn audio_inputs(tc: &Value) -> Option<(Vec<i32>, u32)> {
253
+ let inputs = inputs(tc)?;
254
+ Some((i32_entries(inputs.first()?)?, bits_at(inputs, 1)?))
255
+ }
256
+
257
+ /// Parse the inputs `[frame_sigs, bits]` of a `gen_video_code_v0` case.
258
+ fn video_inputs(tc: &Value) -> Option<(Vec<Vec<i32>>, u32)> {
259
+ let inputs = inputs(tc)?;
260
+ let frame_sigs = inputs
261
+ .first()?
262
+ .as_array()?
263
+ .iter()
264
+ .map(i32_entries)
265
+ .collect::<Option<_>>()?;
266
+ Some((frame_sigs, bits_at(inputs, 1)?))
267
+ }
268
+
269
+ /// Parse the inputs `[codes, bits]` of a `gen_mixed_code_v0` case.
270
+ pub(crate) fn mixed_inputs(tc: &Value) -> Option<(Vec<&str>, u32)> {
271
+ let inputs = inputs(tc)?;
272
+ Some((string_entries(inputs.first()?)?, bits_at(inputs, 1)?))
273
+ }
274
+
275
+ /// Parse the inputs `["stream:<hex>", bits]` of a Data-Code or Instance-Code case.
276
+ pub(crate) fn stream_inputs(tc: &Value) -> Option<(Vec<u8>, u32)> {
277
+ let inputs = inputs(tc)?;
278
+ let bytes = decode_stream(inputs.first()?.as_str()?)?;
279
+ Some((bytes, bits_at(inputs, 1)?))
280
+ }
281
+
282
+ /// Parse the inputs `[codes]` of a `gen_iscc_code_v0` case.
283
+ pub(crate) fn iscc_inputs(tc: &Value) -> Option<Vec<&str>> {
284
+ string_entries(inputs(tc)?.first()?)
285
+ }
286
+
287
+ /// Check one `gen_meta_code_v0` case.
288
+ #[cfg(feature = "meta-code")]
289
+ fn meta_case(tc: &Value) -> Option<Verdict> {
290
+ let m = meta_inputs(tc)?;
291
+ let expected = expected_iscc(tc)?;
292
+ let result = gen_meta_code_v0(m.name, m.description, m.meta.as_deref(), m.bits);
293
+ Some(judge(result.map(|r| r.iscc), expected))
294
+ }
295
+
296
+ /// Check one `gen_text_code_v0` case.
297
+ #[cfg(feature = "text-processing")]
298
+ fn text_case(tc: &Value) -> Option<Verdict> {
299
+ let (text, bits) = text_inputs(tc)?;
300
+ let expected = expected_iscc(tc)?;
301
+ Some(judge(
302
+ gen_text_code_v0(text, bits).map(|r| r.iscc),
303
+ expected,
304
+ ))
305
+ }
306
+
307
+ /// Check one `gen_image_code_v0` case.
308
+ fn image_case(tc: &Value) -> Option<Verdict> {
309
+ let (pixels, bits) = image_inputs(tc)?;
310
+ let expected = expected_iscc(tc)?;
311
+ Some(judge(
312
+ gen_image_code_v0(&pixels, bits).map(|r| r.iscc),
313
+ expected,
314
+ ))
315
+ }
316
+
317
+ /// Check one `gen_audio_code_v0` case.
318
+ fn audio_case(tc: &Value) -> Option<Verdict> {
319
+ let (cv, bits) = audio_inputs(tc)?;
320
+ let expected = expected_iscc(tc)?;
321
+ Some(judge(
322
+ gen_audio_code_v0(&cv, bits).map(|r| r.iscc),
323
+ expected,
324
+ ))
325
+ }
326
+
327
+ /// Check one `gen_video_code_v0` case.
328
+ fn video_case(tc: &Value) -> Option<Verdict> {
329
+ let (frame_sigs, bits) = video_inputs(tc)?;
330
+ let expected = expected_iscc(tc)?;
331
+ let result = gen_video_code_v0(&frame_sigs, bits);
332
+ Some(judge(result.map(|r| r.iscc), expected))
333
+ }
334
+
335
+ /// Check one `gen_mixed_code_v0` case.
336
+ fn mixed_case(tc: &Value) -> Option<Verdict> {
337
+ let (codes, bits) = mixed_inputs(tc)?;
338
+ let expected = expected_iscc(tc)?;
339
+ Some(judge(
340
+ gen_mixed_code_v0(&codes, bits).map(|r| r.iscc),
341
+ expected,
342
+ ))
343
+ }
344
+
345
+ /// Check one `gen_data_code_v0` case.
346
+ fn data_case(tc: &Value) -> Option<Verdict> {
347
+ let (bytes, bits) = stream_inputs(tc)?;
348
+ let expected = expected_iscc(tc)?;
349
+ Some(judge(
350
+ gen_data_code_v0(&bytes, bits).map(|r| r.iscc),
351
+ expected,
352
+ ))
353
+ }
354
+
355
+ /// Check one `gen_instance_code_v0` case.
356
+ fn instance_case(tc: &Value) -> Option<Verdict> {
357
+ let (bytes, bits) = stream_inputs(tc)?;
358
+ let expected = expected_iscc(tc)?;
359
+ Some(judge(
360
+ gen_instance_code_v0(&bytes, bits).map(|r| r.iscc),
361
+ expected,
362
+ ))
363
+ }
364
+
365
+ /// Check one `gen_iscc_code_v0` case.
366
+ fn iscc_case(tc: &Value) -> Option<Verdict> {
367
+ let codes = iscc_inputs(tc)?;
368
+ let expected = expected_iscc(tc)?;
369
+ // Conformance vectors use default (non-wide) mode
370
+ Some(judge(
371
+ gen_iscc_code_v0(&codes, false).map(|r| r.iscc),
372
+ expected,
373
+ ))
374
+ }
375
+
376
+ /// Decode a `"bytes:<hex>"` value into bytes.
377
+ fn decode_bytes(s: &str) -> Option<Vec<u8>> {
378
+ let hex_data = s.strip_prefix("bytes:")?;
379
+ hex::decode(hex_data).ok()
380
+ }
381
+
382
+ /// Check one `encode_seq` case (inputs `[[str…]]`, output `"bytes:<hex>"`).
383
+ ///
384
+ /// Both sides are compared as lower-case hex so a mismatch reads as hex.
385
+ fn encode_seq_case(tc: &Value) -> Option<Verdict> {
386
+ let units = string_entries(tc["inputs"].as_array()?.first()?)?;
387
+ let expected = hex::encode(decode_bytes(tc["outputs"].as_str()?)?);
388
+ Some(judge(encode_seq(&units).map(hex::encode), expected))
389
+ }
390
+
391
+ /// Check one `decode_seq` case (inputs `["bytes:<hex>"]`, output `[str…]`).
392
+ fn decode_seq_case(tc: &Value) -> Option<Verdict> {
393
+ let seq = decode_bytes(tc["inputs"].as_array()?.first()?.as_str()?)?;
394
+ let expected: Vec<String> = tc["outputs"]
395
+ .as_array()?
396
+ .iter()
397
+ .map(|v| v.as_str().map(String::from))
398
+ .collect::<Option<_>>()?;
399
+ Some(judge(decode_seq(&seq), expected))
400
+ }
401
+
402
+ #[cfg(test)]
403
+ mod tests {
404
+ use super::*;
405
+
406
+ /// Look up the case check of `section` in [`SECTIONS`]; panics if it has no row.
407
+ fn check_of(section: &str) -> CaseCheck {
408
+ SECTIONS
409
+ .iter()
410
+ .find(|(name, _)| *name == section)
411
+ .map(|&(_, check)| check)
412
+ .unwrap_or_else(|| panic!("no runner for {section}"))
413
+ }
414
+
415
+ /// Run the `section` cases of `data` through that section's table row.
416
+ fn run(data: &Value, section: &str) -> bool {
417
+ run_section(data, section, check_of(section))
418
+ }
419
+
420
+ #[test]
421
+ fn test_conformance_selftest_passes() {
422
+ assert!(conformance_selftest());
423
+ }
424
+
425
+ #[cfg(feature = "meta-code")]
426
+ #[test]
427
+ fn test_sections_match_data_json() {
428
+ // The table must name every data.json section exactly once, and nothing else.
429
+ use std::collections::BTreeSet;
430
+ let data = test_data().unwrap();
431
+ let keys: BTreeSet<&str> = data
432
+ .as_object()
433
+ .unwrap()
434
+ .keys()
435
+ .map(String::as_str)
436
+ .filter(|key| *key != "_metadata")
437
+ .collect();
438
+ let names: BTreeSet<&str> = SECTIONS.iter().map(|&(name, _)| name).collect();
439
+ assert_eq!(names.len(), SECTIONS.len(), "a section has two table rows");
440
+ assert!(!keys.is_empty(), "data.json has no sections");
441
+ assert_eq!(names, keys, "table rows differ from data.json sections");
442
+ }
443
+
444
+ #[test]
445
+ fn test_sections_have_cases() {
446
+ // An empty section passes the selftest, so every table row needs at least one case.
447
+ let data = test_data().unwrap();
448
+ for &(name, _) in SECTIONS {
449
+ let count = cases(&data, name).map_or(0, Map::len);
450
+ assert!(count > 0, "section {name} has no cases");
451
+ }
452
+ }
453
+
454
+ #[test]
455
+ fn test_seq_section_counts() {
456
+ let data = test_data().unwrap();
457
+ assert_eq!(data["encode_seq"].as_object().unwrap().len(), 4);
458
+ assert_eq!(data["decode_seq"].as_object().unwrap().len(), 4);
459
+ }
460
+
461
+ #[test]
462
+ fn test_seq_sections_missing_fail() {
463
+ let empty = serde_json::json!({});
464
+ assert!(!run(&empty, "encode_seq"));
465
+ assert!(!run(&empty, "decode_seq"));
466
+ }
467
+
468
+ #[test]
469
+ fn test_seq_mismatch_and_parse_failures_fail() {
470
+ // One case per section, so each failure arm (mismatch, error, parse) is proven alone.
471
+ let encode_cases = [
472
+ serde_json::json!({"inputs": [["ISCC:GAAAAAAAAA"]], "outputs": "bytes:00"}),
473
+ serde_json::json!({"inputs": [[""]], "outputs": "bytes:00"}),
474
+ serde_json::json!({"inputs": [[1]], "outputs": "bytes:00"}),
475
+ ];
476
+ for tc in encode_cases {
477
+ let data = serde_json::json!({"encode_seq": {"case": tc}});
478
+ assert!(!run(&data, "encode_seq"), "{data}");
479
+ }
480
+ let decode_cases = [
481
+ serde_json::json!({"inputs": ["bytes:300000000000"], "outputs": ["ISCC:X"]}),
482
+ serde_json::json!({"inputs": ["bytes:"], "outputs": []}),
483
+ serde_json::json!({"inputs": ["300000000000"], "outputs": []}),
484
+ ];
485
+ for tc in decode_cases {
486
+ let data = serde_json::json!({"decode_seq": {"case": tc}});
487
+ assert!(!run(&data, "decode_seq"), "{data}");
488
+ }
489
+ }
490
+
491
+ #[test]
492
+ fn test_gen_section_missing_fails() {
493
+ let empty = serde_json::json!({});
494
+ assert!(!run(&empty, "gen_data_code_v0"));
495
+ assert!(!run(&empty, "gen_iscc_code_v0"));
496
+ }
497
+
498
+ #[test]
499
+ fn test_gen_section_positive_case() {
500
+ // Guards the failure-arm test: the same shape with a correct output passes.
501
+ let iscc = gen_data_code_v0(&[], 64).unwrap().iscc;
502
+ let tc = serde_json::json!({"inputs": ["stream:", 64], "outputs": {"iscc": iscc}});
503
+ assert!(run(
504
+ &serde_json::json!({"gen_data_code_v0": {"case": tc}}),
505
+ "gen_data_code_v0"
506
+ ));
507
+ }
508
+
509
+ #[test]
510
+ fn test_gen_section_failure_arms_fail() {
511
+ // One case per call, so each failure arm (mismatch, error, parse) is proven alone.
512
+ assert!(
513
+ gen_data_code_v0(&[], 7).is_err(),
514
+ "bits 7 must reach the error arm"
515
+ );
516
+ let cases = [
517
+ serde_json::json!({"inputs": ["stream:", 64], "outputs": {"iscc": "ISCC:X"}}),
518
+ serde_json::json!({"inputs": ["stream:", 7], "outputs": {"iscc": "ISCC:X"}}),
519
+ serde_json::json!({"inputs": ["00ff", 64], "outputs": {"iscc": "ISCC:X"}}),
520
+ serde_json::json!({"inputs": ["stream:", 64], "outputs": {}}),
521
+ serde_json::json!({"inputs": [], "outputs": {"iscc": "ISCC:X"}}),
522
+ serde_json::json!({"inputs": ["stream:"], "outputs": {"iscc": "ISCC:X"}}),
523
+ ];
524
+ for tc in cases {
525
+ let data = serde_json::json!({"gen_data_code_v0": {"case": tc}});
526
+ assert!(!run(&data, "gen_data_code_v0"), "{data}");
527
+ }
528
+ }
529
+
530
+ #[test]
531
+ fn test_gen_section_short_inputs_fail() {
532
+ // A short inputs list is a parse failure, never a panic.
533
+ #[cfg(feature = "meta-code")]
534
+ {
535
+ let tc =
536
+ serde_json::json!({"inputs": ["Name", "", null], "outputs": {"iscc": "ISCC:X"}});
537
+ assert!(meta_inputs(&tc).is_none());
538
+ assert!(!run(
539
+ &serde_json::json!({"gen_meta_code_v0": {"case": tc}}),
540
+ "gen_meta_code_v0"
541
+ ));
542
+ }
543
+ let tc = serde_json::json!({"inputs": [], "outputs": {"iscc": "ISCC:X"}});
544
+ assert!(iscc_inputs(&tc).is_none());
545
+ assert!(!run(
546
+ &serde_json::json!({"gen_iscc_code_v0": {"case": tc}}),
547
+ "gen_iscc_code_v0"
548
+ ));
549
+ }
550
+
551
+ /// Parse and run one synthetic case of `section`; return `(parsed, passed)`.
552
+ fn probe(section: &str, inputs: Value, iscc: &str) -> (bool, bool) {
553
+ let tc = serde_json::json!({"inputs": inputs, "outputs": {"iscc": iscc}});
554
+ let data = serde_json::json!({section: {"case": tc.clone()}});
555
+ let check = check_of(section);
556
+ (check(&tc).is_some(), run_section(&data, section, check))
557
+ }
558
+
559
+ /// Return 1024 pixel values, all zero except the first, which is `first`.
560
+ fn pixels_with(first: Value) -> Value {
561
+ let mut pixels = vec![Value::from(0); 1024];
562
+ pixels[0] = first;
563
+ Value::from(pixels)
564
+ }
565
+
566
+ /// Return one 380-entry frame signature, all zero except the first, which is `first`.
567
+ fn frame_with(first: Value) -> Value {
568
+ let mut frame = vec![Value::from(0); 380];
569
+ frame[0] = first;
570
+ Value::from(frame)
571
+ }
572
+
573
+ /// One synthetic case: `(section, inputs, expected iscc)`.
574
+ type Row = (&'static str, Value, String);
575
+
576
+ /// Assert that every `bad` row fails the parse arm alone and every `good` row passes.
577
+ ///
578
+ /// Each bad row's output is what the coerced, truncated or skipped reading
579
+ /// would produce, so only the parse arm can fail it.
580
+ fn assert_rows(bad: Vec<Row>, good: Vec<Row>) {
581
+ for (section, inputs, iscc) in bad {
582
+ let shown: String = inputs.to_string().chars().take(60).collect();
583
+ assert_eq!(
584
+ probe(section, inputs, &iscc),
585
+ (false, false),
586
+ "{section} {shown}"
587
+ );
588
+ }
589
+ for (section, inputs, iscc) in good {
590
+ let shown: String = inputs.to_string().chars().take(60).collect();
591
+ assert_eq!(
592
+ probe(section, inputs, &iscc),
593
+ (true, true),
594
+ "{section} {shown}"
595
+ );
596
+ }
597
+ }
598
+
599
+ #[test]
600
+ fn test_wrong_type_vector_values_are_unparsable() {
601
+ // One bad case per call: every row must fail the parse arm alone.
602
+ use serde_json::json;
603
+ let data64 = gen_data_code_v0(&[], 64).unwrap().iscc;
604
+ let image = gen_image_code_v0(&[0; 1024], 64).unwrap().iscc;
605
+ let audio = gen_audio_code_v0(&[i32::MIN], 64).unwrap().iscc;
606
+ let mut frame = vec![0; 380];
607
+ frame[0] = i32::MIN;
608
+ let video = gen_video_code_v0(&[frame], 64).unwrap().iscc;
609
+ let audio_ok = gen_audio_code_v0(&[1, 2, 3], 64).unwrap().iscc;
610
+ let mixed = gen_mixed_code_v0(&[&image, &audio_ok], 64).unwrap().iscc;
611
+ let instance = gen_instance_code_v0(&[], 64).unwrap().iscc;
612
+ let iscc = gen_iscc_code_v0(&[&data64, &instance], false).unwrap().iscc;
613
+ let wrapped = json!(2147483648_i64);
614
+ let bad = vec![
615
+ ("gen_data_code_v0", json!(["stream:", 64.0]), data64.clone()),
616
+ ("gen_data_code_v0", json!(["stream:", 64.5]), data64.clone()),
617
+ ("gen_data_code_v0", json!(["stream:", -1]), data64.clone()),
618
+ (
619
+ "gen_data_code_v0",
620
+ json!(["stream:", 4294967296_u64]),
621
+ data64.clone(),
622
+ ),
623
+ (
624
+ "gen_mixed_code_v0",
625
+ json!([[&image, &audio_ok, 1], 64]),
626
+ mixed.clone(),
627
+ ),
628
+ (
629
+ "gen_mixed_code_v0",
630
+ json!([[&image, &audio_ok, null], 64]),
631
+ mixed.clone(),
632
+ ),
633
+ (
634
+ "gen_iscc_code_v0",
635
+ json!([[&data64, &instance, 1]]),
636
+ iscc.clone(),
637
+ ),
638
+ (
639
+ "gen_image_code_v0",
640
+ json!([pixels_with(json!(0.5)), 64]),
641
+ image.clone(),
642
+ ),
643
+ (
644
+ "gen_image_code_v0",
645
+ json!([pixels_with(json!(-256)), 64]),
646
+ image.clone(),
647
+ ),
648
+ (
649
+ "gen_image_code_v0",
650
+ json!([pixels_with(json!(256)), 64]),
651
+ image.clone(),
652
+ ),
653
+ ("gen_audio_code_v0", json!([[wrapped.clone()], 64]), audio),
654
+ (
655
+ "gen_video_code_v0",
656
+ json!([[frame_with(wrapped)], 64]),
657
+ video,
658
+ ),
659
+ ];
660
+ let good = vec![
661
+ ("gen_data_code_v0", json!(["stream:", 64]), data64.clone()),
662
+ ("gen_mixed_code_v0", json!([[&image, &audio_ok], 64]), mixed),
663
+ ("gen_iscc_code_v0", json!([[&data64, &instance]]), iscc),
664
+ (
665
+ "gen_image_code_v0",
666
+ json!([pixels_with(json!(0)), 64]),
667
+ image,
668
+ ),
669
+ ("gen_audio_code_v0", json!([[1, 2, 3], 64]), audio_ok),
670
+ ];
671
+ assert_rows(bad, good);
672
+ }
673
+
674
+ #[cfg(feature = "meta-code")]
675
+ #[test]
676
+ fn test_wrong_type_meta_values_are_unparsable() {
677
+ // A null name or description and a number or array meta fail the parse arm.
678
+ use serde_json::json;
679
+ let meta = gen_meta_code_v0("Name", None, None, 64).unwrap().iscc;
680
+ let with_meta = gen_meta_code_v0("Name", None, Some(r#"{"a":1}"#), 64);
681
+ let bad = vec![
682
+ (
683
+ "gen_meta_code_v0",
684
+ json!(["Name", null, null, 64]),
685
+ meta.clone(),
686
+ ),
687
+ (
688
+ "gen_meta_code_v0",
689
+ json!([null, "", null, 64]),
690
+ meta.clone(),
691
+ ),
692
+ ("gen_meta_code_v0", json!(["Name", "", 5, 64]), meta.clone()),
693
+ (
694
+ "gen_meta_code_v0",
695
+ json!(["Name", "", [], 64]),
696
+ meta.clone(),
697
+ ),
698
+ ];
699
+ let good = vec![
700
+ ("gen_meta_code_v0", json!(["Name", "", null, 64]), meta),
701
+ (
702
+ "gen_meta_code_v0",
703
+ json!(["Name", "", {"a": 1}, 64]),
704
+ with_meta.unwrap().iscc,
705
+ ),
706
+ ];
707
+ assert_rows(bad, good);
708
+ }
709
+
710
+ #[cfg(feature = "text-processing")]
711
+ #[test]
712
+ fn test_wrong_type_text_value_is_unparsable() {
713
+ // A null text fails the parse arm; an empty text parses.
714
+ use serde_json::json;
715
+ let text = gen_text_code_v0("", 64).unwrap().iscc;
716
+ let bad = vec![("gen_text_code_v0", json!([null, 64]), text.clone())];
717
+ let good = vec![("gen_text_code_v0", json!(["", 64]), text)];
718
+ assert_rows(bad, good);
719
+ }
720
+
721
+ #[test]
722
+ fn test_seq_wrong_type_values_are_unparsable() {
723
+ // A non-string unit fails encode_seq; a null output unit fails decode_seq.
724
+ let encode = serde_json::json!({"inputs": [["ISCC:GAAAAAAAAA", null]],
725
+ "outputs": "bytes:300000000000"});
726
+ assert!(!run(
727
+ &serde_json::json!({"encode_seq": {"case": encode}}),
728
+ "encode_seq"
729
+ ));
730
+ let decode = serde_json::json!({"inputs": ["bytes:300000000000"],
731
+ "outputs": ["ISCC:GAAAAAAAAA", null]});
732
+ assert!(!run(
733
+ &serde_json::json!({"decode_seq": {"case": decode}}),
734
+ "decode_seq"
735
+ ));
736
+ }
737
+
738
+ #[test]
739
+ fn test_check_sections() {
740
+ // Every key but `_metadata` must map to an object of case objects.
741
+ assert_eq!(check_sections(&test_data().unwrap()), Ok(()));
742
+ let ok = serde_json::json!({"_metadata": 5, "encode_seq": {"case": {}}});
743
+ assert_eq!(check_sections(&ok), Ok(()));
744
+ let bad = [
745
+ serde_json::json!({"gen_data_code_v0": 5}),
746
+ serde_json::json!({"gen_data_code_v0": null}),
747
+ serde_json::json!({"gen_data_code_v0": {"case": 5}}),
748
+ serde_json::json!([]),
749
+ ];
750
+ for data in bad {
751
+ assert!(check_sections(&data).is_err(), "{data}");
752
+ }
753
+ }
754
+ }