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
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::ValueNotType("str"))
	}
}

impl AsType<'_> for i64 {
	fn from_value(value: &Value) -> Result<Self, JsonValueExtError> {
		value.as_i64().ok_or(JsonValueExtError::ValueNotType("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::ValueNotType("i32"))
	}
}

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::ValueNotType("u32"))
	}
}

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