ion_rs/types/
sequence.rs

1use crate::element::builders::SequenceBuilder;
2use crate::element::iterators::ElementsIterator;
3use crate::element::Element;
4use crate::ion_data::{IonEq, IonOrd};
5use std::cmp::Ordering;
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct Sequence {
9    elements: Vec<Element>,
10}
11
12impl Sequence {
13    pub fn new<E: Into<Element>, I: IntoIterator<Item = E>>(elements: I) -> Sequence {
14        let elements = elements.into_iter().map(|e| e.into()).collect();
15        Sequence { elements }
16    }
17
18    pub fn builder() -> SequenceBuilder {
19        SequenceBuilder::new()
20    }
21
22    pub fn clone_builder(&self) -> SequenceBuilder {
23        SequenceBuilder::with_initial_elements(&self.elements)
24    }
25
26    pub fn elements(&self) -> ElementsIterator<'_> {
27        ElementsIterator::new(&self.elements)
28    }
29
30    pub fn get(&self, index: usize) -> Option<&Element> {
31        self.elements.get(index)
32    }
33
34    pub fn len(&self) -> usize {
35        self.elements.len()
36    }
37
38    pub fn is_empty(&self) -> bool {
39        self.len() == 0
40    }
41}
42
43impl AsRef<Sequence> for Sequence {
44    fn as_ref(&self) -> &Sequence {
45        self
46    }
47}
48
49// This is more efficient than Sequence::new(), which will iterate over and convert each value to
50// an Element for better ergonomics.
51impl From<Vec<Element>> for Sequence {
52    fn from(elements: Vec<Element>) -> Self {
53        Sequence { elements }
54    }
55}
56
57impl<'a> IntoIterator for &'a Sequence {
58    type Item = &'a Element;
59    // TODO: Change once `impl Trait` type aliases are stable
60    // type IntoIter = impl Iterator<Item = &'a Element>;
61    type IntoIter = ElementsIterator<'a>;
62
63    fn into_iter(self) -> Self::IntoIter {
64        self.elements()
65    }
66}
67
68impl IonEq for Sequence {
69    fn ion_eq(&self, other: &Self) -> bool {
70        self.elements.ion_eq(&other.elements)
71    }
72}
73
74impl IonOrd for Sequence {
75    fn ion_cmp(&self, other: &Self) -> Ordering {
76        self.elements.ion_cmp(&other.elements)
77    }
78}