use crate::alloc_prelude::*;
use crate::document::Document;
use crate::io::destination::{DestinationExt, XmlDestination};
use crate::node::{NodeId, NodeKind};
use babbel_core::io::traits::IDestination;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CanonicalOptions {
pub with_comments: bool,
}
impl Default for CanonicalOptions {
fn default() -> Self {
Self {
with_comments: false,
}
}
}
pub struct CanonicalSerializer;
impl CanonicalSerializer {
pub const MAX_CANONICAL_DEPTH: usize = 512;
pub fn canonicalize(doc: &Document, options: &CanonicalOptions) -> String {
let mut dest = XmlDestination::new();
Self::serialize_canonical(doc, options, &mut dest);
dest.into_string()
}
pub fn serialize_canonical(
doc: &Document,
options: &CanonicalOptions,
dest: &mut dyn IDestination,
) {
if let Some(root_elem_id) = doc.root_element_id() {
Self::serialize_canonical_node(doc, root_elem_id, options, dest, 0);
}
}
fn serialize_canonical_node(
doc: &Document,
node_id: NodeId,
options: &CanonicalOptions,
dest: &mut dyn IDestination,
depth: usize,
) {
if depth > Self::MAX_CANONICAL_DEPTH {
return;
}
let node = match doc.get_node(node_id) {
Some(n) => n,
None => return,
};
match &node.kind {
NodeKind::Element { name, attributes } => {
dest.write_str("<");
dest.write_str(name);
let mut sorted_attrs = attributes.clone();
sorted_attrs.sort_by(|a, b| {
let a_is_xmlns = a.name.starts_with("xmlns");
let b_is_xmlns = b.name.starts_with("xmlns");
if a_is_xmlns && !b_is_xmlns {
core::cmp::Ordering::Less
} else if !a_is_xmlns && b_is_xmlns {
core::cmp::Ordering::Greater
} else {
a.name.cmp(&b.name)
}
});
for attr in &sorted_attrs {
dest.write_str(" ");
dest.write_str(&attr.name);
dest.write_str("=\"");
Self::write_canonical_attr(&attr.value, dest);
dest.write_str("\"");
}
dest.write_str(">");
for &child_id in &node.children {
Self::serialize_canonical_node(doc, child_id, options, dest, depth + 1);
}
dest.write_str("</");
dest.write_str(name);
dest.write_str(">");
}
NodeKind::Text(t) => {
Self::write_canonical_text(t, dest);
}
NodeKind::CData(c) => {
Self::write_canonical_text(c, dest);
}
NodeKind::Comment(com) => {
if options.with_comments {
dest.write_str("<!--");
dest.write_str(com);
dest.write_str("-->");
}
}
NodeKind::ProcessingInstruction { target, data } => {
dest.write_str("<?");
dest.write_str(target);
if !data.is_empty() {
dest.write_str(" ");
dest.write_str(data);
}
dest.write_str("?>");
}
_ => {}
}
}
fn write_canonical_text(text: &str, dest: &mut dyn IDestination) {
for ch in text.chars() {
match ch {
'&' => dest.write_str("&"),
'<' => dest.write_str("<"),
'>' => dest.write_str(">"),
'\r' => dest.write_str("
"),
_ => dest.write_char(ch),
}
}
}
fn write_canonical_attr(value: &str, dest: &mut dyn IDestination) {
for ch in value.chars() {
match ch {
'&' => dest.write_str("&"),
'<' => dest.write_str("<"),
'"' => dest.write_str("""),
'\t' => dest.write_str("	"),
'\n' => dest.write_str("
"),
'\r' => dest.write_str("
"),
_ => dest.write_char(ch),
}
}
}
}