Skip to content

Commit

Permalink
refactor(all): The Grand Refactoring
Browse files Browse the repository at this point in the history
ordian committed Dec 9, 2017
1 parent 80ba274 commit f09bd5d
Showing 16 changed files with 423 additions and 582 deletions.
4 changes: 1 addition & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -16,10 +16,8 @@ appveyor = { repository = "ordian/toml_edit" }

[dependencies]
chrono = "0.4"
intrusive-collections = "0.6"
linked-hash-map = "0.4"
typed-arena = "1.3"
combine = "3.0.0-alpha.2"
combine = "=3.0.0-alpha.2"

[dev-dependencies]
serde_json = "1.0"
4 changes: 3 additions & 1 deletion fuzz/run.sh
Original file line number Diff line number Diff line change
@@ -2,7 +2,9 @@

set -e

wget https://github.com/rust-fuzz/targets/raw/master/run-fuzzer.sh -O run-fuzzer.sh
if [ ! -f run-fuzzer.sh ]; then
wget https://github.com/rust-fuzz/targets/raw/master/run-fuzzer.sh -O run-fuzzer.sh
fi

crate="$(dirname $0)"
target="parse_document"
19 changes: 11 additions & 8 deletions src/array_of_tables.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,36 @@
use table::Table;
use table::{Item, Table};

/// Type representing a TOML array of tables
#[derive(Clone, Debug, Default)]
pub struct ArrayOfTables {
pub(crate) values: Vec<Table>,
// always Vec<Item::Table>
pub(crate) values: Vec<Item>,
}

type ArrayOfTablesIter<'a> = Box<Iterator<Item = &'a Table> + 'a>;

impl ArrayOfTables {
pub fn new() -> Self {
Default::default()
}

/// Returns an iterator over tables
pub fn iter<'a>(&'a self) -> Box<Iterator<Item = &'a Table> + 'a> {
Box::new(self.values.iter())
pub fn iter(&self) -> ArrayOfTablesIter {
Box::new(self.values.iter().filter_map(Item::as_table))
}

/// Returns an optional reference to the table
pub fn get(&self, index: usize) -> Option<&Table> {
self.values.get(index)
self.values.get(index).and_then(Item::as_table)
}

/// Returns an optional mutable reference to the table
pub fn get_mut(&mut self, index: usize) -> Option<&mut Table> {
self.values.get_mut(index)
self.values.get_mut(index).and_then(Item::as_table_mut)
}

pub fn append(&mut self, table: Table) -> &mut Table {
self.values.push(table);
self.values.push(Item::Table(table));
let i = self.len() - 1;
self.get_mut(i).unwrap()
}
@@ -41,7 +44,7 @@ impl ArrayOfTables {
}

pub fn len(&self) -> usize {
self.values.len()
self.values.iter().filter(|i| i.is_table()).count()
}

pub fn is_empty(&self) -> bool {
60 changes: 36 additions & 24 deletions src/display.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::fmt::{Display, Formatter, Result};
use value::{Array, DateTime, InlineTable, KeyValue, Value};
use value::{Array, DateTime, InlineTable, Value};
use decor::{Formatted, Repr};
use document::Document;
use table::{Container, Table};
use table::{Item, Table};
use std::cell::{Cell, RefCell};

impl Display for Repr {
@@ -51,7 +51,7 @@ impl Display for Value {
impl Display for Array {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}[", self.decor.prefix)?;
join(f, self.values.iter(), ",")?;
join(f, self.iter(), ",")?;
if self.trailing_comma {
write!(f, ",")?;
}
@@ -60,17 +60,21 @@ impl Display for Array {
}
}

impl Display for KeyValue {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}={}", self.key, self.value)
}
}

impl Display for InlineTable {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}{{", self.decor.prefix)?;
write!(f, "{}", self.preamble)?;
join(f, self.key_value_pairs.values(), ",")?;
for (i, (key, value)) in self.items
.iter()
.filter(|&(_, kv)| kv.value.is_value())
.map(|(_, kv)| (&kv.key, kv.value.as_value().unwrap()))
.enumerate()
{
if i > 0 {
write!(f, ",")?;
}
write!(f, "{}={}", key, value)?;
}
write!(f, "}}{}", self.decor.suffix)
}
}
@@ -84,17 +88,18 @@ impl<'a> Display for TableFormatState<'a> {
fn fmt(&self, f: &mut Formatter) -> Result {
let table = self.table.get();

join(f, table.key_value_pairs.values(), "\n")?;
if !table.key_value_pairs.is_empty() {
write!(f, "\n")?;
for kv in table.items.values() {
if let Item::Value(ref value) = kv.value {
write!(f, "{}={}\n", kv.key, value)?;
}
}

for &(ref name, ref c) in table.containers.values() {
match *c {
Container::Table(ref t) => {
self.path.borrow_mut().push(name);
for kv in table.items.values() {
match kv.value {
Item::Table(ref t) => {
self.path.borrow_mut().push(&kv.key.raw_value);
self.table.set(t);
if !t.implicit {
if !(t.implicit && t.values_len() == 0) {
write!(f, "{}[", t.decor.prefix)?;
write!(f, "{}", self.path.borrow().join("."))?;
write!(f, "]{}\n", t.decor.suffix)?;
@@ -103,9 +108,9 @@ impl<'a> Display for TableFormatState<'a> {
self.table.set(table);
self.path.borrow_mut().pop();
}
Container::Array(ref a) => {
self.path.borrow_mut().push(name);
for t in &a.values {
Item::ArrayOfTables(ref a) => {
self.path.borrow_mut().push(&kv.key.raw_value);
for t in a.iter() {
self.table.set(t);
write!(f, "{}[[", t.decor.prefix)?;
write!(f, "{}", self.path.borrow().join("."))?;
@@ -115,19 +120,26 @@ impl<'a> Display for TableFormatState<'a> {
self.table.set(table);
self.path.borrow_mut().pop();
}
_ => {}
}
}
Ok(())
}
}

impl Display for Document {
impl Display for Table {
fn fmt(&self, f: &mut Formatter) -> Result {
let state = TableFormatState {
path: RefCell::new(Vec::new()),
table: Cell::new(&self.root),
table: Cell::new(self),
};
write!(f, "{}", state)?;
write!(f, "{}", state)
}
}

impl Display for Document {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", self.root)?;
write!(f, "{}", self.trailing)
}
}
4 changes: 2 additions & 2 deletions src/document.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::str::FromStr;
use table::{Table, TableChild};
use table::{Iter, Table};
use decor::InternalString;
use parser;

@@ -18,7 +18,7 @@ impl Document {
Default::default()
}

pub fn iter<'a>(&'a self) -> Box<Iterator<Item = (&'a str, TableChild<'a>)> + 'a> {
pub fn iter(&self) -> Iter {
self.root.iter()
}
}
54 changes: 34 additions & 20 deletions src/formatted.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
use value::{Array, DateTime, InlineTable, KeyValue, KeyValuePairs, Value};
use value::{Array, DateTime, InlineTable, Value};
use table::{Item, KeyValuePairs, TableKeyValue};
use decor::{Decor, Formatted, InternalString, Repr};
use key::Key;
use std::iter::FromIterator;


pub(crate) fn decorate_array(array: &mut Array) {
for (i, val) in array.values.iter_mut().enumerate() {
for (i, val) in array.values
.iter_mut()
.filter_map(|i| i.as_value_mut())
.enumerate() {
// [value1, value2, value3]
if i > 0 {
decorate(val, " ", "");
@@ -16,15 +20,21 @@ pub(crate) fn decorate_array(array: &mut Array) {
}

pub(crate) fn decorate_inline_table(table: &mut InlineTable) {
let n = table.key_value_pairs.len();
for (i, (_, kv)) in table.key_value_pairs.iter_mut().enumerate() {
let n = table.len();
for (i, (mut key, mut value)) in table
.items
.iter_mut()
.filter(|&(_, ref kv)| kv.value.is_value())
.map(|(_, kv)| (&mut kv.key, kv.value.as_value_mut().unwrap()))
.enumerate()
{
// { key1 = value1, key2 = value2 }
kv.key.decor.prefix = InternalString::from(" ");
kv.key.decor.suffix = InternalString::from(" ");
key.decor.prefix = InternalString::from(" ");
key.decor.suffix = InternalString::from(" ");
if i == n - 1 {
decorate(&mut kv.value, " ", " ");
decorate(value, " ", " ");
} else {
decorate(&mut kv.value, " ", "");
decorate(value, " ", "");
}
}
}
@@ -43,7 +53,7 @@ pub(crate) fn decorate(value: &mut Value, prefix: &str, suffix: &str) {
decor.suffix = InternalString::from(suffix);
}

pub(crate) fn decorated(mut value: Value, prefix: &str, suffix: &str) -> Value {
pub fn decorated(mut value: Value, prefix: &str, suffix: &str) -> Value {
{
decorate(&mut value, prefix, suffix);
}
@@ -73,17 +83,21 @@ pub(crate) fn value(mut val: Value, raw: &str) -> Value {
val
}

pub(crate) fn to_key_value(key: &str, mut value: Value) -> KeyValue {
pub(crate) fn to_key_value(key: &str, mut value: Value) -> TableKeyValue {
decorate(&mut value, " ", "");
KeyValue {
key: Repr {
decor: Decor {
prefix: InternalString::from(""),
suffix: InternalString::from(" "),
},
raw_value: key.into(),
TableKeyValue {
key: key_repr(key),
value: Item::Value(value),
}
}

pub(crate) fn key_repr(raw: &str) -> Repr {
Repr {
decor: Decor {
prefix: InternalString::from(""),
suffix: InternalString::from(" "),
},
value: value,
raw_value: raw.into(),
}
}

@@ -145,7 +159,7 @@ impl<V: Into<Value>> FromIterator<V> for Value {
where
I: IntoIterator<Item = V>,
{
let v = iter.into_iter().map(|a| a.into());
let v = iter.into_iter().map(|a| Item::Value(a.into()));
let mut array = Array {
values: v.collect(),
..Default::default()
@@ -174,7 +188,7 @@ impl<'k, K: Into<&'k Key>, V: Into<Value>> FromIterator<(K, V)> for Value {
I: IntoIterator<Item = (K, V)>,
{
let mut table = InlineTable {
key_value_pairs: to_key_value_pairs(iter),
items: to_key_value_pairs(iter),
..Default::default()
};
decorate_inline_table(&mut table);
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -26,9 +26,9 @@
//! assert_eq!(doc.unwrap().to_string(), toml);
//! }
//! ```
extern crate chrono;
#[macro_use]
extern crate combine;
extern crate chrono;
extern crate linked_hash_map;


@@ -41,10 +41,11 @@ mod key;
mod array_of_tables;
mod table;
mod document;
mod index;

pub use value::{Array, InlineTable, Value};
pub use key::Key;
pub use parser::TomlError;
pub use table::{Iter, IterMut, Table, TableChild, TableChildMut, TableEntry};
pub use table::{array, table, value, Item, Iter, Table};
pub use array_of_tables::ArrayOfTables;
pub use document::Document;
6 changes: 1 addition & 5 deletions src/parser/array.rs
Original file line number Diff line number Diff line change
@@ -26,11 +26,7 @@ fn array_from_vec(v: Vec<Value>, comma: bool, trailing: &str) -> Result<Array, C
got: format!("{:?}", val.get_type()),
expected: format!("{:?}", array.value_type()),
});
if !array.push_value(
val,
/* decorate = */
false,
) {
if !array.push_value(val, /* decorate = */ false) {
return err;
}
}
Loading
Oops, something went wrong.

0 comments on commit f09bd5d

Please sign in to comment.