multisql/data/value/
convert.rs

1use {
2	super::{Value, ValueError},
3	crate::result::Result,
4	chrono::NaiveDateTime,
5};
6
7// TODO: No clone versions
8
9pub trait Convert<Core> {
10	fn convert(self) -> Result<Core>;
11}
12
13pub trait ConvertFrom<Value>: Sized {
14	fn convert_from(value: Value) -> Result<Self>;
15}
16impl<Core, Value> ConvertFrom<Value> for Core
17where
18	Value: Convert<Core> + Clone,
19{
20	fn convert_from(value: Value) -> Result<Core> {
21		value.convert()
22	}
23}
24
25impl Convert<bool> for Value {
26	fn convert(self) -> Result<bool> {
27		Ok(match self {
28			Value::Bool(inner) => inner,
29			other => return Err(ValueError::CannotConvert(other, "BOOLEAN").into()),
30		})
31	}
32}
33
34impl Convert<u64> for Value {
35	fn convert(self) -> Result<u64> {
36		Ok(match self {
37			Value::U64(inner) => inner,
38			other => return Err(ValueError::CannotConvert(other, "UINTEGER").into()),
39		})
40	}
41}
42
43impl Convert<i64> for Value {
44	fn convert(self) -> Result<i64> {
45		Ok(match self {
46			Value::I64(inner) => inner,
47			other => return Err(ValueError::CannotConvert(other, "INTEGER").into()),
48		})
49	}
50}
51
52impl Convert<f64> for Value {
53	fn convert(self) -> Result<f64> {
54		Ok(match self {
55			Value::F64(inner) => inner,
56			#[cfg(feature = "implicit_float_conversion")]
57			Value::I64(inner) => inner as f64,
58			other => return Err(ValueError::CannotConvert(other, "FLOAT").into()),
59		})
60	}
61}
62
63impl Convert<String> for Value {
64	fn convert(self) -> Result<String> {
65		Ok(match self {
66			Value::Str(inner) => inner,
67			other => return Err(ValueError::CannotConvert(other, "TEXT").into()),
68		})
69	}
70}
71
72impl Convert<NaiveDateTime> for Value {
73	fn convert(self) -> Result<NaiveDateTime> {
74		let secs = self.convert()?;
75		Ok(NaiveDateTime::from_timestamp(secs, 0))
76	}
77}