Skip to content

Commit

Permalink
Initial toml-test
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Aug 10, 2021
1 parent 05dd8ef commit df1c5c7
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[workspace]
members = [
"crates/data",
]

[package]
name = "toml-test"
version = "0.1.0"
edition = "2018"

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[dev-dependencies]
toml-test-data = { version = "1", path = "crates/data" }
85 changes: 85 additions & 0 deletions src/encoded.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum Encoded {
Value(EncodedValue),
Table(std::collections::HashMap<String, Encoded>),
Array(Vec<Encoded>),
}

impl Encoded {
pub fn from_slice(v: &[u8]) -> Result<Self, serde_json::Error> {
serde_json::from_slice(v)
}
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EncodedValue {
#[serde(rename = "type")]
toml_type: EncodedValueType,
value: String,
}

impl<'a> From<&'a str> for EncodedValue {
fn from(other: &'a str) -> Self {
Self {
toml_type: EncodedValueType::String,
value: other.to_owned(),
}
}
}

impl From<String> for EncodedValue {
fn from(other: String) -> Self {
Self {
toml_type: EncodedValueType::String,
value: other,
}
}
}

impl From<i64> for EncodedValue {
fn from(other: i64) -> Self {
Self {
toml_type: EncodedValueType::Integer,
value: other.to_string(),
}
}
}

impl From<bool> for EncodedValue {
fn from(other: bool) -> Self {
Self {
toml_type: EncodedValueType::Integer,
value: other.to_string(),
}
}
}

impl From<f64> for EncodedValue {
fn from(other: f64) -> Self {
let s = format!("{:.15}", other);
let s = s.trim_end_matches('0');
let s = if s.ends_with('.') {
format!("{}0", s)
} else {
s.to_owned()
};
Self {
toml_type: EncodedValueType::Integer,
value: s,
}
}
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum EncodedValueType {
String,
Integer,
Float,
Bool,
Datetime,
DatetimeLocal,
DateLocal,
TimeLocal,
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod encoded;
6 changes: 6 additions & 0 deletions tests/encoded.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#[test]
fn can_load() {
for valid in toml_test_data::valid() {
toml_test::encoded::Encoded::from_slice(valid.expected).unwrap();
}
}

0 comments on commit df1c5c7

Please sign in to comment.