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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
use std::ops::{Index, IndexMut};
use crate::{models::JsonNode, errors::JsonNodeError};
#[derive(Debug, Clone, PartialEq)]
pub struct JsonPropertyMap(Vec<(String, JsonNode)>);
impl JsonPropertyMap {
/// Create a new property map with no mappings.
pub fn new() -> Self {
Self(Vec::new())
}
/// Get the `JsonNode` associated with a name.
///
/// # Arguments
///
/// * `property_name` - The name of the property you want.
///
/// # Examples
///
/// ```
/// use json_node::{JsonNode, JsonValue, JsonPropertyMap};
///
/// // Create node with mappings.
/// let object_node = JsonNode::Object(JsonPropertyMap::from([
/// ("name".to_owned(), JsonNode::Value(JsonValue::String("John Doe".to_owned()))),
/// ("age".to_owned(), JsonNode::Value(JsonValue::Integer(42))),
/// ]));
///
/// let map = object_node.as_object().unwrap(); // &JsonPropertyMap.
/// let property = map.get("name").unwrap(); // &JsonNode.
/// let value = property.as_value().unwrap(); // &JsonValue.
/// let name = value.as_string().unwrap(); // &str.
///
/// assert_eq!(name, "John Doe");
/// ```
pub fn get(&self, property_name: &str) -> Option<&JsonNode> {
self.0.iter()
.find(|(k, _)| k == property_name)
.map(|(_, v)| v)
}
/// Get the `JsonNode` associated with a name as a mutable value.
///
/// # Arguments
///
/// * `property_name` - The name of the property you want.
///
/// # Examples
///
/// ```
/// use json_node::{JsonNode, JsonValue, JsonPropertyMap};
///
/// // Create node with mappings.
/// let mut object_node = JsonNode::Object(JsonPropertyMap::from([
/// ("name".to_owned(), JsonNode::Value(JsonValue::String("John Doe".to_owned()))),
/// ("age".to_owned(), JsonNode::Value(JsonValue::Integer(42))),
/// ]));
///
/// let mut_map = object_node.as_object_mut().unwrap(); // &mut JsonPropertyMap.
/// let mut_property = mut_map.get_mut("name").unwrap(); // &mut JsonNode.
/// let mut_value = mut_property.as_value_mut().unwrap(); // &mut JsonValue.
/// let mut_name = mut_value.as_string_mut().unwrap(); // &mut str.
///
/// mut_name.make_ascii_uppercase(); // Mutates the string slice.
///
/// let map = object_node.as_object().unwrap(); // &JsonPropertyMap.
/// let property = map.get("name").unwrap(); // &JsonNode.
/// let value = property.as_value().unwrap(); // &JsonValue.
/// let name = value.as_string().unwrap(); // &String.
///
/// assert_eq!(name, "JOHN DOE");
/// ```
pub fn get_mut(&mut self, property_name: &str) -> Option<&mut JsonNode> {
self.0.iter_mut()
.find(|(k, _)| k == property_name)
.map(|(_, v)| v)
}
/// Adds a new mapping to the object.
///
/// # Arguments
///
/// * `property_name` - Name of the new property.
/// * `json_node` - The `JsonNode` to be associated with the `property_name`.
///
/// # Examples
///
/// ```
/// use json_node::{JsonNode, JsonValue, JsonPropertyMap};
///
/// let mut map = JsonPropertyMap::new();
///
/// map.add("number", JsonNode::Value(JsonValue::Integer(42)));
///
/// let expected = JsonPropertyMap::from([
/// ("number".to_owned(), JsonNode::Value(JsonValue::Integer(42)))
/// ]);
///
/// assert_eq!(map, expected);
/// ```
pub fn add(&mut self, property_name: &str, json_node: JsonNode) {
if self.contains_property(&property_name) {
return;
}
self.0.push((property_name.to_owned(), json_node));
}
/// Removes a mapping from the object if it exists.
///
/// # Arguments
///
/// * `property_name` - Name of the property to be removed.
///
/// # Examples
///
/// ```
/// use json_node::{JsonNode, JsonValue, JsonPropertyMap};
///
/// let mut map = JsonPropertyMap::from([
/// ("number".to_owned(), JsonNode::Value(JsonValue::Integer(42)))
/// ]);
///
/// map.remove("number");
///
/// let expected = JsonPropertyMap::new();
/// assert_eq!(map, expected);
/// ```
pub fn remove(&mut self, property_name: &str) -> crate::Result<JsonNode> {
if self.0.iter().filter(|(k, _)| k == property_name).count() > 1 {
return Err(JsonNodeError::MultiplePropertiesWithSameKey(property_name.to_string()))
}
self.0.iter()
.position(|(k, _)| k == property_name)
.map(|i| self.0.remove(i).1)
.ok_or(JsonNodeError::KeyNotFound(property_name.to_string()))
}
/// Checks if a property with the name `property_name` exists.
///
/// # Arguments
///
/// * `property_name` - The name to check for.
///
/// # Examples
///
/// ```
/// use json_node::{JsonNode, JsonValue, JsonPropertyMap};
///
/// let mut map = JsonPropertyMap::from([
/// ("number".to_owned(), JsonNode::Value(JsonValue::Integer(42)))
/// ]);
///
/// assert!(map.contains_property("number"));
/// assert!(!map.contains_property("name"));
/// ```
pub fn contains_property(&self, property_name: &str) -> bool {
self.0.iter().any(|(k, _)| k == property_name)
}
/// Gets all property names in the object.
pub fn property_names(&self) -> Vec<&String> {
self.0.iter().map(|(k, _)| k).collect()
}
pub fn property_names_mut(&mut self) -> Vec<&mut String> {
self.0.iter_mut().map(|(k, _)| k).collect()
}
/// Gets all child nodes in the object.
pub fn nodes(&self) -> Vec<&JsonNode> {
self.0.iter().map(|(_, v)| v).collect()
}
/// Gets all child nodes in the object as mutable references.
pub fn nodes_mut(&mut self) -> Vec<&mut JsonNode> {
self.0.iter_mut().map(|(_, v)| v).collect()
}
/// Clears the map of all mappings.
pub fn clear(&mut self) {
self.0.clear();
}
/// Returns an iterator over the mappings represented as tuples.
pub fn iter(&self) -> std::slice::Iter<(String, JsonNode)> {
self.0.iter()
}
/// Returns an iterator over the mappings represented as tuples that allows modifying each element and its name.
pub fn iter_mut(&mut self) -> std::slice::IterMut<(String, JsonNode)> {
self.0.iter_mut()
}
/// Returns the number of mappings in the object.
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns true if the object has zero mappings.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Serialized the object as a JSON object string.
///
/// # Remarks
///
/// This function does zero formatting meaning the JSON string will have no spaces or new-lines.
pub fn to_json_string(&self) -> String {
let mut result = "{".to_string();
for (key, value) in &self.0 {
result.push_str(&format!("\"{}\":{},", key, value.to_json_string()));
}
result.pop(); // Pops the trailing comma
result.push('}');
result
}
}
impl Index<usize> for JsonPropertyMap {
type Output = (String, JsonNode);
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
impl IndexMut<usize> for JsonPropertyMap {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.0[index]
}
}
impl FromIterator<(String, JsonNode)> for JsonPropertyMap {
fn from_iter<T: IntoIterator<Item = (String, JsonNode)>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
impl From<Vec<(String, JsonNode)>> for JsonPropertyMap {
fn from(value: Vec<(String, JsonNode)>) -> Self {
Self(value)
}
}
impl<const COUNT: usize> From<[(String, JsonNode); COUNT]> for JsonPropertyMap {
fn from(value: [(String, JsonNode); COUNT]) -> Self {
Self(value.to_vec())
}
}
#[cfg(test)]
mod tests {
#[test]
fn get_mut() {
use crate::{JsonNode, JsonValue, JsonPropertyMap};
// Create node with mappings.
let mut object_node = JsonNode::Object(JsonPropertyMap::from([
("name".to_owned(), JsonNode::Value(JsonValue::String("John Doe".to_owned()))),
("age".to_owned(), JsonNode::Value(JsonValue::Integer(42))),
]));
let mut_map = object_node.as_object_mut().unwrap(); // &mut JsonPropertyMap.
let mut_property = mut_map.get_mut("name").unwrap(); // &mut JsonNode.
let mut_value = mut_property.as_value_mut().unwrap(); // &mut JsonValue.
let mut_name = mut_value.as_string_mut().unwrap(); // &mut str.
mut_name.make_ascii_uppercase(); // Mutates the string slice.
let map = object_node.as_object().unwrap(); // &JsonPropertyMap.
let property = map.get("name").unwrap(); // &JsonNode.
let value = property.as_value().unwrap(); // &JsonValue.
let name = value.as_string().unwrap(); // &String.
assert_eq!(name, "JOHN DOE");
}
}