oicp_kit/types/extensions.rs
1//! `Extensions` — the map that keeps JSON fields this crate has never heard of.
2
3use std::collections::BTreeMap;
4
5use serde::{Deserialize, Serialize};
6
7use super::validate::{Validate, Validator};
8
9/// Undocumented JSON fields found on an OICP object, preserved verbatim.
10///
11/// # Why every object carries one
12///
13/// OICP 2.3 has no extensibility chapter and no version negotiation — but it *is* edited in place.
14/// Hubject revises the 2.3 documents without bumping the version: `IsHubjectCompatible` and
15/// `IsOpen24Hours` were added to `PullEvseData` this way, and the CDR schema gained a
16/// `PartnerProductID` clarification in 2026. A partner's stack that was built against last year's
17/// snapshot is still expected to forward this year's payloads intact.
18///
19/// So every wire object in this crate carries an `extensions` field marked `#[serde(flatten)]`.
20/// A field that arrives, survives and is written back unchanged is the difference between a hub
21/// that can sit between two parties who have agreed on something it knows nothing about, and one
22/// that quietly destroys their data.
23///
24/// Keys are kept in a [`BTreeMap`], so serialisation order is deterministic.
25///
26/// ```
27/// use oicp_kit::types::Extensions;
28///
29/// let json = r#"{"HubjectFutureField":"whatever","acme_note":3}"#;
30/// let extensions: Extensions = serde_json::from_str(json).unwrap();
31///
32/// assert_eq!(extensions.get::<u32>("acme_note").unwrap(), Some(3));
33/// assert_eq!(serde_json::to_string(&extensions).unwrap(), json);
34/// ```
35///
36/// In place, on a real object:
37///
38#[cfg_attr(feature = "cpo", doc = "```rust")]
39#[cfg_attr(not(feature = "cpo"), doc = "```rust,ignore")]
40/// # use oicp_kit::cpo::EvseStatusRecord;
41/// let json = r#"{"EvseID":"DE*XYZ*ETEST1","EvseStatus":"Available","HubjectAddedThis":42}"#;
42/// let record: EvseStatusRecord = serde_json::from_str(json).unwrap();
43/// assert_eq!(record.extensions.get::<u32>("HubjectAddedThis").unwrap(), Some(42));
44/// assert_eq!(serde_json::to_string(&record).unwrap(), json);
45/// ```
46#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
47#[serde(transparent)]
48pub struct Extensions(BTreeMap<String, serde_json::Value>);
49
50impl Extensions {
51 /// An empty set of extensions.
52 #[must_use]
53 pub fn new() -> Self {
54 Self::default()
55 }
56
57 /// Whether no undocumented field was present.
58 ///
59 /// Objects skip serialising their `extensions` field when this is true, so an object that
60 /// carried no extensions is written back byte-identically.
61 #[must_use]
62 pub fn is_empty(&self) -> bool {
63 self.0.is_empty()
64 }
65
66 /// How many undocumented fields are present.
67 #[must_use]
68 pub fn len(&self) -> usize {
69 self.0.len()
70 }
71
72 /// The raw JSON value stored under `key`, if any.
73 #[must_use]
74 pub fn get_raw(&self, key: &str) -> Option<&serde_json::Value> {
75 self.0.get(key)
76 }
77
78 /// Deserialises the value stored under `key` into `T`.
79 ///
80 /// Returns `Ok(None)` when the key is absent, and `Err` when it is present but does not
81 /// deserialise into `T`.
82 ///
83 /// # Errors
84 ///
85 /// Returns the `serde_json` error when the stored value is not a `T`.
86 pub fn get<T: serde::de::DeserializeOwned>(&self, key: &str) -> Result<Option<T>, serde_json::Error> {
87 self.0.get(key).map(|v| serde_json::from_value(v.clone())).transpose()
88 }
89
90 /// Whether `key` is present.
91 #[must_use]
92 pub fn contains_key(&self, key: &str) -> bool {
93 self.0.contains_key(key)
94 }
95
96 /// Stores `value` under `key`, returning what was there before.
97 ///
98 /// # Errors
99 ///
100 /// Returns the `serde_json` error when `value` cannot be serialised.
101 pub fn insert<T: Serialize>(
102 &mut self,
103 key: impl Into<String>,
104 value: T,
105 ) -> Result<(), serde_json::Error> {
106 self.0.insert(key.into(), serde_json::to_value(value)?);
107 Ok(())
108 }
109
110 /// Removes `key`, returning the raw value that was stored.
111 pub fn remove(&mut self, key: &str) -> Option<serde_json::Value> {
112 self.0.remove(key)
113 }
114
115 /// The keys present, in sorted order.
116 pub fn keys(&self) -> impl Iterator<Item = &str> {
117 self.0.keys().map(String::as_str)
118 }
119
120 /// The entries, in sorted key order.
121 pub fn iter(&self) -> impl Iterator<Item = (&str, &serde_json::Value)> {
122 self.0.iter().map(|(k, v)| (k.as_str(), v))
123 }
124}
125
126impl Validate for Extensions {
127 /// Extensions carry no spec constraints — that is the point of them.
128 fn validate_in(&self, _v: &mut Validator) {}
129}
130
131impl FromIterator<(String, serde_json::Value)> for Extensions {
132 fn from_iter<I: IntoIterator<Item = (String, serde_json::Value)>>(iter: I) -> Self {
133 Self(iter.into_iter().collect())
134 }
135}
136
137#[cfg(feature = "schema")]
138impl schemars::JsonSchema for Extensions {
139 fn schema_name() -> std::borrow::Cow<'static, str> {
140 "Extensions".into()
141 }
142 fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
143 schemars::json_schema!({ "type": "object", "additionalProperties": true })
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 #[test]
152 fn unknown_fields_survive_a_round_trip_in_sorted_order() {
153 let json = r#"{"a_first":1,"z_last":"text"}"#;
154 let ext: Extensions = serde_json::from_str(json).unwrap();
155 assert_eq!(ext.len(), 2);
156 assert_eq!(serde_json::to_string(&ext).unwrap(), json);
157 }
158
159 #[test]
160 fn typed_access_reports_a_mismatch_rather_than_guessing() {
161 let ext: Extensions = serde_json::from_str(r#"{"n":3,"s":"x"}"#).unwrap();
162 assert_eq!(ext.get::<u32>("n").unwrap(), Some(3));
163 assert_eq!(ext.get::<u32>("missing").unwrap(), None);
164 assert!(ext.get::<u32>("s").is_err());
165 }
166}