firebase_rs_sdk/firestore/value/
value.rs

1use std::collections::BTreeMap;
2
3use crate::firestore::model::{GeoPoint, Timestamp};
4use crate::firestore::value::{ArrayValue, BytesValue, MapValue};
5
6#[derive(Clone, Debug, PartialEq)]
7pub struct FirestoreValue {
8    kind: ValueKind,
9}
10
11#[derive(Clone, Debug, PartialEq)]
12pub enum ValueKind {
13    Null,
14    Boolean(bool),
15    Integer(i64),
16    Double(f64),
17    Timestamp(Timestamp),
18    String(String),
19    Bytes(BytesValue),
20    Reference(String),
21    GeoPoint(GeoPoint),
22    Array(ArrayValue),
23    Map(MapValue),
24}
25
26impl FirestoreValue {
27    pub fn null() -> Self {
28        Self {
29            kind: ValueKind::Null,
30        }
31    }
32
33    pub fn from_bool(value: bool) -> Self {
34        Self {
35            kind: ValueKind::Boolean(value),
36        }
37    }
38
39    pub fn from_integer(value: i64) -> Self {
40        Self {
41            kind: ValueKind::Integer(value),
42        }
43    }
44
45    pub fn from_double(value: f64) -> Self {
46        Self {
47            kind: ValueKind::Double(value),
48        }
49    }
50
51    pub fn from_timestamp(value: Timestamp) -> Self {
52        Self {
53            kind: ValueKind::Timestamp(value),
54        }
55    }
56
57    pub fn from_string(value: impl Into<String>) -> Self {
58        Self {
59            kind: ValueKind::String(value.into()),
60        }
61    }
62
63    pub fn from_bytes(value: BytesValue) -> Self {
64        Self {
65            kind: ValueKind::Bytes(value),
66        }
67    }
68
69    pub fn from_reference(path: impl Into<String>) -> Self {
70        Self {
71            kind: ValueKind::Reference(path.into()),
72        }
73    }
74
75    pub fn from_geo_point(value: GeoPoint) -> Self {
76        Self {
77            kind: ValueKind::GeoPoint(value),
78        }
79    }
80
81    pub fn from_array(values: Vec<FirestoreValue>) -> Self {
82        Self {
83            kind: ValueKind::Array(ArrayValue::new(values)),
84        }
85    }
86
87    pub fn from_map(map: BTreeMap<String, FirestoreValue>) -> Self {
88        Self {
89            kind: ValueKind::Map(MapValue::new(map)),
90        }
91    }
92
93    pub fn kind(&self) -> &ValueKind {
94        &self.kind
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn builds_basic_values() {
104        let v = FirestoreValue::from_string("hello");
105        match v.kind() {
106            ValueKind::String(value) => assert_eq!(value, "hello"),
107            _ => panic!("unexpected kind"),
108        }
109    }
110}