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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
//! JSON is an ubiquitous format used in many applications.
//! There is no single way of storing JSON values depending on the context,
//! sometimes leading some applications to use multiples representations of JSON values in the same place.
//! This can cause a problem for JSON processing libraries that should not care about the actual internal representation of JSON values,
//! but are forced to stick to a particular format,
//! leading to unwanted and costly conversions between the different formats.
//!
//! This crate abstracts the JSON data structures defined in different library dealing with JSON such as `json`, `serde_json`, etc.
//! The goal is to remove hard dependencies to these libraries when possible,
//! and allow downstream users to choose its preferred library.
//! It basically defines a trait `Json` and a `ValueRef` type abstracting away the implementation details.
//!
//! The `Json` trait must be implemented by the JSON value type
//! and defines what opaque types are used to represent each component of a JSON value.
//! It also provides a function returning the value as a `ValueRef` enum type.
//! Its simplified definition is as follows:
//! ```rust
//! # pub struct ValueRef<'a, T>(std::marker::PhantomData<&'a T>);
//! /// JSON model.
//! pub trait Json: Sized + 'static {
//!     /// Literal number type.
//!     type Number;
//!
//!     /// String type.
//!     type String;
//!
//!     /// Array type.
//!     type Array;
//!
//!     /// Object key type.
//!     type Key;
//!
//!     /// Object type.
//!     type Object;
//!
//!     /// Returns a reference to this value as a `ValueRef`.
//!     fn value(&self) -> ValueRef<'_, Self>;
//!
//!     /// Metadata type attached to each value.
//!     type MetaData;
//!
//!     fn metadata(&self) -> &Self::MetaData;
//! }
//! ```
//!
//! The `ValueRef` exposes the structure of a reference to a JSON value:
//! ```rust
//! # use generic_json::Json;
//! pub enum ValueRef<'v, T: Json> {
//!     Null,
//!     Bool(bool),
//!     Number(&'v T::Number),
//!     String(&'v T::String),
//!     Array(&'v T::Array),
//!     Object(&'v T::Object)
//! }
//! ```
//!
//! In the same way, this crate also defines a `ValueMut` type for mutable references.
//! This allows each implementor to have their own inner representation of values while allowing interoperability.
//!
//! ## Trait aliases
//!
//! When the `nightly` feature is enabled,
//! this crate also defines some trait aliases that define common
//! requirements for JSON data types.
//! For instance the `JsonClone` trait alias ensures that every component
//! of the JSON value implements `Clone`.
#![cfg_attr(feature = "nightly", feature(trait_alias))]
#![feature(generic_associated_types)]
use cc_traits::{Get, Iter, Keyed, Len, MapIter};
use std::{hash::Hash, ops::Deref};

mod impls;
mod number;
mod reference;
mod value;

#[cfg(feature = "nightly")]
mod aliases;

pub use number::*;
pub use reference::*;
pub use value::*;

#[cfg(feature = "nightly")]
pub use aliases::*;

/// JSON object key.
pub trait Key<M>: Eq + Hash + Deref<Target = str> {
	fn metadata(&self) -> &M;
}

impl Key<()> for String {
	fn metadata(&self) -> &() {
		&()
	}
}

#[cfg(feature = "smallkey")]
impl<A: smallvec::Array<Item = u8>> Key<()> for smallstr::SmallString<A> {
	fn metadata(&self) -> &() {
		&()
	}
}

/// JSON value attached to some metadata.
pub trait Json: Sized + Eq {
	/// Metadata type attached to each value.
	///
	/// The metadata should be ignored during comparison/ordering/hashing of JSON values.
	type MetaData: Clone;

	/// Literal number type.
	type Number: Number;

	/// String type.
	type String: Eq + Deref<Target = str> + for<'a> From<&'a str>;

	/// Array type.
	type Array: Get<usize, Item = Self> + Len + Iter + IntoIterator<Item = Self>;

	/// Object key type.
	type Key: Key<Self::MetaData>;

	/// Object type.
	type Object: Keyed<Key = Self::Key, Item = Self>
		+ Len
		+ for<'a> Get<&'a str>
		+ MapIter
		+ IntoIterator<Item = (Self::Key, Self)>;

	/// Returns a reference to the actual JSON value (without the metadata).
	fn as_value_ref(&self) -> ValueRef<'_, Self>;

	/// Returns a mutable reference to the actual JSON value (without the metadata).
	fn as_value_mut(&mut self) -> ValueMut<'_, Self>;

	/// Transforms this JSON value into a `Value` and `MetaData`.
	fn into_parts(self) -> (Value<Self>, Self::MetaData);

	/// Transforms this JSON value into a `Value`.
	fn into_value(self) -> Value<Self> {
		self.into_parts().0
	}

	/// Returns a reference to the metadata associated to the JSON value.
	fn metadata(&self) -> &Self::MetaData;

	/// Returns a pair containing a reference to the JSON value and a reference to its metadata.
	fn as_pair(&self) -> (ValueRef<'_, Self>, &Self::MetaData) {
		(self.as_value_ref(), self.metadata())
	}

	/// Returns a pair containing a mutable reference to the JSON value and a reference to its metadata.
	fn as_pair_mut(&mut self) -> (ValueMut<'_, Self>, &Self::MetaData);

	/// Returns `true` if the value is a `Null`. Returns `false` otherwise.
	fn is_null(&self) -> bool {
		self.as_value_ref().is_null()
	}

	/// Checks if the value is an empty array.
	#[inline]
	fn is_empty_array(&self) -> bool {
		match self.as_value_ref() {
			ValueRef::Array(a) => a.is_empty(),
			_ => false,
		}
	}

	/// Checks if the value is an empty object.
	#[inline]
	fn is_empty_object(&self) -> bool {
		match self.as_value_ref() {
			ValueRef::Array(a) => a.is_empty(),
			_ => false,
		}
	}

	/// Checks if the value is an empty array or empty object.
	#[inline]
	fn is_empty_array_or_object(&self) -> bool {
		match self.as_value_ref() {
			ValueRef::Array(a) => a.is_empty(),
			ValueRef::Object(o) => o.is_empty(),
			_ => false,
		}
	}

	/// Returns `true` if the value is a boolean. Returns `false` otherwise.
	///
	/// For any value on which `is_bool` returns `true`,
	/// [`as_bool`](Self::as_bool()) is guaranteed to return the boolean value.
	fn is_bool(&self) -> bool {
		self.as_value_ref().is_bool()
	}

	/// Returns `true` if the value is a number. Returns `false` otherwise.
	///
	/// For any value on which `is_number` returns `true`,
	/// [`as_number`](Self::as_number()) is guaranteed to return the number value.
	fn is_number(&self) -> bool {
		self.as_value_ref().is_number()
	}

	/// Returns `true` if the value is a string.
	/// Returns `false` otherwise.
	///
	/// For any value on which `is_string` returns `true`,
	/// [`as_str`](Self::as_str()) is guaranteed to return the string value.
	fn is_string(&self) -> bool {
		self.as_value_ref().is_string()
	}

	/// Returns `true` if the value is an array.
	/// Returns `false` otherwise.
	///
	/// For any value on which `is_array` returns `true`,
	/// [`as_array`](Self::as_array()) is guaranteed to return the array value.
	fn is_array(&self) -> bool {
		self.as_value_ref().is_array()
	}

	/// Returns `true` if the value is an object.
	/// Returns `false` otherwise.
	///
	/// For any value on which `is_object` returns `true`,
	/// [`as_object`](Self::as_object()) is guaranteed to return the object value.
	fn is_object(&self) -> bool {
		self.as_value_ref().is_object()
	}

	/// If the value is a boolean, returns the associated `bool`.
	/// Returns `None` otherwise.
	fn as_bool(&self) -> Option<bool> {
		self.as_value_ref().as_bool()
	}

	/// If the value is a number, returns a reference to it.
	/// Returns `None` otherwise.
	fn as_number(&self) -> Option<&Self::Number> {
		self.as_value_ref().as_number()
	}

	/// Returns this number as an `u32` if it can be exactly represented as such.
	fn as_u32(&self) -> Option<u32> {
		self.as_value_ref().as_u32()
	}

	/// Returns this number as an `u64` if it can be exactly represented as such.
	fn as_u64(&self) -> Option<u64> {
		self.as_value_ref().as_u64()
	}

	/// Returns this number as an `i32` if it can be exactly represented as such.
	fn as_i32(&self) -> Option<i32> {
		self.as_value_ref().as_i32()
	}

	/// Returns this number as an `i64` if it can be exactly represented as such.
	fn as_i64(&self) -> Option<i64> {
		self.as_value_ref().as_i64()
	}

	/// Returns this number as an `f32` if it can be exactly represented as such.
	fn as_f32(&self) -> Option<f32> {
		self.as_value_ref().as_f32()
	}

	/// Returns this number as an `f32` if it is a number, potentially losing precision in the process.
	fn as_f32_lossy(&self) -> Option<f32> {
		self.as_value_ref().as_f32_lossy()
	}

	/// Returns this number as an `f64` if it can be exactly represented as such.
	fn as_f64(&self) -> Option<f64> {
		self.as_value_ref().as_f64()
	}

	/// Returns this number as an `f64` if it is a number, potentially losing precision in the process.
	fn as_f64_lossy(&self) -> Option<f64> {
		self.as_value_ref().as_f64_lossy()
	}

	/// If the value is a string, returns its associated [`str`].
	/// Returns `None` otherwise.
	fn as_str(&self) -> Option<&str> {
		self.as_value_ref().into_str()
	}

	/// If the value is an array, returns a reference to it.
	/// Returns `None` otherwise.
	fn as_array(&self) -> Option<&Self::Array> {
		self.as_value_ref().as_array()
	}

	/// If the value is an array, returns a mutable reference to it.
	/// Returns `None` otherwise.
	fn as_array_mut(&mut self) -> Option<&mut Self::Array> {
		self.as_value_mut().into_array_mut()
	}

	/// If the value is an object, returns a reference to it.
	/// Returns `None` otherwise.
	fn as_object(&self) -> Option<&Self::Object> {
		self.as_value_ref().as_object()
	}

	/// If the value is an object, returns a mutable reference to it.
	/// Returns `None` otherwise.
	fn as_object_mut(&mut self) -> Option<&mut Self::Object> {
		self.as_value_mut().into_object_mut()
	}
}

impl<J: Json> From<J> for Value<J> {
	fn from(j: J) -> Value<J> {
		j.into_value()
	}
}

/// Constructible JSON type.
pub trait JsonNew: Json {
	/// Creates a new "meta value" from a `Value` and its associated metadata.
	fn new(value: Value<Self>, metadata: Self::MetaData) -> Self;

	/// Creates a new object key.
	fn new_key(key: &str, metadata: Self::MetaData) -> Self::Key;

	/// Creates a new `null` value.
	fn null(metadata: Self::MetaData) -> Self {
		Self::new(Value::Null, metadata)
	}

	/// Creates a new boolean value.
	fn boolean(b: bool, metadata: Self::MetaData) -> Self {
		Self::new(Value::Boolean(b), metadata)
	}

	/// Creates a new number value.
	fn number(n: Self::Number, metadata: Self::MetaData) -> Self {
		Self::new(Value::Number(n), metadata)
	}

	/// Creates a new string value.
	fn string(s: Self::String, metadata: Self::MetaData) -> Self {
		Self::new(Value::String(s), metadata)
	}

	/// Creates a new array value.
	fn array(a: Self::Array, metadata: Self::MetaData) -> Self {
		Self::new(Value::Array(a), metadata)
	}

	/// Creates a new empty object value.
	fn empty_array(metadata: Self::MetaData) -> Self
	where
		Self::Array: Default,
	{
		Self::array(Self::Array::default(), metadata)
	}

	/// Creates a new object value.
	fn object(o: Self::Object, metadata: Self::MetaData) -> Self {
		Self::new(Value::Object(o), metadata)
	}

	/// Creates a new empty object value.
	fn empty_object(metadata: Self::MetaData) -> Self
	where
		Self::Object: Default,
	{
		Self::object(Self::Object::default(), metadata)
	}
}