f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
//! Where the body reader found a block or a row in the bytes of its part (its source
//! span), for the edits of `foffice`: the walk that numbers the addresses of the
//! text blocks also gives their elements, so that a reader and an edit cannot name different
//! elements. Layout never reads it.

use std::ops::Range;

use f_office_xml::{Document, NodeId};

/// The span of the element that a paragraph, a table or a row was read from, in the bytes of
/// its part, or none for one that F-Office made itself or one of a part that has no spans (a
/// part not in UTF-8).
///
/// Every two values are equal, so that two blocks with the same content stay the same block
/// for the layout, wherever their elements lie: the layout compares and copies blocks, and
/// their places in the file must not change what it does.
#[derive(Clone, Debug, Default)]
pub struct SourceSpan(Option<Range<usize>>);

impl SourceSpan {
    /// No span: a block that F-Office made itself.
    pub const NONE: Self = Self(None);

    /// The span of `node` in `doc`.
    pub(crate) fn of(doc: &Document, node: NodeId) -> Self {
        Self(doc.span(node).ok())
    }

    /// The byte range of the element in its part.
    pub(crate) fn range(&self) -> Option<Range<usize>> {
        self.0.clone()
    }
}

impl PartialEq for SourceSpan {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

impl Eq for SourceSpan {}

#[cfg(test)]
mod tests {
    use super::SourceSpan;

    #[test]
    fn two_spans_are_always_equal_and_keep_their_ranges() {
        let doc =
            f_office_xml::Document::parse(b"<a><b/><c/></a>", &f_office_xml::Limits::default())
                .unwrap();
        let root = doc.root().unwrap();
        let children: Vec<_> = doc.child_elements(root).collect();
        let (b, c) = (
            SourceSpan::of(&doc, children[0]),
            SourceSpan::of(&doc, children[1]),
        );
        assert_eq!(b, c);
        assert_eq!(b, SourceSpan::NONE);
        assert_eq!((b.range(), c.range()), (Some(3..7), Some(7..11)));
        assert_eq!(SourceSpan::NONE.range(), None);
    }
}