cmw 0.1.2

Rust implementation of CMW
Documentation
// Copyright 2025 Contributors to the Veraison project.
// SPDX-License-Identifier: Apache-2.0

use std::env;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
use xml::reader::{EventReader, XmlEvent};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    if !cfg!(feature = "rebuild-cfmap") {
        return Ok(());
    }
    // --- 1. Download XML content ---
    let url = "https://www.iana.org/assignments/core-parameters/core-parameters.xml";
    let client = reqwest::blocking::Client::builder()
        .user_agent("rust-iana-parser/1.0")
        .build()?;
    let response = client.get(url).send()?.error_for_status()?;

    // --- 2. Parse the XML stream ---
    let parser = EventReader::new(response);
    let mut in_content_formats_registry = false;
    let mut current_tag = String::new();
    let mut content_type = String::new();
    let mut content_id = String::new();
    let mut entries: Vec<(String, u16)> = Vec::new();

    for e in parser {
        match e {
            Ok(XmlEvent::StartElement {
                name, attributes, ..
            }) => {
                if !in_content_formats_registry && name.local_name == "registry" {
                    if let Some(id_attr) =
                        attributes.iter().find(|&attr| attr.name.local_name == "id")
                    {
                        if id_attr.value == "content-formats" {
                            in_content_formats_registry = true;
                        }
                    }
                } else if in_content_formats_registry {
                    if name.local_name == "record" {
                        content_type.clear();
                        content_id.clear();
                    }
                    current_tag = name.local_name;
                }
            }
            Ok(XmlEvent::EndElement { name }) => {
                if in_content_formats_registry {
                    if name.local_name == "registry" {
                        break;
                    }
                    if name.local_name == "record"
                        && !content_id.contains('-')
                        && !content_type.to_lowercase().contains("unassigned")
                        && !content_type.to_lowercase().contains("reserved")
                    {
                        if let Ok(id_val) = content_id.parse::<u16>() {
                            entries.push((content_type.clone(), id_val));
                        }
                    }
                }
                current_tag.clear();
            }
            Ok(XmlEvent::Characters(s)) if in_content_formats_registry => {
                match current_tag.as_str() {
                    "contenttype" => content_type.push_str(&s),
                    "id" => content_id.push_str(&s),
                    _ => {}
                }
            }
            Err(e) => {
                eprintln!("XML parsing error: {}", e);
                break;
            }
            _ => {}
        }
    }

    // --- 3. Write the generated code to cfmap.rs in OUT_DIR ---
    let out_dir = env::var("OUT_DIR")?;
    let dest_path = Path::new(&out_dir).join("cfmap.rs");
    let mut f = BufWriter::new(File::create(dest_path)?);

    writeln!(f, "// Generated by build.rs from IANA XML")?;
    writeln!(f, "use once_cell::sync::Lazy;")?;
    writeln!(f, "use std::collections::HashMap;")?;

    // --- Write the MT_TO_CF (forward) map ---
    writeln!(
        f,
        "\npub static MT_TO_CF: Lazy<HashMap<&'static str, u16>> = Lazy::new(|| {{"
    )?;
    writeln!(f, "    let mut m = HashMap::new();")?;
    for (ct, id) in &entries {
        if ct.contains('"') {
            writeln!(f, r##"    m.insert(r#"{}"#, {});"##, ct, id)?;
        } else {
            writeln!(f, r#"    m.insert("{}", {});"#, ct, id)?;
        }
    }
    writeln!(f, "    m")?;
    writeln!(f, "}});")?;

    // --- Write the CF_TO_MT (reverse) map ---
    writeln!(
        f,
        "\npub static CF_TO_MT: Lazy<HashMap<u16, &'static str>> = Lazy::new(|| {{"
    )?;
    writeln!(f, "    let mut m = HashMap::new();")?;
    // Use the same `entries` vector. HashMap::insert will handle duplicates by keeping the last one seen.
    for (ct, id) in entries {
        if ct.contains('"') {
            writeln!(f, r##"    m.insert({}, r#"{}"#);"##, id, ct)?;
        } else {
            writeln!(f, r#"    m.insert({}, "{}");"#, id, ct)?;
        }
    }
    writeln!(f, "    m")?;
    writeln!(f, "}});")?;

    // Tell cargo to re-run this script only if it changes.
    println!("cargo:rerun-if-changed=build.rs");

    Ok(())
}