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};
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)]
181pub struct Span {
182 range: Range<usize>,
183 pub(crate) inner: Option<(usize, usize)>,
186 source: Arc<str>,
187}
188
189impl Span {
190 pub fn new(range: Range<usize>, source: Arc<str>) -> Span {
192 Span {
193 range,
194 inner: None,
195 source,
196 }
197 }
198
199 pub fn range(&self) -> Range<usize> {
201 self.range.clone()
202 }
203
204 pub fn source(&self) -> &Arc<str> {
206 &self.source
207 }
208
209 pub fn text(&self) -> Option<&str> {
211 self.source.get(self.range.clone())
212 }
213
214 pub fn start(&self) -> Position {
216 Position::of(self.source.as_bytes(), self.range.start)
217 }
218
219 pub fn end(&self) -> Position {
223 Position::of(self.source.as_bytes(), self.range.end)
224 }
225
226 pub(crate) fn start_range(&self) -> (usize, usize) {
227 match self.inner {
228 Some((start_end, _)) => (self.range.start, start_end),
229 None => (self.range.start, self.range.end),
230 }
231 }
232
233 pub(crate) fn end_range(&self) -> Option<(usize, usize)> {
234 self.inner.map(|(_, end_start)| (end_start, self.range.end))
235 }
236
237 pub(crate) fn set_end(&mut self, end_start: usize, end: usize) {
238 self.inner = Some((self.range.end, end_start));
239 self.range.end = end;
240 }
241}
242
243impl fmt::Debug for Span {
244 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245 f.debug_struct("Span")
246 .field("range", &self.range)
247 .finish_non_exhaustive()
248 }
249}
250
251static NULL: Value = Value::null();
252
253impl Value {
254 pub const fn null() -> Value {
256 Value {
257 kind: Kind::Null,
258 meta: None,
259 }
260 }
261
262 pub const fn new(kind: Kind) -> Value {
264 Value { kind, meta: None }
265 }
266
267 pub fn ext<T: Extension>(value: T) -> Value {
277 Value::from(ExtValue::owned(value))
278 }
279
280 pub fn bytes<B: Into<Vec<u8>>>(data: B) -> Value {
282 Value::new(Kind::Bytes(Bytes::new(data.into())))
283 }
284
285 pub fn kind(&self) -> &Kind {
287 &self.kind
288 }
289
290 pub fn kind_mut(&mut self) -> &mut Kind {
292 &mut self.kind
293 }
294
295 pub fn into_kind(self) -> Kind {
297 self.kind
298 }
299
300 pub fn into_parts(self) -> (Kind, Option<Meta>) {
302 (self.kind, self.meta.map(|meta| *meta))
303 }
304
305 pub fn meta(&self) -> Option<&Meta> {
307 self.meta.as_deref()
308 }
309
310 pub fn meta_mut(&mut self) -> &mut Meta {
314 self.meta.get_or_insert_with(Default::default)
315 }
316
317 pub fn take_meta(&mut self) -> Option<Meta> {
319 self.meta.take().map(|meta| *meta)
320 }
321
322 pub fn set_meta(&mut self, meta: Option<Meta>) {
324 self.meta = meta.filter(|meta| !meta.is_empty()).map(Box::new);
325 }
326
327 pub fn with_meta(mut self, meta: Meta) -> Value {
329 self.set_meta(Some(meta));
330 self
331 }
332
333 pub fn span(&self) -> Option<&Span> {
337 self.meta().and_then(Meta::span)
338 }
339
340 pub fn event_data(&self) -> Option<&EventData> {
344 self.meta().map(Meta::event_data)
345 }
346
347 pub fn take(&mut self) -> Value {
349 std::mem::take(self)
350 }
351}
352
353impl Default for Value {
354 fn default() -> Value {
355 Value::null()
356 }
357}
358
359impl Deref for Value {
360 type Target = Kind;
361
362 fn deref(&self) -> &Kind {
363 &self.kind
364 }
365}
366
367impl DerefMut for Value {
368 fn deref_mut(&mut self) -> &mut Kind {
369 &mut self.kind
370 }
371}
372
373impl Clone for Value {
374 fn clone(&self) -> Value {
375 Value {
376 kind: self.kind.clone(),
377 meta: self.meta.clone(),
378 }
379 }
380}
381
382impl PartialEq for Value {
383 fn eq(&self, other: &Value) -> bool {
384 tree::eq_kind(&self.kind, &other.kind)
385 }
386}
387
388impl Eq for Value {}
389
390impl Hash for Value {
391 fn hash<H: Hasher>(&self, state: &mut H) {
392 tree::hash_kind(&self.kind, state);
393 }
394}
395
396impl fmt::Debug for Value {
397 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
398 tree::fmt_kind(&self.kind, f)
399 }
400}
401
402impl<I: ValueIndex> std::ops::Index<I> for Value {
403 type Output = Value;
404
405 fn index(&self, index: I) -> &Value {
409 index.index_into(&self.kind).unwrap_or(&NULL)
410 }
411}
412
413impl<I: ValueIndex> std::ops::IndexMut<I> for Value {
414 fn index_mut(&mut self, index: I) -> &mut Value {
424 index.index_or_insert(self)
425 }
426}
427
428impl Kind {
429 pub fn name(&self) -> &str {
431 match self {
432 Kind::Null => "null",
433 Kind::Bool(_) => "bool",
434 Kind::U64(_) => "unsigned integer",
435 Kind::I64(_) => "signed integer",
436 Kind::F32(_) | Kind::F64(_) => "float",
437 Kind::Char(_) => "char",
438 Kind::Str(_) | Kind::Lexical(_) => "string",
439 Kind::Bytes(_) => "bytes",
440 Kind::Ext(ext) => ext.name(),
441 Kind::Implicit(value) => value.value().name(),
442 Kind::Seq(_) => "sequence",
443 Kind::Map(_) => "map",
444 }
445 }
446
447 pub fn is_null(&self) -> bool {
451 match self {
452 Kind::Null => true,
453 Kind::Ext(ext) => matches!(ext.fallback(), Atom::Null),
454 Kind::Implicit(value) => value.value() == ImplicitValue::Null,
455 _ => false,
456 }
457 }
458
459 pub fn as_bool(&self) -> Option<bool> {
461 match self {
462 Kind::Bool(value) => Some(*value),
463 Kind::Ext(ext) => match ext.fallback() {
464 Atom::Bool(value) => Some(value),
465 _ => None,
466 },
467 Kind::Implicit(value) => Kind::from_implicit(value.value()).as_bool(),
468 _ => None,
469 }
470 }
471
472 pub fn as_u64(&self) -> Option<u64> {
474 self.as_i128().and_then(|value| u64::try_from(value).ok())
475 }
476
477 pub fn as_i64(&self) -> Option<i64> {
479 self.as_i128().and_then(|value| i64::try_from(value).ok())
480 }
481
482 pub fn as_u128(&self) -> Option<u128> {
484 match self {
485 Kind::Ext(ext) if ext.is::<u128>() => ext.downcast_ref::<u128>().copied(),
486 _ => self.as_i128().and_then(|value| u128::try_from(value).ok()),
487 }
488 }
489
490 pub fn as_i128(&self) -> Option<i128> {
492 match self {
493 Kind::U64(value) => Some(i128::from(*value)),
494 Kind::I64(value) => Some(i128::from(*value)),
495 Kind::Implicit(value) => Kind::from_implicit(value.value()).as_i128(),
496 Kind::Ext(ext) => {
497 if let Some(value) = ext.downcast_ref::<i128>() {
498 Some(*value)
499 } else if let Some(value) = ext.downcast_ref::<u128>() {
500 i128::try_from(*value).ok()
501 } else {
502 match ext.fallback() {
503 Atom::U64(value) => Some(i128::from(value)),
504 Atom::I64(value) => Some(i128::from(value)),
505 _ => None,
506 }
507 }
508 }
509 _ => None,
510 }
511 }
512
513 pub fn as_f64(&self) -> Option<f64> {
517 match self {
518 Kind::F64(value) => Some(*value),
519 Kind::F32(value) => Some(f64::from(*value)),
520 Kind::U64(value) => Some(*value as f64),
521 Kind::I64(value) => Some(*value as f64),
522 Kind::Implicit(value) => Kind::from_implicit(value.value()).as_f64(),
523 Kind::Ext(ext) => match ext.fallback() {
524 Atom::F64(value) => Some(value),
525 Atom::F32(value) => Some(f64::from(value)),
526 Atom::U64(value) => Some(value as f64),
527 Atom::I64(value) => Some(value as f64),
528 _ => None,
529 },
530 _ => None,
531 }
532 }
533
534 pub fn as_char(&self) -> Option<char> {
536 match self {
537 Kind::Char(value) => Some(*value),
538 _ => None,
539 }
540 }
541
542 pub fn as_str(&self) -> Option<&str> {
547 match self {
548 Kind::Str(value) | Kind::Lexical(value) => Some(value),
549 Kind::Ext(ext) => match ext.fallback() {
550 Atom::Str(value) => value.borrowed_str(),
551 _ => None,
552 },
553 _ => None,
554 }
555 }
556
557 pub fn as_bytes(&self) -> Option<&[u8]> {
559 match self {
560 Kind::Bytes(value) => Some(value.data()),
561 _ => None,
562 }
563 }
564
565 pub fn as_seq(&self) -> Option<&Seq> {
567 match self {
568 Kind::Seq(value) => Some(value),
569 _ => None,
570 }
571 }
572
573 pub fn as_seq_mut(&mut self) -> Option<&mut Seq> {
575 match self {
576 Kind::Seq(value) => Some(value),
577 _ => None,
578 }
579 }
580
581 pub fn as_map(&self) -> Option<&Map> {
583 match self {
584 Kind::Map(value) => Some(value),
585 _ => None,
586 }
587 }
588
589 pub fn as_map_mut(&mut self) -> Option<&mut Map> {
591 match self {
592 Kind::Map(value) => Some(value),
593 _ => None,
594 }
595 }
596
597 pub fn as_ext(&self) -> Option<&ExtValue<'static>> {
599 match self {
600 Kind::Ext(value) => Some(value),
601 _ => None,
602 }
603 }
604
605 pub fn downcast_ext<T: Extension>(&self) -> Option<&T> {
610 self.as_ext().and_then(|ext| ext.downcast_ref::<T>())
611 }
612
613 pub fn downcast_ext_value<K: BorrowedExtension>(&self) -> Option<&K::Value<'_>> {
627 self.as_ext().and_then(|ext| ext.downcast_value_ref::<K>())
628 }
629
630 pub fn is_str(&self) -> bool {
634 matches!(self, Kind::Str(_) | Kind::Lexical(_))
635 }
636
637 pub fn is_lexical(&self) -> bool {
639 matches!(self, Kind::Lexical(_))
640 }
641
642 pub fn is_seq(&self) -> bool {
644 matches!(self, Kind::Seq(_))
645 }
646
647 pub fn is_map(&self) -> bool {
649 matches!(self, Kind::Map(_))
650 }
651
652 pub fn get<I: ValueIndex>(&self, index: I) -> Option<&Value> {
663 index.index_into(self)
664 }
665
666 pub fn get_mut<I: ValueIndex>(&mut self, index: I) -> Option<&mut Value> {
668 index.index_into_mut(self)
669 }
670
671 #[inline]
673 pub(crate) fn has_children(&self) -> bool {
674 match self {
675 Kind::Seq(seq) => !seq.is_empty(),
676 Kind::Map(map) => !map.is_empty(),
677 _ => false,
678 }
679 }
680}
681
682impl Clone for Kind {
683 fn clone(&self) -> Kind {
684 tree::clone_kind(self)
685 }
686}
687
688impl PartialEq for Kind {
689 fn eq(&self, other: &Kind) -> bool {
690 tree::eq_kind(self, other)
691 }
692}
693
694impl Eq for Kind {}
695
696impl Hash for Kind {
697 fn hash<H: Hasher>(&self, state: &mut H) {
698 tree::hash_kind(self, state);
699 }
700}
701
702impl fmt::Debug for Kind {
703 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704 tree::fmt_kind(self, f)
705 }
706}
707
708impl From<Kind> for Value {
709 fn from(kind: Kind) -> Value {
710 Value::new(kind)
711 }
712}
713
714impl From<()> for Value {
715 fn from(_: ()) -> Value {
716 Value::null()
717 }
718}
719
720impl From<bool> for Value {
721 fn from(value: bool) -> Value {
722 Value::new(Kind::Bool(value))
723 }
724}
725
726impl From<char> for Value {
727 fn from(value: char) -> Value {
728 Value::new(Kind::Char(value))
729 }
730}
731
732macro_rules! from_unsigned {
733 ($($ty:ty),*) => {
734 $(
735 impl From<$ty> for Value {
736 fn from(value: $ty) -> Value {
737 Value::new(Kind::U64(value as u64))
738 }
739 }
740 )*
741 };
742}
743
744macro_rules! from_signed {
745 ($($ty:ty),*) => {
746 $(
747 impl From<$ty> for Value {
748 fn from(value: $ty) -> Value {
749 Value::new(Kind::from_i64(value as i64))
750 }
751 }
752 )*
753 };
754}
755
756from_unsigned!(u8, u16, u32, u64, usize);
757from_signed!(i8, i16, i32, i64, isize);
758
759impl Kind {
760 pub(crate) fn from_i64(value: i64) -> Kind {
762 match u64::try_from(value) {
763 Ok(value) => Kind::U64(value),
764 Err(_) => Kind::I64(value),
765 }
766 }
767
768 pub(crate) fn from_implicit(value: ImplicitValue) -> Kind {
770 match value {
771 ImplicitValue::Null => Kind::Null,
772 ImplicitValue::Bool(value) => Kind::Bool(value),
773 ImplicitValue::U64(value) => Kind::U64(value),
774 ImplicitValue::I64(value) => Kind::from_i64(value),
775 ImplicitValue::F64(value) => Kind::F64(value),
776 _ => Kind::Null,
777 }
778 }
779
780 pub(crate) fn from_ext(ext: ExtValue<'_>) -> Kind {
784 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 owned = Bytes::new(bytes.into_owned());
916 match fallback {
917 Some(format) => owned.with_fallback(format),
918 None => owned,
919 }
920}
921
922impl PartialEq<str> for Value {
923 fn eq(&self, other: &str) -> bool {
924 matches!(self.kind, Kind::Str(ref value) | Kind::Lexical(ref value) if value == other)
925 }
926}
927
928impl PartialEq<&str> for Value {
929 fn eq(&self, other: &&str) -> bool {
930 *self == **other
931 }
932}
933
934impl PartialEq<String> for Value {
935 fn eq(&self, other: &String) -> bool {
936 *self == **other
937 }
938}
939
940impl PartialEq<bool> for Value {
941 fn eq(&self, other: &bool) -> bool {
942 matches!(self.kind, Kind::Bool(value) if value == *other)
943 }
944}
945
946impl PartialEq<f64> for Value {
947 fn eq(&self, other: &f64) -> bool {
948 match self.kind {
949 Kind::F64(value) => value == *other,
950 Kind::F32(value) => f64::from(value) == *other,
951 _ => false,
952 }
953 }
954}
955
956impl PartialEq<f32> for Value {
957 fn eq(&self, other: &f32) -> bool {
958 *self == f64::from(*other)
959 }
960}
961
962macro_rules! eq_int {
963 ($($ty:ty),*) => {
964 $(
965 impl PartialEq<$ty> for Value {
966 fn eq(&self, other: &$ty) -> bool {
967 match self.kind {
968 Kind::U64(value) => i128::from(value) == *other as i128,
969 Kind::I64(value) => i128::from(value) == *other as i128,
970 _ => false,
971 }
972 }
973 }
974 )*
975 };
976}
977
978eq_int!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);