f-office-xml 0.2.3

Minimal read-only XML tree for Office Open XML and SVG parts.
Documentation
//! A fragment of XML, parsed as the content of an element of another document, with the
//! namespace declarations in scope there.

use crate::{Builder, Document, Error, Limits, NodeId};

/// The name of the element that holds a fragment while it is parsed.
const CONTAINER: &str = "fragment";

/// XML parsed as the content of an element of another document ([`Document::parse_fragment`]):
/// a document whose nodes stand for the fragment's, in order.
#[derive(Clone, Debug)]
pub struct Fragment {
    document: Document,
    nodes: Vec<NodeId>,
}

impl Fragment {
    /// The document that holds the fragment's nodes. Its spans count from the fragment's
    /// first byte.
    #[must_use]
    pub const fn document(&self) -> &Document {
        &self.document
    }

    /// The fragment's nodes at its top, in order: its elements, text, comments and processing
    /// instructions.
    #[must_use]
    pub fn nodes(&self) -> &[NodeId] {
        &self.nodes
    }
}

impl Document {
    /// Parses `bytes` as the content of an element at which the namespace declarations
    /// `in_scope` are in scope, such as the bytes of an element's span or the new XML of an
    /// edit in its place: each prefix (`""` for the default namespace) with its URI, as
    /// [`Document::namespaces_in_scope`] gives them. Each URI binds as given: the reader binds
    /// a namespace to its declaration's value as written, with no reference resolved, so a
    /// URI of a part binds the same in the fragment. A prefix that neither the fragment nor
    /// `in_scope` declares is an error here, unlike in a part, because the fragment is to
    /// stand in a part where it must read.
    ///
    /// # Errors
    ///
    /// Returns [`Error::UndeclaredPrefix`] for a prefix without a declaration, and every error
    /// of [`Document::parse`]; a prefix of `in_scope` that is no name, a URI that holds both
    /// quotation marks, and a fragment that closes the element that it stands in, are
    /// [`Error::Syntax`].
    pub fn parse_fragment(
        bytes: &[u8],
        in_scope: &[(String, String)],
        limits: &Limits,
    ) -> Result<Fragment, Error> {
        let fragment = Self::parse_fragment_with_aliases_at(bytes, in_scope, &[], 0, limits)?;
        if let Some(prefix) = fragment.document.undeclared_prefixes.first() {
            return Err(Error::UndeclaredPrefix(prefix.clone()));
        }
        Ok(fragment)
    }

    /// Parses `bytes` as a slice of a larger XML part starting at `base_offset`, resolving
    /// namespace declarations `in_scope` and namespace `aliases`, while recording undeclared
    /// prefixes on [`Document::undeclared_prefixes`] instead of failing.
    ///
    /// Node byte spans returned by [`Document::span`] are shifted by `base_offset` so they match
    /// exact byte offsets in the enclosing part.
    ///
    /// # Errors
    ///
    /// Returns the errors of [`Document::parse_with_aliases`], or [`Error::Syntax`] when
    /// `in_scope` contains an invalid prefix/URI or `bytes` closes the synthetic container.
    pub fn parse_fragment_with_aliases_at(
        bytes: &[u8],
        in_scope: &[(String, String)],
        aliases: &[(&str, &str)],
        base_offset: u64,
        limits: &Limits,
    ) -> Result<Fragment, Error> {
        let mut container = format!("<{CONTAINER}");
        for (prefix, uri) in in_scope {
            if prefix != "xml" && prefix != "xmlns" {
                container.push_str(&declaration(prefix, uri)?);
            }
        }
        container.push('>');
        let offset = container.len();
        let mut wrapped = container.into_bytes();
        wrapped.extend_from_slice(bytes);
        wrapped.extend_from_slice(format!("</{CONTAINER}>").as_bytes());
        let mut builder = Builder::new(*limits, aliases);
        builder.offset = offset as u64;
        builder.base_offset = base_offset;
        let document = builder.run(&wrapped)?;
        let [container] = document.top.as_slice() else {
            return Err(Error::Syntax(
                "the fragment closes the element that it stands in".to_owned(),
            ));
        };
        let nodes = document.children(*container).to_vec();
        Ok(Fragment { document, nodes })
    }
}

/// The attribute that declares `prefix` (`""` for the default namespace) with `uri` as written,
/// in a quotation mark that the URI does not hold.
fn declaration(prefix: &str, uri: &str) -> Result<String, Error> {
    if !prefix
        .chars()
        .all(|ch| ch.is_alphanumeric() || matches!(ch, '_' | '-' | '.'))
    {
        return Err(Error::Syntax(format!(
            "{prefix:?} is not a namespace prefix"
        )));
    }
    let quote = match (uri.contains('"'), uri.contains('\'')) {
        (false, _) => '"',
        (true, false) => '\'',
        (true, true) => {
            return Err(Error::Syntax(
                "a namespace URI holds both quotation marks".to_owned(),
            ));
        }
    };
    let name = if prefix.is_empty() {
        "xmlns".to_owned()
    } else {
        format!("xmlns:{prefix}")
    };
    Ok(format!(" {name}={quote}{uri}{quote}"))
}