Skip to main content

google_protobuf/
repeated.rs

1// Protocol Buffers - Google's data interchange format
2// Copyright 2023 Google LLC.  All rights reserved.
3//
4// Use of this source code is governed by a BSD-style
5// license that can be found in the LICENSE file or at
6// https://developers.google.com/open-source/licenses/bsd
7
8use std::fmt::{self, Debug};
9use std::iter;
10use std::iter::FusedIterator;
11/// Repeated scalar fields are implemented around the runtime-specific
12/// `RepeatedField` struct. `RepeatedField` stores an opaque pointer to the
13/// runtime-specific representation of a repeated scalar (`upb_Array*` on upb,
14/// and `RepeatedField<T>*` on cpp).
15use std::marker::PhantomData;
16
17use crate::{
18    __internal::runtime::{InnerRepeated, InnerRepeatedMut, RawRepeatedField},
19    __internal::{Private, SealedInternal},
20    AsMut, AsView, IntoMut, IntoProxied, IntoView, Message, Mut, MutProxied, Proxied, Singular,
21    View,
22};
23
24/// A `repeated` field of `T`, used as the owned target for `Proxied`.
25///
26/// Users will generally write [`View<Repeated<T>>`](RepeatedView) or
27/// [`Mut<Repeated<T>>`](RepeatedMut) to access the repeated elements
28pub struct Repeated<T: Singular> {
29    pub(crate) inner: InnerRepeated,
30    _phantom: PhantomData<T>,
31}
32
33// SAFETY: `Repeated` is Sync because it does not implement interior mutability.
34unsafe impl<T: Singular> Sync for Repeated<T> {}
35
36// SAFETY: `Repeated` is Send because it's not bound to a specific thread e.g.
37// it does not use thread-local data or similar.
38unsafe impl<T: Singular> Send for Repeated<T> {}
39
40impl<T: Singular> Repeated<T> {
41    pub fn new() -> Self {
42        T::repeated_new(Private)
43    }
44
45    pub(crate) fn as_mut(&mut self) -> RepeatedMut<'_, T> {
46        RepeatedMut { inner: self.inner.as_mut(), _phantom: PhantomData }
47    }
48
49    pub fn as_view(&self) -> View<'_, Repeated<T>> {
50        RepeatedView { raw: self.inner.raw(), _phantom: PhantomData }
51    }
52
53    #[doc(hidden)]
54    pub fn inner(&self, _private: Private) -> &InnerRepeated {
55        &self.inner
56    }
57
58    #[doc(hidden)]
59    pub fn from_inner(_private: Private, inner: InnerRepeated) -> Self {
60        Self { inner, _phantom: PhantomData }
61    }
62}
63
64impl<T: Singular, I, U> IntoProxied<Repeated<T>> for I
65where
66    I: Iterator<Item = U>,
67    U: IntoProxied<T>,
68{
69    fn into_proxied(self, _private: Private) -> Repeated<T> {
70        let mut repeated: Repeated<T> = Repeated::new();
71        repeated.as_mut().extend(self);
72        repeated
73    }
74}
75
76impl<T: Singular> Default for Repeated<T> {
77    fn default() -> Self {
78        Repeated::new()
79    }
80}
81
82impl<T: Singular> Drop for Repeated<T> {
83    fn drop(&mut self) {
84        // SAFETY: only called once
85        unsafe { T::repeated_free(Private, self) }
86    }
87}
88
89impl<T: Singular> Proxied for Repeated<T> {
90    type View<'msg>
91        = RepeatedView<'msg, T>
92    where
93        Repeated<T>: 'msg;
94}
95
96impl<T: Singular> SealedInternal for Repeated<T> {}
97
98impl<T: Singular> crate::codegen_traits::EntityType for Repeated<T> {
99    type Tag = crate::codegen_traits::entity_tag::RepeatedTag;
100}
101
102impl<T: Singular> AsView for Repeated<T> {
103    type Proxied = Self;
104
105    fn as_view(&self) -> RepeatedView<'_, T> {
106        self.as_view()
107    }
108}
109
110impl<T: Singular> MutProxied for Repeated<T> {
111    type Mut<'msg>
112        = RepeatedMut<'msg, T>
113    where
114        Repeated<T>: 'msg;
115}
116
117impl<T: Singular> AsMut for Repeated<T> {
118    type MutProxied = Self;
119
120    fn as_mut(&mut self) -> RepeatedMut<'_, T> {
121        self.as_mut()
122    }
123}
124
125/// Views the elements in a `repeated` field of `T`.
126#[repr(transparent)]
127pub struct RepeatedView<'msg, T> {
128    // This does not need to carry an arena in upb, so it can be just the raw repeated field
129    raw: RawRepeatedField,
130    _phantom: PhantomData<&'msg T>,
131}
132
133impl<'msg, T> Copy for RepeatedView<'msg, T> {}
134impl<'msg, T> Clone for RepeatedView<'msg, T> {
135    fn clone(&self) -> Self {
136        *self
137    }
138}
139
140unsafe impl<'msg, T> Sync for RepeatedView<'msg, T> {}
141unsafe impl<'msg, T> Send for RepeatedView<'msg, T> {}
142
143impl<'msg, T> Debug for RepeatedView<'msg, T> {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        f.debug_struct("RepeatedView").field("raw", &self.raw).finish()
146    }
147}
148
149impl<'msg, T: Singular> SealedInternal for RepeatedView<'msg, T> {}
150
151#[doc(hidden)]
152impl<'msg, T> RepeatedView<'msg, T> {
153    #[doc(hidden)]
154    #[inline]
155    pub fn as_raw(&self, _private: Private) -> RawRepeatedField {
156        self.raw
157    }
158
159    /// # Safety
160    /// - `inner` must be valid to read from for `'msg`
161    #[doc(hidden)]
162    #[inline]
163    pub unsafe fn from_raw(_private: Private, raw: RawRepeatedField) -> Self {
164        Self { raw, _phantom: PhantomData }
165    }
166}
167
168impl<'msg, T: Singular> RepeatedView<'msg, T> {
169    /// Gets the length of the repeated field.
170    #[inline]
171    pub fn len(&self) -> usize {
172        T::repeated_len(Private, *self)
173    }
174
175    /// Returns true if the repeated field has no values.
176    #[inline]
177    pub fn is_empty(&self) -> bool {
178        self.len() == 0
179    }
180
181    /// Gets the value at `index`.
182    ///
183    /// Returns `None` if `index > len`.
184    #[inline]
185    pub fn get(self, index: usize) -> Option<View<'msg, T>> {
186        if index >= self.len() {
187            return None;
188        }
189        // SAFETY: `index` has been checked to be in-bounds
190        Some(unsafe { self.get_unchecked(index) })
191    }
192
193    /// Gets the value at `index` without bounds-checking.
194    ///
195    /// # Safety
196    /// Undefined behavior if `index >= len`
197    #[inline]
198    pub unsafe fn get_unchecked(self, index: usize) -> View<'msg, T> {
199        // SAFETY: in-bounds as promised
200        unsafe { T::repeated_get_unchecked(Private, self, index) }
201    }
202
203    /// Iterates over the values in the repeated field.
204    pub fn iter(self) -> RepeatedIter<'msg, T> {
205        self.into_iter()
206    }
207
208    /// Returns the first element of the repeated field, or `None` if it is empty.
209    #[inline]
210    pub fn first(self) -> Option<View<'msg, T>> {
211        self.get(0)
212    }
213
214    /// Returns the last element of the repeated field, or `None` if it is empty.
215    #[inline]
216    pub fn last(self) -> Option<View<'msg, T>> {
217        let len = self.len();
218        if len == 0 {
219            None
220        } else {
221            // SAFETY: len is not 0, so len - 1 is a valid index
222            unsafe { Some(self.get_unchecked(len - 1)) }
223        }
224    }
225}
226
227impl<'msg, T: Singular> AsView for RepeatedView<'msg, T> {
228    type Proxied = Repeated<T>;
229
230    #[inline]
231    fn as_view(&self) -> View<'msg, Self::Proxied> {
232        *self
233    }
234}
235
236impl<'msg, T: Singular> IntoView<'msg> for RepeatedView<'msg, T> {
237    #[inline]
238    fn into_view<'shorter>(self) -> View<'shorter, Self::Proxied>
239    where
240        'msg: 'shorter,
241    {
242        RepeatedView { raw: self.raw, _phantom: PhantomData }
243    }
244}
245
246impl<'msg, T: Singular> IntoProxied<Repeated<T>> for RepeatedView<'msg, T> {
247    fn into_proxied(self, _private: Private) -> Repeated<T> {
248        let mut repeated: Repeated<T> = Repeated::new();
249        T::repeated_copy_from(Private, self, repeated.as_mut());
250        repeated
251    }
252}
253
254/// Mutates the elements in a `repeated` field of `T`.
255pub struct RepeatedMut<'msg, T> {
256    pub(crate) inner: InnerRepeatedMut<'msg>,
257    _phantom: PhantomData<&'msg mut T>,
258}
259
260unsafe impl<'msg, T> Sync for RepeatedMut<'msg, T> {}
261
262impl<'msg, T> Debug for RepeatedMut<'msg, T> {
263    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264        f.debug_struct("RepeatedMut").field("raw", &self.inner.raw).finish()
265    }
266}
267
268#[doc(hidden)]
269impl<'msg, T> RepeatedMut<'msg, T> {
270    /// # Safety
271    /// - `inner` must be valid to read and write from for `'msg`
272    /// - There must be no aliasing references or mutations on the same
273    ///   underlying object.
274    #[doc(hidden)]
275    #[inline]
276    pub unsafe fn from_inner(_private: Private, inner: InnerRepeatedMut<'msg>) -> Self {
277        Self { inner, _phantom: PhantomData }
278    }
279
280    #[doc(hidden)]
281    #[inline]
282    pub fn as_raw(&mut self, _private: Private) -> RawRepeatedField {
283        self.inner.raw
284    }
285}
286
287impl<'msg, T: Singular> RepeatedMut<'msg, T> {
288    /// Gets the length of the repeated field.
289    #[inline]
290    pub fn len(&self) -> usize {
291        self.as_view().len()
292    }
293
294    /// Returns true if the repeated field has no values.
295    #[inline]
296    pub fn is_empty(&self) -> bool {
297        self.len() == 0
298    }
299
300    /// Gets the value at `index`.
301    ///
302    /// Returns `None` if `index >= len`.
303    #[inline]
304    pub fn get(&self, index: usize) -> Option<View<'_, T>> {
305        self.as_view().get(index)
306    }
307
308    /// Gets the value at `index`.
309    ///
310    /// Returns `None` if `index >= len`.
311    #[inline]
312    pub fn get_mut(&mut self, index: usize) -> Option<Mut<'_, T>>
313    where
314        T: Message,
315    {
316        if index >= self.len() {
317            return None;
318        }
319        // SAFETY: `index` has been checked to be in-bounds
320        Some(unsafe { self.get_mut_unchecked(index) })
321    }
322
323    /// Gets the value at `index` without bounds-checking.
324    ///
325    /// # Safety
326    /// Undefined behavior if `index >= len`.
327    #[inline]
328    pub unsafe fn get_mut_unchecked(&mut self, index: usize) -> Mut<'_, T>
329    where
330        T: Message,
331    {
332        // SAFETY: in-bounds as promised
333        unsafe { T::repeated_get_mut_unchecked(Private, self.as_mut(), index) }
334    }
335
336    /// Gets the value at `index` without bounds-checking.
337    ///
338    /// # Safety
339    /// Undefined behavior if `index >= len`.
340    #[inline]
341    pub unsafe fn get_unchecked(&self, index: usize) -> View<'_, T> {
342        // SAFETY: in-bounds as promised
343        unsafe { self.as_view().get_unchecked(index) }
344    }
345
346    /// Appends `val` to the end of the repeated field.
347    #[inline]
348    pub fn push(&mut self, val: impl IntoProxied<T>) {
349        T::repeated_push(Private, self.as_mut(), val);
350    }
351
352    /// Appends the default message instance of T and returns a mutable reference to it.
353    #[inline]
354    pub fn push_default(&mut self) -> Mut<'_, T>
355    where
356        T: Message,
357    {
358        // TODO: This should be optimized on Cpp kernel by adding another thunk to expose Add().
359        self.push(T::default());
360        // SAFETY: we just pushed a value into the repeated field, so there is at least one element.
361        unsafe { self.get_mut_unchecked(self.len() - 1) }
362    }
363
364    /// Sets the value at `index` to the value `val`.
365    ///
366    /// # Panics
367    /// Panics if `index >= len`.
368    #[inline]
369    pub fn set(&mut self, index: usize, val: impl IntoProxied<T>) {
370        let len = self.len();
371        if index >= len {
372            panic!("index {index} >= repeated len {len}");
373        }
374        unsafe { self.set_unchecked(index, val) }
375    }
376
377    /// Sets the value at `index` to the value `val`.
378    ///
379    /// # Safety
380    /// Undefined behavior if `index >= len`.
381    #[inline]
382    pub unsafe fn set_unchecked(&mut self, index: usize, val: impl IntoProxied<T>) {
383        unsafe { T::repeated_set_unchecked(Private, self.as_mut(), index, val) }
384    }
385
386    /// Iterates over the values in the repeated field.
387    pub fn iter(&self) -> RepeatedIter<'_, T> {
388        self.as_view().into_iter()
389    }
390
391    /// Copies from the `src` repeated field into this one.
392    pub fn copy_from(&mut self, src: RepeatedView<'_, T>) {
393        T::repeated_copy_from(Private, src, self.as_mut())
394    }
395
396    /// Clears the repeated field.
397    pub fn clear(&mut self) {
398        T::repeated_clear(Private, self.as_mut())
399    }
400
401    /// Returns the first element of the repeated field, or `None` if it is empty.
402    #[inline]
403    pub fn first(&self) -> Option<View<'_, T>> {
404        self.as_view().first()
405    }
406
407    /// Returns the last element of the repeated field, or `None` if it is empty.
408    #[inline]
409    pub fn last(&self) -> Option<View<'_, T>> {
410        self.as_view().last()
411    }
412}
413
414impl<'msg, T: Singular> IntoProxied<Repeated<T>> for RepeatedMut<'msg, T> {
415    fn into_proxied(self, _private: Private) -> Repeated<T> {
416        IntoProxied::into_proxied(self.as_view(), _private)
417    }
418}
419
420impl<'msg, T: Singular> SealedInternal for RepeatedMut<'msg, T> {}
421
422impl<'msg, T: Singular> AsView for RepeatedMut<'msg, T> {
423    type Proxied = Repeated<T>;
424
425    #[inline]
426    fn as_view(&self) -> RepeatedView<'_, T> {
427        RepeatedView { raw: self.inner.raw, _phantom: PhantomData }
428    }
429}
430
431impl<'msg, T: Singular> IntoView<'msg> for RepeatedMut<'msg, T> {
432    #[inline]
433    fn into_view<'shorter>(self) -> RepeatedView<'shorter, T>
434    where
435        'msg: 'shorter,
436    {
437        RepeatedView { raw: self.inner.raw, _phantom: PhantomData }
438    }
439}
440
441impl<'msg, T: Singular> AsMut for RepeatedMut<'msg, T> {
442    type MutProxied = Repeated<T>;
443
444    #[inline]
445    fn as_mut(&mut self) -> RepeatedMut<'_, T> {
446        RepeatedMut { inner: self.inner, _phantom: PhantomData }
447    }
448}
449
450impl<'msg, T: Singular> IntoMut<'msg> for RepeatedMut<'msg, T> {
451    #[inline]
452    fn into_mut<'shorter>(self) -> RepeatedMut<'shorter, T>
453    where
454        'msg: 'shorter,
455    {
456        RepeatedMut { inner: self.inner, _phantom: PhantomData }
457    }
458}
459
460impl<'msg, T: Singular, ViewT> Extend<ViewT> for RepeatedMut<'msg, T>
461where
462    ViewT: IntoProxied<T>,
463{
464    fn extend<I: IntoIterator<Item = ViewT>>(&mut self, iter: I) {
465        let iter = iter.into_iter();
466        T::repeated_reserve(Private, self.as_mut(), iter.size_hint().0);
467        for item in iter {
468            self.push(item);
469        }
470    }
471}
472
473impl<T: Singular, U> std::iter::FromIterator<U> for Repeated<T>
474where
475    U: IntoProxied<T>,
476{
477    fn from_iter<I: IntoIterator<Item = U>>(iter: I) -> Self {
478        let mut repeated = Repeated::new();
479        repeated.as_mut().extend(iter);
480        repeated
481    }
482}
483
484/// An iterator over the values inside of a [`View<Repeated<T>>`](RepeatedView).
485#[derive(Clone)]
486pub struct RepeatedIter<'msg, T> {
487    view: RepeatedView<'msg, T>,
488    current_index: usize,
489    end_index: usize,
490}
491
492impl<'msg, T> Debug for RepeatedIter<'msg, T> {
493    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
494        f.debug_struct("RepeatedIter")
495            .field("view", &self.view)
496            .field("current_index", &self.current_index)
497            .finish()
498    }
499}
500
501impl<'msg, T: Singular> iter::Iterator for RepeatedIter<'msg, T> {
502    type Item = View<'msg, T>;
503
504    #[inline]
505    fn next(&mut self) -> Option<Self::Item> {
506        if self.current_index >= self.end_index {
507            return None;
508        }
509        // SAFETY: current_index < end_index <= view.len()
510        let val = unsafe { self.view.get_unchecked(self.current_index) };
511        self.current_index += 1;
512        Some(val)
513    }
514
515    fn size_hint(&self) -> (usize, Option<usize>) {
516        let len = self.len();
517        (len, Some(len))
518    }
519}
520
521impl<'msg, T: Singular> ExactSizeIterator for RepeatedIter<'msg, T> {
522    fn len(&self) -> usize {
523        self.end_index - self.current_index
524    }
525}
526
527impl<'msg, T: Singular> iter::DoubleEndedIterator for RepeatedIter<'msg, T> {
528    #[inline]
529    fn next_back(&mut self) -> Option<Self::Item> {
530        if self.current_index >= self.end_index {
531            return None;
532        }
533        self.end_index -= 1;
534        // SAFETY: current_index <= end_index < view.len()
535        Some(unsafe { self.view.get_unchecked(self.end_index) })
536    }
537}
538
539impl<'msg, T: Singular> FusedIterator for RepeatedIter<'msg, T> {}
540
541impl<'msg, T: Singular> iter::IntoIterator for RepeatedView<'msg, T> {
542    type Item = View<'msg, T>;
543    type IntoIter = RepeatedIter<'msg, T>;
544
545    fn into_iter(self) -> Self::IntoIter {
546        RepeatedIter { view: self, current_index: 0, end_index: self.len() }
547    }
548}
549
550impl<'msg, T: Singular> iter::IntoIterator for &'_ RepeatedView<'msg, T> {
551    type Item = View<'msg, T>;
552    type IntoIter = RepeatedIter<'msg, T>;
553
554    fn into_iter(self) -> Self::IntoIter {
555        RepeatedIter { view: *self, current_index: 0, end_index: self.len() }
556    }
557}
558
559impl<'borrow, T: Singular> iter::IntoIterator for &'borrow RepeatedMut<'_, T> {
560    type Item = View<'borrow, T>;
561    type IntoIter = RepeatedIter<'borrow, T>;
562
563    fn into_iter(self) -> Self::IntoIter {
564        let view = self.as_view();
565        RepeatedIter { view, current_index: 0, end_index: view.len() }
566    }
567}
568
569/// An iterator over the mutable values inside of a [`RepeatedMut`].
570///
571/// **WARNING**: This has transitioned to a **Lending Iterator**. Standard `for` loops are not
572/// supported anymore. Use `while let Some(item) = iter.next()` instead.
573pub struct RepeatedMutIter<'msg, T> {
574    inner: InnerRepeatedMut<'msg>,
575    current_index: usize,
576    end_index: usize,
577    _phantom: PhantomData<&'msg mut T>,
578}
579
580impl<'msg, T: Message> RepeatedMutIter<'msg, T> {
581    #[inline]
582    pub fn next(&mut self) -> Option<Mut<'_, T>> {
583        if self.current_index >= self.end_index {
584            return None;
585        }
586        let index = self.current_index;
587        self.current_index += 1;
588
589        // SAFETY: index is valid.
590        let val = unsafe {
591            let temp_repeated = RepeatedMut::from_inner(Private, self.inner);
592            T::repeated_get_mut_unchecked(Private, temp_repeated, index)
593        };
594
595        Some(val)
596    }
597
598    #[inline]
599    pub fn len(&self) -> usize {
600        self.end_index - self.current_index
601    }
602
603    #[inline]
604    pub fn next_back(&mut self) -> Option<Mut<'_, T>> {
605        if self.current_index >= self.end_index {
606            return None;
607        }
608        self.end_index -= 1;
609        let index = self.end_index;
610
611        // SAFETY: index is guaranteed to be in bounds.
612        let val = unsafe {
613            let temp_repeated = RepeatedMut::from_inner(Private, self.inner);
614            T::repeated_get_mut_unchecked(Private, temp_repeated, index)
615        };
616
617        Some(val)
618    }
619}
620
621impl<'msg, T: Message> RepeatedMut<'msg, T> {
622    /// Returns an iterator that allows modifying each value.
623    pub fn iter_mut(self) -> RepeatedMutIter<'msg, T> {
624        RepeatedMutIter {
625            end_index: self.len(),
626            inner: self.inner,
627            current_index: 0,
628            _phantom: PhantomData,
629        }
630    }
631
632    /// Returns a mutable reference to the first element of the repeated field, or `None` if it is empty.
633    #[inline]
634    pub fn first_mut<'r>(&'r mut self) -> Option<Mut<'msg, T>>
635    where
636        'r: 'msg,
637    {
638        self.get_mut(0)
639    }
640
641    /// Returns a mutable reference to the last element of the repeated field, or `None` if it is empty.
642    #[inline]
643    pub fn last_mut<'r>(&'r mut self) -> Option<Mut<'msg, T>>
644    where
645        'r: 'msg,
646    {
647        let len = self.len();
648        if len == 0 {
649            None
650        } else {
651            // SAFETY: len is not 0, so len - 1 is valid
652            Some(unsafe { self.get_mut_unchecked(len - 1) })
653        }
654    }
655}
656
657#[cfg(test)]
658mod tests {
659    use super::*;
660    use googletest::prelude::*;
661
662    #[gtest]
663    fn test_primitive_repeated() {
664        macro_rules! primitive_repeated_tests {
665            ($($t:ty => [$($vals:expr),* $(,)?]),* $(,)?) => {
666                $({
667                // Constructs a new, owned, `Repeated`, only used for tests.
668                let mut r = Repeated::<$t>::new();
669                let mut r = r.as_mut();
670                assert_that!(r.len(), eq(0));
671                assert!(r.iter().next().is_none(), "starts with empty iter");
672                assert!(r.iter().next().is_none(), "starts with empty mut iter");
673                assert!(r.is_empty(), "starts is_empty");
674
675                let mut expected_len = 0usize;
676                $(
677                    let val: View<$t> = $vals;
678                    r.push(val);
679                    assert_that!(r.get(expected_len), eq(Some(val)));
680                    expected_len += 1;
681                    assert_that!(r.len(), eq(expected_len));
682
683                )*
684                assert_that!(r, elements_are![$(eq($vals)),*]);
685                r.set(0, <$t as Default>::default());
686                assert_that!(r.get(0).expect("elem 0"), eq(<$t as Default>::default()));
687
688                r.clear();
689                assert!(r.is_empty(), "is_empty after clear");
690                assert!(r.iter().next().is_none(), "iter empty after clear");
691                assert!(r.into_iter().next().is_none(), "mut iter empty after clear");
692                })*
693            }
694        }
695        primitive_repeated_tests!(
696            u32 => [1,2,3],
697            i32 => [1,2],
698            f64 => [10.0, 0.1234f64],
699            bool => [false, true, true, false],
700        );
701    }
702
703    #[gtest]
704    fn test_repeated_extend() {
705        let mut r = Repeated::<i32>::new();
706
707        r.as_mut().extend([0; 0]);
708        assert_that!(r.as_mut().len(), eq(0));
709
710        r.as_mut().extend([0, 1]);
711        assert_that!(r.as_mut(), elements_are![eq(0), eq(1)]);
712        let mut x = Repeated::<i32>::new();
713        x.as_mut().extend([2, 3]);
714
715        r.as_mut().extend(&x.as_mut());
716
717        assert_that!(r.as_mut(), elements_are![eq(0), eq(1), eq(2), eq(3)]);
718    }
719
720    #[gtest]
721    fn test_repeated_iter() {
722        let r: Repeated<i32> = [0, 1, 2, 3].into_iter().into_proxied(Private);
723        assert_that!(r.as_view(), elements_are![eq(0), eq(1), eq(2), eq(3)]);
724
725        let mut iter = r.as_view().into_iter();
726        assert_that!(iter.next(), eq(Some(0)));
727        let mut clone = iter.clone();
728        assert_that!(clone.next(), eq(Some(1)));
729        assert_that!(iter.next(), eq(Some(1)));
730    }
731    #[gtest]
732    fn test_first_last() {
733        let mut r = Repeated::<i32>::new();
734        assert!(r.as_view().first().is_none());
735        assert!(r.as_view().last().is_none());
736        assert!(r.as_mut().first().is_none());
737        assert!(r.as_mut().last().is_none());
738
739        let mut m = r.as_mut();
740        m.push(10);
741        assert_that!(m.first(), eq(Some(10)));
742        assert_that!(m.last(), eq(Some(10)));
743        assert_that!(m.as_view().first(), eq(Some(10)));
744        assert_that!(m.as_view().last(), eq(Some(10)));
745
746        m.push(20);
747        assert_that!(m.first(), eq(Some(10)));
748        assert_that!(m.last(), eq(Some(20)));
749    }
750
751    #[gtest]
752    fn test_double_ended_iter() {
753        let r: Repeated<i32> = [1, 2, 3].into_iter().collect();
754        let mut iter = r.as_view().into_iter();
755        assert_that!(iter.next(), eq(Some(1)));
756        assert_that!(iter.next_back(), eq(Some(3)));
757        assert_that!(iter.next(), eq(Some(2)));
758        assert_that!(iter.next(), eq(None));
759        assert_that!(iter.next_back(), eq(None));
760    }
761
762    #[gtest]
763    fn test_from_iter() {
764        let r: Repeated<i32> = [10, 20, 30].into_iter().collect();
765        assert_that!(r.as_view(), elements_are![eq(10), eq(20), eq(30)]);
766    }
767}