Skip to main content

reddb_types/
conversions.rs

1//! Ergonomic `From<primitive>` conversions into [`Value`].
2//!
3//! These fluent-API conversions previously lived in
4//! `reddb-server`'s `storage::unified::devx::conversions`. Once [`Value`]
5//! moved to this keystone crate (ADR 0052) the orphan rule required them to
6//! live with the type they construct: both sides — `Value` and the std
7//! primitive — must have a local anchor, and that anchor is `Value` here.
8//! The bodies are byte-faithful relocations; behaviour is unchanged.
9
10use crate::Value;
11
12impl From<&str> for Value {
13    fn from(s: &str) -> Self {
14        Value::text(s.to_string())
15    }
16}
17
18impl From<String> for Value {
19    fn from(s: String) -> Self {
20        Value::text(s)
21    }
22}
23
24impl From<i32> for Value {
25    fn from(n: i32) -> Self {
26        Value::Integer(n as i64)
27    }
28}
29
30impl From<i64> for Value {
31    fn from(n: i64) -> Self {
32        Value::Integer(n)
33    }
34}
35
36impl From<f32> for Value {
37    fn from(n: f32) -> Self {
38        Value::Float(n as f64)
39    }
40}
41
42impl From<f64> for Value {
43    fn from(n: f64) -> Self {
44        Value::Float(n)
45    }
46}
47
48impl From<bool> for Value {
49    fn from(b: bool) -> Self {
50        Value::Boolean(b)
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn primitive_conversions_construct_expected_value_variants() {
60        assert_eq!(Value::from("red"), Value::text("red"));
61        assert_eq!(Value::from("db".to_string()), Value::text("db"));
62        assert_eq!(Value::from(7_i32), Value::Integer(7));
63        assert_eq!(Value::from(9_i64), Value::Integer(9));
64        assert_eq!(Value::from(1.5_f32), Value::Float(1.5));
65        assert_eq!(Value::from(2.25_f64), Value::Float(2.25));
66        assert_eq!(Value::from(true), Value::Boolean(true));
67    }
68}