Skip to content
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

Extract StateTracker trait #46

Open
wants to merge 3 commits into
base: master
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: 1 addition & 1 deletion rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
unstable_features = true

required_version = "1.4.11"
required_version = "1.4.21"
edition = "2018"

format_code_in_doc_comments = true
Expand Down
6 changes: 3 additions & 3 deletions src/decoding/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use core::str;

use crate::{
decoding::{Error, Object},
state_tracker::{StateTracker, StructureError, Token},
state_tracker::{StateTracker, StrictTracker, StructureError, Token},
};

/// A bencode decoder
Expand All @@ -14,7 +14,7 @@ use crate::{
pub struct Decoder<'a> {
source: &'a [u8],
offset: usize,
state: StateTracker<&'a [u8], Error>,
state: StrictTracker<&'a [u8], Error>,
}

impl<'ser> Decoder<'ser> {
Expand All @@ -23,7 +23,7 @@ impl<'ser> Decoder<'ser> {
Decoder {
source: buffer,
offset: 0,
state: StateTracker::new(),
state: StrictTracker::new(),
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/encoding/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ use std::{collections::BTreeMap, vec::Vec};

use crate::{
encoding::{Error, PrintableInteger, ToBencode},
state_tracker::{StateTracker, StructureError, Token},
state_tracker::{StateTracker, StrictTracker, StructureError, Token},
};

/// The actual encoder. Unlike the decoder, this is not zero-copy, as that would
/// result in a horrible interface
#[derive(Default, Debug)]
pub struct Encoder {
state: StateTracker<Vec<u8>, Error>,
state: StrictTracker<Vec<u8>, Error>,
output: Vec<u8>,
}

Expand Down
10 changes: 7 additions & 3 deletions src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,8 +531,8 @@ mod tests {

#[test]
fn borrowed_value() {
use std::borrow::Cow;
use crate::value::Value;
use std::borrow::Cow;

#[derive(Debug, Deserialize, PartialEq, Eq)]
#[serde(crate = "serde_")]
Expand All @@ -542,8 +542,12 @@ mod tests {
}

assert_eq!(
Deserializer::from_bytes(b"d1:v3:\x01\x02\x03e").deserialize::<Dict<'_>>().unwrap(),
Dict { v: Value::Bytes(Cow::Owned(vec![1, 2, 3]))},
Deserializer::from_bytes(b"d1:v3:\x01\x02\x03e")
.deserialize::<Dict<'_>>()
.unwrap(),
Dict {
v: Value::Bytes(Cow::Owned(vec![1, 2, 3]))
},
);
}
}
6 changes: 5 additions & 1 deletion src/state_tracker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,8 @@ mod structure_error;
mod token;

pub use self::token::Token;
pub(crate) use self::{stack::Stack, state::StateTracker, structure_error::StructureError};
pub(crate) use self::{
stack::Stack,
state::{StateTracker, StrictTracker},
structure_error::StructureError,
};
54 changes: 43 additions & 11 deletions src/state_tracker/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,34 @@ use alloc::vec::Vec;

use crate::state_tracker::{Stack, StructureError, Token};

//------------------------------------------------------------------------------
// StateTracker
//------------------------------------------------------------------------------

/// Used to validate that a structure is valid
pub(crate) trait StateTracker<S, E> {
fn new() -> Self;

fn set_max_depth(&mut self, new_max_depth: usize);

fn remaining_depth(&self) -> usize;

/// Observe that an EOF was seen. This function is idempotent.
fn observe_eof(&mut self) -> Result<(), E>;

fn observe_token<'a>(&mut self, token: &Token<'a>) -> Result<(), E>
where
S: From<&'a [u8]>;

fn latch_err<T>(&mut self, result: Result<T, E>) -> Result<T, E>;

fn check_error(&self) -> Result<(), E>;
}

//------------------------------------------------------------------------------
// State
//------------------------------------------------------------------------------

/// The state of current level of the decoder
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
enum State<S: AsRef<[u8]>, E> {
Expand All @@ -16,41 +44,45 @@ enum State<S: AsRef<[u8]>, E> {
Failed(E),
}

//------------------------------------------------------------------------------
// StrictTracker
//------------------------------------------------------------------------------

/// Used to validate that a structure is valid
#[derive(Debug)]
pub struct StateTracker<S: AsRef<[u8]>, E = StructureError> {
pub struct StrictTracker<S: AsRef<[u8]>, E = StructureError> {
state: Vec<State<S, E>>,
max_depth: usize,
}

impl<S: AsRef<[u8]>, E> Default for StateTracker<S, E> {
impl<S: AsRef<[u8]>, E> Default for StrictTracker<S, E> {
fn default() -> Self {
StateTracker {
StrictTracker {
state: Vec::new(),
max_depth: 2048,
}
}
}

impl<S: AsRef<[u8]>, E> StateTracker<S, E>
impl<S, E> StateTracker<S, E> for StrictTracker<S, E>
where
S: AsRef<[u8]>,
E: From<StructureError> + Clone,
{
pub fn new() -> Self {
fn new() -> Self {
<Self as Default>::default()
}

pub fn set_max_depth(&mut self, new_max_depth: usize) {
fn set_max_depth(&mut self, new_max_depth: usize) {
self.max_depth = new_max_depth
}

pub fn remaining_depth(&self) -> usize {
fn remaining_depth(&self) -> usize {
self.max_depth - self.state.len()
}

/// Observe that an EOF was seen. This function is idempotent.
pub fn observe_eof(&mut self) -> Result<(), E> {
fn observe_eof(&mut self) -> Result<(), E> {
self.check_error()?;

if self.state.is_empty() {
Expand All @@ -61,7 +93,7 @@ where
}

#[allow(clippy::match_same_arms)]
pub fn observe_token<'a>(&mut self, token: &Token<'a>) -> Result<(), E>
fn observe_token<'a>(&mut self, token: &Token<'a>) -> Result<(), E>
where
S: From<&'a [u8]>,
{
Expand Down Expand Up @@ -141,15 +173,15 @@ where
Ok(())
}

pub fn latch_err<T>(&mut self, result: Result<T, E>) -> Result<T, E> {
fn latch_err<T>(&mut self, result: Result<T, E>) -> Result<T, E> {
self.check_error()?;
if let Err(ref err) = result {
self.state.push(State::Failed(err.clone()))
}
result
}

pub fn check_error(&self) -> Result<(), E> {
fn check_error(&self) -> Result<(), E> {
if let Some(&State::Failed(ref error)) = self.state.peek() {
Err(error.clone())
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl<'a> ToBencode for Value<'a> {

impl<'a> FromBencode for Value<'a> {
const EXPECTED_RECURSION_DEPTH: usize = <Self as ToBencode>::MAX_DEPTH;

fn decode_bencode_object(object: Object) -> Result<Self, crate::decoding::Error> {
match object {
Object::Bytes(bytes) => Ok(Value::Bytes(Cow::Owned(bytes.to_owned()))),
Expand Down