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
#![doc = include_str!("../README.md")]
#![deny(missing_docs)]

use std::borrow::Borrow;
use std::fmt::{Debug, Formatter};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

pub mod impls;

pub use impls::columns::ColumnsRegion;
pub use impls::mirror::MirrorRegion;
pub use impls::option::OptionRegion;
pub use impls::result::ResultRegion;
pub use impls::slice::SliceRegion;
pub use impls::slice_copy::OwnedRegion;
pub use impls::string::StringRegion;

/// An index into a region. Automatically implemented for relevant types.
///
/// We require an index to be [`Copy`] and to support serde.
#[cfg(feature = "serde")]
pub trait Index: Copy + Serialize + for<'a> Deserialize<'a> {}
#[cfg(feature = "serde")]
impl<T: Copy + Serialize + for<'a> Deserialize<'a>> Index for T {}

/// An index into a region. Automatically implemented for relevant types.
///
/// We require an index to be [`Copy`].
#[cfg(not(feature = "serde"))]
pub trait Index: Copy {}
#[cfg(not(feature = "serde"))]
impl<T: Copy> Index for T {}

/// A region to absorb presented data and present it as a type with a lifetime.
///
/// This type absorbs data and provides an index to look up an equivalent representation
/// of this data at a later time. It is up to an implementation to select the appropriate
/// presentation of the data, and what data it can absorb.
///
/// Implement the [`Push`] trait for all types that can be copied into a region.
pub trait Region: Default {
    /// An owned type that can be constructed from a read item.
    type Owned;

    /// The type of the data that one gets out of the container.
    type ReadItem<'a>: IntoOwned<'a, Owned = Self::Owned>
    where
        Self: 'a;

    /// The type to index into the container. Should be treated
    /// as an opaque type, even if known.
    type Index: Index;

    /// Construct a region that can absorb the contents of `regions` in the future.
    fn merge_regions<'a>(regions: impl Iterator<Item = &'a Self> + Clone) -> Self
    where
        Self: 'a;

    /// Index into the container. The index must be obtained by
    /// pushing data into the container.
    #[must_use]
    fn index(&self, index: Self::Index) -> Self::ReadItem<'_>;

    /// Ensure that the region can absorb the items of `regions` without reallocation
    fn reserve_regions<'a, I>(&mut self, regions: I)
    where
        Self: 'a,
        I: Iterator<Item = &'a Self> + Clone;

    /// Remove all elements from this region, but retain allocations if possible.
    fn clear(&mut self);

    /// Heap size, size - capacity
    fn heap_size<F: FnMut(usize, usize)>(&self, callback: F);

    /// Converts a read item into one with a narrower lifetime.
    #[must_use]
    fn reborrow<'b, 'a: 'b>(item: Self::ReadItem<'a>) -> Self::ReadItem<'b>
    where
        Self: 'a;
}

/// A trait to let types express a default container type and an owned type, which can
/// be used to define regions in simpler terms.
///
/// # Example
///
/// ```
/// # use flatcontainer::{FlatStack, RegionPreference};
/// let _ = FlatStack::<<((Vec<String>, &[usize]), Option<String>, Result<u8, u16>) as RegionPreference>::Region>::default();
/// ```
pub trait RegionPreference {
    /// The owned type of the region.
    type Owned;
    /// The recommended container type.
    type Region: Region<Owned = Self::Owned>;
}

impl<T: RegionPreference + ?Sized> RegionPreference for &T {
    type Owned = T::Owned;
    type Region = T::Region;
}

/// Push an item `T` into a region.
pub trait Push<T>: Region {
    /// Push `item` into self, returning an index that allows to look up the
    /// corresponding read item.
    #[must_use]
    fn push(&mut self, item: T) -> Self::Index;
}

/// Reserve space in the receiving region.
///
/// Closely related to [`Push`], but separate because target type is likely different.
pub trait ReserveItems<T>: Region {
    /// Ensure that the region can absorb `items` without reallocation.
    fn reserve_items<I>(&mut self, items: I)
    where
        I: Iterator<Item = T> + Clone;
}

/// A reference type corresponding to an owned type, supporting conversion in each direction.
///
/// This trait can be implemented by a GAT, and enables owned types to be borrowed as a GAT.
/// This trait is analogous to `ToOwned`, but not as prescriptive. Specifically, it avoids the
/// requirement that the other trait implement `Borrow`, for which a borrow must result in a
/// `&'self Borrowed`, which cannot move the lifetime into a GAT borrowed type.
pub trait IntoOwned<'a> {
    /// Owned type into which this type can be converted.
    type Owned;
    /// Conversion from an instance of this type to the owned type.
    #[must_use]
    fn into_owned(self) -> Self::Owned;
    /// Clones `self` onto an existing instance of the owned type.
    fn clone_onto(self, other: &mut Self::Owned);
    /// Borrows an owned instance as oneself.
    #[must_use]
    fn borrow_as(owned: &'a Self::Owned) -> Self;
}

impl<'a, T: ToOwned + ?Sized> IntoOwned<'a> for &'a T {
    type Owned = T::Owned;
    #[inline]
    fn into_owned(self) -> Self::Owned {
        self.to_owned()
    }
    #[inline]
    fn clone_onto(self, other: &mut Self::Owned) {
        <T as ToOwned>::clone_into(self, other)
    }
    #[inline]
    fn borrow_as(owned: &'a Self::Owned) -> Self {
        owned.borrow()
    }
}

/// A container for indices into a region.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
    feature = "serde",
    serde(
        bound = "R: Serialize + for<'a> Deserialize<'a>, R::Index: Serialize + for<'a> Deserialize<'a>"
    )
)]
pub struct FlatStack<R: Region> {
    /// The indices, which we use to lookup items in the region.
    indices: Vec<R::Index>,
    /// A region to index into.
    region: R,
}

impl<R: Region> Default for FlatStack<R> {
    #[inline]
    fn default() -> Self {
        Self {
            indices: Vec::default(),
            region: R::default(),
        }
    }
}

impl<R: Region> Debug for FlatStack<R>
where
    for<'a> R::ReadItem<'a>: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<R: Region> FlatStack<R> {
    /// Default implementation based on the preference of type `T`.
    #[inline]
    #[must_use]
    pub fn default_impl<T: RegionPreference<Region = R>>() -> Self {
        Self::default()
    }

    /// Returns a flat stack that can absorb `capacity` indices without reallocation.
    ///
    /// Prefer [`Self::merge_capacity`] over this function to also pre-size the regions.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            indices: Vec::with_capacity(capacity),
            region: R::default(),
        }
    }

    /// Returns a flat stack that can absorb the contents of `iter` without reallocation.
    #[must_use]
    pub fn merge_capacity<'a, I: Iterator<Item = &'a Self> + Clone + 'a>(stacks: I) -> Self
    where
        R: 'a,
    {
        Self {
            indices: Vec::with_capacity(stacks.clone().map(|s| s.indices.len()).sum()),
            region: R::merge_regions(stacks.map(|r| &r.region)),
        }
    }

    /// Appends the element to the back of the stack.
    #[inline]
    pub fn copy<T>(&mut self, item: T)
    where
        R: Push<T>,
    {
        let index = self.region.push(item);
        self.indices.push(index);
    }

    /// Returns the element at the `offset` position.
    #[inline]
    #[must_use]
    pub fn get(&self, offset: usize) -> R::ReadItem<'_> {
        self.region.index(self.indices[offset])
    }

    /// Returns the number of indices in the stack.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.indices.len()
    }

    /// Returns `true` if the stack contains no elements.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.indices.is_empty()
    }

    /// Returns the total number of indices the stack can hold without reallocation.
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.indices.capacity()
    }

    /// Reserves space to hold `additional` indices.
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.indices.reserve(additional);
    }

    /// Remove all elements while possibly retaining allocations.
    #[inline]
    pub fn clear(&mut self) {
        self.indices.clear();
        self.region.clear();
    }

    /// Reserve space for the items returned by the iterator.
    #[inline]
    pub fn reserve_items<T>(&mut self, items: impl Iterator<Item = T> + Clone)
    where
        R: ReserveItems<T>,
    {
        ReserveItems::reserve_items(&mut self.region, items);
    }

    /// Reserve space for the regions returned by the iterator.
    #[inline]
    pub fn reserve_regions<'a>(&mut self, regions: impl Iterator<Item = &'a R> + Clone)
    where
        R: 'a,
    {
        self.region.reserve_regions(regions);
    }

    /// Iterate the items in this stack.
    #[inline]
    pub fn iter(&self) -> Iter<'_, R> {
        self.into_iter()
    }

    /// Heap size, size - capacity
    #[inline]
    pub fn heap_size<F: FnMut(usize, usize)>(&self, mut callback: F) {
        use crate::impls::offsets::OffsetContainer;
        self.region.heap_size(&mut callback);
        OffsetContainer::heap_size(&self.indices, callback);
    }
}

impl<T, R: Region + Push<T>> Extend<T> for FlatStack<R> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        self.reserve(iter.size_hint().0);
        for item in iter {
            self.indices.push(self.region.push(item));
        }
    }
}

impl<'a, R: Region> IntoIterator for &'a FlatStack<R> {
    type Item = R::ReadItem<'a>;
    type IntoIter = Iter<'a, R>;

    fn into_iter(self) -> Self::IntoIter {
        Iter {
            inner: self.indices.iter(),
            region: &self.region,
        }
    }
}

/// An iterator over [`FlatStack`]. The iterator yields [`Region::ReadItem`] elements, which
/// it obtains by looking up indices.
pub struct Iter<'a, R: Region> {
    /// Iterator over indices.
    inner: std::slice::Iter<'a, R::Index>,
    /// Region to map indices to read items.
    region: &'a R,
}

impl<'a, R: Region> Iterator for Iter<'a, R> {
    type Item = R::ReadItem<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|idx| self.region.index(*idx))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<R: Region> ExactSizeIterator for Iter<'_, R> {}

impl<R: Region> Clone for Iter<'_, R> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            region: self.region,
        }
    }
}

impl<R: Region + Push<T>, T> FromIterator<T> for FlatStack<R> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let mut c = Self::with_capacity(iter.size_hint().0);
        c.extend(iter);
        c
    }
}

impl<R: Region + Clone> Clone for FlatStack<R> {
    fn clone(&self) -> Self {
        Self {
            region: self.region.clone(),
            indices: self.indices.clone(),
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.region.clone_from(&source.region);
        self.indices.clone_from(&source.indices);
    }
}

/// A type to wrap and copy iterators onto regions.
///
/// This only exists to avoid blanket implementations that might conflict with more specific
/// implementations offered by some regions.
#[repr(transparent)]
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct CopyIter<I>(pub I);

#[cfg(test)]
mod tests {
    use crate::impls::deduplicate::{CollapseSequence, ConsecutiveOffsetPairs};
    use crate::impls::tuple::TupleARegion;

    use super::*;

    fn copy<R: Region + Push<T>, T>(r: &mut R, item: T) -> R::Index {
        r.push(item)
    }

    #[test]
    fn test_readme() {
        let r: Result<_, u16> = Ok("abc");
        let mut c = FlatStack::default_impl::<Result<&str, u16>>();
        c.copy(r);
        assert_eq!(r, c.get(0));
    }

    #[test]
    fn test_slice_string_onto() {
        let mut c = <StringRegion>::default();
        let index = c.push("abc".to_string());
        assert_eq!("abc", c.index(index));
        let index = c.push("def");
        assert_eq!("def", c.index(index));
    }

    #[test]
    fn test_container_string() {
        let mut c = FlatStack::default_impl::<String>();
        c.copy(&"abc".to_string());
        assert_eq!("abc", c.get(0));
        c.copy("def");
        assert_eq!("def", c.get(1));
    }

    #[test]
    fn test_vec() {
        let mut c = <SliceRegion<MirrorRegion<_>>>::default();
        let slice = &[1u8, 2, 3];
        let idx = c.push(slice);
        assert!(slice.iter().copied().eq(c.index(idx)));
    }

    #[test]
    fn test_vec_onto() {
        let mut c = <SliceRegion<MirrorRegion<u8>>>::default();
        let slice = &[1u8, 2, 3][..];
        let idx = c.push(slice);
        assert!(slice.iter().copied().eq(c.index(idx)));
    }

    #[test]
    fn test_result() {
        let r: Result<_, u16> = Ok("abc");
        let mut c = <ResultRegion<StringRegion, MirrorRegion<_>>>::default();
        let idx = copy(&mut c, r);
        assert_eq!(r, c.index(idx));
    }

    #[test]
    fn all_types() {
        fn test_copy<T, R: Region + Clone>(t: T)
        where
            for<'a> R: Push<T> + Push<<R as Region>::ReadItem<'a>>,
            // Make sure that types are debug, even if we don't use this in the test.
            for<'a> R::ReadItem<'a>: Debug,
        {
            let mut c = FlatStack::default();
            c.copy(t);

            let mut cc = c.clone();
            cc.copy(c.get(0));

            c.clear();

            let mut r = R::default();
            let _ = r.push(cc.get(0));

            c.reserve_regions(std::iter::once(&r));

            let mut c = FlatStack::merge_capacity(std::iter::once(&c));
            c.copy(cc.get(0));
        }

        test_copy::<_, StringRegion>(&"a".to_string());
        test_copy::<_, StringRegion>("a".to_string());
        test_copy::<_, StringRegion>("a");

        test_copy::<_, MirrorRegion<()>>(());
        test_copy::<_, MirrorRegion<()>>(&());
        test_copy::<_, MirrorRegion<bool>>(true);
        test_copy::<_, MirrorRegion<bool>>(&true);
        test_copy::<_, MirrorRegion<char>>(' ');
        test_copy::<_, MirrorRegion<char>>(&' ');
        test_copy::<_, MirrorRegion<u8>>(0u8);
        test_copy::<_, MirrorRegion<u8>>(&0u8);
        test_copy::<_, MirrorRegion<u16>>(0u16);
        test_copy::<_, MirrorRegion<u16>>(&0u16);
        test_copy::<_, MirrorRegion<u32>>(0u32);
        test_copy::<_, MirrorRegion<u32>>(&0u32);
        test_copy::<_, MirrorRegion<u64>>(0u64);
        test_copy::<_, MirrorRegion<u64>>(&0u64);
        test_copy::<_, MirrorRegion<u128>>(0u128);
        test_copy::<_, MirrorRegion<u128>>(&0u128);
        test_copy::<_, MirrorRegion<usize>>(0usize);
        test_copy::<_, MirrorRegion<usize>>(&0usize);
        test_copy::<_, MirrorRegion<i8>>(0i8);
        test_copy::<_, MirrorRegion<i8>>(&0i8);
        test_copy::<_, MirrorRegion<i16>>(0i16);
        test_copy::<_, MirrorRegion<i16>>(&0i16);
        test_copy::<_, MirrorRegion<i32>>(0i32);
        test_copy::<_, MirrorRegion<i32>>(&0i32);
        test_copy::<_, MirrorRegion<i64>>(0i64);
        test_copy::<_, MirrorRegion<i64>>(&0i64);
        test_copy::<_, MirrorRegion<i128>>(0i128);
        test_copy::<_, MirrorRegion<i128>>(&0i128);
        test_copy::<_, MirrorRegion<isize>>(0isize);
        test_copy::<_, MirrorRegion<isize>>(&0isize);
        test_copy::<_, MirrorRegion<f32>>(0f32);
        test_copy::<_, MirrorRegion<f32>>(&0f32);
        test_copy::<_, MirrorRegion<f64>>(0f64);
        test_copy::<_, MirrorRegion<f64>>(&0f64);
        test_copy::<_, MirrorRegion<std::num::Wrapping<i8>>>(std::num::Wrapping(0i8));
        test_copy::<_, MirrorRegion<std::num::Wrapping<i8>>>(&std::num::Wrapping(0i8));
        test_copy::<_, MirrorRegion<std::num::Wrapping<i16>>>(std::num::Wrapping(0i16));
        test_copy::<_, MirrorRegion<std::num::Wrapping<i16>>>(&std::num::Wrapping(0i16));
        test_copy::<_, MirrorRegion<std::num::Wrapping<i32>>>(std::num::Wrapping(0i32));
        test_copy::<_, MirrorRegion<std::num::Wrapping<i32>>>(&std::num::Wrapping(0i32));
        test_copy::<_, MirrorRegion<std::num::Wrapping<i64>>>(std::num::Wrapping(0i64));
        test_copy::<_, MirrorRegion<std::num::Wrapping<i64>>>(&std::num::Wrapping(0i64));
        test_copy::<_, MirrorRegion<std::num::Wrapping<i128>>>(std::num::Wrapping(0i128));
        test_copy::<_, MirrorRegion<std::num::Wrapping<i128>>>(&std::num::Wrapping(0i128));
        test_copy::<_, MirrorRegion<std::num::Wrapping<isize>>>(std::num::Wrapping(0isize));
        test_copy::<_, MirrorRegion<std::num::Wrapping<isize>>>(&std::num::Wrapping(0isize));

        test_copy::<_, ResultRegion<MirrorRegion<u8>, MirrorRegion<u8>>>(Result::<u8, u8>::Ok(0));
        test_copy::<_, ResultRegion<MirrorRegion<u8>, MirrorRegion<u8>>>(&Result::<u8, u8>::Ok(0));
        test_copy::<_, ResultRegion<MirrorRegion<u8>, MirrorRegion<u8>>>(Result::<u8, u8>::Err(0));
        test_copy::<_, ResultRegion<MirrorRegion<u8>, MirrorRegion<u8>>>(&Result::<u8, u8>::Err(0));

        test_copy::<_, SliceRegion<MirrorRegion<u8>>>([0u8].as_slice());
        test_copy::<_, SliceRegion<MirrorRegion<u8>>>(vec![0u8]);
        test_copy::<_, SliceRegion<MirrorRegion<u8>>>(&vec![0u8]);

        test_copy::<_, SliceRegion<StringRegion>>(["a"].as_slice());
        test_copy::<_, SliceRegion<StringRegion>>(vec!["a"]);
        test_copy::<_, SliceRegion<StringRegion>>(&vec!["a"]);

        test_copy::<_, SliceRegion<TupleARegion<StringRegion>>>([("a",)].as_slice());
        test_copy::<_, SliceRegion<TupleARegion<StringRegion>>>(vec![("a",)]);
        test_copy::<_, SliceRegion<TupleARegion<StringRegion>>>(&vec![("a",)]);

        test_copy::<_, OwnedRegion<_>>([0u8].as_slice());
        test_copy::<_, OwnedRegion<_>>(&[0u8].as_slice());

        test_copy::<_, <(u8, u8) as RegionPreference>::Region>((1, 2));
        test_copy::<_, <(u8, u8) as RegionPreference>::Region>(&(1, 2));

        test_copy::<_, ConsecutiveOffsetPairs<OwnedRegion<_>>>([1, 2, 3].as_slice());

        test_copy::<_, CollapseSequence<OwnedRegion<_>>>([1, 2, 3].as_slice());
        test_copy::<_, CollapseSequence<OwnedRegion<_>>>(&[1, 2, 3]);

        test_copy::<_, OptionRegion<StringRegion>>(Some("abc"));
        test_copy::<_, OptionRegion<StringRegion>>(&Some("abc"));
        test_copy::<_, OptionRegion<StringRegion>>(Option::<&'static str>::None);
        test_copy::<_, OptionRegion<StringRegion>>(&Option::<&'static str>::None);

        test_copy::<_, ResultRegion<StringRegion, MirrorRegion<u8>>>(
            Result::<&'static str, u8>::Ok("abc"),
        );
        test_copy::<_, ResultRegion<StringRegion, MirrorRegion<u8>>>(
            &Result::<&'static str, u8>::Ok("abc"),
        );
        test_copy::<_, ResultRegion<StringRegion, MirrorRegion<u8>>>(
            Result::<&'static str, u8>::Err(1),
        );
        test_copy::<_, ResultRegion<StringRegion, MirrorRegion<u8>>>(
            Result::<&'static str, u8>::Err(2),
        );
    }

    #[test]
    fn slice_region_read_item() {
        fn is_clone<T: Clone>(_: &T) {}

        let mut c = FlatStack::<SliceRegion<MirrorRegion<u8>>>::default();
        c.copy(vec![1, 2, 3]);

        let mut r = SliceRegion::<MirrorRegion<u8>>::default();
        let idx = r.push([1, 2, 3]);
        let read_item = r.index(idx);
        is_clone(&read_item);
        let _read_item3 = read_item;
        assert_eq!(vec![1, 2, 3], read_item.into_iter().collect::<Vec<_>>());
    }

    #[test]
    fn nested_slice_copy() {
        let mut c = FlatStack::default_impl::<[[[[[u8; 1]; 1]; 1]; 1]; 1]>();

        c.copy([[[[[1]]]]]);
        c.copy(&[[[[[1]]]]]);
        c.copy(&[[[[[&1]]]]]);
        c.copy([[[[[&1]]]]]);
        c.copy([[&[[[&1]]]]]);
        c.copy([[[[[1]]; 1]; 1]; 1]);
        c.copy(&[[[[[1; 1]; 1]; 1]; 1]; 1]);
        c.copy(&[[[[[&1; 1]; 1]; 1]; 1]; 1]);
        c.copy([[[[[&1; 1]; 1]; 1]; 1]; 1]);
        c.copy([[&[[[&1; 1]; 1]; 1]; 1]; 1]);
        c.copy([[vec![[[1; 1]; 1]; 1]; 1]; 1]);
        c.copy(&[[vec![[[1; 1]; 1]; 1]; 1]; 1]);
        c.copy(&[[vec![[[&1; 1]; 1]; 1]; 1]; 1]);
        c.copy([[[vec![[&1; 1]; 1]; 1]; 1]; 1]);
        c.copy([[&vec![[[&1; 1]; 1]; 1]; 1]; 1]);
    }

    #[test]
    fn test_owned() {
        fn owned_roundtrip<R, O>(region: &mut R, index: R::Index)
        where
            for<'a> R: Region + Push<<<R as Region>::ReadItem<'a> as IntoOwned<'a>>::Owned>,
            for<'a> R::ReadItem<'a>: IntoOwned<'a, Owned = O> + Eq + Debug,
        {
            let item = region.index(index);
            let owned = item.into_owned();
            let index2 = region.push(owned);
            let item = region.index(index);
            assert_eq!(item, region.index(index2));
        }

        let mut c = <StringRegion>::default();
        let index = c.push("abc".to_string());
        owned_roundtrip::<StringRegion, String>(&mut c, index);
    }

    /// Test that items and owned variants can be reborrowed to shorten their lifetimes.
    fn _test_reborrow<R>(item: R::ReadItem<'_>, owned: &R::Owned)
    where
        R: Region,
        for<'a> R::ReadItem<'a>: Eq,
    {
        // The following line requires `reborrow` because otherwise owned must outlive '_.
        // fn _test_reborrow<R>(item: R::ReadItem<'_>, owned: &R::Owned) where R: Region, for<'a> R::ReadItem<'a>: Eq {
        //                      ----                          - let's call the lifetime of this reference `'1`
        //                      |
        //                      has type `<R as Region>::ReadItem<'2>`
        //     // The following line requires `reborrow` because otherwise owned must outlive '_.
        //     let _ = item == IntoOwned::borrow_as(owned);
        //                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'1` must outlive `'2`
        // let _ = item == IntoOwned::borrow_as(owned);
        let _ = R::reborrow(item) == R::reborrow(IntoOwned::borrow_as(owned));
    }
}