-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathmod.rs
1396 lines (1297 loc) · 52.7 KB
/
mod.rs
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Amazon.com, Inc. or its affiliates.
//! Provides a in-memory tree representation of Ion values that can be operated on in
//! a dynamically typed way.
//!
//! This module consists of two submodules that implement the value traits:
//!
//! * The [`owned`] module provides an implementation of values that have no associated
//! lifetime. These types are convenient, but may imply extra copying/cloning.
//! * The [`borrowed`] module provides an implementation of values that are tied to some
//! associated lifetime and borrow a reference to their underlying data in some way
//! (e.g. storing a `&str` in the value versus a fully owned `String`).
//! * The [`reader`] module provides API and implementation to read Ion data into [`IonElement`]
//! instances.
//! * The [`writer`] module provides API and implementation to write Ion data from [`IonElement`]
//! instances.
//!
//! ## Examples
//! In general, users will use the [`ElementReader`](reader::ElementReader) trait to read in data:
//!
//! ```
//! use ion_rs::IonType;
//! use ion_rs::result::IonResult;
//! use ion_rs::value::{IonElement, IonStruct};
//! use ion_rs::value::reader::element_reader;
//! use ion_rs::value::reader::ElementReader;
//!
//! fn main() -> IonResult<()> {
//! let mut iter = element_reader().iterate_over(br#""hello!""#)?;
//! if let Some(Ok(elem)) = iter.next() {
//! assert_eq!(IonType::String, elem.ion_type());
//! assert_eq!("hello!", elem.as_str().unwrap());
//! } else {
//! panic!("Expected an element!");
//! }
//! assert!(iter.next().is_none());
//! Ok(())
//! }
//! ```
//!
//! [`ElementReader::read_all`](reader::ElementReader::read_all) is a convenient way to put all of the
//! parsed [`IonElement`] into a [`Vec`], with a single [`IonError`](crate::result::IonError) wrapper:
//!
//! ```
//! # use ion_rs::IonType;
//! # use ion_rs::result::IonResult;
//! # use ion_rs::value::{IonElement, IonStruct};
//! # use ion_rs::value::reader::element_reader;
//! # use ion_rs::value::reader::ElementReader;
//! # fn main() -> IonResult<()> {
//! #
//! let elems = element_reader().read_all(br#""hello" world"#)?;
//! assert_eq!(2, elems.len());
//! assert_eq!(IonType::String, elems[0].ion_type());
//! assert_eq!("hello", elems[0].as_str().unwrap());
//! assert_eq!(IonType::Symbol, elems[1].ion_type());
//! assert_eq!("world", elems[1].as_str().unwrap());
//! #
//! # Ok(())
//! # }
//! ```
//!
//! [`ElementReader::read_one`](reader::ElementReader::read_one) is another convenient way to parse a single
//! top-level element into a [`IonElement`]. This method will return an error if the data has
//! a parsing error or if there is more than one [`IonElement`] in the stream:
//!
//! ```
//! # use ion_rs::IonType;
//! # use ion_rs::result::IonResult;
//! use ion_rs::types::integer::IntAccess;
//! # use ion_rs::value::{IonElement, IonStruct};
//! # use ion_rs::value::reader::element_reader;
//! # use ion_rs::value::reader::ElementReader;
//! # fn main() -> IonResult<()> {
//! #
//! // read a single value from binary: 42
//! let elem = element_reader().read_one(&[0xE0, 0x01, 0x00, 0xEA, 0x21, 0x2A])?;
//! assert_eq!(IonType::Integer, elem.ion_type());
//! assert_eq!(42, elem.as_i64().unwrap());
//!
//! // cannot read two values in a stream this way: 42 0
//! assert!(element_reader().read_one(&[0xE0, 0x01, 0x00, 0xEA, 0x21, 0x2A, 0x20]).is_err());
//!
//! // cannot read an empty stream (binary IVM only)
//! assert!(element_reader().read_one(&[0xE0, 0x01, 0x00, 0xEA]).is_err());
//!
//! // normal malformed binary is a failure!
//! assert!(element_reader().read_one(&[0xE0, 0x01, 0x00, 0xEA, 0xF0]).is_err());
//!
//! // also an error if malformed data happens after valid single value
//! assert!(element_reader().read_one(&[0xE0, 0x01, 0x00, 0xEA, 0x20, 0x30]).is_err());
//! #
//! # Ok(())
//! # }
//! ```
//!
//! To serialize data, users can use the [`ElementWriter`](writer::ElementWriter) trait to serialize data
//! from [`IonElement`] to binary or text Ion:
//!
//! ```
//! use ion_rs::result::IonResult;
//! use ion_rs::value::reader::{element_reader, ElementReader};
//! use ion_rs::value::writer::ElementWriter;
//! use ion_rs::{BinaryWriterBuilder};
//! use ion_rs::value::native_writer::NativeElementWriter;
//!
//! fn main() -> IonResult<()> {
//! let elems = element_reader().read_all(b"null true 1")?;
//!
//! let mut buf: Vec<u8> = vec![];
//! let mut writer = NativeElementWriter::new(BinaryWriterBuilder::new().build(&mut buf)?);
//! writer.write_all(elems.iter())?;
//!
//! writer.finish()?;
//! assert_eq!(&[0xE0, 0x01, 0x00, 0xEA, 0x0F, 0x11, 0x21, 0x01], buf.as_slice());
//!
//! Ok(())
//! }
//! ```
//!
//! Users should use the traits in this module to make their code work
//! in contexts that have either [`borrowed`] or [`owned`] values. This can be done
//! most easily by writing generic functions that can work with a reference of any type.
//!
//! For example, consider a fairly contrived, but generic `extract_text` function that unwraps
//! and converts [`IonSymbolToken::text()`] into an owned `String`:
//!
//! ```
//! use ion_rs::Symbol;
//! use ion_rs::value::IonSymbolToken;
//! use ion_rs::SymbolRef;
//!
//! fn extract_text<T: IonSymbolToken>(tok: &T) -> String {
//! tok.text().unwrap().into()
//! }
//!
//! let owned_token: Symbol = "hello".into();
//!
//! // owned value to emphasize lifetime
//! let text = String::from("hello");
//! let borrowed_token: SymbolRef = text.as_str().into();
//!
//! let owned_text = extract_text(&owned_token);
//! let borrowed_text = extract_text(&borrowed_token);
//! assert_eq!(owned_text, borrowed_text);
//! ```
//!
//! This extends to the [`IonElement`] trait as well which is the "top-level" API type for
//! any Ion datum. Consider a contrived function that extracts and returns the annotations
//! of an underlying element as a `Vec<String>`. Note that it filters out any annotation
//! that may not have text (so data could be dropped):
//!
//! ```
//! use ion_rs::value::{IonElement, IonSymbolToken};
//! use ion_rs::value::borrowed::{
//! ValueRef,
//! ElementRef,
//! text_token as borrowed_text_token
//! };
//! use ion_rs::value::owned::{
//! Value,
//! Element,
//! text_token as owned_text_token
//! };
//!
//! fn extract_annotations<T: IonElement>(elem: &T) -> Vec<Option<String>> {
//! elem.annotations().map(
//! |tok| tok.text().map(|text_ref| text_ref.to_string())
//! ).collect()
//! }
//!
//! let owned_elem = Element::new(
//! vec![
//! owned_text_token("foo"),
//! owned_text_token("bar")
//! ],
//! Value::String("baz".into())
//! );
//!
//! // owned values to emphasize lifetime
//! let strings: Vec<String> =
//! vec!["foo", "bar", "baz"].iter().map(|x| x.to_string()).collect();
//! let borrowed_elem = ElementRef::new(
//! vec![
//! borrowed_text_token(&strings[0]),
//! borrowed_text_token(&strings[1])
//! ],
//! ValueRef::String(&strings[2])
//! );
//!
//! let owned_annotations = extract_annotations(&owned_elem);
//! let borrowed_annotations = extract_annotations(&borrowed_elem);
//! assert_eq!(owned_annotations, borrowed_annotations);
//! ```
//!
//! For reference here are a couple other _value_ style APIs for JSON:
//! * [`simd_json`'s `Value` API][simd-json-value]
//! * [`serde_json`'s `Value` API][serde-json-value]
//!
//! [simd-json-value]: https://docs.rs/simd-json/latest/simd_json/value/index.html
//! [serde-json-value]: https://docs.serde.rs/serde_json/value/enum.Value.html
use crate::symbol_ref::AsSymbolRef;
use crate::types::decimal::Decimal;
use crate::types::integer::Integer;
use crate::types::timestamp::Timestamp;
use crate::types::SymbolId;
use crate::IonType;
use num_bigint::BigInt;
use std::fmt::Debug;
pub mod borrowed;
mod element_stream_reader;
mod iterators;
pub mod native_reader;
pub mod native_writer;
pub mod owned;
pub mod reader;
pub mod writer;
/// A view of a symbolic token.
///
/// This can be either a content associated with a symbol value, an annotation,
/// or a struct field name.
///
/// A given token may have `text`, a symbol ID ("SID"), or both depending on that implementation's
/// level of abstraction. For example:
///
/// * A symbol token implementation used by a raw binary reader might _only_ have a symbol ID, as
/// raw readers do not process symbol tables and so are not able to map symbol IDs to text.
/// * A symbol token implementation used by a raw text reader might have _either_ a symbol ID or
/// text, as text streams can encode symbols as either inline text (`foo`) or as
/// symbol IDs (`$10`).
/// * A symbol token implementation used by a user-level reader might always have text (because a
/// user-level reader can map symbol IDs to text) and choose to discard the symbol ID that was
/// used to encode that text because it is no longer necessary.
///
/// It is illegal for an implementation to return `None` for BOTH the text and local SID. If the
/// symbol token does not have known text, the implementation must return a local SID of `0`
/// (or another local SID whose value in the symbol table is `null`).
///
/// If an implementation represents a _resolved_ token...
/// * ...and the token has known text, the `text()` method MUST return `Some`.
/// * ...and the token has explicitly undefined text (for example, `$0` or any symbol ID whose
/// value in the symbol table is `null`), the `symbol_id()` method MUST return `Some(0)`.
/// (For example, if the symbol token in the stream is `$38` and its corresponding symbol table
/// entry is `null`, the `symbol_id` method must return `0` instead of `38`.)
///
/// This enables consistent equality testing; two raw tokens with different symbol IDs can be said
/// to be unequal because neither is resolved. In contrast, two resolved tokens with different
/// symbol IDs must be considered equal if those symbol IDs point to the same text or both have
/// undefined text.
pub trait IonSymbolToken: Debug + PartialEq {
/// The text of the token.
///
/// If the token was encoded as a symbol ID but has not been resolved (that is: mapped to text
/// via the symbol table), this method will return `None`.
///
/// If this token was encoded as a symbol ID whose text is explicitly known to be *undefined*
/// (for example: `$0`), this method will return `None`.
fn text(&self) -> Option<&str>;
/// The symbol ID of the token, which may be `None` if no ID is associated with the
/// token (e.g. Ion text symbols).
fn symbol_id(&self) -> Option<SymbolId>;
/// Decorates the [`IonSymbolToken`] with text.
fn with_text(self, text: &'static str) -> Self;
/// Decorates the [`IonSymbolToken`] with a symbol ID.
fn with_symbol_id(self, symbol_id: SymbolId) -> Self;
/// Constructs an [`IonSymbolToken`] with text and no symbol ID.
/// A common case for text and synthesizing tokens.
fn text_token(text: &'static str) -> Self;
/// Constructs an [`IonSymbolToken`] with unknown text and a local symbol ID.
/// A common case for binary parsing (though technically relevant in text).
fn symbol_id_token(symbol_id: SymbolId) -> Self;
/// Returns `true` if this token has been resolved.
///
/// Tokens with text are inherently resolved. Tokens without text are considered resolved if
/// they explicitly have unknown text (i.e. `$0` or a symbol ID whose corresponding value in the
/// symbol table is `null`.)
///
/// If a token has unknown text but `is_resolved` returns `false`, it may or may not have
/// associated text.
fn is_resolved(&self) -> bool {
self.text().is_some() || self.symbol_id() == Some(0)
}
}
/// Represents a either a borrowed or owned Ion value and its associated annotations (if any). There
/// are/will be specific APIs for _borrowed_ and _owned_ implementations, but this trait unifies
/// operations on either.
pub trait IonElement
where
Self: From<i64>
+ From<bool>
+ From<Decimal>
+ From<Timestamp>
+ From<f64>
+ From<BigInt>
+ Debug
+ PartialEq,
{
type SymbolToken: IonSymbolToken + Debug + PartialEq;
type Sequence: IonSequence<Element = Self> + ?Sized + Debug + PartialEq;
type Struct: IonStruct<FieldName = Self::SymbolToken, Element = Self>
+ ?Sized
+ Debug
+ PartialEq;
type Builder: Builder<SymbolToken = Self::SymbolToken, Element = Self> + ?Sized;
type AnnotationsIterator<'a>: Iterator<Item = &'a Self::SymbolToken>
where
Self: 'a;
/// The type of data this element represents.
fn ion_type(&self) -> IonType;
/// The annotations for this element.
///
/// ## Usage
/// ```
/// # use ion_rs::value::*;
/// # use ion_rs::value::owned::*;
/// # use ion_rs::value::borrowed::*;
/// // simple function to extract the annotations to owned strings.
/// // will panic if the text is not there!
/// fn annotation_strings<T: IonElement>(elem: &T) -> Vec<String> {
/// elem.annotations().map(|tok| tok.text().unwrap().into()).collect()
/// }
///
/// let strs = vec!["a", "b", "c"];
/// let owned_elem = Element::new(
/// strs.iter().map(|s| (*s).into()).collect(),
/// Value::String("moo".into())
/// );
/// let borrowed_elem = ElementRef::new(
/// strs.iter().map(|s| (*s).into()).collect(),
/// ValueRef::String("moo")
/// );
///
/// let expected: Vec<String> = strs.iter().map(|s| (*s).into()).collect();
/// assert_eq!(expected, annotation_strings(&owned_elem));
/// assert_eq!(expected, annotation_strings(&borrowed_elem));
///
/// // check if the element contains a particular annotation
/// assert!(&owned_elem.has_annotation("a"));
/// assert!(!&owned_elem.has_annotation("d"));
/// assert!(&borrowed_elem.has_annotation("a"));
/// assert!(!&borrowed_elem.has_annotation("d"));
/// ```
fn annotations(&self) -> Self::AnnotationsIterator<'_>;
/// Return an `Element` with given annotations
fn with_annotations<I: IntoIterator<Item = Self::SymbolToken>>(self, annotations: I) -> Self;
/// Return true if an `Element` contains given annotation otherwise return false
fn has_annotation(&self, annotation: &str) -> bool;
/// Returns whether this element is a `null` value
fn is_null(&self) -> bool;
/// Returns a reference to the underlying [`Integer`] for this element.
///
/// This will return `None` if the type is not `int` or the value is any `null`.
fn as_integer(&self) -> Option<&Integer>;
/// Returns a reference to the underlying float value for this element.
///
/// This will return `None` if the type is not `float` or the value is any `null`.
fn as_f64(&self) -> Option<f64>;
/// Returns a reference to the underlying [`Decimal`] for this element.
///
/// This will return `None` if the type is not `decimal` or the value is any `null`.
fn as_decimal(&self) -> Option<&Decimal>;
/// Returns a reference to the underlying [`Timestamp`] for this element.
///
/// This will return `None` if the type is not `timestamp` or the value is any `null`.
fn as_timestamp(&self) -> Option<&Timestamp>;
/// Returns a slice to the textual value of this element.
///
/// This will return `None` in the case that the type is not `string`/`symbol`,
/// if the value is any `null`, or the text of the `symbol` is not defined.
fn as_str(&self) -> Option<&str>;
/// Returns a reference to the [`IonSymbolToken`] of this element.
///
/// This will return `None` in the case that the type is not `symbol` or the value is
/// any `null`.
fn as_sym(&self) -> Option<&Self::SymbolToken>;
/// Returns a reference to the boolean value of this element.
///
/// This will return `None` in the case that the type is not `bool` or the value is
/// any `null`.
fn as_bool(&self) -> Option<bool>;
/// Returns a reference to the underlying bytes of this element.
///
/// This will return `None` in the case that the type is not `blob`/`clob` or the value is
/// any `null`.
fn as_bytes(&self) -> Option<&[u8]>;
/// Returns a reference to the [`IonSequence`] of this element.
///
/// This will return `None` in the case that the type is not `sexp`/`list` or
/// if the value is any `null`.
fn as_sequence(&self) -> Option<&Self::Sequence>;
/// Returns a reference to the [`IonStruct`] of this element.
///
/// This will return `None` in the case that the type is not `struct` or the value is
/// any `null`.
fn as_struct(&self) -> Option<&Self::Struct>;
// TODO add all the accessors to the trait
// TODO add mutation methods to the trait
}
/// Represents the _value_ of sequences of Ion elements (i.e. `list` and `sexp`).
pub trait IonSequence: Debug + PartialEq {
type Element: IonElement + ?Sized;
type ElementsIterator<'a>: Iterator<Item = &'a Self::Element>
where
Self: 'a;
/// The children of the sequence.
fn iter(&self) -> Self::ElementsIterator<'_>;
/// Returns a reference to the element in the sequence at the given index or
/// returns `None` if the index is out of the bounds.
fn get(&self, i: usize) -> Option<&Self::Element>;
/// Returns the length of the sequence
fn len(&self) -> usize;
/// Returns true if the sequence is empty otherwise returns false
fn is_empty(&self) -> bool;
}
/// Represents the _value_ of `struct` of Ion elements.
pub trait IonStruct: Debug + PartialEq {
type FieldName: IonSymbolToken + ?Sized;
type Element: IonElement + ?Sized;
type FieldsIterator<'a>: Iterator<Item = (&'a Self::FieldName, &'a Self::Element)>
where
Self: 'a;
type ValuesIterator<'a>: Iterator<Item = &'a Self::Element>
where
Self: 'a;
/// The fields of the structure.
fn iter(&self) -> Self::FieldsIterator<'_>;
/// Returns the last value corresponding to the field_name in the struct or
/// returns `None` if the field_name does not exist in the struct
///
/// ## Usage
/// Using the [borrowed] API:
/// ```
/// # use ion_rs::value::*;
/// # use ion_rs::value::borrowed::*;
/// let fields: Vec<(&str, ValueRef)>= vec![("e", "f"), ("g", "h")]
/// .into_iter().map(|(k, v)| (k, ValueRef::String(v))).collect();
/// let borrowed: StructRef = fields.into_iter().collect();
/// assert_eq!("h", borrowed.get("g".to_string()).map(|e| e.as_str()).flatten().unwrap());
/// ```
///
/// Using the [owned] API:
/// ```
/// # use ion_rs::value::*;
/// # use ion_rs::value::owned::*;
/// let fields: Vec<(&str, Value)>= vec![("a", "b"), ("c", "d")]
/// .into_iter().map(|(k, v)| (k, Value::String(v.into()))).collect();
/// let owned: Struct = fields.into_iter().collect();
/// assert_eq!("d", owned.get("c".to_string()).map(|e| e.as_str()).flatten().unwrap());
/// ```
fn get<T: AsSymbolRef>(&self, field_name: T) -> Option<&Self::Element>;
/// Returns an iterator with all the values corresponding to the field_name in the struct or
/// returns an empty iterator if the field_name does not exist in the struct
///
/// ## Usage
/// Using the [borrowed] API:
/// ```
/// # use ion_rs::value::*;
/// # use ion_rs::value::borrowed::*;
/// let fields: Vec<(&str, ValueRef)>= vec![("a", "b"), ("c", "d"), ("c", "e")]
/// .into_iter().map(|(k, v)| (k, ValueRef::String(v))).collect();
/// let borrowed: StructRef = fields.into_iter().collect();
/// assert_eq!(
/// vec!["d", "e"],
/// borrowed.get_all("c").flat_map(|e| e.as_str()).collect::<Vec<&str>>()
/// );
/// ```
///
/// Using the [owned] API:
/// ```
/// # use ion_rs::value::*;
/// # use ion_rs::value::owned::*;
/// let fields: Vec<(&str, Value)>= vec![("d", "e"), ("d", "f"), ("g", "h")]
/// .into_iter().map(|(k, v)| (k, Value::String(v.into()))).collect();
/// let owned: Struct = fields.into_iter().collect();
/// assert_eq!(
/// vec!["e", "f"],
/// owned.get_all("d").flat_map(|e| e.as_str()).collect::<Vec<&str>>()
/// );
/// ```
fn get_all<T: AsSymbolRef>(&self, field_name: T) -> Self::ValuesIterator<'_>;
}
pub trait Builder {
type Element: IonElement + ?Sized;
type SymbolToken: IonSymbolToken + PartialEq;
type Sequence: IonSequence<Element = Self::Element> + ?Sized;
type Struct: IonStruct<FieldName = Self::SymbolToken, Element = Self::Element> + ?Sized;
/// Builds a `null` from IonType using Builder.
fn new_null(e_type: IonType) -> Self::Element;
/// Builds a `bool` using Builder.
fn new_bool(bool: bool) -> Self::Element;
/// Builds a `string` using Builder.
fn new_string(str: &'static str) -> Self::Element;
/// Builds a `symbol` from SymbolToken using Builder.
fn new_symbol(sym: Self::SymbolToken) -> Self::Element;
/// Builds a `i64` using Builder.
fn new_i64(int: i64) -> Self::Element;
/// Builds a `big int` using Builder.
fn new_big_int(big_int: BigInt) -> Self::Element;
/// Builds a `decimal` using Builder.
fn new_decimal(decimal: Decimal) -> Self::Element;
/// Builds a `timestamp` using Builder.
fn new_timestamp(timestamp: Timestamp) -> Self::Element;
/// Builds a `f64` using Builder.
fn new_f64(float: f64) -> Self::Element;
/// Builds a `clob` using Builder.
fn new_clob(bytes: &'static [u8]) -> Self::Element;
/// Builds a `blob` using Builder.
fn new_blob(bytes: &'static [u8]) -> Self::Element;
/// Builds a `list` from Sequence using Builder.
fn new_list<I: IntoIterator<Item = Self::Element>>(seq: I) -> Self::Element;
/// Builds a `sexp` from Sequence using Builder.
fn new_sexp<I: IntoIterator<Item = Self::Element>>(seq: I) -> Self::Element;
/// Builds a `struct` from Struct using Builder.
fn new_struct<K, V, I>(structure: I) -> Self::Element
where
K: Into<Self::SymbolToken>,
V: Into<Self::Element>,
I: IntoIterator<Item = (K, V)>;
}
#[cfg(test)]
mod generic_value_tests {
use super::*;
use crate::types::timestamp::Timestamp;
use crate::value::borrowed::*;
use crate::value::owned::*;
use crate::value::IonElement;
use crate::IonType;
use chrono::*;
use rstest::*;
use std::iter::{once, Once};
/// Makes a timestamp from an RFC-3339 string and panics if it can't
fn make_timestamp<T: AsRef<str>>(text: T) -> Timestamp {
DateTime::parse_from_rfc3339(text.as_ref()).unwrap().into()
}
struct CaseAnnotations<E: IonElement> {
elem: E,
annotations: Vec<E::SymbolToken>,
}
fn annotations_text_case<E: IonElement>() -> CaseAnnotations<E> {
CaseAnnotations {
elem: E::Builder::new_i64(10).with_annotations(vec![
E::SymbolToken::text_token("foo"),
E::SymbolToken::text_token("bar"),
E::SymbolToken::text_token("baz"),
]),
annotations: vec![
E::SymbolToken::text_token("foo"),
E::SymbolToken::text_token("bar"),
E::SymbolToken::text_token("baz"),
],
}
}
fn annotations_local_sid_case<E: IonElement>() -> CaseAnnotations<E>
where
E::Builder: Builder<SymbolToken = E::SymbolToken>,
{
CaseAnnotations {
elem: E::Builder::new_i64(10).with_annotations(vec![
E::SymbolToken::symbol_id_token(21),
E::SymbolToken::symbol_id_token(22),
]),
annotations: vec![
E::SymbolToken::symbol_id_token(21),
E::SymbolToken::symbol_id_token(22),
],
}
}
fn no_annotations_case<E: IonElement>() -> CaseAnnotations<E>
where
E::Builder: Builder<SymbolToken = E::SymbolToken>,
{
CaseAnnotations {
elem: E::Builder::new_i64(10),
annotations: vec![],
}
}
#[rstest]
#[case::owned_annotations_text(annotations_text_case::<Element>())]
#[case::borrowed_annotations_text(annotations_text_case::<ElementRef>())]
#[case::owned_annotations_local_sid(annotations_local_sid_case::<Element>())]
#[case::borrowed_annotations_local_sid(annotations_local_sid_case::<ElementRef>())]
#[case::owned_no_annotations(no_annotations_case::<Element>())]
#[case::borrowed_no_annotations(no_annotations_case::<ElementRef>())]
fn annotations_with_element<E: IonElement>(#[case] input: CaseAnnotations<E>) {
let actual: Vec<&E::SymbolToken> = input.elem.annotations().collect();
let expected: Vec<&E::SymbolToken> = input.annotations.iter().collect();
assert_eq!(actual, expected);
}
struct CaseSym<E: IonElement> {
eq_annotations: Vec<E::SymbolToken>,
ne_annotations: Vec<E::SymbolToken>,
}
fn sym_text_case<E: IonElement>() -> CaseSym<E>
where
E::Builder: Builder<SymbolToken = E::SymbolToken>,
{
// SymbolTokens with same text are equivalent
CaseSym {
eq_annotations: vec![
E::SymbolToken::text_token("foo"),
E::SymbolToken::text_token("foo").with_symbol_id(10),
],
ne_annotations: vec![
E::SymbolToken::text_token("bar"),
E::SymbolToken::symbol_id_token(10),
],
}
}
fn sym_local_sid_case<E: IonElement>() -> CaseSym<E>
where
E::Builder: Builder<SymbolToken = E::SymbolToken>,
{
// local sids with no text are equivalent to each other and to SID $0
CaseSym {
eq_annotations: vec![
E::SymbolToken::symbol_id_token(200),
E::SymbolToken::symbol_id_token(100),
E::SymbolToken::symbol_id_token(0),
],
ne_annotations: vec![E::SymbolToken::text_token("foo")],
}
}
/// Each case is a set of tokens that are the same, and a set of tokens that are not ever equal to the first.
/// This should test symmetry/transitivity/commutativity
#[rstest]
#[case::owned_sym_text(sym_text_case::<Element>())]
#[case::borrowed_sym_text(sym_text_case::<ElementRef>())]
#[case::owned_sym_local_sid(sym_local_sid_case::<Element>())]
#[case::borrowed_sym_local_sid(sym_local_sid_case::<ElementRef>())]
fn symbol_token_eq<E: IonElement>(#[case] input: CaseSym<E>) {
// check if equivalent vector contains set of tokens that are all equal
for eq_this_token in &input.eq_annotations {
for eq_other_token in &input.eq_annotations {
assert_eq!(eq_this_token, eq_other_token);
}
}
// check if non_equivalent vector contains a set of tokens that are not ever equal
// to the equivalent set tokens.
for eq_token in &input.eq_annotations {
for non_eq_token in &input.ne_annotations {
assert_ne!(eq_token, non_eq_token);
}
}
}
/// A struct that defines input case for `struct_accessors` method
struct CaseStruct<E: IonElement> {
/// set of struct elements that are the same
eq_annotations: Vec<E>,
/// set of struct elements that are never equal to `eq_annotations`
ne_annotations: Vec<E>,
}
fn struct_with_local_sid_case<E: IonElement>() -> CaseStruct<E>
where
E::Builder: Builder<SymbolToken = E::SymbolToken>,
{
CaseStruct {
eq_annotations: vec![
E::Builder::new_struct(
vec![(
E::SymbolToken::symbol_id_token(21),
E::Builder::new_string("hello"),
)]
.into_iter(),
),
// SymbolToken with local SID and no text are equivalent to each other and to SID $0
E::Builder::new_struct(
vec![(
E::SymbolToken::symbol_id_token(22),
E::Builder::new_string("hello"),
)]
.into_iter(),
),
],
ne_annotations: vec![
// structs with different symbol token values
E::Builder::new_struct(
vec![(
E::SymbolToken::symbol_id_token(21).with_text("foo"),
E::Builder::new_string("hello"),
)]
.into_iter(),
),
// struct with annotated value
E::Builder::new_struct(
vec![(
E::SymbolToken::symbol_id_token(21),
E::Builder::new_string("hello")
.with_annotations(vec![E::SymbolToken::text_token("foo")]),
)]
.into_iter(),
),
// struct with different value for (field,value) pair
E::Builder::new_struct(
vec![(E::SymbolToken::symbol_id_token(21), E::Builder::new_i64(10))]
.into_iter(),
),
// structs with different fields length
E::Builder::new_struct(
vec![
(
E::SymbolToken::symbol_id_token(21),
E::Builder::new_string("hello"),
),
(
E::SymbolToken::symbol_id_token(21),
E::Builder::new_string("hi"),
),
]
.into_iter(),
),
],
}
}
fn struct_with_multiple_fields_case<E: IonElement>() -> CaseStruct<E>
where
E::Builder: Builder<SymbolToken = E::SymbolToken>,
{
CaseStruct {
eq_annotations: vec![
E::Builder::new_struct(
vec![
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("hello"),
),
(
E::SymbolToken::text_token("name"),
E::Builder::new_string("Ion"),
),
]
.into_iter(),
),
// structs with different order of fields
E::Builder::new_struct(
vec![
(
E::SymbolToken::text_token("name"),
E::Builder::new_string("Ion"),
),
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("hello"),
),
]
.into_iter(),
),
],
ne_annotations: vec![
// structs with different length and duplicates
E::Builder::new_struct(
vec![
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("hello"),
),
(
E::SymbolToken::text_token("name"),
E::Builder::new_string("Ion"),
),
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("hello"),
),
]
.into_iter(),
),
// structs with different fields length and duplicates
E::Builder::new_struct(
vec![
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("hello"),
),
(
E::SymbolToken::text_token("name"),
E::Builder::new_string("Ion"),
),
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("bye"),
),
]
.into_iter(),
),
// structs with different fields length
E::Builder::new_struct(
vec![
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("hello"),
),
(
E::SymbolToken::text_token("name"),
E::Builder::new_string("Ion"),
),
(
E::SymbolToken::text_token("message"),
E::Builder::new_string("bye"),
),
]
.into_iter(),
),
],
}
}
fn struct_with_duplicates_in_multiple_fields_case<E: IonElement>() -> CaseStruct<E>
where
E::Builder: Builder<SymbolToken = E::SymbolToken>,
{
CaseStruct {
eq_annotations: vec![
E::Builder::new_struct(
vec![
(E::SymbolToken::text_token("a"), E::Builder::new_i64(1)),
(E::SymbolToken::text_token("a"), E::Builder::new_i64(1)),
(E::SymbolToken::text_token("a"), E::Builder::new_i64(1)),
]
.into_iter(),
),
// structs with different symbol token sids
E::Builder::new_struct(
vec![
(
E::SymbolToken::text_token("a").with_symbol_id(21),
E::Builder::new_i64(1),
),
(E::SymbolToken::text_token("a"), E::Builder::new_i64(1)),
(E::SymbolToken::text_token("a"), E::Builder::new_i64(1)),
]
.into_iter(),
),
],
ne_annotations: vec![
// structs with different length
E::Builder::new_struct(
vec![
(E::SymbolToken::text_token("a"), E::Builder::new_i64(1)),
(E::SymbolToken::text_token("a"), E::Builder::new_i64(1)),
]
.into_iter(),
),
// structs with annotated values
E::Builder::new_struct(
vec![
(E::SymbolToken::text_token("a"), E::Builder::new_i64(1)),
(
E::SymbolToken::text_token("a"),
E::Builder::new_i64(1)
.with_annotations(vec![E::SymbolToken::text_token("a")]),
),
(E::SymbolToken::text_token("a"), E::Builder::new_i64(1)),
]
.into_iter(),
),
// structs with different value for duplicates
E::Builder::new_struct(
vec![
(E::SymbolToken::text_token("a"), E::Builder::new_i64(2)),
(E::SymbolToken::text_token("a"), E::Builder::new_i64(1)),
]
.into_iter(),
),
],
}
}
fn struct_with_duplicate_fieldnames_case<E: IonElement>() -> CaseStruct<E>
where
E::Builder: Builder<SymbolToken = E::SymbolToken>,
{
CaseStruct {
eq_annotations: vec![
E::Builder::new_struct(
vec![
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("hello"),
),
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("world"),
),
]
.into_iter(),
),
// structs with unordered fields
E::Builder::new_struct(
vec![
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("world"),
),
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("hello"),
),
]
.into_iter(),
),
],
ne_annotations: vec![
// structs with different length and duplicates
E::Builder::new_struct(
vec![
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("hello"),
),
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("world"),
),
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("hey"),
),
]
.into_iter(),
),
// structs with annotated values
E::Builder::new_struct(
vec![
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("hello"),
),
(
E::SymbolToken::text_token("greetings"),
E::Builder::new_string("world")
.with_annotations(vec![E::SymbolToken::text_token("foo")]),
),
]
.into_iter(),