value_ext/json/
as_type.rs

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
78
79
80
81
82
83
84
use crate::JsonValueExtError;
use serde_json::Value;

pub trait AsType<'a>: Sized {
	fn from_value(value: &'a Value) -> Result<Self, JsonValueExtError>;
}

impl<'a> AsType<'a> for &'a str {
	fn from_value(value: &'a Value) -> Result<Self, JsonValueExtError> {
		value.as_str().ok_or(JsonValueExtError::ValueNotOfType("str"))
	}
}

impl<'a> AsType<'a> for Option<&'a str> {
	fn from_value(value: &'a Value) -> Result<Self, JsonValueExtError> {
		Ok(value.as_str())
	}
}

impl AsType<'_> for f64 {
	fn from_value(value: &Value) -> Result<Self, JsonValueExtError> {
		value.as_f64().ok_or(JsonValueExtError::ValueNotOfType("f64"))
	}
}

impl AsType<'_> for Option<f64> {
	fn from_value(value: &Value) -> Result<Self, JsonValueExtError> {
		Ok(value.as_f64())
	}
}

impl AsType<'_> for i64 {
	fn from_value(value: &Value) -> Result<Self, JsonValueExtError> {
		value.as_i64().ok_or(JsonValueExtError::ValueNotOfType("i64"))
	}
}

impl AsType<'_> for Option<i64> {
	fn from_value(value: &Value) -> Result<Self, JsonValueExtError> {
		Ok(value.as_i64())
	}
}

impl AsType<'_> for i32 {
	fn from_value(value: &Value) -> Result<Self, JsonValueExtError> {
		value
			.as_i64()
			.and_then(|v| i32::try_from(v).ok())
			.ok_or(JsonValueExtError::ValueNotOfType("i32"))
	}
}

impl AsType<'_> for Option<i32> {
	fn from_value(value: &Value) -> Result<Self, JsonValueExtError> {
		Ok(value.as_i64().and_then(|v| i32::try_from(v).ok()))
	}
}

impl AsType<'_> for u32 {
	fn from_value(value: &Value) -> Result<Self, JsonValueExtError> {
		value
			.as_u64()
			.and_then(|v| u32::try_from(v).ok())
			.ok_or(JsonValueExtError::ValueNotOfType("u32"))
	}
}

impl AsType<'_> for Option<u32> {
	fn from_value(value: &Value) -> Result<Self, JsonValueExtError> {
		Ok(value.as_u64().and_then(|v| u32::try_from(v).ok()))
	}
}

impl AsType<'_> for bool {
	fn from_value(value: &Value) -> Result<Self, JsonValueExtError> {
		value.as_bool().ok_or(JsonValueExtError::ValueNotOfType("bool"))
	}
}

impl AsType<'_> for Option<bool> {
	fn from_value(value: &Value) -> Result<Self, JsonValueExtError> {
		Ok(value.as_bool())
	}
}