Skip to content

add xml wrap for parser #89

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,11 @@ use std::path::Path;

pub mod node;
pub mod parser;
pub mod xml_svg;

pub use crate::node::Node;
pub use crate::parser::Parser;
pub use xml_svg::XMLSvg;

/// A document.
pub type Document = node::element::SVG;
Expand Down
3 changes: 3 additions & 0 deletions src/node/blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ impl Node for Blob {
fn get_name(&self) -> &str {
"blob"
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}

impl super::NodeDefaultHash for Blob {
Expand Down
10 changes: 7 additions & 3 deletions src/node/comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl Comment {
impl fmt::Display for Comment {
#[inline]
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "<!-- {} -->", self.content)
write!(formatter, "<!--{}-->", self.content)
}
}

Expand All @@ -50,6 +50,10 @@ impl Node for Comment {
fn get_name(&self) -> &str {
"comment"
}

fn as_any(&self) -> &dyn std::any::Any {
self
}
}

impl super::NodeDefaultHash for Comment {
Expand All @@ -65,10 +69,10 @@ mod tests {

#[test]
fn comment_display() {
let comment = Comment::new("valid");
let comment = Comment::new(" valid ");
assert_eq!(comment.to_string(), "<!-- valid -->");

let comment = Comment::new("invalid -->");
let comment = Comment::new(" invalid --> ");
assert_eq!(comment.to_string(), "<!-- invalid --> -->");
}
}
8 changes: 8 additions & 0 deletions src/node/element/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ impl Node for Element {
fn get_children_mut(&mut self) -> Option<&mut Children> {
Self::get_children_mut(self).into()
}

fn as_any(&self) -> &dyn std::any::Any {
self
}
}

macro_rules! implement_nested(
Expand Down Expand Up @@ -185,6 +189,10 @@ macro_rules! implement_nested(
self.$field_name.get_name()
}

fn as_any(&self) -> &dyn std::any::Any {
self
}

#[inline]
fn get_attributes(&self) -> Option<&Attributes> {
self.$field_name.get_attributes().into()
Expand Down
2 changes: 2 additions & 0 deletions src/node/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! The nodes.

use std::any::Any;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::fmt;
Expand Down Expand Up @@ -76,6 +77,7 @@ pub trait Node:
fn is_bareable(&self) -> bool {
false
}
fn as_any(&self) -> &dyn Any;
}

#[doc(hidden)]
Expand Down
4 changes: 4 additions & 0 deletions src/node/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ impl Node for Text {
fn is_bare(&self) -> bool {
true
}

fn as_any(&self) -> &dyn std::any::Any {
self
}
}

impl super::NodeDefaultHash for Text {
Expand Down
5 changes: 4 additions & 1 deletion src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,10 @@ impl<'l> Parser<'l> {
fn read_comment(&mut self) -> Option<Event<'l>> {
match self.reader.capture(|reader| reader.consume_comment()) {
None => raise!(self, "found a malformed comment"),
Some(content) => Some(Event::Comment(content)),
Some(content) => {
let comment_content = &content[4..content.len() - 3];
Some(Event::Comment(comment_content))
}
}
}

Expand Down
125 changes: 125 additions & 0 deletions src/xml_svg.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
use core::fmt;

use crate::{
node::element::{tag::Type, Element},
parser::{Error, Event},
Node, Parser,
};

#[derive(Debug)]
pub struct XMLSvg {
inner: Vec<Box<dyn Node>>,
}

impl XMLSvg {
pub fn from_childrens(childrens: &Vec<Box<dyn Node>>) -> Self {
Self {
inner: childrens.to_vec(),
}
}

pub fn from_string(svg_str: &str) -> Result<Self, Error> {
let svg = Element::new("document");
let mut stack: Vec<Element> = Vec::new();
stack.push(svg.clone());

for event in Parser::new(svg_str) {
match event {
Event::Tag(tag, typed, attributes) => {
let mut node = Element::new(tag);
node.get_attributes_mut().extend(attributes);
match typed {
Type::Start => {
stack.push(node);
}
Type::End => {
if stack.len() > 1 {
let to_add = stack.pop().unwrap();
if let Some(parent) = stack.last_mut() {
parent.append(to_add);
}
}
}
Type::Empty => {
if let Some(parent) = stack.last_mut() {
parent.append(node);
}
}
}
}
Event::Comment(comment) => {
// remove 4 first chart and 3 last chart
if let Some(parent) = stack.last_mut() {
parent.append(crate::node::Comment::new(comment));
}
}
Event::Text(text) => {
if let Some(parent) = stack.last_mut() {
parent.append(crate::node::Text::new(text));
}
}
Event::Declaration(declaration) => {
if let Some(parent) = stack.last_mut() {
parent.append(crate::node::Blob::new(declaration));
}
}
Event::Instruction(instruction) => {
if let Some(parent) = stack.last_mut() {
parent.append(crate::node::Blob::new(instruction));
}
}
Event::Error(e) => {
// return the error
return Err(e);
}
}
}

if let Some(root) = stack.first() {
return Ok(XMLSvg::from_childrens(root.get_children()));
}

Err(Error::new((0, 0), "No root element found"))
}

pub fn get_svg(&self) -> Option<&Element> {
self.inner.iter().find_map(|node| {
if node.get_name() == "svg" {
return Some(node.as_any().downcast_ref::<Element>().unwrap());
}
None
})
}
}

impl fmt::Display for XMLSvg {
#[inline]
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
for node in &self.inner {
node.fmt(formatter)?;
writeln!(formatter)?;
}
Ok(())
}
}

#[cfg(test)]
mod tests {
use crate::{node::element::Element, XMLSvg};

#[test]

fn high_level_parsing() {
let svg = include_str!("../tests/fixtures/benton.svg");
// replace line endings
let svg = svg.replace("\r\n", "\n");
let xml_svg = XMLSvg::from_string(&svg).unwrap();
println!("{:#?}", xml_svg);
// assert only the first 60 characters
// attributes are not in the same order
assert_eq!(xml_svg.to_string()[..60], svg[..60]);
let svg: &Element = xml_svg.get_svg().unwrap();
assert_eq!(svg.get_name(), "svg");
assert_eq!(svg.get_children().len(), 4);
}
}