edifact-rs 0.5.0

Zero-copy EDIFACT parser, writer, serde traits, and extensible validation 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
use smallvec::SmallVec;
use std::borrow::Cow;

/// A half-open byte span within an EDIFACT payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Span {
    /// Start byte offset (inclusive).
    pub start: usize,
    /// End byte offset (exclusive).
    pub end: usize,
}

impl Span {
    #[inline]
    /// Construct a span from inclusive start and exclusive end offsets.
    pub const fn new(start: usize, end: usize) -> Self {
        Self { start, end }
    }

    #[inline]
    /// Shift the span by `delta` bytes.
    pub const fn offset(self, delta: usize) -> Self {
        Self {
            start: self.start + delta,
            end: self.end + delta,
        }
    }

    /// Length of the span in bytes.
    #[inline]
    pub const fn len(self) -> usize {
        self.end - self.start
    }

    /// Returns `true` if the span covers zero bytes.
    #[inline]
    pub const fn is_empty(self) -> bool {
        self.start == self.end
    }
}

impl std::fmt::Display for Span {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}..{}", self.start, self.end)
    }
}

/// A single EDIFACT segment, borrowing its data from the source input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Segment<'a> {
    /// Segment tag, usually three uppercase letters.
    pub tag: &'a str,
    /// Span covering the whole segment payload.
    pub span: Span,
    /// Span covering only the segment tag.
    pub tag_span: Span,
    /// Segment elements in positional order.
    pub elements: Vec<Element<'a>>,
}

impl<'a> Segment<'a> {
    #[inline]
    /// Construct a segment with default spans.
    pub fn new(tag: &'a str, elements: Vec<Element<'a>>) -> Self {
        Self {
            tag,
            span: Span::default(),
            tag_span: Span::default(),
            elements,
        }
    }

    /// Return the element at position `n` (0-indexed), if it exists.
    #[inline]
    pub fn get_element(&self, n: usize) -> Option<&Element<'a>> {
        self.elements.get(n)
    }

    /// Shorthand: get component 0 of element `n` — the most common access pattern.
    #[inline]
    pub fn element_str(&self, n: usize) -> Option<&str> {
        self.elements.get(n)?.get_component(0)
    }

    /// Return the byte span of the element at position `n`, if it exists.
    #[inline]
    pub fn element_span(&self, n: usize) -> Option<Span> {
        Some(self.elements.get(n)?.span)
    }
}

/// A data element, which may have one or more component values.
///
/// Uses [`SmallVec`] with an inline capacity of 4 to avoid heap allocation
/// for the common case (≤ 4 components).  Component values borrow from the
/// original input; if the value contained a release-character sequence the
/// resolved string is stored as an owned [`Cow::Owned`] variant instead of
/// using `Box::leak`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Element<'a> {
    /// Span covering the whole element.
    pub span: Span,
    /// Element components in positional order.
    pub components: SmallVec<[Cow<'a, str>; 4]>,
    /// Byte spans for each component in [`Self::components`].
    pub component_spans: SmallVec<[Span; 4]>,
}

impl<'a> Element<'a> {
    /// Return the component at position `n` (0-indexed), if it exists.
    #[inline]
    pub fn get_component(&self, n: usize) -> Option<&str> {
        self.components.get(n).map(|c| c.as_ref())
    }

    /// Return the component at position `n`, or `""` if absent.
    #[inline]
    pub fn component_or_empty(&self, n: usize) -> &str {
        self.components.get(n).map(|c| c.as_ref()).unwrap_or("")
    }

    /// Return the byte span of the component at position `n`, if it exists.
    #[inline]
    pub fn component_span(&self, n: usize) -> Option<Span> {
        self.component_spans.get(n).copied()
    }

    /// Convenience constructor: wraps string literals as borrowed components.
    ///
    /// Useful in tests and when constructing segments for writing.
    pub fn of(components: &[&'a str]) -> Self {
        Self {
            span: Span::default(),
            components: components.iter().copied().map(Cow::Borrowed).collect(),
            component_spans: std::iter::repeat_n(Span::default(), components.len()).collect(),
        }
    }
}

/// Owned data element used by reader-based parsing APIs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnedElement {
    /// Span covering the whole element.
    pub span: Span,
    /// Owned element components in positional order.
    pub components: SmallVec<[String; 4]>,
    /// Byte spans for each component in [`Self::components`].
    pub component_spans: SmallVec<[Span; 4]>,
}

impl OwnedElement {
    #[inline]
    /// Shift all stored spans by `delta` bytes.
    pub fn offset(mut self, delta: usize) -> Self {
        self.span = self.span.offset(delta);
        for span in &mut self.component_spans {
            *span = span.offset(delta);
        }
        self
    }
}

impl<'a> From<Element<'a>> for OwnedElement {
    fn from(value: Element<'a>) -> Self {
        Self {
            span: value.span,
            components: value
                .components
                .into_iter()
                .map(|component| component.into_owned())
                .collect(),
            component_spans: value.component_spans,
        }
    }
}

/// Owned segment used by reader-based parsing APIs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnedSegment {
    /// Segment tag, usually three uppercase letters.
    pub tag: String,
    /// Span covering the whole segment payload.
    pub span: Span,
    /// Span covering only the segment tag.
    pub tag_span: Span,
    /// Owned segment elements in positional order.
    pub elements: Vec<OwnedElement>,
}

/// Zero-allocation view of an [`OwnedElement`].
///
/// Implements the same accessor methods as [`Element`] without constructing
/// any intermediate `SmallVec` or `Cow` values.  Use this when you hold an
/// `&OwnedSegment` reference and want to inspect element data without the
/// `Vec<Element>` allocation that [`OwnedSegment::as_borrowed`] incurs.
///
/// Construct via `BorrowedElement::from(&owned_element)` or through
/// [`BorrowedSegment::get_element`].
#[derive(Debug, Clone, Copy)]
pub struct BorrowedElement<'a>(pub(crate) &'a OwnedElement);

impl<'a> From<&'a OwnedElement> for BorrowedElement<'a> {
    #[inline]
    fn from(elem: &'a OwnedElement) -> Self {
        BorrowedElement(elem)
    }
}

impl<'a> BorrowedElement<'a> {
    /// Return the component at position `n` (0-indexed), if it exists.
    #[inline]
    pub fn get_component(&self, n: usize) -> Option<&'a str> {
        self.0.components.get(n).map(|s| s.as_str())
    }

    /// Return the component at position `n`, or `""` if absent.
    #[inline]
    pub fn component_or_empty(&self, n: usize) -> &'a str {
        self.0.components.get(n).map(|s| s.as_str()).unwrap_or("")
    }

    /// Return the byte span of the component at position `n`, if it exists.
    #[inline]
    pub fn component_span(&self, n: usize) -> Option<Span> {
        self.0.component_spans.get(n).copied()
    }

    /// The byte span covering the whole element.
    #[inline]
    pub fn span(&self) -> Span {
        self.0.span
    }

    /// Number of components in this element.
    #[inline]
    pub fn len(&self) -> usize {
        self.0.components.len()
    }

    /// Returns `true` if this element has no components.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0.components.is_empty()
    }

    /// Iterate over all component strings.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = &'a str> {
        self.0.components.iter().map(|c| c.as_str())
    }
}

/// Zero-allocation view of an [`OwnedSegment`].
///
/// Implements the same accessor methods as [`Segment`] without constructing
/// a `Vec<Element>`.  Use this when you hold an `&OwnedSegment` reference and
/// want to read data without the allocations incurred by
/// [`OwnedSegment::as_borrowed`].
///
/// # Construction
///
/// The idiomatic way to obtain a `BorrowedSegment` is via [`OwnedSegment::borrow`]
/// or the [`From`] impl:
///
/// ```rust
/// use edifact_rs::{BorrowedSegment, OwnedSegment, Span};
///
/// let seg = OwnedSegment {
///     tag: "BGM".into(),
///     span: Span::new(0, 3),
///     tag_span: Span::new(0, 3),
///     elements: vec![],
/// };
/// let borrowed = BorrowedSegment::from(&seg);
/// assert_eq!(borrowed.tag(), "BGM");
/// ```
///
/// The `'a` lifetime is tied to the referent — you cannot outlive the
/// `OwnedSegment` you borrowed from.
#[derive(Debug, Clone, Copy)]
pub struct BorrowedSegment<'a>(pub(crate) &'a OwnedSegment);

impl<'a> From<&'a OwnedSegment> for BorrowedSegment<'a> {
    #[inline]
    fn from(seg: &'a OwnedSegment) -> Self {
        BorrowedSegment(seg)
    }
}

impl<'a> BorrowedSegment<'a> {
    /// The segment tag (e.g. `"BGM"`).
    #[inline]
    pub fn tag(&self) -> &'a str {
        &self.0.tag
    }

    /// Byte span covering the whole segment.
    #[inline]
    pub fn span(&self) -> Span {
        self.0.span
    }

    /// Byte span covering only the segment tag.
    #[inline]
    pub fn tag_span(&self) -> Span {
        self.0.tag_span
    }

    /// Return the element at position `n` (0-indexed), if it exists.
    #[inline]
    pub fn get_element(&self, n: usize) -> Option<BorrowedElement<'a>> {
        self.0.elements.get(n).map(BorrowedElement)
    }

    /// Shorthand: first component of element `n` — the most common access pattern.
    #[inline]
    pub fn element_str(&self, n: usize) -> Option<&'a str> {
        self.0.elements.get(n)?.components.first().map(|c| c.as_str())
    }

    /// Return the byte span of the element at position `n`, if it exists.
    #[inline]
    pub fn element_span(&self, n: usize) -> Option<Span> {
        Some(self.0.elements.get(n)?.span)
    }

    /// Iterate over all elements as zero-allocation views.
    #[inline]
    pub fn elements(&self) -> impl Iterator<Item = BorrowedElement<'a>> {
        self.0.elements.iter().map(BorrowedElement)
    }
}

impl OwnedSegment {
    /// Get the first component of element `n`, or `None` if absent.
    ///
    /// This is the zero-allocation equivalent of `as_borrowed().element_str(n)`.
    /// Used internally by [`crate::find_segment_owned`] and the derived
    /// [`crate::EdifactDeserialize::edifact_deserialize_owned`] implementations.
    #[inline]
    pub fn element_str(&self, n: usize) -> Option<&str> {
        self.elements.get(n)?.components.first().map(|s| s.as_str())
    }

    /// Get component `comp` of element `elem`, or `None` if absent.
    ///
    /// Zero-allocation equivalent of `as_borrowed().get_element(elem)?.get_component(comp)`.
    #[inline]
    pub fn component_str(&self, elem: usize, comp: usize) -> Option<&str> {
        self.elements.get(elem)?.components.get(comp).map(|s| s.as_str())
    }

    #[inline]
    /// Shift all stored spans by `delta` bytes.
    pub fn offset(mut self, delta: usize) -> Self {
        self.span = self.span.offset(delta);
        self.tag_span = self.tag_span.offset(delta);
        for element in &mut self.elements {
            element.span = element.span.offset(delta);
            for span in &mut element.component_spans {
                *span = span.offset(delta);
            }
        }
        self
    }

    #[inline]
    /// View this owned segment as a borrowed [`Segment`].
    ///
    /// **Performance note**: allocates a `Vec<Element<'_>>` on every call.
    /// When only individual field access is needed, prefer
    /// [`OwnedSegment::borrow`] → [`BorrowedSegment`] which is O(1).
    /// `as_borrowed` remains necessary when the callee requires `&[Segment<'_>]`.
    pub fn as_borrowed(&self) -> Segment<'_> {
        Segment {
            tag: self.tag.as_str(),
            span: self.span,
            tag_span: self.tag_span,
            elements: self
                .elements
                .iter()
                .map(|elem| Element {
                    span: elem.span,
                    components: elem
                        .components
                        .iter()
                        .map(|c| Cow::Borrowed(c.as_str()))
                        .collect(),
                    component_spans: elem.component_spans.clone(),
                })
                .collect(),
        }
    }

    /// Return a zero-allocation view of this segment.
    ///
    /// Unlike [`as_borrowed`][OwnedSegment::as_borrowed], this is `O(1)` and
    /// performs no heap allocation.  The view cannot be passed to APIs that
    /// require `&[Segment<'_>]`; use [`as_borrowed`][OwnedSegment::as_borrowed]
    /// for those call sites.
    #[inline]
    pub fn borrow(&self) -> BorrowedSegment<'_> {
        BorrowedSegment(self)
    }
}

impl<'a> From<Segment<'a>> for OwnedSegment {
    fn from(value: Segment<'a>) -> Self {
        Self {
            tag: value.tag.to_string(),
            span: value.span,
            tag_span: value.tag_span,
            elements: value.elements.into_iter().map(OwnedElement::from).collect(),
        }
    }
}