1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use {
	super::{Value, ValueError},
	crate::result::Result,
	chrono::NaiveDateTime,
};

// TODO: No clone versions

pub trait Convert<Core> {
	fn convert(self) -> Result<Core>;
}

pub trait ConvertFrom<Value>: Sized {
	fn convert_from(value: Value) -> Result<Self>;
}
impl<Core, Value> ConvertFrom<Value> for Core
where
	Value: Convert<Core> + Clone,
{
	fn convert_from(value: Value) -> Result<Core> {
		value.convert()
	}
}

impl Convert<bool> for Value {
	fn convert(self) -> Result<bool> {
		Ok(match self {
			Value::Bool(inner) => inner,
			other => return Err(ValueError::CannotConvert(other, "BOOLEAN").into()),
		})
	}
}

impl Convert<u64> for Value {
	fn convert(self) -> Result<u64> {
		Ok(match self {
			Value::U64(inner) => inner,
			other => return Err(ValueError::CannotConvert(other, "UINTEGER").into()),
		})
	}
}

impl Convert<i64> for Value {
	fn convert(self) -> Result<i64> {
		Ok(match self {
			Value::I64(inner) => inner,
			other => return Err(ValueError::CannotConvert(other, "INTEGER").into()),
		})
	}
}

impl Convert<f64> for Value {
	fn convert(self) -> Result<f64> {
		Ok(match self {
			Value::F64(inner) => inner,
			#[cfg(feature = "implicit_float_conversion")]
			Value::I64(inner) => inner as f64,
			other => return Err(ValueError::CannotConvert(other, "FLOAT").into()),
		})
	}
}

impl Convert<String> for Value {
	fn convert(self) -> Result<String> {
		Ok(match self {
			Value::Str(inner) => inner,
			other => return Err(ValueError::CannotConvert(other, "TEXT").into()),
		})
	}
}

impl Convert<NaiveDateTime> for Value {
	fn convert(self) -> Result<NaiveDateTime> {
		let secs = self.convert()?;
		Ok(NaiveDateTime::from_timestamp(secs, 0))
	}
}