Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
kornelski committed Mar 31, 2024
1 parent a7b8acd commit 87723fd
Show file tree
Hide file tree
Showing 28 changed files with 110 additions and 135 deletions.
12 changes: 6 additions & 6 deletions examples/print_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn main() {
XmlEvent::EndDocument => {
println!("EndDocument");
break;
}
},
XmlEvent::ProcessingInstruction { name, data } => {
println!("ProcessingInstruction({name}={:?})", data.as_deref().unwrap_or_default());
},
Expand All @@ -37,22 +37,22 @@ fn main() {
.collect();
println!("StartElement({name} [{}])", attrs.join(", "));
}
}
},
XmlEvent::EndElement { name } => {
println!("EndElement({name})");
},
XmlEvent::Comment(data) => {
println!(r#"Comment("{}")"#, data.escape_debug());
}
},
XmlEvent::CData(data) => println!(r#"CData("{}")"#, data.escape_debug()),
XmlEvent::Characters(data) => {
println!(r#"Characters("{}")"#, data.escape_debug());
}
},
XmlEvent::Whitespace(data) => {
println!(r#"Whitespace("{}")"#, data.escape_debug());
}
},
}
}
},
Err(e) => {
eprintln!("Error at {}: {e}", reader.position());
break;
Expand Down
7 changes: 3 additions & 4 deletions examples/rewrite.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! See <https://lib.rs/crates/svg-hush> for a real-world example.
use xml::EmitterConfig;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use xml::reader::{ParserConfig, Result};
use xml::EmitterConfig;

fn main() -> Result<(), Box<dyn std::error::Error>> {
let arg = std::env::args_os().nth(1);
Expand All @@ -30,7 +30,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
match reader_event {
xml::reader::XmlEvent::EndDocument => break,
xml::reader::XmlEvent::StartElement { name, mut attributes, namespace } => {
let event = xml::writer::XmlEvent::StartElement {
let event = xml::writer::XmlEvent::StartElement {
name: name.borrow(),
namespace: namespace.borrow(),
attributes: attributes.iter_mut().map(|attr| {
Expand All @@ -54,9 +54,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
if let Some(writer_event) = other.as_writer_event() {
writer.write(writer_event)?;
}
}
},
}

}
Ok(())
}
Expand Down
15 changes: 7 additions & 8 deletions src/analyze.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
#![forbid(unsafe_code)]

use std::cmp;
use std::collections::HashSet;
use std::env;
use std::fs::File;
use std::io::{self, BufReader, Read};
use std::{cmp, env};

use xml::reader::XmlEvent;
use xml::ParserConfig;
Expand Down Expand Up @@ -46,28 +45,28 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
),
XmlEvent::EndDocument => println!("Document finished"),
XmlEvent::ProcessingInstruction { .. } => processing_instructions += 1,
XmlEvent::Whitespace(_) => {} // can't happen due to configuration
XmlEvent::Whitespace(_) => {}, // can't happen due to configuration
XmlEvent::Characters(s) => {
character_blocks += 1;
characters += s.len();
}
},
XmlEvent::CData(s) => {
cdata_blocks += 1;
characters += s.len();
}
},
XmlEvent::Comment(s) => {
comment_blocks += 1;
comment_characters += s.len();
}
},
XmlEvent::StartElement { namespace, .. } => {
depth += 1;
max_depth = cmp::max(max_depth, depth);
elements += 1;
namespaces.extend(namespace.0.into_values());
}
},
XmlEvent::EndElement { .. } => {
depth -= 1;
}
},
};
}

Expand Down
12 changes: 8 additions & 4 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,18 +113,22 @@ pub fn is_whitespace_str(s: &str) -> bool {
}

/// Is it a valid character in XML 1.0
#[must_use] pub fn is_xml10_char(c: char) -> bool {
#[must_use]
pub fn is_xml10_char(c: char) -> bool {
matches!(c, '\u{09}' | '\u{0A}' | '\u{0D}' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..)
}

/// Is it a valid character in XML 1.1
#[must_use] pub fn is_xml11_char(c: char) -> bool {
#[must_use]
pub fn is_xml11_char(c: char) -> bool {
matches!(c, '\u{01}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..)
}

/// Is it a valid character in XML 1.1 but not part of the restricted character set
#[must_use] pub fn is_xml11_char_not_restricted(c: char) -> bool {
is_xml11_char(c) && !matches!(c, '\u{01}'..='\u{08}' | '\u{0B}'..='\u{0C}' | '\u{0E}'..='\u{1F}' | '\u{7F}'..='\u{84}' | '\u{86}'..='\u{9F}')
#[must_use]
pub fn is_xml11_char_not_restricted(c: char) -> bool {
is_xml11_char(c) &&
!matches!(c, '\u{01}'..='\u{08}' | '\u{0B}'..='\u{0C}' | '\u{0E}'..='\u{1F}' | '\u{7F}'..='\u{84}' | '\u{86}'..='\u{9F}')
}

/// Checks whether the given character is a name start character (`NameStartChar`)
Expand Down
9 changes: 4 additions & 5 deletions src/escape.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//! Contains functions for performing XML special characters escaping.
use std::{borrow::Cow, marker::PhantomData, fmt::{Display, Result, Formatter}};
use std::borrow::Cow;
use std::fmt::{Display, Formatter, Result};
use std::marker::PhantomData;

pub(crate) trait Escapes {
fn escape(c: u8) -> Option<&'static str>;
Expand Down Expand Up @@ -33,10 +35,7 @@ impl<'a, E: Escapes> Display for Escaped<'a, E> {
let mut total_remaining = self.to_escape;

// find the next occurence
while let Some(n) = total_remaining
.bytes()
.position(E::byte_needs_escaping)
{
while let Some(n) = total_remaining.bytes().position(E::byte_needs_escaping) {
let (start, remaining) = total_remaining.split_at(n);

f.write_str(start)?;
Expand Down
6 changes: 2 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@
#![cfg_attr(doctest, doc = include_str!("../README.md"))]

pub use crate::reader::EventReader;
pub use crate::reader::ParserConfig;
pub use crate::reader::{EventReader, ParserConfig};
pub use crate::util::Encoding;
pub use crate::writer::EmitterConfig;
pub use crate::writer::EventWriter;
pub use crate::writer::{EmitterConfig, EventWriter};

pub mod attribute;
pub mod common;
Expand Down
6 changes: 3 additions & 3 deletions src/namespace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl Namespace {
Entry::Vacant(ve) => {
ve.insert(uri.into());
true
}
},
}
}

Expand Down Expand Up @@ -185,8 +185,8 @@ pub type NamespaceMappings<'a> = Map<
>;

impl<'a> IntoIterator for &'a Namespace {
type Item = UriMapping<'a>;
type IntoIter = NamespaceMappings<'a>;
type Item = UriMapping<'a>;

fn into_iter(self) -> Self::IntoIter {
fn mapper<'a>((prefix, uri): (&'a String, &'a String)) -> UriMapping<'a> {
Expand Down Expand Up @@ -436,8 +436,8 @@ impl<'a> Iterator for NamespaceStackMappings<'a> {
}

impl<'a> IntoIterator for &'a NamespaceStack {
type Item = UriMapping<'a>;
type IntoIter = NamespaceStackMappings<'a>;
type Item = UriMapping<'a>;

fn into_iter(self) -> Self::IntoIter {
NamespaceStackMappings {
Expand Down
13 changes: 5 additions & 8 deletions src/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,18 @@ use std::result;

use crate::common::{Position, TextPosition};

pub use self::config::ParserConfig;
pub use self::config::ParserConfig2;
pub use self::config::{ParserConfig, ParserConfig2};
pub use self::error::{Error, ErrorKind};
pub use self::events::XmlEvent;

use self::parser::PullParser;

mod config;
mod error;
mod events;
mod indexset;
mod lexer;
mod parser;
mod indexset;
mod error;


/// A result type yielded by `XmlReader`.
pub type Result<T, E = Error> = result::Result<T, E>;
Expand Down Expand Up @@ -69,7 +67,7 @@ impl<R: Read> EventReader<R> {
XmlEvent::StartElement { .. } => depth += 1,
XmlEvent::EndElement { .. } => depth -= 1,
XmlEvent::EndDocument => unreachable!(),
_ => {}
_ => {},
}
}

Expand Down Expand Up @@ -105,8 +103,8 @@ impl<B: Read> Position for EventReader<B> {
}

impl<R: Read> IntoIterator for EventReader<R> {
type Item = Result<XmlEvent>;
type IntoIter = Events<R>;
type Item = Result<XmlEvent>;

fn into_iter(self) -> Events<R> {
Events { reader: self, finished: false }
Expand Down Expand Up @@ -138,7 +136,6 @@ impl<R: Read> Events<R> {
///
/// It's not recommended to use it while the events are still being parsed
pub fn source_mut(&mut self) -> &mut R { &mut self.reader.source }

}

impl<R: Read> FusedIterator for Events<R> {
Expand Down
13 changes: 5 additions & 8 deletions src/reader/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,10 +233,10 @@ impl Default for ParserConfig2 {
allow_multiple_root_elements: true,
max_entity_expansion_length: DEFAULT_MAX_ENTITY_EXPANSION_LENGTH,
max_entity_expansion_depth: DEFAULT_MAX_ENTITY_EXPANSION_DEPTH,
max_attributes: 1<<16,
max_attribute_length: 1<<30,
max_data_length: 1<<30,
max_name_length: 1<<18,
max_attributes: 1 << 16,
max_attribute_length: 1 << 30,
max_data_length: 1 << 30,
max_name_length: 1 << 18,
}
}
}
Expand Down Expand Up @@ -293,10 +293,7 @@ impl ParserConfig2 {
impl From<ParserConfig> for ParserConfig2 {
#[inline]
fn from(c: ParserConfig) -> Self {
Self {
c,
..Default::default()
}
Self { c, ..Default::default() }
}
}

Expand Down
12 changes: 5 additions & 7 deletions src/reader/error.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
use crate::Encoding;
use crate::reader::lexer::Token;
use crate::Encoding;

use std::borrow::Cow;
use std::error;
use std::error::Error as _;
use std::fmt;
use std::io;
use std::str;
use std::{error, fmt, io, str};

use crate::common::{Position, TextPosition};
use crate::util;
Expand Down Expand Up @@ -98,7 +95,7 @@ impl SyntaxError {
Self::CannotUndefinePrefix(ref ln) => format!("Cannot undefine prefix '{ln}'").into(),
Self::ConflictingEncoding(a, b) => format!("Declared encoding {a}, but uses {b}").into(),
Self::InvalidCharacterEntity(num) => format!("Invalid character U+{num:04X}").into(),
Self::InvalidDefaultNamespace(ref name) => format!( "Namespace '{name}' cannot be default").into(),
Self::InvalidDefaultNamespace(ref name) => format!("Namespace '{name}' cannot be default").into(),
Self::InvalidNamePrefix(ref prefix) => format!("'{prefix}' cannot be an element name prefix").into(),
Self::InvalidNumericEntity(ref v) => format!("Invalid numeric entity: {v}").into(),
Self::InvalidQualifiedName(ref e) => format!("Qualified name is invalid: {e}").into(),
Expand Down Expand Up @@ -161,7 +158,8 @@ impl Error {
#[cold]
#[doc(hidden)]
#[allow(deprecated)]
#[must_use] pub fn msg(&self) -> &str {
#[must_use]
pub fn msg(&self) -> &str {
use self::ErrorKind::{Io, Syntax, UnexpectedEof, Utf8};
match &self.kind {
Io(io_error) => io_error.description(),
Expand Down
2 changes: 1 addition & 1 deletion src/reader/events.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! Contains `XmlEvent` datatype, instances of which are emitted by the parser.
use std::fmt;
use crate::attribute::OwnedAttribute;
use crate::common::XmlVersion;
use crate::name::OwnedName;
use crate::namespace::Namespace;
use std::fmt;

/// An element of an XML input stream.
///
Expand Down
4 changes: 1 addition & 3 deletions src/reader/indexset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ use crate::name::OwnedName;

use std::collections::hash_map::RandomState;
use std::collections::HashSet;
use std::hash::BuildHasher;
use std::hash::Hash;
use std::hash::Hasher;
use std::hash::{BuildHasher, Hash, Hasher};

/// An ordered set
pub(crate) struct AttributesSet {
Expand Down
17 changes: 6 additions & 11 deletions src/reader/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,13 @@
//!
//! This module is for internal use. Use `xml::pull` module to do parsing.

use crate::reader::ErrorKind;
use crate::common::{is_name_char, is_whitespace_char, is_xml10_char, is_xml11_char, Position, TextPosition};
use crate::reader::error::SyntaxError;
use crate::reader::{Error, ErrorKind};
use crate::util::{CharReader, Encoding};
use std::collections::VecDeque;
use std::fmt;
use std::io::Read;
use std::result;
use crate::common::{is_name_char, is_whitespace_char, Position, TextPosition, is_xml10_char, is_xml11_char};
use crate::reader::Error;
use crate::util::{CharReader, Encoding};
use std::{fmt, result};

use super::ParserConfig2;

Expand Down Expand Up @@ -250,7 +247,7 @@ impl Lexer {
reader: CharReader::new(),
pos: TextPosition::new(),
head_pos: TextPosition::new(),
char_queue: VecDeque::with_capacity(4), // TODO: check size
char_queue: VecDeque::with_capacity(4), // TODO: check size
st: State::Normal,
normal_state: State::Normal,
inside_token: false,
Expand Down Expand Up @@ -354,8 +351,7 @@ impl Lexer {
self.eof_handled = false;
Ok(Some(self.move_to_with_unread(State::Normal, &[']'], Token::Character(']'))))
},
State::Normal =>
Ok(None),
State::Normal => Ok(None),
}
}

Expand All @@ -368,7 +364,6 @@ impl Lexer {
}
}


#[inline(never)]
fn dispatch_char(&mut self, c: char) -> Result {
match self.st {
Expand Down
Loading

0 comments on commit 87723fd

Please sign in to comment.