Possible
Rust library providing a three state enum for differentiating between an explicit null value and the absense of a value. This is intended to be used with serde
serialization and deserialization to address an ambiguity between null values and the absense of a value where Option
comflates the two.
Possible
is an enumerator over three possibilities Some(T)
, None
, and Void
. The intended use is that Some(T)
is used for storing some data like with an Option
; None
represents explicitly null values; and Void
represents the absense of any value.
Possible
implements most of the same functionality as Option
, and can often be used as a direct replacement. Even though there is disambiguation between None
and Void
, they will tend to be treated in the same way for most Option
functionality to behave in an expected way.
Installation
With cargo-edit, run the following to add this library to your project.
Otherwise add the following to the Cargo.toml
file of your project under the [dependencies]
table section.
# Under [dependencies]
= "0.1.0"
Usage
In it's most simple case, Possible
can be used in similar ways to Option
.
use Possible;
let possible_value: = Some;
assert_eq!;
if let Some = possible_value
let halved_possible_value = possible_value.map;
assert_eq!;
let unwrapped_value = possible_value.unwrap;
assert_eq!;
Matching can be done similarly to Option
type variants.
use Possible;
let possible_value: = Default default; // defaults to Possible::Void
if let Void = possible_value
match possible_value
assert_eq!;
assert_eq!;
assert_eq!;
The primary use case for this library is paired with serde
serialization and deserialization from formats like JSON. This is useful when the a null value (or None
) is a valid value yet the absence of a value is still significant to capture.
use Serialize;
use json;
use Possible;
// serde(skip_serializing_if = "Possible::is_void") is required to implicitly
// omit values that are set as Possible::Void from being serialized
let intended_output = OutputJsonData ;
let serialized = to_string.unwrap;
assert_eq!;
use Deserialize;
use Possible;
let input = r#"{
"id": 1324,
"name": "Ferris"
}"#;
// serde(default) is required to implicitly parse
// missing values as Possible::Void instead of Possible::None
let parsed_input: InputJsonData = from_str.unwrap;
assert_eq!;
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.