Skip to main content

edifact_rs/
ser.rs

1//! Custom serialization trait for EDIFACT.
2//!
3//! [`EdifactSerialize`] emits typed EDIFACT events rather than the generic
4//! key/value tokens of standard `serde`.  This matches EDIFACT's positional,
5//! qualifier-based data model — see `docs/writing.md` for the design rationale.
6
7use crate::EdifactError;
8use crate::event::{EdifactEvent, EventEmitter, WriterEmitter};
9use std::io::Write;
10
11// ── trait ─────────────────────────────────────────────────────────────────────
12
13/// Types that can serialize themselves to an EDIFACT event stream.
14///
15/// Implement manually or derive with `#[derive(EdifactSerialize)]` from the
16/// `edifact-rs-derive` crate.
17pub trait EdifactSerialize {
18    /// Serialize `self` by emitting events into `emitter`.
19    fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError>;
20}
21
22/// Types that can serialize themselves as a composite EDIFACT element.
23///
24/// Implement this for custom composite structs used with
25/// `#[edifact(composite)]` in derive macros.
26pub trait EdifactCompositeSerialize {
27    /// Serialize `self` as one composite element into `emitter`.
28    fn edifact_serialize_composite<E: EventEmitter>(
29        &self,
30        emitter: &mut E,
31    ) -> Result<(), EdifactError>;
32}
33
34impl EdifactCompositeSerialize for Vec<String> {
35    fn edifact_serialize_composite<E: EventEmitter>(
36        &self,
37        emitter: &mut E,
38    ) -> Result<(), EdifactError> {
39        if self.is_empty() {
40            return emitter.emit(EdifactEvent::Element { value: "" });
41        }
42
43        emitter.emit(EdifactEvent::Element { value: &self[0] })?;
44        for component in self.iter().skip(1) {
45            emitter.emit(EdifactEvent::ComponentElement { value: component })?;
46        }
47        Ok(())
48    }
49}
50
51// ── blanket impls for scalar types ────────────────────────────────────────────
52
53impl EdifactSerialize for str {
54    #[inline]
55    fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError> {
56        emitter.emit(EdifactEvent::Element { value: self })
57    }
58}
59
60impl EdifactSerialize for String {
61    #[inline]
62    fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError> {
63        emitter.emit(EdifactEvent::Element {
64            value: self.as_str(),
65        })
66    }
67}
68
69/// `None` → empty element `""`; `Some(v)` → `v.edifact_serialize(emitter)`.
70impl<T: EdifactSerialize> EdifactSerialize for Option<T> {
71    fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError> {
72        match self {
73            Some(v) => v.edifact_serialize(emitter),
74            None => emitter.emit(EdifactEvent::Element { value: "" }),
75        }
76    }
77}
78
79/// Each element is serialized independently (repeated segments for groups).
80impl<T: EdifactSerialize> EdifactSerialize for Vec<T> {
81    fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError> {
82        for item in self {
83            item.edifact_serialize(emitter)?;
84        }
85        Ok(())
86    }
87}
88
89/// Each element is serialized independently (repeated segments for groups).
90impl<T: EdifactSerialize> EdifactSerialize for [T] {
91    fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError> {
92        for item in self {
93            item.edifact_serialize(emitter)?;
94        }
95        Ok(())
96    }
97}
98
99macro_rules! impl_serialize_int {
100    ($($t:ty),+ $(,)?) => {
101        $(
102            impl EdifactSerialize for $t {
103                fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError> {
104                    // 42-byte buffer: i128::MIN is 40 chars; 2 spare bytes as safety margin.
105                    use std::io::Write as _;
106                    let mut buf = [0u8; 42];
107                    let mut w: &mut [u8] = &mut buf;
108                    if write!(w, "{self}").is_ok() {
109                        let written = 42 - w.len();
110                        // Display output for all integer/bool types is ASCII-only.
111                        let s = std::str::from_utf8(&buf[..written]).map_err(|_| EdifactError::InvalidUtf8)?;
112                        emitter.emit(EdifactEvent::Element { value: s })
113                    } else {
114                        // Extraordinary case: fall back to heap to avoid any panic.
115                        let s = format!("{self}");
116                        emitter.emit(EdifactEvent::Element { value: &s })
117                    }
118                }
119            }
120        )+
121    };
122}
123
124// Boolean is also bounded (max "false" = 5 bytes).
125impl_serialize_int!(
126    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, bool
127);
128
129// ── decimal-mark-aware float wrapper ─────────────────────────────────────────
130
131/// Decimal-mark-aware wrapper for `f32` or `f64` serialization.
132///
133/// Rust's [`Display`][std::fmt::Display] for `f32`/`f64` always uses `.` as the
134/// decimal separator.  EDIFACT interchanges can declare a different decimal mark
135/// in the UNA service string — most commonly `,` in German EDI\@Energy messages.
136///
137/// # Required for float serialization
138///
139/// `edifact-rs` intentionally provides **no** blanket `EdifactSerialize` impl for
140/// `f32`/`f64`.  This forces callers to make the decimal-mark intent explicit:
141///
142/// ```
143/// use edifact_rs::ser::DecimalFloat;
144/// use edifact_rs::{EdifactSerialize, VecEmitter, OwnedEdifactEvent};
145///
146/// let mut emitter = VecEmitter::default();
147/// DecimalFloat(12.5_f64).edifact_serialize(&mut emitter).unwrap();
148/// assert!(matches!(&emitter.events[0], OwnedEdifactEvent::Element { value } if value == "12.5"));
149/// ```
150///
151/// When the emitter's [`EventEmitter::decimal_mark`] is `b','`, the output will be `"12,5"`.
152///
153/// # Supported inner types
154///
155/// `DecimalFloat<f32>`, `DecimalFloat<f64>`. For any type that implements
156/// [`std::fmt::Display`], use [`DecimalFloatDisplay`] instead.
157#[derive(Debug, Clone, Copy, PartialEq)]
158pub struct DecimalFloat<T>(pub T);
159
160/// Decimal-mark-aware serializer for any [`std::fmt::Display`] value.
161///
162/// Like [`DecimalFloat`] but works with any type whose `Display` uses `.` as a
163/// decimal point (e.g., `rust_decimal::Decimal`, `bigdecimal::BigDecimal`).
164#[derive(Debug, Clone, Copy, PartialEq)]
165pub struct DecimalFloatDisplay<T: std::fmt::Display>(pub T);
166
167fn serialize_with_decimal_mark<E: EventEmitter>(
168    display: &dyn std::fmt::Display,
169    emitter: &mut E,
170) -> Result<(), EdifactError> {
171    use std::io::Write as _;
172    let mark = emitter.decimal_mark();
173
174    // Fast path: standard interchange — avoid any string manipulation.
175    if mark == b'.' {
176        let mut buf = [0u8; 320];
177        let mut w: &mut [u8] = &mut buf;
178        if write!(w, "{display}").is_ok() {
179            let written = 320 - w.len();
180            // INVARIANT: float Display output is ASCII-only.
181            let s = std::str::from_utf8(&buf[..written]).map_err(|_| EdifactError::InvalidUtf8)?;
182            return emitter.emit(EdifactEvent::Element { value: s });
183        }
184        // Buffer overflow fallback (extraordinarily large exponent).
185        let s = format!("{display}");
186        return emitter.emit(EdifactEvent::Element { value: &s });
187    }
188
189    // Non-standard decimal mark: format as string then replace '.'.
190    // INVARIANT: `mark` is ASCII (validated by ServiceStringAdvice::is_valid()).
191    let s = format!("{display}");
192    if s.contains('.') {
193        // Encode `mark` as a 1–4 byte UTF-8 slice on the stack; no heap allocation.
194        let mut mark_buf = [0u8; 4];
195        let mark_str = (mark as char).encode_utf8(&mut mark_buf);
196        let replaced = s.replace('.', mark_str);
197        emitter.emit(EdifactEvent::Element { value: &replaced })
198    } else {
199        emitter.emit(EdifactEvent::Element { value: &s })
200    }
201}
202
203impl EdifactSerialize for DecimalFloat<f32> {
204    #[inline]
205    fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError> {
206        serialize_with_decimal_mark(&self.0, emitter)
207    }
208}
209
210impl EdifactSerialize for DecimalFloat<f64> {
211    #[inline]
212    fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError> {
213        serialize_with_decimal_mark(&self.0, emitter)
214    }
215}
216
217impl<T: std::fmt::Display> EdifactSerialize for DecimalFloatDisplay<T> {
218    #[inline]
219    fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError> {
220        serialize_with_decimal_mark(&self.0, emitter)
221    }
222}
223
224/// Emit one segment from `(element_index, component_index, value)` triples.
225///
226/// Values may arrive in any order and need not cover every slot: the triples
227/// are sorted, gaps are filled with empty elements and components, and the
228/// result is a single well-formed segment.
229///
230/// This exists because a derive that addresses fields by UN/EDIFACT data element
231/// identifier (`#[edifact(element = "3055")]`) only learns the numeric slots
232/// during *const evaluation*, after the macro has already expanded — so it
233/// cannot lay out the emit order at expansion time the way a positional derive
234/// can.  Handing the resolved slots to this function moves the ordering to
235/// runtime, where they are known.
236///
237/// `parts` is taken by mutable reference because it is sorted in place; the
238/// caller keeps the allocation.
239///
240/// If two triples claim the same slot the **first** one wins and the rest are
241/// dropped — emitting both would shift every following component by one and
242/// silently corrupt the segment's positions. (The derive cannot produce a
243/// duplicate: it rejects colliding slots at compile time.)
244///
245/// # Example
246///
247/// ```rust
248/// use edifact_rs::{VecEmitter, emit_sparse_segment};
249/// use std::borrow::Cow;
250///
251/// let mut parts = vec![
252///     (1, 2, Cow::Borrowed("293")),
253///     (0, 0, Cow::Borrowed("MS")),
254///     (1, 0, Cow::Borrowed("9900112233445")),
255/// ];
256/// let mut emitter = VecEmitter::default();
257/// emit_sparse_segment(&mut emitter, "NAD", &mut parts)?;
258/// // Slot (1, 1) was never supplied, so it is emitted as an empty component:
259/// // NAD+MS+9900112233445::293'
260/// assert_eq!(emitter.events.len(), 6);
261/// # Ok::<(), edifact_rs::EdifactError>(())
262/// ```
263///
264/// # Errors
265///
266/// Propagates any error returned by the emitter.
267pub fn emit_sparse_segment<E: EventEmitter>(
268    emitter: &mut E,
269    tag: &str,
270    parts: &mut [(usize, usize, std::borrow::Cow<'_, str>)],
271) -> Result<(), EdifactError> {
272    parts.sort_by_key(|(element, component, _)| (*element, *component));
273
274    emitter.emit(EdifactEvent::StartSegment { tag })?;
275
276    // `parts` is sorted, so the last entry carries the highest element index and
277    // one linear walk covers every slot.
278    let mut cursor = 0usize;
279    let element_count = parts.last().map_or(0, |(element, _, _)| *element + 1);
280    for element in 0..element_count {
281        // Component 0 opens the element; every later component extends it.
282        let mut next_component = 0usize;
283        let mut opened = false;
284        while cursor < parts.len() && parts[cursor].0 == element {
285            let (_, component, value) = &parts[cursor];
286            if *component < next_component {
287                // A slot already emitted: first value wins.  Emitting this one
288                // too would push every later component one position right.
289                cursor += 1;
290                continue;
291            }
292            // Fill any skipped component slots so positions stay meaningful.
293            while next_component < *component {
294                let event = if opened {
295                    EdifactEvent::ComponentElement { value: "" }
296                } else {
297                    EdifactEvent::Element { value: "" }
298                };
299                emitter.emit(event)?;
300                opened = true;
301                next_component += 1;
302            }
303            let event = if opened {
304                EdifactEvent::ComponentElement { value }
305            } else {
306                EdifactEvent::Element { value }
307            };
308            emitter.emit(event)?;
309            opened = true;
310            next_component += 1;
311            cursor += 1;
312        }
313        if !opened {
314            // No value for this element at all — emit an empty placeholder so
315            // the following elements keep their positions.
316            emitter.emit(EdifactEvent::Element { value: "" })?;
317        }
318    }
319
320    emitter.emit(EdifactEvent::EndSegment)
321}
322
323/// Serialize `value` to the given [`Write`] implementation.
324pub fn to_writer<T, W>(inner: W, value: &T) -> Result<(), EdifactError>
325where
326    T: EdifactSerialize,
327    W: Write,
328{
329    let mut emitter = WriterEmitter::new(inner);
330    value.edifact_serialize(&mut emitter)?;
331    emitter.finish().map(|_| ())
332}
333
334/// Serialize `value` to an owned `Vec<u8>`.
335pub fn to_bytes<T: EdifactSerialize>(value: &T) -> Result<Vec<u8>, EdifactError> {
336    let mut buf = Vec::new();
337    to_writer(&mut buf, value)?;
338    Ok(buf)
339}
340
341/// Serialize `value` to a UTF-8 `String`.
342///
343/// # Allocations
344///
345/// Allocates one `Vec<u8>` via [`to_bytes`].  The subsequent conversion to
346/// `String` reuses that allocation in-place via [`String::from_utf8`] — no
347/// second allocation occurs.  When you only need raw bytes (e.g. for a network
348/// write), prefer [`to_bytes`] directly.
349pub fn to_edifact_string<T: EdifactSerialize>(value: &T) -> Result<String, EdifactError> {
350    let bytes = to_bytes(value)?;
351    String::from_utf8(bytes).map_err(|_| EdifactError::InvalidUtf8)
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357    use crate::event::{OwnedEdifactEvent, VecEmitter};
358    use std::borrow::Cow;
359
360    /// Render a sparse-emit result to wire bytes, which is what the shape of
361    /// the event stream actually has to produce.
362    fn sparse_to_wire(parts: &mut [(usize, usize, Cow<'_, str>)], tag: &str) -> String {
363        let mut buf = Vec::new();
364        {
365            let mut emitter = crate::WriterEmitter::new(&mut buf);
366            emit_sparse_segment(&mut emitter, tag, parts).expect("emit");
367            emitter.finish().expect("finish");
368        }
369        String::from_utf8(buf).expect("utf-8")
370    }
371
372    #[test]
373    fn emit_sparse_segment_fills_gaps_in_elements_and_components() {
374        let mut parts = vec![
375            (1, 2, Cow::Borrowed("293")),
376            (0, 0, Cow::Borrowed("MS")),
377            (3, 1, Cow::Borrowed("late")),
378        ];
379        // Element 2 is absent entirely, element 3 skips component 0, and
380        // element 1 skips component 1 — every gap holds its position.
381        assert_eq!(sparse_to_wire(&mut parts, "NAD"), "NAD+MS+::293++:late'");
382    }
383
384    #[test]
385    fn emit_sparse_segment_first_value_wins_on_a_duplicate_slot() {
386        // Emitting both would push `293` from component 2 to component 3 and
387        // silently corrupt every later position.
388        let mut parts = vec![
389            (0, 0, Cow::Borrowed("MS")),
390            (1, 0, Cow::Borrowed("first")),
391            (1, 0, Cow::Borrowed("second")),
392            (1, 2, Cow::Borrowed("293")),
393        ];
394        assert_eq!(sparse_to_wire(&mut parts, "NAD"), "NAD+MS+first::293'");
395    }
396
397    #[test]
398    fn emit_sparse_segment_with_no_parts_writes_a_bare_tag() {
399        assert_eq!(sparse_to_wire(&mut [], "UNS"), "UNS'");
400    }
401
402    struct BgmSegment {
403        doc_name_code: String,
404        pruef_id: String,
405        msg_function: Option<String>,
406    }
407
408    impl EdifactSerialize for BgmSegment {
409        fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError> {
410            emitter.emit(EdifactEvent::StartSegment { tag: "BGM" })?;
411            emitter.emit(EdifactEvent::Element {
412                value: &self.doc_name_code,
413            })?;
414            emitter.emit(EdifactEvent::Element {
415                value: &self.pruef_id,
416            })?;
417            self.msg_function.edifact_serialize(emitter)?;
418            emitter.emit(EdifactEvent::EndSegment)?;
419            Ok(())
420        }
421    }
422
423    #[test]
424    fn vec_emitter_captures_segment_events() {
425        let seg = BgmSegment {
426            doc_name_code: "E03".to_owned(),
427            pruef_id: "11042".to_owned(),
428            msg_function: None,
429        };
430        let mut emitter = VecEmitter::default();
431        seg.edifact_serialize(&mut emitter).unwrap();
432
433        assert_eq!(
434            emitter.events[0],
435            OwnedEdifactEvent::StartSegment {
436                tag: "BGM".to_owned()
437            }
438        );
439        assert_eq!(emitter.events.last(), Some(&OwnedEdifactEvent::EndSegment));
440    }
441
442    #[test]
443    fn to_bytes_produces_valid_edifact() {
444        let seg = BgmSegment {
445            doc_name_code: "E03".to_owned(),
446            pruef_id: "11042".to_owned(),
447            msg_function: Some("9".to_owned()),
448        };
449        let bytes = to_bytes(&seg).unwrap();
450        assert_eq!(std::str::from_utf8(&bytes).unwrap(), "BGM+E03+11042+9'");
451    }
452
453    #[test]
454    fn option_none_emits_empty_element() {
455        let val: Option<String> = None;
456        let mut emitter = VecEmitter::default();
457        val.edifact_serialize(&mut emitter).unwrap();
458        assert_eq!(
459            emitter.events[0],
460            OwnedEdifactEvent::Element {
461                value: String::new()
462            }
463        );
464    }
465
466    #[test]
467    fn option_some_emits_value() {
468        let val: Option<String> = Some("TEST".to_owned());
469        let mut emitter = VecEmitter::default();
470        val.edifact_serialize(&mut emitter).unwrap();
471        assert_eq!(
472            emitter.events[0],
473            OwnedEdifactEvent::Element {
474                value: "TEST".to_owned()
475            }
476        );
477    }
478
479    #[test]
480    fn integer_types_serialize_without_alloc() {
481        let mut emitter = VecEmitter::default();
482        42u32.edifact_serialize(&mut emitter).unwrap();
483        assert_eq!(
484            emitter.events[0],
485            OwnedEdifactEvent::Element {
486                value: "42".to_owned()
487            }
488        );
489        // i128::MIN should fit exactly in the 40-byte buffer
490        let mut emitter2 = VecEmitter::default();
491        i128::MIN.edifact_serialize(&mut emitter2).unwrap();
492        assert_eq!(
493            emitter2.events[0],
494            OwnedEdifactEvent::Element {
495                value: "-170141183460469231731687303715884105728".to_owned()
496            }
497        );
498    }
499
500    #[test]
501    fn float_extremes_do_not_panic() {
502        use super::DecimalFloat;
503        // Rust Display for f64 picks the shortest round-trip form; a 320-byte buffer covers all values.
504        let mut emitter = VecEmitter::default();
505        DecimalFloat(f64::MAX)
506            .edifact_serialize(&mut emitter)
507            .unwrap();
508        let s = match &emitter.events[0] {
509            OwnedEdifactEvent::Element { value } => value.clone(),
510            _ => panic!("expected Element event"),
511        };
512        assert!(!s.is_empty());
513        // f32::MAX too
514        let mut emitter2 = VecEmitter::default();
515        DecimalFloat(f32::MAX)
516            .edifact_serialize(&mut emitter2)
517            .unwrap();
518        assert!(matches!(
519            &emitter2.events[0],
520            OwnedEdifactEvent::Element { .. }
521        ));
522    }
523
524    #[test]
525    fn vec_serializes_each_item() {
526        let segments = vec![
527            BgmSegment {
528                doc_name_code: "E03".to_owned(),
529                pruef_id: "11042".to_owned(),
530                msg_function: None,
531            },
532            BgmSegment {
533                doc_name_code: "E01".to_owned(),
534                pruef_id: "11043".to_owned(),
535                msg_function: None,
536            },
537        ];
538        let bytes = to_bytes(&segments).unwrap();
539        let s = std::str::from_utf8(&bytes).unwrap();
540        assert!(s.contains("BGM+E03+11042"));
541        assert!(s.contains("BGM+E01+11043"));
542    }
543}