1use std::borrow::Cow;
2use std::fmt;
3use std::hash::{Hash, Hasher};
4use std::ops::{Deref, DerefMut, Range};
5use std::sync::Arc;
6
7use deser_core::ext::{BorrowedExtension, ExtValue, Extension, RawInput};
8use deser_core::{Atom, Bytes, EventData, Implicit, ImplicitValue, Position};
9
10use crate::index::ValueIndex;
11use crate::map::Map;
12use crate::seq::Seq;
13use crate::tree;
14
15pub struct Value {
71 pub(crate) kind: Kind,
72 pub(crate) meta: Option<Box<Meta>>,
73}
74
75#[non_exhaustive]
79pub enum Kind {
80 Null,
81 Bool(bool),
82 U64(u64),
84 I64(i64),
88 F32(f32),
94 F64(f64),
96 Char(char),
97 Str(String),
98 Lexical(String),
107 Bytes(Bytes<'static>),
108 Ext(ExtValue<'static>),
110 Implicit(Implicit<'static>),
120 Seq(Seq),
121 Map(Map),
122}
123
124#[derive(Clone, Default, Debug)]
128pub struct Meta {
129 event_data: EventData,
130 span: Option<Span>,
131}
132
133impl Meta {
134 pub fn new() -> Meta {
136 Meta::default()
137 }
138
139 pub fn event_data(&self) -> &EventData {
143 &self.event_data
144 }
145
146 pub fn event_data_mut(&mut self) -> &mut EventData {
148 &mut self.event_data
149 }
150
151 pub fn span(&self) -> Option<&Span> {
153 self.span.as_ref()
154 }
155
156 pub fn set_span(&mut self, span: Option<Span>) {
158 self.span = span;
159 }
160
161 pub fn is_empty(&self) -> bool {
163 self.event_data.is_empty() && self.span.is_none()
164 }
165
166 pub(crate) fn from_parts(event_data: EventData, span: Option<Span>) -> Meta {
167 Meta { event_data, span }
168 }
169
170 pub(crate) fn span_mut(&mut self) -> Option<&mut Span> {
171 self.span.as_mut()
172 }
173}
174
175#[derive(Clone)]
182pub struct Span {
183 range: Range<usize>,
184 pub(crate) inner: Option<(usize, usize)>,
187 source: Arc<str>,
188}
189
190impl Span {
191 pub fn new(range: Range<usize>, source: Arc<str>) -> Span {
193 Span {
194 range,
195 inner: None,
196 source,
197 }
198 }
199
200 pub fn range(&self) -> Range<usize> {
202 self.range.clone()
203 }
204
205 pub fn source(&self) -> &Arc<str> {
207 &self.source
208 }
209
210 pub fn text(&self) -> Option<&str> {
212 self.source.get(self.range.clone())
213 }
214
215 pub fn start(&self) -> Position {
217 Position::of(self.source.as_bytes(), self.range.start)
218 }
219
220 pub fn end(&self) -> Position {
224 Position::of(self.source.as_bytes(), self.range.end)
225 }
226
227 pub(crate) fn start_range(&self) -> (usize, usize) {
228 match self.inner {
229 Some((start_end, _)) => (self.range.start, start_end),
230 None => (self.range.start, self.range.end),
231 }
232 }
233
234 pub(crate) fn end_range(&self) -> Option<(usize, usize)> {
235 self.inner.map(|(_, end_start)| (end_start, self.range.end))
236 }
237
238 pub(crate) fn set_end(&mut self, end_start: usize, end: usize) {
239 self.inner = Some((self.range.end, end_start));
240 self.range.end = end;
241 }
242}
243
244impl fmt::Debug for Span {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246 f.debug_struct("Span")
247 .field("range", &self.range)
248 .finish_non_exhaustive()
249 }
250}
251
252static NULL: Value = Value::null();
253
254impl Value {
255 pub const fn null() -> Value {
257 Value {
258 kind: Kind::Null,
259 meta: None,
260 }
261 }
262
263 pub const fn new(kind: Kind) -> Value {
265 Value { kind, meta: None }
266 }
267
268 pub fn ext<T: Extension>(value: T) -> Value {
278 Value::from(ExtValue::owned(value))
279 }
280
281 pub fn bytes<B: Into<Vec<u8>>>(data: B) -> Value {
283 Value::new(Kind::Bytes(Bytes::new(data.into())))
284 }
285
286 pub fn kind(&self) -> &Kind {
288 &self.kind
289 }
290
291 pub fn kind_mut(&mut self) -> &mut Kind {
293 &mut self.kind
294 }
295
296 pub fn into_kind(self) -> Kind {
298 self.kind
299 }
300
301 pub fn into_parts(self) -> (Kind, Option<Meta>) {
303 (self.kind, self.meta.map(|meta| *meta))
304 }
305
306 pub fn meta(&self) -> Option<&Meta> {
308 self.meta.as_deref()
309 }
310
311 pub fn meta_mut(&mut self) -> &mut Meta {
315 self.meta.get_or_insert_with(Default::default)
316 }
317
318 pub fn take_meta(&mut self) -> Option<Meta> {
320 self.meta.take().map(|meta| *meta)
321 }
322
323 pub fn set_meta(&mut self, meta: Option<Meta>) {
325 self.meta = meta.filter(|meta| !meta.is_empty()).map(Box::new);
326 }
327
328 pub fn span(&self) -> Option<&Span> {
332 self.meta().and_then(Meta::span)
333 }
334
335 pub fn event_data(&self) -> Option<&EventData> {
339 self.meta().map(Meta::event_data)
340 }
341
342 pub fn take(&mut self) -> Value {
344 std::mem::take(self)
345 }
346}
347
348impl Default for Value {
349 fn default() -> Value {
350 Value::null()
351 }
352}
353
354impl Deref for Value {
355 type Target = Kind;
356
357 fn deref(&self) -> &Kind {
358 &self.kind
359 }
360}
361
362impl DerefMut for Value {
363 fn deref_mut(&mut self) -> &mut Kind {
364 &mut self.kind
365 }
366}
367
368impl Clone for Value {
369 fn clone(&self) -> Value {
370 Value {
371 kind: self.kind.clone(),
372 meta: self.meta.clone(),
373 }
374 }
375}
376
377impl PartialEq for Value {
378 fn eq(&self, other: &Value) -> bool {
379 tree::eq_kind(&self.kind, &other.kind)
380 }
381}
382
383impl Eq for Value {}
384
385impl Hash for Value {
386 fn hash<H: Hasher>(&self, state: &mut H) {
387 tree::hash_kind(&self.kind, state);
388 }
389}
390
391impl fmt::Debug for Value {
392 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393 tree::fmt_kind(&self.kind, f)
394 }
395}
396
397impl<I: ValueIndex> std::ops::Index<I> for Value {
398 type Output = Value;
399
400 fn index(&self, index: I) -> &Value {
404 index.index_into(&self.kind).unwrap_or(&NULL)
405 }
406}
407
408impl<I: ValueIndex> std::ops::IndexMut<I> for Value {
409 fn index_mut(&mut self, index: I) -> &mut Value {
419 index.index_or_insert(self)
420 }
421}
422
423impl Kind {
424 pub fn name(&self) -> &str {
426 match self {
427 Kind::Null => "null",
428 Kind::Bool(_) => "bool",
429 Kind::U64(_) => "unsigned integer",
430 Kind::I64(_) => "signed integer",
431 Kind::F32(_) | Kind::F64(_) => "float",
432 Kind::Char(_) => "char",
433 Kind::Str(_) | Kind::Lexical(_) => "string",
434 Kind::Bytes(_) => "bytes",
435 Kind::Ext(ext) => ext.name(),
436 Kind::Implicit(value) => value.value().name(),
437 Kind::Seq(_) => "sequence",
438 Kind::Map(_) => "map",
439 }
440 }
441
442 pub fn is_null(&self) -> bool {
446 match self {
447 Kind::Null => true,
448 Kind::Ext(ext) => matches!(ext.fallback(), Atom::Null),
449 Kind::Implicit(value) => value.value() == ImplicitValue::Null,
450 _ => false,
451 }
452 }
453
454 pub fn as_bool(&self) -> Option<bool> {
456 match self {
457 Kind::Bool(value) => Some(*value),
458 Kind::Ext(ext) => match ext.fallback() {
459 Atom::Bool(value) => Some(value),
460 _ => None,
461 },
462 Kind::Implicit(value) => Kind::from_implicit(value.value()).as_bool(),
463 _ => None,
464 }
465 }
466
467 pub fn as_u64(&self) -> Option<u64> {
469 self.as_i128().and_then(|value| u64::try_from(value).ok())
470 }
471
472 pub fn as_i64(&self) -> Option<i64> {
474 self.as_i128().and_then(|value| i64::try_from(value).ok())
475 }
476
477 pub fn as_u128(&self) -> Option<u128> {
479 match self {
480 Kind::Ext(ext) if ext.is::<u128>() => ext.downcast_ref::<u128>().copied(),
481 _ => self.as_i128().and_then(|value| u128::try_from(value).ok()),
482 }
483 }
484
485 pub fn as_i128(&self) -> Option<i128> {
487 match self {
488 Kind::U64(value) => Some(i128::from(*value)),
489 Kind::I64(value) => Some(i128::from(*value)),
490 Kind::Implicit(value) => Kind::from_implicit(value.value()).as_i128(),
491 Kind::Ext(ext) => {
492 if let Some(value) = ext.downcast_ref::<i128>() {
493 Some(*value)
494 } else if let Some(value) = ext.downcast_ref::<u128>() {
495 i128::try_from(*value).ok()
496 } else {
497 match ext.fallback() {
498 Atom::U64(value) => Some(i128::from(value)),
499 Atom::I64(value) => Some(i128::from(value)),
500 _ => None,
501 }
502 }
503 }
504 _ => None,
505 }
506 }
507
508 pub fn as_f64(&self) -> Option<f64> {
512 match self {
513 Kind::F64(value) => Some(*value),
514 Kind::F32(value) => Some(f64::from(*value)),
515 Kind::U64(value) => Some(*value as f64),
516 Kind::I64(value) => Some(*value as f64),
517 Kind::Implicit(value) => Kind::from_implicit(value.value()).as_f64(),
518 Kind::Ext(ext) => match ext.fallback() {
519 Atom::F64(value) => Some(value),
520 Atom::F32(value) => Some(f64::from(value)),
521 Atom::U64(value) => Some(value as f64),
522 Atom::I64(value) => Some(value as f64),
523 _ => None,
524 },
525 _ => None,
526 }
527 }
528
529 pub fn as_char(&self) -> Option<char> {
531 match self {
532 Kind::Char(value) => Some(*value),
533 _ => None,
534 }
535 }
536
537 pub fn as_str(&self) -> Option<&str> {
542 match self {
543 Kind::Str(value) | Kind::Lexical(value) => Some(value),
544 Kind::Ext(ext) => match ext.fallback() {
545 Atom::Str(value) => value.borrowed_str(),
546 _ => None,
547 },
548 _ => None,
549 }
550 }
551
552 pub fn as_bytes(&self) -> Option<&[u8]> {
554 match self {
555 Kind::Bytes(value) => Some(value.data()),
556 _ => None,
557 }
558 }
559
560 pub fn as_seq(&self) -> Option<&Seq> {
562 match self {
563 Kind::Seq(value) => Some(value),
564 _ => None,
565 }
566 }
567
568 pub fn as_seq_mut(&mut self) -> Option<&mut Seq> {
570 match self {
571 Kind::Seq(value) => Some(value),
572 _ => None,
573 }
574 }
575
576 pub fn as_map(&self) -> Option<&Map> {
578 match self {
579 Kind::Map(value) => Some(value),
580 _ => None,
581 }
582 }
583
584 pub fn as_map_mut(&mut self) -> Option<&mut Map> {
586 match self {
587 Kind::Map(value) => Some(value),
588 _ => None,
589 }
590 }
591
592 pub fn as_ext(&self) -> Option<&ExtValue<'static>> {
594 match self {
595 Kind::Ext(value) => Some(value),
596 _ => None,
597 }
598 }
599
600 pub fn downcast_ext<T: Extension>(&self) -> Option<&T> {
605 self.as_ext().and_then(|ext| ext.downcast_ref::<T>())
606 }
607
608 pub fn downcast_ext_value<K: BorrowedExtension>(&self) -> Option<&K::Value<'_>> {
622 self.as_ext().and_then(|ext| ext.downcast_value_ref::<K>())
623 }
624
625 pub fn is_str(&self) -> bool {
629 matches!(self, Kind::Str(_) | Kind::Lexical(_))
630 }
631
632 pub fn is_lexical(&self) -> bool {
634 matches!(self, Kind::Lexical(_))
635 }
636
637 pub fn is_seq(&self) -> bool {
639 matches!(self, Kind::Seq(_))
640 }
641
642 pub fn is_map(&self) -> bool {
644 matches!(self, Kind::Map(_))
645 }
646
647 pub fn get<I: ValueIndex>(&self, index: I) -> Option<&Value> {
658 index.index_into(self)
659 }
660
661 pub fn get_mut<I: ValueIndex>(&mut self, index: I) -> Option<&mut Value> {
663 index.index_into_mut(self)
664 }
665
666 #[inline]
668 pub(crate) fn has_children(&self) -> bool {
669 match self {
670 Kind::Seq(seq) => !seq.is_empty(),
671 Kind::Map(map) => !map.is_empty(),
672 _ => false,
673 }
674 }
675}
676
677impl Clone for Kind {
678 fn clone(&self) -> Kind {
679 tree::clone_kind(self)
680 }
681}
682
683impl PartialEq for Kind {
684 fn eq(&self, other: &Kind) -> bool {
685 tree::eq_kind(self, other)
686 }
687}
688
689impl Eq for Kind {}
690
691impl Hash for Kind {
692 fn hash<H: Hasher>(&self, state: &mut H) {
693 tree::hash_kind(self, state);
694 }
695}
696
697impl fmt::Debug for Kind {
698 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
699 tree::fmt_kind(self, f)
700 }
701}
702
703impl From<Kind> for Value {
704 fn from(kind: Kind) -> Value {
705 Value::new(kind)
706 }
707}
708
709impl From<()> for Value {
710 fn from(_: ()) -> Value {
711 Value::null()
712 }
713}
714
715impl From<bool> for Value {
716 fn from(value: bool) -> Value {
717 Value::new(Kind::Bool(value))
718 }
719}
720
721impl From<char> for Value {
722 fn from(value: char) -> Value {
723 Value::new(Kind::Char(value))
724 }
725}
726
727macro_rules! from_unsigned {
728 ($($ty:ty),*) => {
729 $(
730 impl From<$ty> for Value {
731 fn from(value: $ty) -> Value {
732 Value::new(Kind::U64(value as u64))
733 }
734 }
735 )*
736 };
737}
738
739macro_rules! from_signed {
740 ($($ty:ty),*) => {
741 $(
742 impl From<$ty> for Value {
743 fn from(value: $ty) -> Value {
744 Value::new(Kind::from_i64(value as i64))
745 }
746 }
747 )*
748 };
749}
750
751from_unsigned!(u8, u16, u32, u64, usize);
752from_signed!(i8, i16, i32, i64, isize);
753
754impl Kind {
755 pub(crate) fn from_i64(value: i64) -> Kind {
757 match u64::try_from(value) {
758 Ok(value) => Kind::U64(value),
759 Err(_) => Kind::I64(value),
760 }
761 }
762
763 pub(crate) fn from_implicit(value: ImplicitValue) -> Kind {
765 match value {
766 ImplicitValue::Null => Kind::Null,
767 ImplicitValue::Bool(value) => Kind::Bool(value),
768 ImplicitValue::U64(value) => Kind::U64(value),
769 ImplicitValue::I64(value) => Kind::from_i64(value),
770 ImplicitValue::F64(value) => Kind::F64(value),
771 _ => Kind::Null,
772 }
773 }
774
775 pub(crate) fn from_ext(ext: ExtValue<'_>) -> Kind {
780 if let Some(input) = ext.downcast_value_ref::<RawInput>() {
781 if let Ok(value) = input.deserialize::<Value>() {
782 return value.kind;
783 }
784 } else if let Some(&value) = ext.downcast_ref::<u128>() {
785 if let Ok(value) = u64::try_from(value) {
786 return Kind::U64(value);
787 }
788 } else if let Some(&value) = ext.downcast_ref::<i128>()
789 && let Ok(value) = i64::try_from(value)
790 {
791 return Kind::from_i64(value);
792 }
793 Kind::Ext(ext.to_static())
794 }
795}
796
797impl From<u128> for Value {
798 fn from(value: u128) -> Value {
799 Value::new(match u64::try_from(value) {
800 Ok(value) => Kind::U64(value),
801 Err(_) => Kind::Ext(ExtValue::owned(value)),
802 })
803 }
804}
805
806impl From<i128> for Value {
807 fn from(value: i128) -> Value {
808 Value::new(match i64::try_from(value) {
809 Ok(value) => Kind::from_i64(value),
810 Err(_) => Kind::Ext(ExtValue::owned(value)),
811 })
812 }
813}
814
815impl From<f32> for Value {
816 fn from(value: f32) -> Value {
817 Value::new(Kind::F32(value))
818 }
819}
820
821impl From<f64> for Value {
822 fn from(value: f64) -> Value {
823 Value::new(Kind::F64(value))
824 }
825}
826
827impl From<&str> for Value {
828 fn from(value: &str) -> Value {
829 Value::new(Kind::Str(value.to_string()))
830 }
831}
832
833impl From<String> for Value {
834 fn from(value: String) -> Value {
835 Value::new(Kind::Str(value))
836 }
837}
838
839impl From<&String> for Value {
840 fn from(value: &String) -> Value {
841 Value::new(Kind::Str(value.clone()))
842 }
843}
844
845impl From<Cow<'_, str>> for Value {
846 fn from(value: Cow<'_, str>) -> Value {
847 Value::new(Kind::Str(value.into_owned()))
848 }
849}
850
851impl From<Bytes<'_>> for Value {
852 fn from(value: Bytes<'_>) -> Value {
853 Value::new(Kind::Bytes(owned_bytes(value)))
854 }
855}
856
857impl From<ExtValue<'_>> for Value {
858 fn from(value: ExtValue<'_>) -> Value {
863 Value::new(Kind::from_ext(value))
864 }
865}
866
867impl From<Seq> for Value {
868 fn from(value: Seq) -> Value {
869 Value::new(Kind::Seq(value))
870 }
871}
872
873impl From<Map> for Value {
874 fn from(value: Map) -> Value {
875 Value::new(Kind::Map(value))
876 }
877}
878
879impl<T: Into<Value>> From<Option<T>> for Value {
880 fn from(value: Option<T>) -> Value {
881 match value {
882 Some(value) => value.into(),
883 None => Value::null(),
884 }
885 }
886}
887
888impl<T: Into<Value>> From<Vec<T>> for Value {
889 fn from(value: Vec<T>) -> Value {
890 Value::from(value.into_iter().collect::<Seq>())
891 }
892}
893
894impl<T: Clone + Into<Value>> From<&[T]> for Value {
895 fn from(value: &[T]) -> Value {
896 Value::from(value.iter().cloned().collect::<Seq>())
897 }
898}
899
900impl<T: Into<Value>> FromIterator<T> for Value {
901 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Value {
902 Value::from(iter.into_iter().collect::<Seq>())
903 }
904}
905
906impl<K: Into<Value>, V: Into<Value>> FromIterator<(K, V)> for Value {
907 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Value {
908 Value::from(iter.into_iter().collect::<Map>())
909 }
910}
911
912pub(crate) fn owned_bytes(bytes: Bytes<'_>) -> Bytes<'static> {
914 let fallback = bytes.fallback;
915 let mut owned = Bytes::new(bytes.into_owned());
916 owned.fallback = fallback;
917 owned
918}
919
920impl PartialEq<str> for Value {
921 fn eq(&self, other: &str) -> bool {
922 matches!(self.kind, Kind::Str(ref value) | Kind::Lexical(ref value) if value == other)
923 }
924}
925
926impl PartialEq<&str> for Value {
927 fn eq(&self, other: &&str) -> bool {
928 *self == **other
929 }
930}
931
932impl PartialEq<String> for Value {
933 fn eq(&self, other: &String) -> bool {
934 *self == **other
935 }
936}
937
938impl PartialEq<bool> for Value {
939 fn eq(&self, other: &bool) -> bool {
940 matches!(self.kind, Kind::Bool(value) if value == *other)
941 }
942}
943
944impl PartialEq<f64> for Value {
945 fn eq(&self, other: &f64) -> bool {
946 match self.kind {
947 Kind::F64(value) => value == *other,
948 Kind::F32(value) => f64::from(value) == *other,
949 _ => false,
950 }
951 }
952}
953
954impl PartialEq<f32> for Value {
955 fn eq(&self, other: &f32) -> bool {
956 *self == f64::from(*other)
957 }
958}
959
960macro_rules! eq_int {
961 ($($ty:ty),*) => {
962 $(
963 impl PartialEq<$ty> for Value {
964 fn eq(&self, other: &$ty) -> bool {
965 match self.kind {
966 Kind::U64(value) => i128::from(value) == *other as i128,
967 Kind::I64(value) => i128::from(value) == *other as i128,
968 _ => false,
969 }
970 }
971 }
972 )*
973 };
974}
975
976eq_int!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);