1use crate::EdifactError;
8use crate::event::{EdifactEvent, EventEmitter, WriterEmitter};
9use std::io::Write;
10
11pub trait EdifactSerialize {
18 fn edifact_serialize<E: EventEmitter>(&self, emitter: &mut E) -> Result<(), EdifactError>;
20}
21
22pub trait EdifactCompositeSerialize {
27 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
51impl 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
69impl<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
79impl<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
89impl<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 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 let s = std::str::from_utf8(&buf[..written]).map_err(|_| EdifactError::InvalidUtf8)?;
112 emitter.emit(EdifactEvent::Element { value: s })
113 } else {
114 let s = format!("{self}");
116 emitter.emit(EdifactEvent::Element { value: &s })
117 }
118 }
119 }
120 )+
121 };
122}
123
124impl_serialize_int!(
126 u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, bool
127);
128
129#[derive(Debug, Clone, Copy, PartialEq)]
158pub struct DecimalFloat<T>(pub T);
159
160#[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 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 let s = std::str::from_utf8(&buf[..written]).map_err(|_| EdifactError::InvalidUtf8)?;
182 return emitter.emit(EdifactEvent::Element { value: s });
183 }
184 let s = format!("{display}");
186 return emitter.emit(EdifactEvent::Element { value: &s });
187 }
188
189 let s = format!("{display}");
192 if s.contains('.') {
193 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
224pub 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 let mut cursor = 0usize;
279 let element_count = parts.last().map_or(0, |(element, _, _)| *element + 1);
280 for element in 0..element_count {
281 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 cursor += 1;
290 continue;
291 }
292 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 emitter.emit(EdifactEvent::Element { value: "" })?;
317 }
318 }
319
320 emitter.emit(EdifactEvent::EndSegment)
321}
322
323pub 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
334pub 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
341pub 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 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 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 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 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 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 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}