use crate::{Builder, Document, Error, Limits, NodeId};
const CONTAINER: &str = "fragment";
#[derive(Clone, Debug)]
pub struct Fragment {
document: Document,
nodes: Vec<NodeId>,
}
impl Fragment {
#[must_use]
pub const fn document(&self) -> &Document {
&self.document
}
#[must_use]
pub fn nodes(&self) -> &[NodeId] {
&self.nodes
}
}
impl Document {
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)
}
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 })
}
}
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}"))
}