1mod json5;
29mod jsonc;
30mod text;
31mod toml;
32mod yaml;
33
34use crate::error::{CoreError, ErrorCode};
35
36pub use text::{LineEnding, TextStyle};
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40#[non_exhaustive]
41pub enum Format {
42 Json,
44 Jsonc,
46 Toml,
47 Json5,
49 Yaml,
50}
51
52impl Format {
53 pub const fn as_str(self) -> &'static str {
54 match self {
55 Format::Json => "json",
56 Format::Jsonc => "jsonc",
57 Format::Toml => "toml",
58 Format::Json5 => "json5",
59 Format::Yaml => "yaml",
60 }
61 }
62}
63
64#[derive(Debug, Clone, PartialEq)]
69pub enum NativeValue {
70 Null,
72 Bool(bool),
73 Integer(i64),
74 Float(f64),
77 String(String),
78 Datetime(String),
80 Array(Vec<NativeValue>),
81 Object(NativeMap),
82}
83
84impl NativeValue {
85 pub fn parse_json(text: &str) -> Result<Self, CoreError> {
88 jsonc::parse_value(text)
89 }
90
91 pub fn as_str(&self) -> Option<&str> {
92 match self {
93 NativeValue::String(value) => Some(value),
94 _ => None,
95 }
96 }
97
98 pub fn as_object(&self) -> Option<&NativeMap> {
99 match self {
100 NativeValue::Object(map) => Some(map),
101 _ => None,
102 }
103 }
104
105 pub fn as_array(&self) -> Option<&[NativeValue]> {
106 match self {
107 NativeValue::Array(items) => Some(items),
108 _ => None,
109 }
110 }
111}
112
113impl From<&str> for NativeValue {
114 fn from(value: &str) -> Self {
115 NativeValue::String(value.to_owned())
116 }
117}
118
119impl From<String> for NativeValue {
120 fn from(value: String) -> Self {
121 NativeValue::String(value)
122 }
123}
124
125impl From<bool> for NativeValue {
126 fn from(value: bool) -> Self {
127 NativeValue::Bool(value)
128 }
129}
130
131impl From<i64> for NativeValue {
132 fn from(value: i64) -> Self {
133 NativeValue::Integer(value)
134 }
135}
136
137impl From<NativeMap> for NativeValue {
138 fn from(value: NativeMap) -> Self {
139 NativeValue::Object(value)
140 }
141}
142
143#[derive(Debug, Clone, Default)]
145pub struct NativeMap {
146 entries: Vec<(String, NativeValue)>,
147}
148
149impl NativeMap {
150 pub fn new() -> Self {
151 Self::default()
152 }
153
154 pub fn len(&self) -> usize {
155 self.entries.len()
156 }
157
158 pub fn is_empty(&self) -> bool {
159 self.entries.is_empty()
160 }
161
162 pub fn get(&self, key: &str) -> Option<&NativeValue> {
163 self.entries
164 .iter()
165 .find(|(name, _)| name == key)
166 .map(|(_, value)| value)
167 }
168
169 pub fn get_mut(&mut self, key: &str) -> Option<&mut NativeValue> {
170 self.entries
171 .iter_mut()
172 .find(|(name, _)| name == key)
173 .map(|(_, value)| value)
174 }
175
176 pub fn contains_key(&self, key: &str) -> bool {
177 self.get(key).is_some()
178 }
179
180 pub fn insert(&mut self, key: impl Into<String>, value: NativeValue) -> Option<NativeValue> {
182 let key = key.into();
183 match self.entries.iter_mut().find(|(name, _)| *name == key) {
184 Some((_, slot)) => Some(std::mem::replace(slot, value)),
185 None => {
186 self.entries.push((key, value));
187 None
188 }
189 }
190 }
191
192 pub fn remove(&mut self, key: &str) -> Option<NativeValue> {
193 let index = self.entries.iter().position(|(name, _)| name == key)?;
194 Some(self.entries.remove(index).1)
195 }
196
197 pub fn keys(&self) -> impl Iterator<Item = &str> {
198 self.entries.iter().map(|(name, _)| name.as_str())
199 }
200
201 pub fn iter(&self) -> impl Iterator<Item = (&str, &NativeValue)> {
202 self.entries
203 .iter()
204 .map(|(name, value)| (name.as_str(), value))
205 }
206}
207
208impl PartialEq for NativeMap {
209 fn eq(&self, other: &Self) -> bool {
210 self.len() == other.len()
211 && self
212 .iter()
213 .all(|(key, value)| other.get(key) == Some(value))
214 }
215}
216
217impl<K: Into<String>> FromIterator<(K, NativeValue)> for NativeMap {
218 fn from_iter<I: IntoIterator<Item = (K, NativeValue)>>(iter: I) -> Self {
219 let mut map = NativeMap::new();
220 for (key, value) in iter {
221 map.insert(key, value);
222 }
223 map
224 }
225}
226
227impl IntoIterator for NativeMap {
228 type Item = (String, NativeValue);
229 type IntoIter = std::vec::IntoIter<(String, NativeValue)>;
230
231 fn into_iter(self) -> Self::IntoIter {
232 self.entries.into_iter()
233 }
234}
235
236#[derive(Debug, Clone)]
245pub struct Document {
246 format: Format,
247 style: TextStyle,
248 body: Body,
249 created: Vec<Vec<String>>,
251}
252
253#[derive(Debug, Clone)]
254enum Body {
255 Json(jsonc::JsonBody),
256 Toml(toml::TomlBody),
257 Json5(json5::Json5Body),
258 Yaml(yaml::YamlBody),
259}
260
261impl Document {
262 pub fn parse(bytes: &[u8], format: Format) -> Result<Self, CoreError> {
266 let (text, style) = text::decode(bytes)?;
267 let body = match format {
268 Format::Json => Body::Json(jsonc::JsonBody::parse(text, true)?),
269 Format::Jsonc => Body::Json(jsonc::JsonBody::parse(text, false)?),
270 Format::Toml => Body::Toml(toml::TomlBody::parse(text)?),
271 Format::Json5 => match jsonc::JsonBody::parse(text.clone(), false) {
272 Ok(body) => Body::Json(body),
273 Err(_) => Body::Json5(json5::Json5Body::parse(text)?),
274 },
275 Format::Yaml => Body::Yaml(yaml::YamlBody::parse(text)?),
276 };
277 Ok(Self {
278 format,
279 style,
280 body,
281 created: Vec::new(),
282 })
283 }
284
285 pub fn empty(format: Format) -> Self {
287 Self::parse(b"", format).expect("an empty document parses")
288 }
289
290 pub fn format(&self) -> Format {
291 self.format
292 }
293
294 pub fn style(&self) -> TextStyle {
297 self.style
298 }
299
300 pub fn list(&self, container: &[&str]) -> Result<Vec<String>, CoreError> {
303 match &self.body {
304 Body::Json(body) => body.list(container),
305 Body::Toml(body) => body.list(container),
306 Body::Json5(body) => body.list(container),
307 Body::Yaml(body) => body.list(container),
308 }
309 }
310
311 pub fn get(&self, container: &[&str], key: &str) -> Result<Option<NativeValue>, CoreError> {
313 match &self.body {
314 Body::Json(body) => body.get(container, key),
315 Body::Toml(body) => body.get(container, key),
316 Body::Json5(body) => body.get(container, key),
317 Body::Yaml(body) => body.get(container, key),
318 }
319 }
320
321 pub fn upsert(
332 &mut self,
333 container: &[&str],
334 key: &str,
335 value: &NativeValue,
336 ) -> Result<bool, CoreError> {
337 let mut created = Vec::new();
338 let changed = match &mut self.body {
339 Body::Json(body) => body.upsert(container, key, value, &mut created)?,
340 Body::Toml(body) => body.upsert(container, key, value, &mut created)?,
341 Body::Json5(body) => {
342 if body.get(container, key)?.as_ref() == Some(value) {
343 false
344 } else {
345 return Err(body.read_only(container));
346 }
347 }
348 Body::Yaml(body) => body.upsert(container, key, value, &mut created)?,
349 };
350 self.created.extend(created);
351 Ok(changed)
352 }
353
354 pub fn remove(&mut self, container: &[&str], key: &str) -> Result<bool, CoreError> {
359 let removed = match &mut self.body {
360 Body::Json(body) => body.remove(container, key)?,
361 Body::Toml(body) => body.remove(container, key)?,
362 Body::Json5(body) => {
363 if body.get(container, key)?.is_some() {
364 return Err(body.read_only(container));
365 }
366 false
367 }
368 Body::Yaml(body) => body.remove(container, key)?,
369 };
370 if removed {
371 self.prune(container)?;
372 }
373 Ok(removed)
374 }
375
376 pub fn set_list_member(
380 &mut self,
381 list: &[&str],
382 member: &str,
383 present: bool,
384 ) -> Result<bool, CoreError> {
385 if list.is_empty() {
386 return Err(CoreError::new(
387 ErrorCode::InvalidValue,
388 "a list path needs at least one key",
389 ));
390 }
391 let mut created = Vec::new();
392 let changed = match &mut self.body {
393 Body::Json(body) => body.set_list_member(list, member, present, &mut created)?,
394 Body::Toml(body) => body.set_list_member(list, member, present, &mut created)?,
395 Body::Json5(body) => {
396 let (name, parent) = list.split_last().expect("checked above");
397 let listed = body.get(parent, name)?.is_some_and(|value| match value {
398 NativeValue::Array(items) => {
399 items.iter().any(|item| item.as_str() == Some(member))
400 }
401 _ => false,
402 });
403 if listed != present {
404 return Err(body.read_only(list));
405 }
406 false
407 }
408 Body::Yaml(body) => body.set_list_member(list, member, present, &mut created)?,
409 };
410 self.created.extend(created);
411 if changed && !present {
412 self.prune(list)?;
413 }
414 Ok(changed)
415 }
416
417 pub fn to_bytes(&self) -> Vec<u8> {
420 let body = match &self.body {
421 Body::Json(body) => body.text(),
422 Body::Toml(body) => body.text(),
423 Body::Json5(body) => body.text(),
424 Body::Yaml(body) => body.text(),
425 };
426 text::encode(&body, self.style)
427 }
428
429 fn prune(&mut self, path: &[&str]) -> Result<(), CoreError> {
432 for len in (0..=path.len()).rev() {
433 let prefix = &path[..len];
434 let Some(index) = self.created.iter().position(|created| *created == prefix) else {
435 return Ok(());
436 };
437 let removed = match &mut self.body {
438 Body::Json(body) => body.remove_if_empty(prefix)?,
439 Body::Toml(body) => body.remove_if_empty(prefix)?,
440 Body::Json5(_) => false,
441 Body::Yaml(body) => body.remove_if_empty(prefix)?,
442 };
443 if !removed {
444 return Ok(());
445 }
446 self.created.remove(index);
447 }
448 Ok(())
449 }
450}
451
452pub fn mapping_path<'p, 'a>(path: &'p [&'a str]) -> &'p [&'a str] {
456 match path.split_last() {
457 Some((last, rest)) if last.len() > 2 && last.starts_with('[') && last.ends_with(']') => {
458 rest
459 }
460 _ => path,
461 }
462}
463
464fn unexpected_shape(format: Format, path: &[&str], expected: &str) -> CoreError {
466 CoreError::new(
467 ErrorCode::UnexpectedShape,
468 format!(
469 "{} is not {expected}",
470 display_path(format, path.iter().copied())
471 ),
472 )
473}
474
475fn display_path<'a>(format: Format, path: impl Iterator<Item = &'a str>) -> String {
478 let path: Vec<&str> = path.collect();
479 match format {
480 Format::Toml if path.is_empty() => "the document root".to_owned(),
481 Format::Toml => path
482 .iter()
483 .map(|key| ::toml_edit::Key::new(*key).display_repr().into_owned())
484 .collect::<Vec<_>>()
485 .join("."),
486 _ if path.is_empty() => "the document root".to_owned(),
487 _ => path
488 .iter()
489 .map(|key| format!("/{}", key.replace('~', "~0").replace('/', "~1")))
490 .collect(),
491 }
492}