use std::ops::Range;
use quick_xml::XmlVersion;
use quick_xml::events::{BytesStart, Event};
use quick_xml::name::ResolveResult;
use quick_xml::reader::NsReader;
use crate::{Error, Limits, UTF8_MARK, declared_encoding};
#[derive(Clone, Debug)]
pub struct StreamedBody {
pub in_scope: Vec<(String, String)>,
pub doc_in_scope: Vec<(String, String)>,
pub background: Option<Range<usize>>,
pub children: Vec<Range<usize>>,
pub has_revisions: bool,
pub has_cross_block_features: bool,
}
pub fn scan_body_children(
bytes: &[u8],
w_namespaces: &[&str],
body_wrappers: &[&str],
limits: &Limits,
) -> Result<Option<StreamedBody>, Error> {
u32::try_from(bytes.len()).map_err(|_| Error::TooLarge)?;
if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) {
return Ok(None);
}
let skipped = if bytes.starts_with(&UTF8_MARK) {
UTF8_MARK.len()
} else {
0
};
let mut reader = NsReader::from_reader(bytes);
reader.config_mut().check_end_names = true;
let mut state = ScanState::new(w_namespaces, body_wrappers, limits, skipped);
let mut buf = Vec::new();
loop {
buf.clear();
let start = state.position(&reader)?;
let (resolved, event) = reader
.read_resolved_event_into(&mut buf)
.map_err(|error| Error::Syntax(error.to_string()))?;
let is_w = state.is_w(&resolved);
let end = state.position(&reader)?;
match event {
Event::Eof => break,
Event::DocType(_) => return Err(Error::DocType),
Event::Decl(decl) => {
if declared_encoding(&decl).is_some() {
return Ok(None);
}
}
Event::Start(tag) => state.on_start(&tag, is_w, start, end, false)?,
Event::Empty(tag) => state.on_start(&tag, is_w, start, end, true)?,
Event::End(_) => state.on_end(end),
Event::Text(_)
| Event::CData(_)
| Event::GeneralRef(_)
| Event::Comment(_)
| Event::PI(_) => {}
}
}
if state.depth != 0 {
return Err(Error::Syntax("unclosed element".to_owned()));
}
Ok(state.finish())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ScanPhase {
BeforeDocument,
InDocument,
InBody,
AfterBody,
}
struct ScanState<'a> {
w_namespaces: &'a [&'a str],
body_wrappers: &'a [&'a str],
limits: &'a Limits,
skipped: usize,
depth: usize,
nodes: usize,
phase: ScanPhase,
doc_decls: Vec<(String, String)>,
body_decls: Vec<(String, String)>,
background_start: Option<usize>,
background: Option<Range<usize>>,
child_start: Option<usize>,
children: Vec<Range<usize>>,
has_revisions: bool,
has_cross_block_features: bool,
}
impl<'a> ScanState<'a> {
fn new(
w_namespaces: &'a [&'a str],
body_wrappers: &'a [&'a str],
limits: &'a Limits,
skipped: usize,
) -> Self {
Self {
w_namespaces,
body_wrappers,
limits,
skipped,
depth: 0,
nodes: 0,
phase: ScanPhase::BeforeDocument,
doc_decls: Vec::new(),
body_decls: Vec::new(),
background_start: None,
background: None,
child_start: None,
children: Vec::new(),
has_revisions: false,
has_cross_block_features: false,
}
}
fn position(&self, reader: &NsReader<&[u8]>) -> Result<usize, Error> {
let pos = usize::try_from(reader.buffer_position())
.map_err(|_| Error::TooLarge)?
.saturating_add(self.skipped);
Ok(pos)
}
fn is_w(&self, resolved: &ResolveResult<'_>) -> bool {
matches!(resolved, ResolveResult::Bound(ns) if self.w_namespaces.contains(&ns.as_ref()))
}
fn on_start(
&mut self,
tag: &BytesStart<'_>,
is_w: bool,
start: usize,
end: usize,
empty: bool,
) -> Result<(), Error> {
self.nodes += 1;
if self.nodes > self.limits.max_nodes {
return Err(Error::TooManyNodes);
}
let next_depth = self.depth + 1;
if !empty && next_depth > self.limits.max_depth {
return Err(Error::TooDeep);
}
let local = tag.local_name();
let local_str = local.as_ref();
match (next_depth, self.phase) {
(1, ScanPhase::BeforeDocument) if is_w && local_str == "document" => {
self.doc_decls = collect_xmlns(tag)?;
if !empty {
self.phase = ScanPhase::InDocument;
}
}
(2, ScanPhase::InDocument) if is_w => {
self.on_document_child(tag, local_str, start, end, empty)?;
}
(3, ScanPhase::InBody) => {
self.on_body_child(local_str, start, end, empty);
}
_ => {}
}
if is_w {
self.flag_features(local_str);
}
if !empty {
self.depth = next_depth;
}
Ok(())
}
fn on_document_child(
&mut self,
tag: &BytesStart<'_>,
local: &str,
start: usize,
end: usize,
empty: bool,
) -> Result<(), Error> {
if local == "background" && self.background.is_none() {
if empty {
self.background = Some(start..end);
} else {
self.background_start = Some(start);
}
} else if local == "body" {
self.body_decls = collect_xmlns(tag)?;
self.phase = if empty {
ScanPhase::AfterBody
} else {
ScanPhase::InBody
};
}
Ok(())
}
fn on_body_child(&mut self, local: &str, start: usize, end: usize, empty: bool) {
if empty {
self.children.push(start..end);
} else {
self.child_start = Some(start);
}
if self.body_wrappers.contains(&local) {
self.has_cross_block_features = true;
}
}
fn flag_features(&mut self, local: &str) {
if matches!(
local,
"del"
| "ins"
| "moveFrom"
| "moveTo"
| "pPrChange"
| "rPrChange"
| "tblPrChange"
| "trPrChange"
| "tcPrChange"
| "sectPrChange"
| "customXmlDelRangeStart"
| "customXmlInsRangeStart"
| "customXmlMoveFromRangeStart"
| "customXmlMoveToRangeStart"
) {
self.has_revisions = true;
} else if matches!(
local,
"commentRangeStart"
| "commentRangeEnd"
| "commentReference"
| "fldSimple"
| "instrText"
) {
self.has_cross_block_features = true;
}
}
fn on_end(&mut self, end: usize) {
match (self.depth, self.phase) {
(3, ScanPhase::InBody) => {
if let Some(start) = self.child_start.take() {
self.children.push(start..end);
}
}
(2, ScanPhase::InBody) => {
self.phase = ScanPhase::AfterBody;
}
(2, ScanPhase::InDocument) => {
if let Some(start) = self.background_start.take() {
self.background = Some(start..end);
}
}
_ => {}
}
self.depth = self.depth.saturating_sub(1);
}
fn finish(self) -> Option<StreamedBody> {
if !matches!(self.phase, ScanPhase::InBody | ScanPhase::AfterBody) {
return None;
}
let mut in_scope = self.body_decls;
for (prefix, uri) in &self.doc_decls {
if in_scope.iter().all(|(known, _)| known != prefix) {
in_scope.push((prefix.clone(), uri.clone()));
}
}
Some(StreamedBody {
in_scope,
doc_in_scope: self.doc_decls,
background: self.background,
children: self.children,
has_revisions: self.has_revisions,
has_cross_block_features: self.has_cross_block_features,
})
}
}
fn collect_xmlns(tag: &BytesStart<'_>) -> Result<Vec<(String, String)>, Error> {
let mut decls = Vec::new();
for attr in tag.attributes() {
let attr = attr.map_err(|error| Error::Syntax(error.to_string()))?;
let key = attr.key;
let prefix = match key.prefix() {
Some(p) if p.as_ref() == "xmlns" => key.local_name().as_ref().to_owned(),
None if key.local_name().as_ref() == "xmlns" => String::new(),
_ => continue,
};
let value = attr
.normalized_value(XmlVersion::Implicit1_0)
.map_err(|error| Error::Syntax(error.to_string()))?
.into_owned();
if decls.iter().all(|(known, _)| known != &prefix) {
decls.push((prefix, value));
}
}
Ok(decls)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Document;
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
const WRAPPERS: [&str; 3] = ["customXml", "sdt", "AlternateContent"];
#[test]
fn scans_body_children_with_exact_byte_spans_and_background() {
let xml = format!(
r#"<?xml version="1.0" encoding="UTF-8"?><w:document xmlns:w="{W}"><w:background w:color="FFEEAA"/><w:body><w:p><w:r><w:t>One</w:t></w:r></w:p><w:tbl/><w:sectPr/></w:body></w:document>"#
);
let streamed = scan_body_children(xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
.unwrap()
.unwrap();
assert_eq!(
(
streamed.has_revisions,
streamed.has_cross_block_features,
streamed.children.len(),
&xml[streamed.background.unwrap()],
&xml[streamed.children[0].clone()],
&xml[streamed.children[1].clone()],
&xml[streamed.children[2].clone()],
),
(
false,
false,
3,
r#"<w:background w:color="FFEEAA"/>"#,
"<w:p><w:r><w:t>One</w:t></w:r></w:p>",
"<w:tbl/>",
"<w:sectPr/>",
)
);
let full = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let full_body = full.child(full.root().unwrap(), W, "body").unwrap();
let full_p = full.child(full_body, W, "p").unwrap();
let range = streamed.children[0].clone();
let frag = Document::parse_fragment_with_aliases_at(
&xml.as_bytes()[range.clone()],
&streamed.in_scope,
&[],
range.start as u64,
&Limits::default(),
)
.unwrap();
let frag_p = frag.nodes()[0];
assert_eq!(
frag.document().span(frag_p).unwrap(),
full.span(full_p).unwrap()
);
}
#[test]
fn flags_revisions_and_cross_block_features() {
let rev_xml = format!(
r#"<w:document xmlns:w="{W}"><w:body><w:p><w:ins><w:r><w:t>hi</w:t></w:r></w:ins></w:p></w:body></w:document>"#
);
let streamed = scan_body_children(rev_xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
.unwrap()
.unwrap();
assert!(streamed.has_revisions);
let toc_xml = format!(
r#"<w:document xmlns:w="{W}"><w:body><w:p><w:r><w:instrText>TOC</w:instrText></w:r></w:p></w:body></w:document>"#
);
let streamed = scan_body_children(toc_xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
.unwrap()
.unwrap();
assert!(streamed.has_cross_block_features);
let custom_xml = format!(
r#"<w:document xmlns:w="{W}"><w:body><w:customXml><w:p><w:r><w:t>inside</w:t></w:r></w:p></w:customXml></w:body></w:document>"#
);
let streamed =
scan_body_children(custom_xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
.unwrap()
.unwrap();
assert!(streamed.has_cross_block_features);
}
}