Getting Started

Install edifact, parse your first EDIFACT interchange, and choose the feature flags you need.

On this page
  1. 1. Add the dependency
    1. Optional features
  2. 2. Parse your first EDIFACT message
  3. 3. Access segment data
  4. 4. Typed mapping with derive macros
  5. 5. Validate a message
  6. 6. Process a reader (large files)
  7. 7. Next steps

Requires Rust 1.88 or later (edition 2024).


1. Add the dependency

cargo add edifact

The default derive feature re-exports the EdifactDeserialize, EdifactSerialize, EdifactCompositeDeserialize and EdifactCompositeSerialize macros from edifact-derive.

Optional features

FeatureDefaultWhat it adds
derive✅ yesProc-macro derive for typed structs
diagnostics❌ nomiette::Diagnostic on EdifactError — human-friendly output
serde❌ noSerialize / Deserialize on ValidationReport, ValidationIssue and the envelope types
dtm❌ noDTM date/time codec for UNCL 2379 codes, no dependencies (Dates and times)
dtm-time❌ nodtm plus conversions to and from the time crate
cargo add edifact --features diagnostics   # enable diagnostics
cargo add edifact --no-default-features    # core parse + write only

2. Parse your first EDIFACT message

use edifact::from_bytes;

fn main() -> Result<(), edifact::EdifactError> {
    // Minimal ORDERS interchange (UNA is optional)
    let input = b"UNA:+.? '\
                  UNH+1+ORDERS:D:11A:UN'\
                  BGM+220+PO-4711+9'\
                  NAD+BY+4000001000002::9'\
                  UNT+4+1'";

    let segments: Vec<_> = from_bytes(input).collect::<Result<_, _>>()?;

    for seg in &segments {
        println!("{} ({} elements)", seg.tag, seg.elements.len());
    }
    // UNH (2 elements)
    // BGM (3 elements)
    // NAD (2 elements)
    // UNT (2 elements)

    Ok(())
}

from_bytes returns an iterator of Result<Segment<'_>, EdifactError>. Each Segment borrows its tag and element text from input.


3. Access segment data

use edifact::from_bytes;

fn main() -> Result<(), edifact::EdifactError> {
    let input = b"BGM+220+PO-4711+9'";
    let segs: Vec<_> = from_bytes(input).collect::<Result<_, _>>()?;
    let bgm = &segs[0];

    // element_str(n) — shorthand for component 0 of element n
    assert_eq!(bgm.element_str(0), Some("220"));
    assert_eq!(bgm.element_str(1), Some("PO-4711"));

    // get_element(n) then get_component(c) for composite access
    let doc_code = bgm
        .get_element(0)
        .and_then(|e| e.get_component(0))
        .unwrap_or_default();
    assert_eq!(doc_code, "220");

    Ok(())
}

4. Typed mapping with derive macros

Instead of accessing elements by index, declare a struct:

use edifact::{EdifactDeserialize, EdifactSerialize, from_bytes};

#[derive(Debug, EdifactDeserialize, EdifactSerialize)]
#[edifact(segment = "BGM")]
struct Bgm {
    #[edifact(element = 0)]
    document_name_code: String,
    #[edifact(element = 1)]
    document_number: String,
    #[edifact(element = 2)]
    function_code: Option<String>,
}

fn main() -> Result<(), edifact::EdifactError> {
    let input = b"BGM+220+PO-4711+9'";
    let segs: Vec<_> = from_bytes(input).collect::<Result<_, _>>()?;
    let bgm = Bgm::edifact_deserialize(&segs)?;

    println!("doc_code={}", bgm.document_name_code);
    println!("doc_number={}", bgm.document_number);
    Ok(())
}

→ Full derive reference: Typed Derive


5. Validate a message

use edifact::{
    ValidationContext, ValidationLayer, Validator, ValidationReport, ValidationRuleContext,
    Segment, from_bytes,
};

struct MyValidator;

impl Validator for MyValidator {
    fn validate_batch(
        &self,
        _segments: &[Segment<'_>],
        _report: &mut ValidationReport,
        _context: &ValidationRuleContext<'_>,
    ) {
        // your validation logic here
    }
}

fn main() -> Result<(), edifact::EdifactError> {
    let input = b"UNH+1+ORDERS:D:11A:UN'BGM+220+PO-4711+9'UNT+3+1'";
    let segs: Vec<_> = from_bytes(input).collect::<Result<_, _>>()?;

    let ctx = ValidationContext::builder()
        .with_message_type("ORDERS")
        .with_validator(ValidationLayer::Structure, MyValidator)
        .build();

    let report = ctx.validate(&segs);
    if report.is_valid() {
        println!("valid");
    } else {
        for issue in report.errors() {
            eprintln!("{}", issue.message);
        }
    }
    Ok(())
}

→ Full validation guide: Validation


6. Process a reader (large files)

use edifact::from_reader;
use std::fs::File;

fn main() -> Result<(), edifact::EdifactError> {
    let f = File::open("interchange.edi")?;
    for result in from_reader(f) {
        let segment = result?;
        println!("{}", segment.tag);
    }
    Ok(())
}

from_reader yields one OwnedSegment (Segment<'static>) at a time without buffering the file. Every entry point is bounded by default: 64 KiB per segment, 16 MiB per message, 256 MiB of input (E036 beyond).

→ Full streaming guide: Streaming


7. Next steps

GoalGuide
Understand UNA, delimiters, release charsCore Concepts
Parse byte slices efficientlyParsing
Write EDIFACT output, build an interchangeWriting
Derive typed structs for segments and messagesTyped Derive
Stream multi-message interchangesStreaming
Validate envelope, syntax and structureValidation
Validate segment-group structureSegment Groups
Decode and compare DTM valuesDates and times
Add business-rule validationProfile Packs
Acknowledge with CONTRLCONTRL
Pretty-print errors in a CLIDiagnostics
Integrate with async / tokioAsync Integration