use std::ops::Deref;
use std::{char, cmp, io, str};
#[cfg(feature = "raw_value")]
use serde::de::Visitor;
use iter::LineColIterator;
use error::{Error, ErrorCode, Result};
#[cfg(feature = "raw_value")]
use raw::{BorrowedRawDeserializer, OwnedRawDeserializer};
pub trait Read<'de>: private::Sealed {
#[doc(hidden)]
fn next(&mut self) -> Result<Option<u8>>;
#[doc(hidden)]
fn peek(&mut self) -> Result<Option<u8>>;
#[doc(hidden)]
fn discard(&mut self);
#[doc(hidden)]
fn position(&self) -> Position;
#[doc(hidden)]
fn peek_position(&self) -> Position;
#[doc(hidden)]
fn byte_offset(&self) -> usize;
#[doc(hidden)]
fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'de, 's, str>>;
#[doc(hidden)]
fn parse_str_raw<'s>(
&'s mut self,
scratch: &'s mut Vec<u8>,
) -> Result<Reference<'de, 's, [u8]>>;
#[doc(hidden)]
fn ignore_str(&mut self) -> Result<()>;
#[doc(hidden)]
fn decode_hex_escape(&mut self) -> Result<u16>;
#[cfg(feature = "raw_value")]
#[doc(hidden)]
fn begin_raw_buffering(&mut self);
#[cfg(feature = "raw_value")]
#[doc(hidden)]
fn end_raw_buffering<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: Visitor<'de>;
}
pub struct Position {
pub line: usize,
pub column: usize,
}
pub enum Reference<'b, 'c, T: ?Sized + 'static> {
Borrowed(&'b T),
Copied(&'c T),
}
impl<'b, 'c, T: ?Sized + 'static> Deref for Reference<'b, 'c, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
match *self {
Reference::Borrowed(b) => b,
Reference::Copied(c) => c,
}
}
}
pub struct IoRead<R>
where
R: io::Read,
{
iter: LineColIterator<io::Bytes<R>>,
ch: Option<u8>,
#[cfg(feature = "raw_value")]
raw_buffer: Option<Vec<u8>>,
}
pub struct SliceRead<'a> {
slice: &'a [u8],
index: usize,
#[cfg(feature = "raw_value")]
raw_buffering_start_index: usize,
}
pub struct StrRead<'a> {
delegate: SliceRead<'a>,
#[cfg(feature = "raw_value")]
data: &'a str,
}
mod private {
pub trait Sealed {}
}
impl<R> IoRead<R>
where
R: io::Read,
{
pub fn new(reader: R) -> Self {
#[cfg(not(feature = "raw_value"))]
{
IoRead {
iter: LineColIterator::new(reader.bytes()),
ch: None,
}
}
#[cfg(feature = "raw_value")]
{
IoRead {
iter: LineColIterator::new(reader.bytes()),
ch: None,
raw_buffer: None,
}
}
}
}
impl<R> private::Sealed for IoRead<R> where R: io::Read {}
impl<R> IoRead<R>
where
R: io::Read,
{
fn parse_str_bytes<'s, T, F>(
&'s mut self,
scratch: &'s mut Vec<u8>,
validate: bool,
result: F,
) -> Result<T>
where
T: 's,
F: FnOnce(&'s Self, &'s [u8]) -> Result<T>,
{
loop {
let ch = try!(next_or_eof(self));
if !ESCAPE[ch as usize] {
scratch.push(ch);
continue;
}
match ch {
b'"' => {
return result(self, scratch);
}
b'\\' => {
try!(parse_escape(self, scratch));
}
_ => {
if validate {
return error(self, ErrorCode::ControlCharacterWhileParsingString);
}
scratch.push(ch);
}
}
}
}
}
impl<'de, R> Read<'de> for IoRead<R>
where
R: io::Read,
{
#[inline]
fn next(&mut self) -> Result<Option<u8>> {
match self.ch.take() {
Some(ch) => {
#[cfg(feature = "raw_value")]
{
if let Some(ref mut buf) = self.raw_buffer {
buf.push(ch);
}
}
Ok(Some(ch))
}
None => match self.iter.next() {
Some(Err(err)) => Err(Error::io(err)),
Some(Ok(ch)) => {
#[cfg(feature = "raw_value")]
{
if let Some(ref mut buf) = self.raw_buffer {
buf.push(ch);
}
}
Ok(Some(ch))
}
None => Ok(None),
},
}
}
#[inline]
fn peek(&mut self) -> Result<Option<u8>> {
match self.ch {
Some(ch) => Ok(Some(ch)),
None => match self.iter.next() {
Some(Err(err)) => Err(Error::io(err)),
Some(Ok(ch)) => {
self.ch = Some(ch);
Ok(self.ch)
}
None => Ok(None),
},
}
}
#[cfg(not(feature = "raw_value"))]
#[inline]
fn discard(&mut self) {
self.ch = None;
}
#[cfg(feature = "raw_value")]
fn discard(&mut self) {
if let Some(ch) = self.ch.take() {
if let Some(ref mut buf) = self.raw_buffer {
buf.push(ch);
}
}
}
fn position(&self) -> Position {
Position {
line: self.iter.line(),
column: self.iter.col(),
}
}
fn peek_position(&self) -> Position {
self.position()
}
fn byte_offset(&self) -> usize {
match self.ch {
Some(_) => self.iter.byte_offset() - 1,
None => self.iter.byte_offset(),
}
}
fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'de, 's, str>> {
self.parse_str_bytes(scratch, true, as_str)
.map(Reference::Copied)
}
fn parse_str_raw<'s>(
&'s mut self,
scratch: &'s mut Vec<u8>,
) -> Result<Reference<'de, 's, [u8]>> {
self.parse_str_bytes(scratch, false, |_, bytes| Ok(bytes))
.map(Reference::Copied)
}
fn ignore_str(&mut self) -> Result<()> {
loop {
let ch = try!(next_or_eof(self));
if !ESCAPE[ch as usize] {
continue;
}
match ch {
b'"' => {
return Ok(());
}
b'\\' => {
try!(ignore_escape(self));
}
_ => {
return error(self, ErrorCode::ControlCharacterWhileParsingString);
}
}
}
}
fn decode_hex_escape(&mut self) -> Result<u16> {
let mut n = 0;
for _ in 0..4 {
match decode_hex_val(try!(next_or_eof(self))) {
None => return error(self, ErrorCode::InvalidEscape),
Some(val) => {
n = (n << 4) + val;
}
}
}
Ok(n)
}
#[cfg(feature = "raw_value")]
fn begin_raw_buffering(&mut self) {
self.raw_buffer = Some(Vec::new());
}
#[cfg(feature = "raw_value")]
fn end_raw_buffering<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: Visitor<'de>,
{
let raw = self.raw_buffer.take().unwrap();
let raw = String::from_utf8(raw).unwrap();
visitor.visit_map(OwnedRawDeserializer {
raw_value: Some(raw),
})
}
}
impl<'a> SliceRead<'a> {
pub fn new(slice: &'a [u8]) -> Self {
#[cfg(not(feature = "raw_value"))]
{
SliceRead {
slice: slice,
index: 0,
}
}
#[cfg(feature = "raw_value")]
{
SliceRead {
slice: slice,
index: 0,
raw_buffering_start_index: 0,
}
}
}
fn position_of_index(&self, i: usize) -> Position {
let mut position = Position { line: 1, column: 0 };
for ch in &self.slice[..i] {
match *ch {
b'\n' => {
position.line += 1;
position.column = 0;
}
_ => {
position.column += 1;
}
}
}
position
}
fn parse_str_bytes<'s, T: ?Sized, F>(
&'s mut self,
scratch: &'s mut Vec<u8>,
validate: bool,
result: F,
) -> Result<Reference<'a, 's, T>>
where
T: 's,
F: for<'f> FnOnce(&'s Self, &'f [u8]) -> Result<&'f T>,
{
let mut start = self.index;
loop {
while self.index < self.slice.len() && !ESCAPE[self.slice[self.index] as usize] {
self.index += 1;
}
if self.index == self.slice.len() {
return error(self, ErrorCode::EofWhileParsingString);
}
match self.slice[self.index] {
b'"' => {
if scratch.is_empty() {
let borrowed = &self.slice[start..self.index];
self.index += 1;
return result(self, borrowed).map(Reference::Borrowed);
} else {
scratch.extend_from_slice(&self.slice[start..self.index]);
self.index += 1;
return result(self, scratch).map(Reference::Copied);
}
}
b'\\' => {
scratch.extend_from_slice(&self.slice[start..self.index]);
self.index += 1;
try!(parse_escape(self, scratch));
start = self.index;
}
_ => {
self.index += 1;
if validate {
return error(self, ErrorCode::ControlCharacterWhileParsingString);
}
}
}
}
}
}
impl<'a> private::Sealed for SliceRead<'a> {}
impl<'a> Read<'a> for SliceRead<'a> {
#[inline]
fn next(&mut self) -> Result<Option<u8>> {
Ok(if self.index < self.slice.len() {
let ch = self.slice[self.index];
self.index += 1;
Some(ch)
} else {
None
})
}
#[inline]
fn peek(&mut self) -> Result<Option<u8>> {
Ok(if self.index < self.slice.len() {
Some(self.slice[self.index])
} else {
None
})
}
#[inline]
fn discard(&mut self) {
self.index += 1;
}
fn position(&self) -> Position {
self.position_of_index(self.index)
}
fn peek_position(&self) -> Position {
self.position_of_index(cmp::min(self.slice.len(), self.index + 1))
}
fn byte_offset(&self) -> usize {
self.index
}
fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'a, 's, str>> {
self.parse_str_bytes(scratch, true, as_str)
}
fn parse_str_raw<'s>(
&'s mut self,
scratch: &'s mut Vec<u8>,
) -> Result<Reference<'a, 's, [u8]>> {
self.parse_str_bytes(scratch, false, |_, bytes| Ok(bytes))
}
fn ignore_str(&mut self) -> Result<()> {
loop {
while self.index < self.slice.len() && !ESCAPE[self.slice[self.index] as usize] {
self.index += 1;
}
if self.index == self.slice.len() {
return error(self, ErrorCode::EofWhileParsingString);
}
match self.slice[self.index] {
b'"' => {
self.index += 1;
return Ok(());
}
b'\\' => {
self.index += 1;
try!(ignore_escape(self));
}
_ => {
return error(self, ErrorCode::ControlCharacterWhileParsingString);
}
}
}
}
fn decode_hex_escape(&mut self) -> Result<u16> {
if self.index + 4 > self.slice.len() {
self.index = self.slice.len();
return error(self, ErrorCode::EofWhileParsingString);
}
let mut n = 0;
for _ in 0..4 {
let ch = decode_hex_val(self.slice[self.index]);
self.index += 1;
match ch {
None => return error(self, ErrorCode::InvalidEscape),
Some(val) => {
n = (n << 4) + val;
}
}
}
Ok(n)
}
#[cfg(feature = "raw_value")]
fn begin_raw_buffering(&mut self) {
self.raw_buffering_start_index = self.index;
}
#[cfg(feature = "raw_value")]
fn end_raw_buffering<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: Visitor<'a>,
{
let raw = &self.slice[self.raw_buffering_start_index..self.index];
let raw = str::from_utf8(raw).unwrap();
visitor.visit_map(BorrowedRawDeserializer {
raw_value: Some(raw),
})
}
}
impl<'a> StrRead<'a> {
pub fn new(s: &'a str) -> Self {
#[cfg(not(feature = "raw_value"))]
{
StrRead {
delegate: SliceRead::new(s.as_bytes()),
}
}
#[cfg(feature = "raw_value")]
{
StrRead {
delegate: SliceRead::new(s.as_bytes()),
data: s,
}
}
}
}
impl<'a> private::Sealed for StrRead<'a> {}
impl<'a> Read<'a> for StrRead<'a> {
#[inline]
fn next(&mut self) -> Result<Option<u8>> {
self.delegate.next()
}
#[inline]
fn peek(&mut self) -> Result<Option<u8>> {
self.delegate.peek()
}
#[inline]
fn discard(&mut self) {
self.delegate.discard();
}
fn position(&self) -> Position {
self.delegate.position()
}
fn peek_position(&self) -> Position {
self.delegate.peek_position()
}
fn byte_offset(&self) -> usize {
self.delegate.byte_offset()
}
fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'a, 's, str>> {
self.delegate.parse_str_bytes(scratch, true, |_, bytes| {
Ok(unsafe { str::from_utf8_unchecked(bytes) })
})
}
fn parse_str_raw<'s>(
&'s mut self,
scratch: &'s mut Vec<u8>,
) -> Result<Reference<'a, 's, [u8]>> {
self.delegate.parse_str_raw(scratch)
}
fn ignore_str(&mut self) -> Result<()> {
self.delegate.ignore_str()
}
fn decode_hex_escape(&mut self) -> Result<u16> {
self.delegate.decode_hex_escape()
}
#[cfg(feature = "raw_value")]
fn begin_raw_buffering(&mut self) {
self.delegate.begin_raw_buffering()
}
#[cfg(feature = "raw_value")]
fn end_raw_buffering<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: Visitor<'a>,
{
let raw = &self.data[self.delegate.raw_buffering_start_index..self.delegate.index];
visitor.visit_map(BorrowedRawDeserializer {
raw_value: Some(raw),
})
}
}
static ESCAPE: [bool; 256] = {
const CT: bool = true;
const QU: bool = true;
const BS: bool = true;
const __: bool = false;
[
CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT,
CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT,
__, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
]
};
fn next_or_eof<'de, R: ?Sized + Read<'de>>(read: &mut R) -> Result<u8> {
match try!(read.next()) {
Some(b) => Ok(b),
None => error(read, ErrorCode::EofWhileParsingString),
}
}
fn error<'de, R: ?Sized + Read<'de>, T>(read: &R, reason: ErrorCode) -> Result<T> {
let position = read.position();
Err(Error::syntax(reason, position.line, position.column))
}
fn as_str<'de, 's, R: Read<'de>>(read: &R, slice: &'s [u8]) -> Result<&'s str> {
str::from_utf8(slice).or_else(|_| error(read, ErrorCode::InvalidUnicodeCodePoint))
}
fn parse_escape<'de, R: Read<'de>>(read: &mut R, scratch: &mut Vec<u8>) -> Result<()> {
let ch = try!(next_or_eof(read));
match ch {
b'"' => scratch.push(b'"'),
b'\\' => scratch.push(b'\\'),
b'/' => scratch.push(b'/'),
b'b' => scratch.push(b'\x08'),
b'f' => scratch.push(b'\x0c'),
b'n' => scratch.push(b'\n'),
b'r' => scratch.push(b'\r'),
b't' => scratch.push(b'\t'),
b'u' => {
let c = match try!(read.decode_hex_escape()) {
0xDC00...0xDFFF => {
return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape);
}
n1 @ 0xD800...0xDBFF => {
if try!(next_or_eof(read)) != b'\\' {
return error(read, ErrorCode::UnexpectedEndOfHexEscape);
}
if try!(next_or_eof(read)) != b'u' {
return error(read, ErrorCode::UnexpectedEndOfHexEscape);
}
let n2 = try!(read.decode_hex_escape());
if n2 < 0xDC00 || n2 > 0xDFFF {
return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape);
}
let n = (((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32) + 0x1_0000;
match char::from_u32(n) {
Some(c) => c,
None => {
return error(read, ErrorCode::InvalidUnicodeCodePoint);
}
}
}
n => match char::from_u32(n as u32) {
Some(c) => c,
None => {
return error(read, ErrorCode::InvalidUnicodeCodePoint);
}
},
};
scratch.extend_from_slice(c.encode_utf8(&mut [0_u8; 4]).as_bytes());
}
_ => {
return error(read, ErrorCode::InvalidEscape);
}
}
Ok(())
}
fn ignore_escape<'de, R: ?Sized + Read<'de>>(read: &mut R) -> Result<()> {
let ch = try!(next_or_eof(read));
match ch {
b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {}
b'u' => {
let n = match try!(read.decode_hex_escape()) {
0xDC00...0xDFFF => {
return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape);
}
n1 @ 0xD800...0xDBFF => {
if try!(next_or_eof(read)) != b'\\' {
return error(read, ErrorCode::UnexpectedEndOfHexEscape);
}
if try!(next_or_eof(read)) != b'u' {
return error(read, ErrorCode::UnexpectedEndOfHexEscape);
}
let n2 = try!(read.decode_hex_escape());
if n2 < 0xDC00 || n2 > 0xDFFF {
return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape);
}
(((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32) + 0x1_0000
}
n => n as u32,
};
if char::from_u32(n).is_none() {
return error(read, ErrorCode::InvalidUnicodeCodePoint);
}
}
_ => {
return error(read, ErrorCode::InvalidEscape);
}
}
Ok(())
}
static HEX: [u8; 256] = {
const __: u8 = 255;
[
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
00, 01, 02, 03, 04, 05, 06, 07, 08, 09, __, __, __, __, __, __,
__, 10, 11, 12, 13, 14, 15, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, 10, 11, 12, 13, 14, 15, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
]
};
fn decode_hex_val(val: u8) -> Option<u16> {
let n = HEX[val as usize] as u16;
if n == 255 {
None
} else {
Some(n)
}
}