cim-kit 0.4.0

IEC CIM/CGMES for power systems: CIM/XML I/O that reproduces the file set, profile-aware validation, typed RDF export
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! The reader must never panic, whatever bytes it is given.
//!
//! `cargo fuzz` needs a nightly toolchain, so the targets under `fuzz/` are not part of
//! the ordinary test run. This file exercises the same contract deterministically on
//! stable: a corpus of hand-written pathological documents, plus systematic mutation of
//! valid ones. It runs on every `cargo test`, so a regression cannot reach a release
//! unnoticed even if nobody has run the fuzzer lately.

#![cfg(feature = "cgmes3")]

mod common;

use cim_kit::cgmes3::SCHEMA;
use cim_kit::prelude::*;
use cim_kit::reader::read_into;

const VALID: &str = r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:eu="http://iec.ch/TC57/CIM100-European#"
         xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#"
         xmlns:dm="http://iec.ch/TC57/61970-552/DifferenceModel/1#"
         xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <md:FullModel rdf:about="urn:uuid:11111111-1111-4111-8111-111111111111">
    <md:Model.scenarioTime>2021-03-25T15:30:00Z</md:Model.scenarioTime>
    <md:Model.profile>http://iec.ch/TC57/ns/CIM/CoreEquipment-EU/3.0</md:Model.profile>
    <md:Model.DependentOn rdf:resource="urn:uuid:22222222-2222-4222-8222-222222222222"/>
  </md:FullModel>
  <cim:ACLineSegment rdf:ID="_33333333-3333-4333-8333-333333333333">
    <cim:IdentifiedObject.name>Line</cim:IdentifiedObject.name>
    <cim:ACLineSegment.r>1.5</cim:ACLineSegment.r>
    <eu:IdentifiedObject.shortName>L</eu:IdentifiedObject.shortName>
  </cim:ACLineSegment>
  <cim:Terminal rdf:ID="_44444444-4444-4444-8444-444444444444">
    <cim:Terminal.ConductingEquipment rdf:resource="#_33333333-3333-4333-8333-333333333333"/>
    <cim:Terminal.phases rdf:resource="http://iec.ch/TC57/CIM100#PhaseCode.ABC"/>
  </cim:Terminal>
  <cim:Location rdf:ID="_55555555-5555-4555-8555-555555555555">
    <cim:Location.mainAddress rdf:parseType="Resource">
      <cim:StreetAddress.postalCode>1000</cim:StreetAddress.postalCode>
      <cim:StreetAddress.townDetail rdf:parseType="Resource">
        <cim:TownDetail.name>Brussels</cim:TownDetail.name>
      </cim:StreetAddress.townDetail>
    </cim:Location.mainAddress>
  </cim:Location>
</rdf:RDF>"##;

/// Read `bytes` under both strictness settings and exercise everything downstream.
///
/// Any panic here is a bug: the documented contract is an error or a model plus
/// diagnostics, never a crash.
///
/// Returns how many of the two reads succeeded, so a caller can assert that a mutation
/// campaign is still reaching the code past the parser rather than erroring out early.
#[must_use]
fn exercise(bytes: &[u8]) -> usize {
    let mut succeeded = 0;
    for options in [ReadOptions::lenient(), ReadOptions::strict()] {
        let mut ds = Dataset::new(SCHEMA);
        let Ok(outcome) = read_into(&mut ds, bytes, Some("fuzz.xml"), &options) else {
            continue;
        };
        succeeded += 1;

        // Everything the API promises about a successfully read dataset must hold.
        let _ = cim_kit::validate::validate(&ds);
        let _ = ds.dangling_references();
        let _ = cim_kit::InverseIndex::build(&ds);
        let _ = cim_kit::validate::profile_coverage(&ds);
        for (id, o) in ds.iter() {
            assert!(ds.get(id).is_some());
            assert!(
                ds.by_mrid(o.mrid()).is_some(),
                "index disagrees with storage"
            );
            for slot in o.slots() {
                // Every stored attribute id must be one the schema defines, and must be
                // reachable from the object's class.
                let def = SCHEMA.attr(slot.attr);
                assert!(
                    SCHEMA.class(o.class()).all_attrs.contains(&slot.attr),
                    "{} stored on {} which does not have it",
                    def.name,
                    SCHEMA.class(o.class()).name
                );
            }
        }

        // Whatever was read must be writable, and our own output must be readable.
        let mut buf = Vec::new();
        if cim_kit::writer::write(&ds, &mut buf, &WriteOptions::default()).is_ok() {
            // Re-reading with *our* reader is the weaker half of this, and on its own it
            // is the blind spot the well-formedness gate had: a tolerant reader accepting
            // its own output says nothing about anyone else's parser. This campaign is
            // where that matters most — it is the only place that generates untidy input
            // deliberately, so it is the only place a writer defect against untidy input
            // can show up at all.
            let text = String::from_utf8(buf.clone())
                .expect("the writer must produce UTF-8, whatever it was given");
            if let Err(e) = common::check_well_formed(&text) {
                panic!("a mutated document produced output that is not well-formed XML: {e}");
            }

            let mut back = Dataset::new(SCHEMA);
            let again = read_into(&mut back, buf.as_slice(), None, &ReadOptions::lenient())
                .expect("the writer must produce readable output");
            assert!(
                !again.report.has_errors(),
                "re-reading our own output produced errors:\n{}",
                again.report
            );
            assert_eq!(back.len(), ds.len(), "round-trip changed the object count");
        }

        if let Some(diff) = outcome.difference {
            let mut copy = Dataset::new(SCHEMA);
            let _ = read_into(&mut copy, bytes, None, &ReadOptions::lenient());
            let _ = copy.apply_difference(&diff);
        }
    }
    succeeded
}

#[test]
fn pathological_documents_do_not_panic() {
    let cases: &[(&str, &str)] = &[
        ("empty", ""),
        ("whitespace", "   \n\t  "),
        ("not xml", "hello world"),
        ("declaration only", r#"<?xml version="1.0"?>"#),
        ("unclosed root", "<rdf:RDF>"),
        ("unclosed element", "<rdf:RDF><cim:Terminal"),
        (
            "no namespaces",
            "<rdf:RDF><cim:Terminal rdf:ID=\"_x\"/></rdf:RDF>",
        ),
        ("wrong root", "<html><body>not cim</body></html>"),
        (
            "root without namespace declarations",
            r#"<rdf:RDF><md:FullModel rdf:about="urn:uuid:1"/></rdf:RDF>"#,
        ),
        (
            "object without identifier",
            r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
                <cim:Terminal><cim:IdentifiedObject.name>x</cim:IdentifiedObject.name></cim:Terminal></rdf:RDF>"##,
        ),
        (
            "deeply nested",
            r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
                <cim:Terminal rdf:ID="_a"><cim:IdentifiedObject.name><b><c><d>x</d></c></b></cim:IdentifiedObject.name></cim:Terminal></rdf:RDF>"##,
        ),
        (
            "attribute without an object",
            r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
                <cim:ACLineSegment.r>1.0</cim:ACLineSegment.r></rdf:RDF>"##,
        ),
        (
            "difference with no statements",
            r##"<rdf:RDF xmlns:dm="http://iec.ch/TC57/61970-552/DifferenceModel/1#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
                <dm:DifferenceModel rdf:about="urn:uuid:1"><dm:forwardDifferences rdf:parseType="Statements"/></dm:DifferenceModel></rdf:RDF>"##,
        ),
        (
            "self-referencing object",
            r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
                <cim:Terminal rdf:ID="_55555555-5555-4555-8555-555555555555">
                <cim:Terminal.ConductingEquipment rdf:resource="#_55555555-5555-4555-8555-555555555555"/>
                </cim:Terminal></rdf:RDF>"##,
        ),
        (
            "duplicate attribute on a single-valued field",
            r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
                <cim:ACLineSegment rdf:ID="_a"><cim:ACLineSegment.r>1</cim:ACLineSegment.r>
                <cim:ACLineSegment.r>2</cim:ACLineSegment.r></cim:ACLineSegment></rdf:RDF>"##,
        ),
        ("valid", VALID),
    ];

    for (name, src) in cases {
        // A panic in `exercise` fails the test and names the case.
        println!("case: {name}");
        let _ = exercise(src.as_bytes());
    }
    // The valid document must actually be readable, or the corpus proves nothing.
    assert_eq!(
        exercise(VALID.as_bytes()),
        2,
        "the valid document did not read"
    );
}

#[test]
fn truncation_at_every_byte_boundary_does_not_panic() {
    // Truncation is the failure mode of a stream that dies mid-transfer, and it reaches
    // every parser state in turn.
    let bytes = VALID.as_bytes();
    let mut readable = 0;
    for cut in 0..bytes.len() {
        readable += exercise(&bytes[..cut]);
    }
    // Truncation inside the body still yields a readable prefix under lenient rules, so
    // the downstream assertions really do run rather than every case erroring out.
    assert!(
        readable > 50,
        "only {readable} truncations parsed; the campaign is not reaching the model"
    );
}

#[test]
fn single_byte_corruption_does_not_panic() {
    // Walk one corrupting byte through the document. This reaches malformed tags,
    // broken entities, invalid UTF-8 and truncated attribute values without needing a
    // fuzzer's randomness, and it is fully deterministic.
    let original = VALID.as_bytes();
    let mut readable = 0;
    let mut cases = 0;
    for replacement in [b'<', b'>', b'"', b'&', b'/', 0x00, 0xff] {
        for i in (0..original.len()).step_by(7) {
            let mut bytes = original.to_vec();
            bytes[i] = replacement;
            readable += exercise(&bytes);
            cases += 1;
        }
    }
    println!("{cases} corruptions, {readable} still readable");
    assert!(readable > cases / 4, "too few corruptions produced a model");
}

#[test]
fn deletion_of_each_region_does_not_panic() {
    let original = VALID.as_bytes();
    let chunk = 16;
    for start in (0..original.len()).step_by(chunk) {
        let end = (start + chunk).min(original.len());
        let mut bytes = Vec::with_capacity(original.len());
        bytes.extend_from_slice(&original[..start]);
        bytes.extend_from_slice(&original[end..]);
        let _ = exercise(&bytes);
    }
}

#[test]
fn pathological_sizes_are_handled() {
    // A very long attribute value, a very long element name, and many repetitions of one
    // attribute: each stresses a different growth path.
    let long_value = "x".repeat(1 << 16);
    let doc = format!(
        r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <cim:ACLineSegment rdf:ID="_66666666-6666-4666-8666-666666666666">
    <cim:IdentifiedObject.name>{long_value}</cim:IdentifiedObject.name>
  </cim:ACLineSegment>
</rdf:RDF>"##
    );
    assert_eq!(exercise(doc.as_bytes()), 2, "a long value must still read");

    let long_name = "A".repeat(4096);
    let doc = format!(
        r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <cim:{long_name} rdf:ID="_a"/>
</rdf:RDF>"##
    );
    let _ = exercise(doc.as_bytes());

    let mut repeated = String::from(
        r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <cim:Diagram rdf:ID="_77777777-7777-4777-8777-777777777777">"##,
    );
    for i in 0..5000 {
        repeated.push_str(&format!(
            "<cim:IdentifiedObject.name>n{i}</cim:IdentifiedObject.name>"
        ));
    }
    repeated.push_str("</cim:Diagram></rdf:RDF>");
    assert_eq!(
        exercise(repeated.as_bytes()),
        2,
        "many repetitions must still read"
    );
}

#[test]
fn invalid_utf8_is_an_error_not_a_panic() {
    let mut bytes = VALID.as_bytes().to_vec();
    // Splice an invalid continuation byte into element text.
    if let Some(pos) = VALID.find("Line") {
        bytes[pos] = 0x80;
    }
    let _ = exercise(&bytes);

    // A document that is entirely invalid UTF-8.
    let _ = exercise(&[0xff, 0xfe, 0xfd, 0x00, 0x80, 0x81]);
}

// ---------------------------------------------------------------------------
// Deviations a malformed document produces that a valid one never does
// ---------------------------------------------------------------------------

/// Read `doc` leniently and hand back the model and what the reader had to say.
fn read_lenient(doc: &str, options: &ReadOptions) -> (Dataset, cim_kit::Report) {
    let mut ds = Dataset::new(SCHEMA);
    let outcome = read_into(&mut ds, doc.as_bytes(), Some("probe.xml"), options).expect("read");
    (ds, outcome.report)
}

fn wrap(body: &str) -> String {
    format!(
        r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#"
         xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
{body}
</rdf:RDF>"##
    )
}

/// A value is the text of its own element and of no other.
///
/// IEC 61970-552 property elements hold text, one `rdf:resource`, or an inline compound —
/// never mixed content, so nesting markup inside a value is malformed. The nested element is
/// skipped with its content rather than donating its text: `<name><x>ignored</x></name>` is
/// an empty name, not `ignored`.
#[test]
fn markup_nested_inside_a_value_does_not_become_the_value() {
    let doc = wrap(
        r##"  <cim:ACLineSegment rdf:ID="_33333333-3333-4333-8333-333333333333">
    <cim:IdentifiedObject.name><vendor:tag xmlns:vendor="http://v/">ignored</vendor:tag></cim:IdentifiedObject.name>
    <cim:IdentifiedObject.description>kept</cim:IdentifiedObject.description>
  </cim:ACLineSegment>"##,
    );
    let (ds, report) = read_lenient(&doc, &ReadOptions::lenient());
    let o = ds
        .by_mrid(&Mrid::parse("33333333-3333-4333-8333-333333333333"))
        .expect("the line");

    assert_eq!(
        o.get(cim_kit::cgmes3::attributes::identified_object::name)
            .and_then(|v| v.as_str()),
        Some(""),
        "the nested element's text is not the value"
    );
    // The property still ends at its own tag, so what follows it is read normally.
    assert_eq!(
        o.get(cim_kit::cgmes3::attributes::identified_object::description)
            .and_then(|v| v.as_str()),
        Some("kept")
    );
    assert!(
        report
            .by_rule(cim_kit::Rule::Structure)
            .any(|d| d.message.contains("inside a value")),
        "the deviation is reported: {report}"
    );
}

/// Objects with no identifier at all are still distinct objects.
///
/// Giving them all the same empty identifier merged them into one, so the later one's
/// values overwrote the earlier one's — under a class they need not even share.
#[test]
fn objects_without_an_identifier_do_not_collapse_into_one() {
    let doc = wrap(
        r##"  <cim:ACLineSegment>
    <cim:IdentifiedObject.name>first</cim:IdentifiedObject.name>
  </cim:ACLineSegment>
  <cim:Terminal>
    <cim:IdentifiedObject.name>second</cim:IdentifiedObject.name>
  </cim:Terminal>"##,
    );
    let (ds, report) = read_lenient(&doc, &ReadOptions::lenient());
    assert_eq!(ds.len(), 2, "two elements, two objects");

    let mut names: Vec<&str> = ds
        .iter()
        .filter_map(|(_, o)| {
            o.get(cim_kit::cgmes3::attributes::identified_object::name)?
                .as_str()
        })
        .collect();
    names.sort_unstable();
    assert_eq!(names, ["first", "second"]);

    // Nothing is invented: the stand-in is opaque, not a plausible-looking UUID, so every
    // later check still sees that the document was wrong.
    assert!(ds.iter().all(|(_, o)| !o.mrid().is_uuid()));
    assert_eq!(report.by_rule(cim_kit::Rule::Structure).count(), 2);
}

/// A lenient read answers a broken document with a diagnostic per problem, so the report
/// grows with how broken the input is. Past the cap it stops growing and says so.
#[test]
fn the_report_a_broken_document_produces_is_bounded() {
    let mut body = String::new();
    for i in 0..5_000 {
        body.push_str(&format!("  <cim:NoSuchClass{i}/>\n"));
    }
    let doc = wrap(&body);

    let (_, capped) = read_lenient(&doc, &ReadOptions::lenient().with_max_diagnostics(100));
    assert_eq!(capped.len(), 101, "100 findings plus the note that says so");
    assert!(
        capped
            .iter()
            .last()
            .is_some_and(|d| d.message.contains("stopped recording")),
        "the truncation is stated rather than silent"
    );

    // Zero means no limit, for a caller that wants every finding.
    let (_, all) = read_lenient(&doc, &ReadOptions::lenient().with_max_diagnostics(0));
    assert_eq!(all.len(), 5_000);
}

// ---------------------------------------------------------------------------
// Entities: never expanded, never fetched, never silent
// ---------------------------------------------------------------------------

/// A DOCTYPE's entities are not definitions this reader honours: IEC 61970-552 documents
/// declare no DTD, so an internal subset is either a mistake or an attack — the billion
/// laughs, or an external entity naming a local file. Neither may expand, and since
/// keeping the reference literally is a tolerance, each one is reported.
///
/// Pins baseline SR-003. It holds today because quick-xml does not process DTDs; this is
/// what notices if an upgrade ever starts to.
#[test]
fn declared_and_external_entities_are_never_expanded() {
    let doc = r##"<?xml version="1.0"?>
<!DOCTYPE rdf:RDF [
  <!ENTITY a "aaaaaaaaaa">
  <!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;">
  <!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
  <!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
  <!ENTITY secret SYSTEM "file:///etc/passwd">
]>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <cim:ACLineSegment rdf:ID="_66666666-6666-4666-8666-666666666666">
    <cim:IdentifiedObject.name>&d;|&secret;</cim:IdentifiedObject.name>
    <cim:ConductingEquipment.BaseVoltage rdf:resource="#_&secret;"/>
  </cim:ACLineSegment>
</rdf:RDF>"##;
    let (ds, report) = read_lenient(doc, &ReadOptions::lenient());

    let line = ds
        .find(&Mrid::parse("_66666666-6666-4666-8666-666666666666"))
        .and_then(|id| ds.get(id))
        .expect("the line is read");
    let name = line.get(cim_kit::cgmes3::names::attributes::identified_object::name);
    assert_eq!(
        name.and_then(Value::as_str),
        Some("&d;|&secret;"),
        "the references stay text"
    );

    let unexpanded: Vec<_> = report
        .iter()
        .filter(|d| d.message.contains("entity"))
        .collect();
    assert_eq!(
        unexpanded.len(),
        3,
        "each undefined reference — two in text, one in an attribute — is reported: {report:?}"
    );
}

// ---------------------------------------------------------------------------
// The input budget
// ---------------------------------------------------------------------------

/// A document of `size` bytes whose padding is a comment, so it is a valid model of one
/// object however large it is made.
fn padded(id: &str, size: usize) -> String {
    let head = wrap(&format!(
        r#"<cim:ACLineSegment rdf:ID="_{id}"><cim:IdentifiedObject.name>x</cim:IdentifiedObject.name></cim:ACLineSegment>
<!--"#
    ));
    let (open, close) = head.split_at(head.rfind("</rdf:RDF>").unwrap());
    let fill = size.saturating_sub(head.len() + 3);
    format!("{open}{}-->\n{close}", " ".repeat(fill))
}

/// A scratch directory for one test, removed and recreated on entry.
fn scratch(name: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("cim-robust-{}-{name}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

fn too_large(e: &cim_kit::Error) -> (u64, u64) {
    match e {
        cim_kit::Error::InputTooLarge { limit, read, .. } => (*limit, *read),
        other => panic!("expected InputTooLarge, got {other:?}"),
    }
}

/// The default is a number the documentation states, so it is a number a test asserts.
#[test]
fn the_default_budget_is_two_gibibytes() {
    assert_eq!(ReadOptions::default().max_input_bytes, 2 << 30);
    assert_eq!(ReadOptions::strict().max_input_bytes, 2 << 30);
}

#[test]
fn a_document_over_the_budget_is_refused() {
    const MIB: u64 = 1 << 20;
    let doc = padded("77777777-7777-4777-8777-777777777777", 2 << 20);
    let mut ds = Dataset::new(SCHEMA);
    let options = ReadOptions::lenient().with_max_input_bytes(MIB);
    let err = read_into(&mut ds, doc.as_bytes(), Some("big.xml"), &options).unwrap_err();
    let (limit, read) = too_large(&err);
    assert_eq!(limit, MIB);
    assert!(
        read > MIB && read <= MIB + (64 << 10),
        "overshoot is one buffer, not the file: {read}"
    );
    assert!(err.to_string().contains("big.xml"), "{err}");
    assert!(err.to_string().contains("with_max_input_bytes"), "{err}");

    // Zero is no limit, as for `max_diagnostics`.
    let mut ds = Dataset::new(SCHEMA);
    read_into(
        &mut ds,
        doc.as_bytes(),
        None,
        &options.clone().with_max_input_bytes(0),
    )
    .expect("an unlimited read takes it all");
    assert_eq!(ds.len(), 1);
}

/// One budget per load, not per file: three files that each fit are one model that does
/// not. And lenient loading, which turns an unreadable file into a `CIM0022` and carries
/// on, must not do that here — what it would carry on with is part of a model.
#[test]
fn a_directory_shares_one_budget_and_leniency_does_not_hide_it() {
    let dir = scratch("budget-dir");
    for (i, id) in ["11", "22", "33"].iter().enumerate() {
        let id = format!("{id}{id}{id}{id}{id}{id}{id}{id}-1111-4111-8111-111111111111");
        std::fs::write(dir.join(format!("{i}_EQ.xml")), padded(&id, 400 << 10)).unwrap();
    }
    let options = ReadOptions::lenient().with_max_input_bytes(1 << 20);
    let mut ds = Dataset::new(SCHEMA);
    let err = ds
        .load_files(cim_kit::instance_files(&dir), &options)
        .expect_err("the third file exceeds the shared budget");
    too_large(&err);
    assert!(
        err.to_string().contains("2_EQ.xml"),
        "names the file it stopped in: {err}"
    );

    // Each file alone is well inside it.
    let mut one = Dataset::new(SCHEMA);
    one.load_file(&dir.join("0_EQ.xml"), &options)
        .expect("one file fits");
}

/// A decompression bomb: a small archive whose entry inflates far past the budget. What is
/// counted is what the parser receives, so the archive's own size fields — which its
/// author writes — are never consulted. The second half makes them lie.
#[test]
#[cfg(feature = "zip")]
fn an_archive_is_charged_its_decompressed_bytes_whatever_it_declares() {
    use std::io::Write as _;

    let dir = scratch("budget-zip");
    let path = dir.join("bomb.zip");
    let inflated = padded("88888888-8888-4888-8888-888888888888", 64 << 20);
    {
        let mut zw = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
        zw.start_file(
            "EQ.xml",
            zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Deflated),
        )
        .unwrap();
        zw.write_all(inflated.as_bytes()).unwrap();
        zw.finish().unwrap();
    }
    let compressed = std::fs::metadata(&path).unwrap().len();
    assert!(
        compressed < 1 << 20,
        "a real bomb: {compressed} bytes on disk"
    );

    let options = ReadOptions::lenient().with_max_input_bytes(1 << 20);
    let mut ds = Dataset::new(SCHEMA);
    let err = ds.load_file(&path, &options).unwrap_err();
    let (_, read) = too_large(&err);
    assert!(
        read <= (1 << 20) + (64 << 10),
        "stopped at the budget: {read}"
    );

    // Now under-declare the entry's size in both the local header and the central
    // directory. The budget is charged what the parser receives, so the lie changes
    // nothing.
    let mut bytes = std::fs::read(&path).unwrap();
    for (signature, offset) in [(0x0403_4b50_u32, 22), (0x0201_4b50_u32, 24)] {
        let at = bytes
            .windows(4)
            .position(|w| w == signature.to_le_bytes())
            .expect("header present");
        bytes[at + offset..at + offset + 4].copy_from_slice(&1024_u32.to_le_bytes());
    }
    let lying = dir.join("lying.zip");
    std::fs::write(&lying, bytes).unwrap();
    // zip itself refuses an entry that inflates past its declared size, before the budget
    // is reached; either way the lie buys nothing, and it is reported as what it is — a
    // broken archive, naming the entry — rather than as malformed XML.
    let mut ds = Dataset::new(SCHEMA);
    let err = ds
        .load_file(&lying, &options)
        .expect_err("a declared kilobyte that inflates to 64 MiB is refused");
    match &err {
        cim_kit::Error::InputTooLarge { read, .. } => assert_eq!(*read, (1 << 20) + 1),
        cim_kit::Error::Zip(m) => assert!(m.contains("EQ.xml") && m.contains("declared"), "{m}"),
        other => panic!("expected the budget or the archive to refuse it, got {other:?}"),
    }
    assert!(
        ds.len() <= 1,
        "nothing past the declared kilobyte was taken as model"
    );
}

/// Sniffing reads the first MiB and no more: `detect_vintage` sniffs every file of a set
/// before loading any, so an unbounded sniff would be a second, uncounted pass.
#[test]
fn sniffing_reads_a_bounded_prefix() {
    let declared = |pad: usize| {
        format!(
            "<?xml version=\"1.0\"?>\n<!--{}-->\n<rdf:RDF xmlns:cim=\"http://iec.ch/TC57/CIM100#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"/>",
            " ".repeat(pad)
        )
    };
    let near = cim_kit::reader::sniff(declared(1000).as_bytes()).unwrap();
    assert!(near.is_some(), "a root in the first MiB is found");
    let far = cim_kit::reader::sniff(declared(2 << 20).as_bytes()).unwrap();
    assert!(far.is_none(), "a root past the first MiB is not looked for");
}