cargo_quickinstall/
json_value_ext.rs1use std::fmt;
2use tinyjson::JsonValue;
3
4pub struct JsonExtError(String);
5
6impl fmt::Display for JsonExtError {
7 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8 f.write_str(&self.0)
9 }
10}
11
12impl fmt::Debug for JsonExtError {
13 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14 f.write_str(&self.0)
15 }
16}
17
18impl std::error::Error for JsonExtError {}
19
20impl JsonExtError {
21 fn unexpected(value: &JsonValue, expected: &str) -> Self {
22 JsonExtError(format!(
23 "Expecting {expected}, but found {}",
24 value.get_value_type()
25 ))
26 }
27}
28
29pub trait JsonValueExt {
30 fn get_owned(self, key: &dyn JsonKey) -> Result<JsonValue, JsonExtError>;
31
32 fn try_into_string(self) -> Result<String, JsonExtError>;
33
34 fn get_value_type(&self) -> &'static str;
35}
36
37impl JsonValueExt for JsonValue {
38 fn get_owned(self, key: &dyn JsonKey) -> Result<JsonValue, JsonExtError> {
39 key.extract_from_value(self)
40 }
41
42 fn try_into_string(self) -> Result<String, JsonExtError> {
43 match self {
44 JsonValue::String(s) => Ok(s),
45 value => Err(JsonExtError::unexpected(&value, "String")),
46 }
47 }
48
49 fn get_value_type(&self) -> &'static str {
50 match self {
51 JsonValue::Number(..) => "Number",
52 JsonValue::Boolean(..) => "Boolean",
53 JsonValue::String(..) => "String",
54 JsonValue::Null => "Null",
55 JsonValue::Array(..) => "Array",
56 JsonValue::Object(..) => "Object",
57 }
58 }
59}
60
61pub trait JsonKey {
62 fn extract_from_value(&self, value: JsonValue) -> Result<JsonValue, JsonExtError>;
63}
64
65impl<T: JsonKey> JsonKey for &T {
66 fn extract_from_value(&self, value: JsonValue) -> Result<JsonValue, JsonExtError> {
67 T::extract_from_value(*self, value)
68 }
69}
70
71impl JsonKey for usize {
72 fn extract_from_value(&self, value: JsonValue) -> Result<JsonValue, JsonExtError> {
73 let index = *self;
74
75 match value {
76 JsonValue::Array(mut values) => {
77 let len = values.len();
78
79 if index < len {
80 Ok(values.swap_remove(index))
81 } else {
82 Err(JsonExtError(format!(
83 "Index {index} is too large for array of len {len}",
84 )))
85 }
86 }
87
88 value => Err(JsonExtError::unexpected(&value, "Array")),
89 }
90 }
91}
92
93impl JsonKey for &str {
94 fn extract_from_value(&self, value: JsonValue) -> Result<JsonValue, JsonExtError> {
95 let key = *self;
96
97 match value {
98 JsonValue::Object(mut map) => map
99 .remove(key)
100 .ok_or_else(|| JsonExtError(format!("Key {key} not found in object"))),
101
102 value => Err(JsonExtError::unexpected(&value, "Object")),
103 }
104 }
105}