asx-rs 0.14.0

AS2 and AS4 B2B messaging library for Rust — signing, encryption, MDN, and ebMS3/AS4 profile support
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
//! Standard Business Document Header (SBDH) — UN/CEFACT SBDH 1.3.
//!
//! SBDH is a standardised envelope used by Peppol, CEF eDelivery, and other
//! European e-invoicing networks to wrap business documents (e.g., UBL invoices
//! or CII credit notes) with routing and identification metadata.
//!
//! This module implements [`StandardBusinessDocument::wrap`] (serialize to XML)
//! and [`StandardBusinessDocument::unwrap`] (parse from XML), covering the
//! mandatory SBDH elements used in production Peppol / EESSI message exchanges.
//!
//! ## Wire format
//!
//! ```xml
//! <StandardBusinessDocument
//!     xmlns="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader">
//!   <StandardBusinessDocumentHeader>
//!     <HeaderVersion>1.0</HeaderVersion>
//!     <Sender>
//!       <Identifier Authority="iso6523-actorid-upis">0007:9876543210987</Identifier>
//!     </Sender>
//!     <Receiver>
//!       <Identifier Authority="iso6523-actorid-upis">0007:1234567890123</Identifier>
//!     </Receiver>
//!     <DocumentIdentification>
//!       <Standard>urn:oasis:names:specification:ubl:schema:xsd:Invoice-2</Standard>
//!       <TypeVersion>2.1</TypeVersion>
//!       <InstanceIdentifier>urn:uuid:550e8400-e29b-41d4-a716-446655440000</InstanceIdentifier>
//!       <Type>Invoice</Type>
//!       <MultipleType>false</MultipleType>
//!       <CreationDateAndTime>2026-01-01T12:00:00+00:00</CreationDateAndTime>
//!     </DocumentIdentification>
//!   </StandardBusinessDocumentHeader>
//!   <!-- business document payload (XML) embedded directly -->
//! </StandardBusinessDocument>
//! ```
//!
//! ## Usage
//!
//! ```rust
//! # use asx_rs::sbdh::{StandardBusinessDocument, SbdhHeader, SbdhParty, SbdhDocumentIdentification};
//! let doc = StandardBusinessDocument {
//!     header: SbdhHeader {
//!         header_version: "1.0".into(),
//!         sender: SbdhParty { identifier: "0007:1234567890".into(), authority: "iso6523-actorid-upis".into() },
//!         receiver: SbdhParty { identifier: "0007:9876543210".into(), authority: "iso6523-actorid-upis".into() },
//!         document_identification: SbdhDocumentIdentification {
//!             standard: "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2".into(),
//!             type_version: "2.1".into(),
//!             instance_identifier: "urn:uuid:abc123".into(),
//!             r#type: "Invoice".into(),
//!             multiple_type: false,
//!             creation_date_and_time: "2026-01-01T12:00:00+00:00".into(),
//!         },
//!     },
//!     payload: b"<Invoice/>".to_vec(),
//! };
//!
//! let wrapped = doc.wrap().unwrap();
//! let parsed = StandardBusinessDocument::unwrap(&wrapped).unwrap();
//! assert_eq!(parsed.header.sender.identifier, "0007:1234567890");
//! assert_eq!(parsed.payload, b"<Invoice/>");
//! ```

use crate::core::{AsxError, ErrorCode, ErrorContext, Result, escape_xml};
use roxmltree::Document;

/// XML namespace for SBDH 1.3 documents.
pub const SBDH_NAMESPACE: &str =
    "http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader";

/// Closing tag used to locate the end of the header block during parsing.
const HEADER_CLOSE_TAG: &[u8] = b"</StandardBusinessDocumentHeader>";

/// Closing tag used to locate the end of the document envelope during parsing.
const DOCUMENT_CLOSE_TAG: &[u8] = b"</StandardBusinessDocument>";

// ── Public types ──────────────────────────────────────────────────────────────

/// Sender or receiver party in an SBDH envelope.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SbdhParty {
    /// Party identifier value.
    ///
    /// For Peppol, this is `<scheme>:<participant-id>` (e.g., `"0007:9876543210987"`
    /// for a German VAT-registered participant).
    pub identifier: String,
    /// Identifier scheme authority.
    ///
    /// Peppol uses `"iso6523-actorid-upis"`.  Other networks may use scheme-specific
    /// authority strings defined in their interoperability agreements.
    pub authority: String,
}

/// Document identification metadata embedded in an SBDH envelope.
///
/// These fields identify the enclosed business document and are used for routing,
/// duplicate detection, and tracking.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SbdhDocumentIdentification {
    /// Document type standard namespace URI.
    ///
    /// Example: `"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"`.
    pub standard: String,
    /// Schema version string (e.g., `"2.1"`, `"D16B"`).
    pub type_version: String,
    /// Globally unique instance identifier.
    ///
    /// Should be a UUID URN (e.g., `"urn:uuid:550e8400-e29b-41d4-a716-446655440000"`)
    /// or another scheme-scoped unique string.
    pub instance_identifier: String,
    /// Human-readable document type (e.g., `"Invoice"`, `"Order"`, `"Despatch Advice"`).
    pub r#type: String,
    /// Whether the document carries multiple document types.  Typically `false`.
    pub multiple_type: bool,
    /// ISO 8601 creation timestamp (e.g., `"2026-05-18T12:00:00+00:00"`).
    pub creation_date_and_time: String,
}

/// Standard Business Document Header metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SbdhHeader {
    /// SBDH schema version.  Always `"1.0"` per UN/CEFACT SBDH 1.3.
    pub header_version: String,
    /// Sending party.
    pub sender: SbdhParty,
    /// Receiving party.
    pub receiver: SbdhParty,
    /// Document identification.
    pub document_identification: SbdhDocumentIdentification,
}

/// A business document wrapped with an SBDH envelope.
///
/// Use [`wrap`](Self::wrap) to serialize to XML and [`unwrap`](Self::unwrap)
/// to parse from XML.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StandardBusinessDocument {
    /// SBDH envelope metadata.
    pub header: SbdhHeader,
    /// Raw business document bytes (typically XML).
    pub payload: Vec<u8>,
}

// ── Serialization ─────────────────────────────────────────────────────────────

impl StandardBusinessDocument {
    /// Serialize this document to UTF-8 XML bytes conforming to SBDH 1.3.
    ///
    /// The payload bytes are embedded verbatim as a child element of
    /// `<StandardBusinessDocument>`.  The caller is responsible for ensuring
    /// the payload is valid XML and that its root element does not conflict
    /// with the SBDH namespace.
    ///
    /// # Errors
    ///
    /// Returns an error if any header field contains XML-unsafe content that
    /// cannot be safely escaped (e.g., invalid UTF-8 in fields derived from
    /// untrusted input).
    pub fn wrap(&self) -> Result<Vec<u8>> {
        let h = &self.header;
        let di = &h.document_identification;
        let multiple_type = if di.multiple_type { "true" } else { "false" };

        let xml = format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<StandardBusinessDocument xmlns="{ns}">
  <StandardBusinessDocumentHeader>
    <HeaderVersion>{hv}</HeaderVersion>
    <Sender>
      <Identifier Authority="{sender_auth}">{sender_id}</Identifier>
    </Sender>
    <Receiver>
      <Identifier Authority="{receiver_auth}">{receiver_id}</Identifier>
    </Receiver>
    <DocumentIdentification>
      <Standard>{standard}</Standard>
      <TypeVersion>{type_version}</TypeVersion>
      <InstanceIdentifier>{instance_id}</InstanceIdentifier>
      <Type>{doc_type}</Type>
      <MultipleType>{multiple_type}</MultipleType>
      <CreationDateAndTime>{created_at}</CreationDateAndTime>
    </DocumentIdentification>
  </StandardBusinessDocumentHeader>
  {payload}
</StandardBusinessDocument>"#,
            ns = SBDH_NAMESPACE,
            hv = escape_xml(&h.header_version),
            sender_auth = escape_xml(&h.sender.authority),
            sender_id = escape_xml(&h.sender.identifier),
            receiver_auth = escape_xml(&h.receiver.authority),
            receiver_id = escape_xml(&h.receiver.identifier),
            standard = escape_xml(&di.standard),
            type_version = escape_xml(&di.type_version),
            instance_id = escape_xml(&di.instance_identifier),
            doc_type = escape_xml(&di.r#type),
            multiple_type = multiple_type,
            created_at = escape_xml(&di.creation_date_and_time),
            payload = std::str::from_utf8(&self.payload).map_err(|_| {
                AsxError::new(
                    ErrorCode::InvalidInput,
                    "SBDH payload is not valid UTF-8",
                    ErrorContext::new("sbdh_wrap"),
                )
            })?,
        );
        Ok(xml.into_bytes())
    }

    // ── Parsing ───────────────────────────────────────────────────────────────

    /// Parse an SBDH-wrapped document from UTF-8 XML bytes.
    ///
    /// The parser extracts the `<StandardBusinessDocumentHeader>` fields and
    /// the raw payload bytes that appear after the closing header tag.
    ///
    /// The payload is returned as the byte slice between the end of
    /// `</StandardBusinessDocumentHeader>` and the start of
    /// `</StandardBusinessDocument>`, trimmed of leading/trailing ASCII whitespace.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorCode::ParseFailed`] when the input is malformed, missing
    /// required SBDH elements, or not valid UTF-8.
    pub fn unwrap(bytes: &[u8]) -> Result<Self> {
        let ctx = || ErrorContext::new("sbdh_unwrap");

        // Locate the end of <StandardBusinessDocumentHeader>.
        let header_end_pos = find_subsequence(bytes, HEADER_CLOSE_TAG).ok_or_else(|| {
            AsxError::new(
                ErrorCode::ParseFailed,
                "SBDH missing </StandardBusinessDocumentHeader>",
                ctx(),
            )
        })?;

        let header = parse_sbdh_header(bytes, ctx)?;

        // Extract payload: everything after </StandardBusinessDocumentHeader>
        // and before </StandardBusinessDocument>.
        let after_header = &bytes[header_end_pos + HEADER_CLOSE_TAG.len()..];
        let payload_end = find_subsequence(after_header, DOCUMENT_CLOSE_TAG).ok_or_else(|| {
            AsxError::new(
                ErrorCode::ParseFailed,
                "SBDH missing </StandardBusinessDocument>",
                ctx(),
            )
        })?;

        let payload_slice = &after_header[..payload_end];
        let payload = trim_ascii(payload_slice).to_vec();

        Ok(Self { header, payload })
    }
}

// ── Internal helpers ──────────────────────────────────────────────────────────

/// Returns the byte offset of the first occurrence of `needle` in `haystack`,
/// or `None` if not found.
fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || needle.len() > haystack.len() {
        return None;
    }
    haystack.windows(needle.len()).position(|w| w == needle)
}

/// Trim leading and trailing ASCII whitespace from a byte slice.
fn trim_ascii(s: &[u8]) -> &[u8] {
    let start = s
        .iter()
        .position(|b| !b.is_ascii_whitespace())
        .unwrap_or(s.len());
    let end = s
        .iter()
        .rposition(|b| !b.is_ascii_whitespace())
        .map(|i| i + 1)
        .unwrap_or(0);
    if start >= end { &[] } else { &s[start..end] }
}

/// Parse the SBDH header from a full SBDH-wrapped document using roxmltree.
///
/// Navigates the DOM to `StandardBusinessDocumentHeader` and extracts all
/// required fields.  Requires the full document bytes (valid XML including the
/// outer `<StandardBusinessDocument>` element and its payload child).
fn parse_sbdh_header(bytes: &[u8], ctx: impl Fn() -> ErrorContext) -> Result<SbdhHeader> {
    let xml_str = std::str::from_utf8(bytes).map_err(|_| {
        AsxError::new(
            ErrorCode::ParseFailed,
            "SBDH document is not valid UTF-8",
            ctx(),
        )
    })?;

    let doc = Document::parse(xml_str).map_err(|e| {
        AsxError::new(
            ErrorCode::ParseFailed,
            format!("SBDH XML is malformed: {e}"),
            ctx(),
        )
    })?;

    // Locate <StandardBusinessDocumentHeader>
    let sbdh = doc
        .root_element()
        .descendants()
        .find(|n| n.is_element() && n.tag_name().name() == "StandardBusinessDocumentHeader")
        .ok_or_else(|| {
            AsxError::new(
                ErrorCode::ParseFailed,
                "SBDH missing StandardBusinessDocumentHeader",
                ctx(),
            )
        })?;

    // Helper: find a direct child element by local name and return its trimmed text.
    let find_text = |parent: roxmltree::Node<'_, '_>, name: &str| -> Option<String> {
        parent
            .children()
            .find(|n| n.is_element() && n.tag_name().name() == name)
            .and_then(|n| n.text())
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
    };

    let header_version = find_text(sbdh, "HeaderVersion").ok_or_else(|| {
        AsxError::new(ErrorCode::ParseFailed, "SBDH missing HeaderVersion", ctx())
    })?;

    // ── Sender ────────────────────────────────────────────────────────────────
    let sender_node = sbdh
        .children()
        .find(|n| n.is_element() && n.tag_name().name() == "Sender")
        .ok_or_else(|| AsxError::new(ErrorCode::ParseFailed, "SBDH missing Sender", ctx()))?;
    let sender_id_node = sender_node
        .children()
        .find(|n| n.is_element() && n.tag_name().name() == "Identifier")
        .ok_or_else(|| {
            AsxError::new(
                ErrorCode::ParseFailed,
                "SBDH missing Sender/Identifier",
                ctx(),
            )
        })?;
    let sender_identifier = sender_id_node
        .text()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .ok_or_else(|| {
            AsxError::new(
                ErrorCode::ParseFailed,
                "SBDH Sender/Identifier is empty",
                ctx(),
            )
        })?;
    let sender_authority = sender_id_node
        .attribute("Authority")
        .unwrap_or("")
        .to_string();

    // ── Receiver ──────────────────────────────────────────────────────────────
    let receiver_node = sbdh
        .children()
        .find(|n| n.is_element() && n.tag_name().name() == "Receiver")
        .ok_or_else(|| AsxError::new(ErrorCode::ParseFailed, "SBDH missing Receiver", ctx()))?;
    let receiver_id_node = receiver_node
        .children()
        .find(|n| n.is_element() && n.tag_name().name() == "Identifier")
        .ok_or_else(|| {
            AsxError::new(
                ErrorCode::ParseFailed,
                "SBDH missing Receiver/Identifier",
                ctx(),
            )
        })?;
    let receiver_identifier = receiver_id_node
        .text()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .ok_or_else(|| {
            AsxError::new(
                ErrorCode::ParseFailed,
                "SBDH Receiver/Identifier is empty",
                ctx(),
            )
        })?;
    let receiver_authority = receiver_id_node
        .attribute("Authority")
        .unwrap_or("")
        .to_string();

    // ── DocumentIdentification ────────────────────────────────────────────────
    let doc_id = sbdh
        .children()
        .find(|n| n.is_element() && n.tag_name().name() == "DocumentIdentification")
        .ok_or_else(|| {
            AsxError::new(
                ErrorCode::ParseFailed,
                "SBDH missing DocumentIdentification",
                ctx(),
            )
        })?;

    let standard = find_text(doc_id, "Standard").ok_or_else(|| {
        AsxError::new(
            ErrorCode::ParseFailed,
            "SBDH missing DocumentIdentification/Standard",
            ctx(),
        )
    })?;
    let type_version = find_text(doc_id, "TypeVersion").ok_or_else(|| {
        AsxError::new(
            ErrorCode::ParseFailed,
            "SBDH missing DocumentIdentification/TypeVersion",
            ctx(),
        )
    })?;
    let instance_identifier = find_text(doc_id, "InstanceIdentifier").ok_or_else(|| {
        AsxError::new(
            ErrorCode::ParseFailed,
            "SBDH missing DocumentIdentification/InstanceIdentifier",
            ctx(),
        )
    })?;
    let doc_type = find_text(doc_id, "Type").ok_or_else(|| {
        AsxError::new(
            ErrorCode::ParseFailed,
            "SBDH missing DocumentIdentification/Type",
            ctx(),
        )
    })?;
    let multiple_type = find_text(doc_id, "MultipleType")
        .map(|t| matches!(t.to_ascii_lowercase().as_str(), "true" | "1"))
        .unwrap_or(false);
    let creation_date_and_time = find_text(doc_id, "CreationDateAndTime").ok_or_else(|| {
        AsxError::new(
            ErrorCode::ParseFailed,
            "SBDH missing DocumentIdentification/CreationDateAndTime",
            ctx(),
        )
    })?;

    Ok(SbdhHeader {
        header_version,
        sender: SbdhParty {
            identifier: sender_identifier,
            authority: sender_authority,
        },
        receiver: SbdhParty {
            identifier: receiver_identifier,
            authority: receiver_authority,
        },
        document_identification: SbdhDocumentIdentification {
            standard,
            type_version,
            instance_identifier,
            r#type: doc_type,
            multiple_type,
            creation_date_and_time,
        },
    })
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_doc() -> StandardBusinessDocument {
        StandardBusinessDocument {
            header: SbdhHeader {
                header_version: "1.0".into(),
                sender: SbdhParty {
                    identifier: "0007:1234567890".into(),
                    authority: "iso6523-actorid-upis".into(),
                },
                receiver: SbdhParty {
                    identifier: "0007:9876543210".into(),
                    authority: "iso6523-actorid-upis".into(),
                },
                document_identification: SbdhDocumentIdentification {
                    standard: "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2".into(),
                    type_version: "2.1".into(),
                    instance_identifier: "urn:uuid:550e8400-e29b-41d4-a716-446655440000".into(),
                    r#type: "Invoice".into(),
                    multiple_type: false,
                    creation_date_and_time: "2026-01-01T12:00:00+00:00".into(),
                },
            },
            payload: b"<Invoice xmlns=\"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\"/>"
                .to_vec(),
        }
    }

    #[test]
    fn wrap_produces_well_formed_xml() {
        let doc = sample_doc();
        let bytes = doc.wrap().expect("wrap");
        let xml = std::str::from_utf8(&bytes).expect("utf8");
        assert!(
            xml.contains("<StandardBusinessDocument"),
            "outer element present"
        );
        assert!(
            xml.contains("<StandardBusinessDocumentHeader>"),
            "header element present"
        );
        assert!(
            xml.contains("<HeaderVersion>1.0</HeaderVersion>"),
            "header version"
        );
        assert!(xml.contains("0007:1234567890"), "sender id");
        assert!(xml.contains("0007:9876543210"), "receiver id");
        assert!(xml.contains("Invoice"), "doc type");
        assert!(xml.contains("<Invoice"), "payload embedded");
    }

    #[test]
    fn unwrap_recovers_header_and_payload() {
        let doc = sample_doc();
        let bytes = doc.wrap().expect("wrap");
        let parsed = StandardBusinessDocument::unwrap(&bytes).expect("unwrap");

        assert_eq!(parsed.header.header_version, "1.0");
        assert_eq!(parsed.header.sender.identifier, "0007:1234567890");
        assert_eq!(parsed.header.sender.authority, "iso6523-actorid-upis");
        assert_eq!(parsed.header.receiver.identifier, "0007:9876543210");
        assert_eq!(parsed.header.document_identification.r#type, "Invoice");
        assert_eq!(parsed.header.document_identification.type_version, "2.1");
        assert!(!parsed.header.document_identification.multiple_type);
        assert_eq!(parsed.payload, doc.payload);
    }

    #[test]
    fn round_trip_preserves_all_fields() {
        let doc = sample_doc();
        let parsed = StandardBusinessDocument::unwrap(&doc.wrap().expect("wrap")).expect("unwrap");
        assert_eq!(parsed, doc);
    }

    #[test]
    fn unwrap_returns_error_on_missing_header_close_tag() {
        let bad = b"<StandardBusinessDocument><StandardBusinessDocumentHeader>";
        let result = StandardBusinessDocument::unwrap(bad);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("StandardBusinessDocumentHeader")
                || err.code == ErrorCode::ParseFailed
        );
    }

    #[test]
    fn unwrap_returns_error_on_missing_document_close_tag() {
        let bad = b"<x/></StandardBusinessDocumentHeader>";
        let result = StandardBusinessDocument::unwrap(bad);
        assert!(result.is_err());
    }

    #[test]
    fn find_subsequence_works() {
        assert_eq!(find_subsequence(b"hello world", b"world"), Some(6));
        assert_eq!(find_subsequence(b"hello", b"xyz"), None);
        assert_eq!(find_subsequence(b"abc", b""), None);
    }

    #[test]
    fn trim_ascii_removes_whitespace() {
        assert_eq!(trim_ascii(b"  hello  "), b"hello");
        assert_eq!(trim_ascii(b"\n\t<Tag/>\n"), b"<Tag/>");
        assert_eq!(trim_ascii(b"   "), b"");
    }
}