Skip to content

Commit

Permalink
feat(value): Add nil value
Browse files Browse the repository at this point in the history
This adds the missing Nil (null) type to the values of liquid, thus allowing
to parse serde_json and others containing null-values in the data directly
  • Loading branch information
gnunicorn committed Oct 30, 2017
1 parent 0f49d8d commit 89f6660
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/filters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,7 @@ pub fn default(input: &Value, args: &[Value]) -> FilterResult {
Array(ref a) => a.is_empty(),
Bool(b) => !b,
Num(_) => false,
Value::Nil => true,
};

if use_default {
Expand Down
8 changes: 8 additions & 0 deletions src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub enum Value {
Str(String),
Array(Array),
Object(Object),
Nil,
}

/// Type representing a Liquid array, payload of the `Value::Array` variant
Expand Down Expand Up @@ -132,6 +133,7 @@ impl PartialEq<Value> for Value {
(&Value::Str(ref x), &Value::Str(ref y)) => x == y,
(&Value::Array(ref x), &Value::Array(ref y)) => x == y,
(&Value::Object(ref x), &Value::Object(ref y)) => x == y,
(&Value::Nil, &Value::Nil) => true,

// encode Ruby truthiness; all values except false and nil
// are true, and we don't have a notion of nil
Expand Down Expand Up @@ -164,6 +166,7 @@ impl ToString for Value {
Value::Num(ref x) => x.to_string(),
Value::Bool(ref x) => x.to_string(),
Value::Str(ref x) => x.to_owned(),
Value::Nil => "".to_owned(),
Value::Array(ref x) => {
let arr: Vec<String> = x.iter().map(|v| v.to_string()).collect();
arr.join(", ")
Expand Down Expand Up @@ -269,6 +272,11 @@ mod test {
assert_eq!(TRUE, Value::Num(0f32));
}

#[test]
fn nil_equality() {
assert_eq!(Value::Nil, Value::Nil);
}

#[test]
fn object_equality() {
let mut values = HashMap::<String, Value>::new();
Expand Down
16 changes: 16 additions & 0 deletions tests/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,22 @@ pub fn deserialize_bool() {
assert_eq!(actual, liquid::Value::Bool(false));
}

#[test]
pub fn serialize_nil() {
let actual = liquid::Value::Nil;
let actual = serde_yaml::to_string(&actual).unwrap();
assert_diff!(&actual, "---\n~", "", 0);
}

#[test]
pub fn deserialize_nil() {
let actual: liquid::Value = serde_yaml::from_str("---\n~").unwrap();
assert_eq!(actual, liquid::Value::Nil);

let actual: liquid::Value = serde_yaml::from_str("---\n- ").unwrap();
assert_eq!(actual, liquid::Value::Array(vec![liquid::Value::Nil]));
}

#[test]
pub fn serialize_str() {
let actual = liquid::Value::str("Hello");
Expand Down

0 comments on commit 89f6660

Please sign in to comment.