use crate::alloc_prelude::*;
use crate::error::Result;
#[cfg(feature = "std")]
use crate::error::XmlError;
pub use crate::io::encoding::Format;
use crate::io::encoding::detect_encoding_and_strip_bom;
#[derive(Debug, Clone)]
pub struct XmlSource {
content: String,
pos: usize,
line: usize,
col: usize,
format: Format,
}
impl XmlSource {
pub fn from_string(xml: &str) -> Self {
let normalized = if xml.contains('\r') {
xml.replace("\r\n", "\n").replace('\r', "\n")
} else {
xml.to_string()
};
Self {
content: normalized,
pos: 0,
line: 1,
col: 1,
format: Format::Utf8,
}
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
let (raw_content, format) = detect_encoding_and_strip_bom(bytes)?;
let normalized = if raw_content.contains('\r') {
raw_content.replace("\r\n", "\n").replace('\r', "\n")
} else {
raw_content
};
Ok(Self {
content: normalized,
pos: 0,
line: 1,
col: 1,
format,
})
}
pub fn from_bytes_with_encoding(bytes: &[u8], encoding: &str) -> Result<Self> {
let (raw_content, format) = crate::io::encoding::decode_with_encoding(bytes, encoding)?;
let normalized = if raw_content.contains('\r') {
raw_content.replace("\r\n", "\n").replace('\r', "\n")
} else {
raw_content
};
Ok(Self {
content: normalized,
pos: 0,
line: 1,
col: 1,
format,
})
}
#[cfg(feature = "std")]
pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self> {
let bytes = std::fs::read(path.as_ref()).map_err(|e| XmlError::Io(e.to_string()))?;
Self::from_bytes(&bytes)
}
#[cfg(feature = "std")]
pub const DEFAULT_MAX_STREAM_SIZE: usize = 50 * 1024 * 1024;
#[cfg(feature = "std")]
pub fn from_reader<R: std::io::Read>(reader: R) -> Result<Self> {
Self::from_reader_with_limit(reader, Self::DEFAULT_MAX_STREAM_SIZE)
}
#[cfg(feature = "std")]
pub fn from_reader_with_limit<R: std::io::Read>(
mut reader: R,
max_bytes: usize,
) -> Result<Self> {
use std::io::Read;
let mut bytes = Vec::new();
let mut limited = (&mut reader).take((max_bytes + 1) as u64);
limited
.read_to_end(&mut bytes)
.map_err(|e| XmlError::Io(e.to_string()))?;
if bytes.len() > max_bytes {
return Err(XmlError::SecurityLimitExceeded(
"Input stream exceeds maximum allowed XML stream size".into(),
));
}
Self::from_bytes(&bytes)
}
pub fn format(&self) -> Format {
self.format
}
pub fn position(&self) -> usize {
self.pos
}
pub fn slice_range(&self, start: usize, end: usize) -> &str {
let max_len = self.content.len();
let s = start.min(max_len);
let e = end.min(max_len);
if s > e || !self.content.is_char_boundary(s) || !self.content.is_char_boundary(e) {
return "";
}
&self.content[s..e]
}
pub fn len(&self) -> usize {
self.content.len()
}
pub fn line(&self) -> usize {
self.line
}
pub fn col(&self) -> usize {
self.col
}
pub fn is_eof(&self) -> bool {
self.pos >= self.content.len()
}
pub fn peek(&self) -> Option<char> {
if self.pos >= self.content.len() {
None
} else {
self.content[self.pos..].chars().next()
}
}
pub fn peek_offset(&self, offset: usize) -> Option<char> {
if self.pos >= self.content.len() {
None
} else {
self.content[self.pos..].chars().nth(offset)
}
}
pub fn next_char(&mut self) -> Option<char> {
if self.pos >= self.content.len() {
return None;
}
let ch = self.content[self.pos..].chars().next()?;
self.pos += ch.len_utf8();
if ch == '\n' {
self.line += 1;
self.col = 1;
} else {
self.col += 1;
}
Some(ch)
}
pub fn starts_with(&self, prefix: &str) -> bool {
if self.pos >= self.content.len() {
false
} else {
self.content[self.pos..].starts_with(prefix)
}
}
pub fn consume(&mut self, prefix: &str) -> bool {
if self.starts_with(prefix) {
for ch in prefix.chars() {
self.pos += ch.len_utf8();
if ch == '\n' {
self.line += 1;
self.col = 1;
} else {
self.col += 1;
}
}
true
} else {
false
}
}
pub fn skip_whitespace(&mut self) -> usize {
let start = self.pos;
let bytes = self.content.as_bytes();
while self.pos < bytes.len() {
let b = bytes[self.pos];
if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' {
self.pos += 1;
if b == b'\n' {
self.line += 1;
self.col = 1;
} else {
self.col += 1;
}
} else {
break;
}
}
self.pos - start
}
pub fn from_source(source: &mut dyn babbel_core::io::traits::ISource) -> Self {
let mut content = String::new();
while source.more() {
if let Some(ch) = source.current() {
content.push(ch);
}
source.next();
}
Self::from_string(&content)
}
}
impl babbel_core::io::traits::ISource for XmlSource {
fn next(&mut self) {
let _ = self.next_char();
}
fn current(&mut self) -> Option<char> {
self.peek()
}
fn more(&mut self) -> bool {
!self.is_eof()
}
fn reset(&mut self) {
self.pos = 0;
self.line = 1;
self.col = 1;
}
}
impl babbel_core::io::traits::IPositionAware for XmlSource {
fn position(&self) -> usize {
self.pos
}
}
impl babbel_core::io::traits::ICharStream for XmlSource {
fn next(&mut self) {
let _ = self.next_char();
}
fn current(&mut self) -> Option<char> {
self.peek()
}
fn more(&mut self) -> bool {
!self.is_eof()
}
}
impl babbel_core::io::traits::IRewindable for XmlSource {
fn reset(&mut self) {
self.pos = 0;
self.line = 1;
self.col = 1;
}
}
impl babbel_core::io::traits::ILocationAware for XmlSource {
fn line(&self) -> usize {
self.line
}
fn column(&self) -> usize {
self.col
}
}
impl babbel_core::io::traits::IStatefulStream for XmlSource {
fn save_state(&mut self) -> babbel_core::io::traits::SaveState {
babbel_core::io::traits::SaveState {
pos: self.pos as u64,
current_byte: self.peek().map(|c| (c as u32 & 0xFF) as u8),
column: self.col,
line: self.line,
}
}
fn restore_state(&mut self, state: babbel_core::io::traits::SaveState) {
self.pos = state.pos as usize;
self.line = state.line;
self.col = state.column;
}
}