Skip to content

Commit

Permalink
Documented RON roundtrip Options
Browse files Browse the repository at this point in the history
  • Loading branch information
juntyr committed Dec 3, 2021
1 parent ef36eae commit 54320e9
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 108 deletions.
31 changes: 18 additions & 13 deletions src/de/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/// Deserialization module.
pub use crate::error::{Error, ErrorCode, Result};
pub use crate::parse::Position;
pub use crate::error::{Error, ErrorCode, Position, Result};

use serde::de::{self, DeserializeSeed, Deserializer as SerdeError, Visitor};
use std::{borrow::Cow, io, str};
Expand Down Expand Up @@ -31,20 +30,26 @@ impl<'de> Deserializer<'de> {
// Cannot implement trait here since output is tied to input lifetime 'de.
#[allow(clippy::should_implement_trait)]
pub fn from_str(input: &'de str) -> Result<Self> {
Deserializer::from_bytes(input.as_bytes())
Self::from_str_with_options(input, Options::default())
}

pub fn from_bytes(input: &'de [u8]) -> Result<Self> {
Ok(Deserializer {
Self::from_bytes_with_options(input, Options::default())
}

pub fn from_str_with_options(input: &'de str, options: Options) -> Result<Self> {
Self::from_bytes_with_options(input.as_bytes(), options)
}

pub fn from_bytes_with_options(input: &'de [u8], options: Options) -> Result<Self> {
let mut deserializer = Deserializer {
bytes: Bytes::new(input)?,
newtype_variant: false,
})
}
};

deserializer.bytes.exts |= options.default_extensions;

#[must_use]
pub fn with_default_extensions(mut self, default_extensions: Extensions) -> Self {
self.bytes.exts |= default_extensions;
self
Ok(deserializer)
}

pub fn remainder(&self) -> Cow<'_, str> {
Expand All @@ -59,7 +64,7 @@ where
R: io::Read,
T: de::DeserializeOwned,
{
Options::build().from_reader(rdr)
Options::default().from_reader(rdr)
}

/// A convenience function for building a deserializer
Expand All @@ -68,7 +73,7 @@ pub fn from_str<'a, T>(s: &'a str) -> Result<T>
where
T: de::Deserialize<'a>,
{
Options::build().from_str(s)
Options::default().from_str(s)
}

/// A convenience function for building a deserializer
Expand All @@ -77,7 +82,7 @@ pub fn from_bytes<'a, T>(s: &'a [u8]) -> Result<T>
where
T: de::Deserialize<'a>,
{
Options::build().from_bytes(s)
Options::default().from_bytes(s)
}

impl<'de> Deserializer<'de> {
Expand Down
14 changes: 12 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use serde::{de, ser};
use std::{error::Error as StdError, fmt, io, str::Utf8Error, string::FromUtf8Error};

pub use crate::parse::Position;

/// This type represents all possible errors that can occur when
/// serializing or deserializing RON data.
#[derive(Clone, Debug, PartialEq)]
Expand Down Expand Up @@ -113,6 +111,18 @@ impl fmt::Display for ErrorCode {
}
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Position {
pub line: usize,
pub col: usize,
}

impl fmt::Display for Position {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.line, self.col)
}
}

impl de::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Self {
Error {
Expand Down
61 changes: 42 additions & 19 deletions src/options.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,60 @@
//! Roundtrip serde Options module.
use std::io;

use serde::{de, ser};
use serde::{de, ser, Deserialize, Serialize};

use crate::de::Deserializer;
use crate::error::Result;
use crate::extensions::Extensions;
use crate::ser::{PrettyConfig, Serializer};

/// Roundtrip serde options.
///
/// # Examples
///
/// ```
/// use ron::{Options, extensions::Extensions};
///
/// let ron = Options::default()
/// .with_default_extension(Extensions::IMPLICIT_SOME);
///
/// let de: Option<i32> = ron.from_str("42").unwrap();
/// let ser = ron.to_string(&de).unwrap();
///
/// assert_eq!(ser, "42");
/// ```
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Options {
default_extensions: Extensions,
/// Extensions that are enabled by default during serialization and
/// deserialization.
/// During serialization, these extensions do NOT have to be explicitly
/// enabled in the parsed RON.
/// During deserialization, these extensions are used, but their explicit
/// activation is NOT included in the output RON.
/// No extensions are enabled by default.
pub default_extensions: Extensions,
}

impl Options {
#[must_use]
pub fn build() -> Self {
impl Default for Options {
fn default() -> Self {
Self {
default_extensions: Extensions::empty(),
}
}
}

impl Options {
#[must_use]
/// Enable `default_extension` by default during serialization and deserialization.
pub fn with_default_extension(mut self, default_extension: Extensions) -> Self {
self.default_extensions |= default_extension;
self
}

#[must_use]
/// Do NOT enable `default_extension` by default during serialization and deserialization.
pub fn without_default_extension(mut self, default_extension: Extensions) -> Self {
self.default_extensions &= !default_extension;
self
Expand Down Expand Up @@ -61,13 +90,13 @@ impl Options {
where
T: de::Deserialize<'a>,
{
let mut deserializer =
Deserializer::from_bytes(s)?.with_default_extensions(self.default_extensions);
let t = T::deserialize(&mut deserializer)?;
let mut deserializer = Deserializer::from_bytes_with_options(s, self.clone())?;

let value = T::deserialize(&mut deserializer)?;

deserializer.end()?;

Ok(t)
Ok(value)
}

/// Serializes `value` into `writer`
Expand All @@ -76,7 +105,7 @@ impl Options {
W: io::Write,
T: ?Sized + ser::Serialize,
{
let mut s = Serializer::new_with_default_extensions(writer, None, self.default_extensions)?;
let mut s = Serializer::with_options(writer, None, self.clone())?;
value.serialize(&mut s)
}

Expand All @@ -86,8 +115,7 @@ impl Options {
W: io::Write,
T: ?Sized + ser::Serialize,
{
let mut s =
Serializer::new_with_default_extensions(writer, Some(config), self.default_extensions)?;
let mut s = Serializer::with_options(writer, Some(config), self.clone())?;
value.serialize(&mut s)
}

Expand All @@ -100,8 +128,7 @@ impl Options {
T: ?Sized + ser::Serialize,
{
let mut output = Vec::new();
let mut s =
Serializer::new_with_default_extensions(&mut output, None, self.default_extensions)?;
let mut s = Serializer::with_options(&mut output, None, self.clone())?;
value.serialize(&mut s)?;
Ok(String::from_utf8(output).expect("Ron should be utf-8"))
}
Expand All @@ -112,11 +139,7 @@ impl Options {
T: ?Sized + ser::Serialize,
{
let mut output = Vec::new();
let mut s = Serializer::new_with_default_extensions(
&mut output,
Some(config),
self.default_extensions,
)?;
let mut s = Serializer::with_options(&mut output, Some(config), self.clone())?;
value.serialize(&mut s)?;
Ok(String::from_utf8(output).expect("Ron should be utf-8"))
}
Expand Down
15 changes: 1 addition & 14 deletions src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

use std::{
char::from_u32 as char_from_u32,
fmt::{Display, Formatter, Result as FmtResult},
str::{from_utf8, from_utf8_unchecked, FromStr},
};

use crate::{
error::{Error, ErrorCode, Result},
error::{Error, ErrorCode, Position, Result},
extensions::Extensions,
};

Expand Down Expand Up @@ -922,18 +921,6 @@ pub enum ParsedStr<'a> {
Slice(&'a str),
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Position {
pub line: usize,
pub col: usize,
}

impl Display for Position {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
write!(f, "{}:{}", self.line, self.col)
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
Loading

0 comments on commit 54320e9

Please sign in to comment.