1use std::cmp::Ordering;
2use std::collections::HashMap;
3use std::fmt;
4use std::hash::{Hash, Hasher};
5
6#[derive(Clone)]
10pub struct JsonString {
11 repr: StringRepr,
12}
13
14#[derive(Clone)]
15enum StringRepr {
16 Utf8(String),
17 Wtf8(Vec<u8>),
20}
21
22impl JsonString {
23 pub fn new() -> Self {
25 Self {
26 repr: StringRepr::Utf8(String::new()),
27 }
28 }
29
30 pub fn from_utf8(s: String) -> Self {
32 Self {
33 repr: StringRepr::Utf8(s),
34 }
35 }
36
37 pub(crate) fn from_wtf8(bytes: Vec<u8>) -> Self {
39 match String::from_utf8(bytes) {
40 Ok(s) => Self {
41 repr: StringRepr::Utf8(s),
42 },
43 Err(e) => Self {
44 repr: StringRepr::Wtf8(e.into_bytes()),
45 },
46 }
47 }
48
49 #[inline]
51 pub fn as_str(&self) -> Option<&str> {
52 match &self.repr {
53 StringRepr::Utf8(s) => Some(s.as_str()),
54 StringRepr::Wtf8(_) => None,
55 }
56 }
57
58 #[inline]
63 pub fn as_bytes(&self) -> &[u8] {
64 match &self.repr {
65 StringRepr::Utf8(s) => s.as_bytes(),
66 StringRepr::Wtf8(b) => b.as_slice(),
67 }
68 }
69
70 #[inline]
72 pub fn len(&self) -> usize {
73 self.as_bytes().len()
74 }
75
76 #[inline]
78 pub fn is_empty(&self) -> bool {
79 self.len() == 0
80 }
81
82 #[inline]
84 pub fn has_lone_surrogates(&self) -> bool {
85 matches!(self.repr, StringRepr::Wtf8(_))
86 }
87
88 pub fn to_string_lossy(&self) -> String {
90 match &self.repr {
91 StringRepr::Utf8(s) => s.clone(),
92 StringRepr::Wtf8(b) => String::from_utf8_lossy(b).into_owned(),
93 }
94 }
95}
96
97impl Default for JsonString {
98 fn default() -> Self {
99 Self::new()
100 }
101}
102
103impl PartialEq for JsonString {
104 #[inline]
105 fn eq(&self, other: &Self) -> bool {
106 self.as_bytes() == other.as_bytes()
107 }
108}
109
110impl Eq for JsonString {}
111
112impl Hash for JsonString {
113 #[inline]
114 fn hash<H: Hasher>(&self, state: &mut H) {
115 self.as_bytes().hash(state);
116 }
117}
118
119impl PartialOrd for JsonString {
120 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
121 Some(self.cmp(other))
122 }
123}
124
125impl Ord for JsonString {
126 fn cmp(&self, other: &Self) -> Ordering {
127 self.as_bytes().cmp(other.as_bytes())
128 }
129}
130
131impl PartialEq<str> for JsonString {
132 #[inline]
133 fn eq(&self, other: &str) -> bool {
134 self.as_str() == Some(other)
135 }
136}
137
138impl PartialEq<&str> for JsonString {
139 #[inline]
140 fn eq(&self, other: &&str) -> bool {
141 self.as_str() == Some(*other)
142 }
143}
144
145impl PartialEq<String> for JsonString {
146 #[inline]
147 fn eq(&self, other: &String) -> bool {
148 self.as_str() == Some(other.as_str())
149 }
150}
151
152impl From<String> for JsonString {
153 #[inline]
154 fn from(s: String) -> Self {
155 Self::from_utf8(s)
156 }
157}
158
159impl From<&str> for JsonString {
160 #[inline]
161 fn from(s: &str) -> Self {
162 Self::from_utf8(s.to_owned())
163 }
164}
165
166impl fmt::Debug for JsonString {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 match &self.repr {
169 StringRepr::Utf8(s) => fmt::Debug::fmt(s, f),
170 StringRepr::Wtf8(_) => {
171 let mut out = String::new();
172 crate::json::write_json_string(self, &mut out);
173 f.write_str(&out)
174 }
175 }
176 }
177}
178
179impl fmt::Display for JsonString {
180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 match &self.repr {
182 StringRepr::Utf8(s) => f.write_str(s),
183 StringRepr::Wtf8(b) => f.write_str(&String::from_utf8_lossy(b)),
184 }
185 }
186}
187
188#[inline]
190pub(crate) fn parse_array_index(key: &JsonString) -> Option<u32> {
191 let s = key.as_str()?;
192 let bytes = s.as_bytes();
193 if bytes.is_empty() || bytes.len() > 10 {
194 return None;
195 }
196 if bytes.len() > 1 && bytes[0] == b'0' {
197 return None;
198 }
199 let mut val: u64 = 0;
200 for &b in bytes {
201 if !b.is_ascii_digit() {
202 return None;
203 }
204 val = val * 10 + (b - b'0') as u64;
205 }
206 if val < 4_294_967_295 {
207 Some(val as u32)
208 } else {
209 None
210 }
211}
212
213const INDEX_THRESHOLD: usize = 16;
214
215#[derive(Clone, Default)]
221pub struct JsonObject {
222 entries: Vec<(JsonString, JsonValue)>,
223 index: Option<HashMap<JsonString, usize>>,
224}
225
226impl JsonObject {
227 pub fn new() -> Self {
229 Self::default()
230 }
231
232 pub fn with_capacity(cap: usize) -> Self {
234 Self {
235 entries: Vec::with_capacity(cap),
236 index: if cap >= INDEX_THRESHOLD {
237 Some(HashMap::with_capacity(cap))
238 } else {
239 None
240 },
241 }
242 }
243
244 #[inline]
246 pub fn len(&self) -> usize {
247 self.entries.len()
248 }
249
250 #[inline]
252 pub fn is_empty(&self) -> bool {
253 self.entries.is_empty()
254 }
255
256 fn ensure_index(&mut self) {
257 if self.index.is_none() && self.entries.len() >= INDEX_THRESHOLD {
258 let mut map = HashMap::with_capacity(self.entries.len() * 2);
259 for (i, (k, _)) in self.entries.iter().enumerate() {
260 map.insert(k.clone(), i);
261 }
262 self.index = Some(map);
263 }
264 }
265
266 fn find_index(&self, key: &JsonString) -> Option<usize> {
267 if let Some(ref map) = self.index {
268 map.get(key).copied()
269 } else {
270 self.entries.iter().position(|(k, _)| k == key)
271 }
272 }
273
274 fn find_index_str(&self, key: &str) -> Option<usize> {
275 if let Some(ref map) = self.index {
276 let k = JsonString::from(key);
278 map.get(&k).copied()
279 } else {
280 self.entries.iter().position(|(k, _)| k == key)
281 }
282 }
283
284 pub fn insert(
287 &mut self,
288 key: impl Into<JsonString>,
289 value: impl Into<JsonValue>,
290 ) -> Option<JsonValue> {
291 let key = key.into();
292 let value = value.into();
293 if let Some(idx) = self.find_index(&key) {
294 let old = std::mem::replace(&mut self.entries[idx].1, value);
295 return Some(old);
296 }
297 let idx = self.entries.len();
298 self.entries.push((key.clone(), value));
299 if let Some(ref mut map) = self.index {
300 map.insert(key, idx);
301 } else {
302 self.ensure_index();
303 }
304 None
305 }
306
307 pub(crate) fn push_unique(&mut self, key: JsonString, value: JsonValue) {
309 let idx = self.entries.len();
310 self.entries.push((key.clone(), value));
311 if let Some(ref mut map) = self.index {
312 map.insert(key, idx);
313 } else {
314 self.ensure_index();
315 }
316 }
317
318 #[inline]
320 pub fn contains_key(&self, key: &str) -> bool {
321 self.find_index_str(key).is_some()
322 }
323
324 #[inline]
326 pub fn contains_json_key(&self, key: &JsonString) -> bool {
327 self.find_index(key).is_some()
328 }
329
330 #[inline]
332 pub fn get(&self, key: &str) -> Option<&JsonValue> {
333 self.find_index_str(key).map(|i| &self.entries[i].1)
334 }
335
336 #[inline]
338 pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue> {
339 let idx = self.find_index_str(key)?;
340 Some(&mut self.entries[idx].1)
341 }
342
343 #[inline]
345 pub fn get_json(&self, key: &JsonString) -> Option<&JsonValue> {
346 self.find_index(key).map(|i| &self.entries[i].1)
347 }
348
349 #[inline]
351 pub fn get_json_mut(&mut self, key: &JsonString) -> Option<&mut JsonValue> {
352 let idx = self.find_index(key)?;
353 Some(&mut self.entries[idx].1)
354 }
355
356 #[inline]
358 pub fn iter(&self) -> std::slice::Iter<'_, (JsonString, JsonValue)> {
359 self.entries.iter()
360 }
361
362 pub fn ordered_entries(&self) -> Vec<(&JsonString, &JsonValue)> {
366 let mut has_array_index = false;
367 for (k, _) in &self.entries {
368 if parse_array_index(k).is_some() {
369 has_array_index = true;
370 break;
371 }
372 }
373 if !has_array_index {
374 return self.entries.iter().map(|(k, v)| (k, v)).collect();
375 }
376 let mut indices: Vec<(u32, usize)> = Vec::new();
377 let mut rest: Vec<usize> = Vec::with_capacity(self.entries.len());
378 for (i, (k, _)) in self.entries.iter().enumerate() {
379 if let Some(n) = parse_array_index(k) {
380 indices.push((n, i));
381 } else {
382 rest.push(i);
383 }
384 }
385 indices.sort_unstable_by_key(|&(n, _)| n);
386 let mut out = Vec::with_capacity(self.entries.len());
387 for (_, i) in indices {
388 let (k, v) = &self.entries[i];
389 out.push((k, v));
390 }
391 for i in rest {
392 let (k, v) = &self.entries[i];
393 out.push((k, v));
394 }
395 out
396 }
397
398 pub fn ordered_keys(&self) -> Vec<&JsonString> {
400 self.ordered_entries().into_iter().map(|(k, _)| k).collect()
401 }
402
403 pub fn normalize_key_order(&mut self) {
405 let mut has_array_index = false;
406 for (k, _) in &self.entries {
407 if parse_array_index(k).is_some() {
408 has_array_index = true;
409 break;
410 }
411 }
412 if !has_array_index {
413 return;
414 }
415 let mut indices: Vec<(u32, usize)> = Vec::new();
416 let mut rest: Vec<usize> = Vec::with_capacity(self.entries.len());
417 for (i, (k, _)) in self.entries.iter().enumerate() {
418 if let Some(n) = parse_array_index(k) {
419 indices.push((n, i));
420 } else {
421 rest.push(i);
422 }
423 }
424 indices.sort_unstable_by_key(|&(n, _)| n);
425 let mut old: Vec<Option<(JsonString, JsonValue)>> =
426 self.entries.drain(..).map(Some).collect();
427 for (_, i) in indices {
428 self.entries.push(old[i].take().unwrap());
429 }
430 for i in rest {
431 self.entries.push(old[i].take().unwrap());
432 }
433 if let Some(ref mut map) = self.index {
434 map.clear();
435 for (i, (k, _)) in self.entries.iter().enumerate() {
436 map.insert(k.clone(), i);
437 }
438 }
439 }
440}
441
442impl PartialEq for JsonObject {
443 fn eq(&self, other: &Self) -> bool {
444 if self.entries.len() != other.entries.len() {
445 return false;
446 }
447 let a = self.ordered_entries();
448 let b = other.ordered_entries();
449 a.iter()
450 .zip(b.iter())
451 .all(|((ka, va), (kb, vb))| ka == kb && va == vb)
452 }
453}
454
455impl fmt::Debug for JsonObject {
456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457 f.debug_map()
458 .entries(self.entries.iter().map(|(k, v)| (k, v)))
459 .finish()
460 }
461}
462
463impl FromIterator<(JsonString, JsonValue)> for JsonObject {
464 fn from_iter<T: IntoIterator<Item = (JsonString, JsonValue)>>(iter: T) -> Self {
465 let mut obj = JsonObject::new();
466 for (k, v) in iter {
467 obj.insert(k, v);
468 }
469 obj
470 }
471}
472
473impl<'a> IntoIterator for &'a JsonObject {
474 type Item = &'a (JsonString, JsonValue);
475 type IntoIter = std::slice::Iter<'a, (JsonString, JsonValue)>;
476
477 fn into_iter(self) -> Self::IntoIter {
478 self.entries.iter()
479 }
480}
481
482impl IntoIterator for JsonObject {
483 type Item = (JsonString, JsonValue);
484 type IntoIter = std::vec::IntoIter<(JsonString, JsonValue)>;
485
486 fn into_iter(self) -> Self::IntoIter {
487 self.entries.into_iter()
488 }
489}
490
491#[derive(Clone, Debug)]
494pub enum JsonValue {
495 Null,
497 Bool(bool),
499 Number(f64),
501 String(JsonString),
503 Array(Vec<JsonValue>),
505 Object(JsonObject),
507}
508
509impl JsonValue {
510 #[inline]
512 pub fn is_null(&self) -> bool {
513 matches!(self, Self::Null)
514 }
515
516 #[inline]
518 pub fn as_bool(&self) -> Option<bool> {
519 match self {
520 Self::Bool(b) => Some(*b),
521 _ => None,
522 }
523 }
524
525 #[inline]
527 pub fn as_f64(&self) -> Option<f64> {
528 match self {
529 Self::Number(n) => Some(*n),
530 _ => None,
531 }
532 }
533
534 #[inline]
536 pub fn as_str(&self) -> Option<&str> {
537 match self {
538 Self::String(s) => s.as_str(),
539 _ => None,
540 }
541 }
542
543 #[inline]
545 pub fn as_json_string(&self) -> Option<&JsonString> {
546 match self {
547 Self::String(s) => Some(s),
548 _ => None,
549 }
550 }
551
552 #[inline]
554 pub fn as_array(&self) -> Option<&[JsonValue]> {
555 match self {
556 Self::Array(a) => Some(a.as_slice()),
557 _ => None,
558 }
559 }
560
561 #[inline]
563 pub fn as_array_mut(&mut self) -> Option<&mut Vec<JsonValue>> {
564 match self {
565 Self::Array(a) => Some(a),
566 _ => None,
567 }
568 }
569
570 #[inline]
572 pub fn as_object(&self) -> Option<&JsonObject> {
573 match self {
574 Self::Object(o) => Some(o),
575 _ => None,
576 }
577 }
578
579 #[inline]
581 pub fn as_object_mut(&mut self) -> Option<&mut JsonObject> {
582 match self {
583 Self::Object(o) => Some(o),
584 _ => None,
585 }
586 }
587
588 pub fn parse_json(text: &str) -> Result<Self, crate::Error> {
590 crate::json::parse_json(text)
591 }
592
593 pub fn to_compact_json(&self) -> String {
595 crate::json::stringify_json(self)
596 }
597}
598
599impl PartialEq for JsonValue {
600 fn eq(&self, other: &Self) -> bool {
601 match (self, other) {
602 (Self::Null, Self::Null) => true,
603 (Self::Bool(a), Self::Bool(b)) => a == b,
604 (Self::Number(a), Self::Number(b)) => {
605 if *a == 0.0 && *b == 0.0 {
607 a.is_sign_negative() == b.is_sign_negative()
608 } else {
609 a == b
610 }
611 }
612 (Self::String(a), Self::String(b)) => a == b,
613 (Self::Array(a), Self::Array(b)) => a == b,
614 (Self::Object(a), Self::Object(b)) => a == b,
615 _ => false,
616 }
617 }
618}
619
620impl From<bool> for JsonValue {
621 fn from(b: bool) -> Self {
622 Self::Bool(b)
623 }
624}
625
626impl From<f64> for JsonValue {
627 fn from(n: f64) -> Self {
628 Self::Number(n)
629 }
630}
631
632impl From<i64> for JsonValue {
633 fn from(n: i64) -> Self {
634 Self::Number(n as f64)
635 }
636}
637
638impl From<i32> for JsonValue {
639 fn from(n: i32) -> Self {
640 Self::Number(f64::from(n))
641 }
642}
643
644impl From<u32> for JsonValue {
645 fn from(n: u32) -> Self {
646 Self::Number(f64::from(n))
647 }
648}
649
650impl From<usize> for JsonValue {
651 fn from(n: usize) -> Self {
652 Self::Number(n as f64)
653 }
654}
655
656impl From<&str> for JsonValue {
657 fn from(s: &str) -> Self {
658 Self::String(JsonString::from(s))
659 }
660}
661
662impl From<String> for JsonValue {
663 fn from(s: String) -> Self {
664 Self::String(JsonString::from(s))
665 }
666}
667
668impl From<JsonString> for JsonValue {
669 fn from(s: JsonString) -> Self {
670 Self::String(s)
671 }
672}
673
674impl From<Vec<JsonValue>> for JsonValue {
675 fn from(a: Vec<JsonValue>) -> Self {
676 Self::Array(a)
677 }
678}
679
680impl From<JsonObject> for JsonValue {
681 fn from(o: JsonObject) -> Self {
682 Self::Object(o)
683 }
684}