From 51e231a988da6d498a53e4d853b344a8f5ff1443 Mon Sep 17 00:00:00 2001 From: trivernis Date: Wed, 5 Oct 2022 13:03:24 +0200 Subject: [PATCH] Add support for Option --- Cargo.toml | 2 +- src/value_trait.rs | 21 ++++++++++++++++++++- tests/structs.rs | 6 +++--- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f3d59b7..e296712 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = [".", "derive"] [package] name = "rusty-value" -version = "0.4.0" +version = "0.4.1" edition = "2021" license = "Apache-2.0" repository = "https://github.com/Trivernis/rusty-value" diff --git a/src/value_trait.rs b/src/value_trait.rs index fda3cc8..c49d168 100644 --- a/src/value_trait.rs +++ b/src/value_trait.rs @@ -1,6 +1,6 @@ use std::{collections::HashMap, ffi::OsString, path::PathBuf}; -use crate::{Fields, Float, HashablePrimitive, HashableValue, Primitive, Struct, Value}; +use crate::{Enum, Fields, Float, HashablePrimitive, HashableValue, Primitive, Struct, Value}; pub trait RustyValue { fn into_rusty_value(self) -> Value; @@ -174,6 +174,25 @@ impl RustyValue for PathBuf { } } +impl RustyValue for Option { + fn into_rusty_value(self) -> Value { + let name = String::from("Option"); + + match self { + Some(val) => Value::Enum(Enum { + name, + variant: String::from("Some"), + fields: Fields::Unnamed(vec![val.into_rusty_value()]), + }), + None => Value::Enum(Enum { + name, + variant: String::from("None"), + fields: Fields::Unit, + }), + } + } +} + impl RustyValue for Vec { fn into_rusty_value(self) -> Value { let value_vec = self diff --git a/tests/structs.rs b/tests/structs.rs index ebfc3f1..c2bb41c 100644 --- a/tests/structs.rs +++ b/tests/structs.rs @@ -35,11 +35,11 @@ fn it_handles_named_fields() { } #[derive(RustyValue)] -struct TestStructUnnamed(String, u64); +struct TestStructUnnamed(String, u64, Option); #[test] fn it_handles_unnamed_fields() { - let test_struct = TestStructUnnamed(String::from("Hello World"), 12); + let test_struct = TestStructUnnamed(String::from("Hello World"), 12, None); let value = test_struct.into_rusty_value(); dbg!(&value); @@ -47,7 +47,7 @@ fn it_handles_unnamed_fields() { assert_eq!(&s.name, "TestStructUnnamed"); if let Fields::Unnamed(fields) = s.fields { - assert_eq!(fields.len(), 2); + assert_eq!(fields.len(), 3); } else { panic!("Struct wasn't serialized as unnamed struct") }