use crate::diff::{ApplyError, Change};
use crate::error::Result;
use crate::node::Node;
use serde_json::Value;
use std::io::Read;
use std::ops::{Deref, DerefMut};
#[derive(Debug, Clone, PartialEq)]
pub struct Document {
root: Node,
}
impl Document {
#[inline]
pub fn new(root: Node) -> Self {
Document { root }
}
pub fn from_json_str(s: &str) -> Result<Self> {
Ok(Document {
root: serde_json::from_str(s)?,
})
}
pub fn from_value(value: Value) -> Result<Self> {
Ok(Document {
root: serde_json::from_value(value)?,
})
}
pub fn from_reader(reader: impl Read) -> Result<Self> {
Ok(Document {
root: serde_json::from_reader(reader)?,
})
}
pub fn to_json_str(&self) -> Result<String> {
Ok(serde_json::to_string(&self.root)?)
}
pub fn to_string_pretty(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(&self.root)?)
}
pub fn to_value(&self) -> Result<Value> {
Ok(serde_json::to_value(&self.root)?)
}
#[inline]
pub fn root(&self) -> &Node {
&self.root
}
#[inline]
pub fn root_mut(&mut self) -> &mut Node {
&mut self.root
}
#[inline]
pub fn into_root(self) -> Node {
self.root
}
pub fn diff(&self, other: &Document) -> Vec<Change> {
self.root.diff(&other.root)
}
pub fn apply(&mut self, changes: &[Change]) -> std::result::Result<(), ApplyError> {
crate::diff::apply(&mut self.root, changes)
}
pub fn invert(&self, changes: &[Change]) -> std::result::Result<Vec<Change>, ApplyError> {
crate::diff::invert(&self.root, changes)
}
pub fn normalize(&mut self) {
self.root.normalize();
}
pub fn normalize_with(&mut self, opts: &crate::NormalizeOptions) {
self.root.normalize_with(opts);
}
pub fn to_html(&self) -> String {
self.root.to_html()
}
pub fn to_html_with(&self, opts: &crate::HtmlOptions) -> String {
self.root.to_html_with(opts)
}
}
impl Deref for Document {
type Target = Node;
#[inline]
fn deref(&self) -> &Node {
&self.root
}
}
impl DerefMut for Document {
#[inline]
fn deref_mut(&mut self) -> &mut Node {
&mut self.root
}
}
impl From<Node> for Document {
#[inline]
fn from(root: Node) -> Self {
Document { root }
}
}