sqnc 1.0.0

Traits and adaptors for sequences
Documentation
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
use crate::traits::*;
use core::marker::PhantomData;

/// Wrapper for a type `S` that, after dereferencing `N` times, implements [`Sequence`].
///
/// This struct implements the [sequence traits][`crate::traits`] by delegating
/// to `S` dereferenced `N` times.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Wrapper<S, N>(S, PhantomData<N>);

impl<S, N> Wrapper<S, N> {
    #[inline]
    pub fn unwrap(self) -> S {
        self.0
    }
}

impl<S, N> From<S> for Wrapper<S, N>
where
    S: DerefSequence<N>,
{
    #[inline]
    fn from(sequence: S) -> Self {
        Self(sequence, PhantomData)
    }
}

impl<S, N> AsRef<S> for Wrapper<S, N> {
    #[inline]
    fn as_ref(&self) -> &S {
        &self.0
    }
}

impl<S, N> AsMut<S> for Wrapper<S, N> {
    #[inline]
    fn as_mut(&mut self) -> &mut S {
        &mut self.0
    }
}

impl<S, N> IntoIterator for Wrapper<S, N>
where
    S: DerefSequence<N> + IntoIterator,
{
    type Item = S::Item;
    type IntoIter = S::IntoIter;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'this, S, N> SequenceTypes<'this> for Wrapper<S, N>
where
    S: DerefSequence<N>,
    S::Sequence: SequenceTypes<'this>,
{
    type Item = <S::Sequence as SequenceTypes<'this>>::Item;
    type Iter = <S::Sequence as SequenceTypes<'this>>::Iter;
}

impl<'this, S, N> MutSequenceTypes<'this> for Wrapper<S, N>
where
    S: DerefSequence<N>,
    S::Sequence: MutSequenceTypes<'this>,
{
    type MutItem = <S::Sequence as MutSequenceTypes<'this>>::MutItem;
    type IterMut = <S::Sequence as MutSequenceTypes<'this>>::IterMut;
}

impl<S, N> Sequence for Wrapper<S, N>
where
    S: DerefSequence<N>,
{
    #[inline]
    fn len(&self) -> usize {
        self.0.deref_sqnc().len()
    }

    #[inline]
    fn is_empty(&self) -> bool {
        self.0.deref_sqnc().is_empty()
    }

    #[inline]
    fn get(&self, index: usize) -> Option<<Self as SequenceTypes<'_>>::Item> {
        self.0.deref_sqnc().get(index)
    }

    #[inline]
    fn rget(&self, rindex: usize) -> Option<<Self as SequenceTypes<'_>>::Item> {
        self.0.deref_sqnc().rget(rindex)
    }

    #[inline]
    fn first(&self) -> Option<<Self as SequenceTypes<'_>>::Item> {
        self.0.deref_sqnc().first()
    }

    #[inline]
    fn last(&self) -> Option<<Self as SequenceTypes<'_>>::Item> {
        self.0.deref_sqnc().last()
    }

    #[inline]
    fn iter(&self) -> <Self as SequenceTypes<'_>>::Iter {
        self.0.deref_sqnc().iter()
    }

    #[inline]
    fn min<'a>(&'a self) -> Option<<Self as SequenceTypes<'a>>::Item>
    where
        <Self as SequenceTypes<'a>>::Item: Ord,
    {
        self.0.deref_sqnc().min()
    }

    #[inline]
    fn max<'a>(&'a self) -> Option<<Self as SequenceTypes<'a>>::Item>
    where
        <Self as SequenceTypes<'a>>::Item: Ord,
    {
        self.0.deref_sqnc().max()
    }
}

impl<S, N> MutSequence for Wrapper<S, N>
where
    S: DerefMutSequence<N>,
    S::Sequence: MutSequence,
{
    #[inline]
    fn get_mut(&mut self, index: usize) -> Option<<Self as MutSequenceTypes<'_>>::MutItem> {
        self.0.deref_mut_sqnc().get_mut(index)
    }

    #[inline]
    fn rget_mut(&mut self, rindex: usize) -> Option<<Self as MutSequenceTypes<'_>>::MutItem> {
        self.0.deref_mut_sqnc().rget_mut(rindex)
    }

    #[inline]
    fn first_mut(&mut self) -> Option<<Self as MutSequenceTypes<'_>>::MutItem> {
        self.0.deref_mut_sqnc().first_mut()
    }

    #[inline]
    fn last_mut(&mut self) -> Option<<Self as MutSequenceTypes<'_>>::MutItem> {
        self.0.deref_mut_sqnc().last_mut()
    }

    #[inline]
    fn iter_mut(&mut self) -> <Self as MutSequenceTypes<'_>>::IterMut {
        self.0.deref_mut_sqnc().iter_mut()
    }
}

// SAFETY: All `Wrapper` does is dereference `S` `N` times. Uniqueness of the
// wrapped `S::Sequence` is therefor inherited.
unsafe impl<S, N> UniqueSequence for Wrapper<S, N>
where
    S: DerefSequence<N>,
    S::Sequence: UniqueSequence,
{
}

/// Wraps a type `S` that, after dereferencing `N` times, implements [`Sequence`].
///
/// The returned [`Wrapper`] implements [`Sequence`], and [`MutSequence`] if
/// applicable`, by delegating to `S` dereferenced `N` times.
///
/// # Motivation
///
/// With automatic dereferencing it is possible to use methods of a trait on
/// types that dereference to a type that implements the trait. For example, we
/// can use [`Sequence::get()`] on an [`std::rc::Rc`] of [`std::ops::Range`]
/// like so:
///
/// ```
/// use sqnc::traits::*;
/// use std::ops::Deref;
/// use std::rc::Rc;
///
/// let a = Rc::new(3..6);
/// assert_eq!(a.get(0), Some(3));
/// // sugar for
/// assert_eq!(Sequence::get(Deref::deref(&a), 0), Some(3));
/// ```
///
/// Unfortunately automatic dereferencing doesn't work for function parameters
/// with trait bounds:
///
/// ```compile_fail
/// use sqnc::traits::*;
/// use std::rc::Rc;
///
/// fn takes_ref_sequence(seq: &impl Sequence) {}
///
/// let a = Rc::new(3..6);
/// takes_ref_sequence(&a); // `Rc<std::ops::Range>` does not implement `Sequence`
/// ```
///
/// We can solve this by manually dereferencing `a` to `Single` using
/// `a.deref()`:
///
/// ```
/// use sqnc::traits::*;
/// use std::ops::Deref;
/// use std::rc::Rc;
///
/// fn takes_ref_sequence(seq: &impl Sequence) {}
///
/// let a = Rc::new(3..6);
/// takes_ref_sequence(a.deref());
/// ```
///
/// But what if the function needs to take ownership of the sequence? The
/// function [`wrap()`] provides a solution to this problem by wrapping any
/// type `S` that, after dereferencing `N` times, implements [`Sequence`]:
///
/// ```
/// use sqnc::traits::*;
/// use std::rc::Rc;
///
/// fn takes_owned_sequence(seq: impl Sequence) {}
///
/// let a = Rc::new(3..6);
/// takes_owned_sequence(sqnc::wrap(a));
/// ```
///
/// To pass a reference to a sequence to a function that requires an owned
/// sequence, use method [`Sequence::as_sqnc()`]:
///
/// ```
/// use sqnc::traits::*;
/// use std::rc::Rc;
///
/// fn takes_owned_sequence(seq: impl Sequence) {}
///
/// let a = Rc::new(3..6);
/// takes_owned_sequence(a.as_sqnc());
/// // We still have ownership of `a`:
/// assert_eq!(a.get(0), Some(3));
/// ```
///
/// # Inner workings
///
/// The [`wrap()`] function takes two generic parameters, `S` and `N`. The
/// first defines the type to be wrapped. The second parameter defines how many
/// times `S` should be dereferenced (using [`std::ops::Deref::deref()`]) such
/// that the dereferenced type (final [`std::ops::Deref::Target`]) implements
/// [`Sequence`]. The `N`-times dereferencing with the described bound is
/// provided by the trait [`DerefSequence`].
///
/// Although a const generic `usize` would be a perfect fit for the dereference
/// depth `N`, it is at the time of writing not possible to define
/// [`DerefSequence`] recursively using const generics. Instead, `N` is defined
/// as nested tuples, starting with the empty tuple, where the number of nested
/// tuples is the dereference depth.
///
/// Rust automatically infers parameter `N` if and only if there is exactly one
/// `N` that satisfies the bound that `S` dereferenced `N` times implements
/// [`Sequence`].
pub fn wrap<S, N>(sequence: S) -> Wrapper<S, N>
where
    S: DerefSequence<N>,
{
    Wrapper(sequence, PhantomData)
}

#[cfg(test)]
mod tests {
    use super::Wrapper;
    use crate::traits::*;

    #[test]
    fn unwrap() {
        assert_eq!(Wrapper::from(2..5).unwrap(), 2..5);
    }

    #[test]
    fn as_ref() {
        assert_eq!(Wrapper::from(2..5).as_ref(), &(2..5));
    }

    #[test]
    fn as_mut() {
        let mut x = [2, 3, 4];
        let mut y = Wrapper::from(&mut x);
        *y.as_mut().get_mut(0).unwrap() = 5;
        assert_eq!(x, [5, 3, 4]);
    }

    #[test]
    fn into_iter() {
        assert!(Wrapper::from(2..5).into_iter().eq(2..5));
    }

    #[test]
    fn len() {
        assert_eq!(Wrapper::from(2..5).len(), 3);
    }

    #[test]
    fn is_empty() {
        assert_eq!(Wrapper::from(2..5).is_empty(), false);
        assert_eq!(Wrapper::from(2..2).is_empty(), true);
    }

    #[test]
    fn get() {
        let x = Wrapper::from(2..5);
        assert_eq!(x.get(0), Some(2));
        assert_eq!(x.get(1), Some(3));
        assert_eq!(x.get(2), Some(4));
        assert_eq!(x.get(3), None);
    }

    #[test]
    fn rget() {
        let x = Wrapper::from(2..5);
        assert_eq!(x.rget(0), Some(4));
        assert_eq!(x.rget(1), Some(3));
        assert_eq!(x.rget(2), Some(2));
        assert_eq!(x.rget(3), None);
    }

    #[test]
    fn first() {
        assert_eq!(Wrapper::from(2..5).first(), Some(2));
        assert_eq!(Wrapper::from(2..2).first(), None);
    }

    #[test]
    fn last() {
        assert_eq!(Wrapper::from(2..5).last(), Some(4));
        assert_eq!(Wrapper::from(2..2).last(), None);
    }

    #[test]
    fn get_mut() {
        let mut x = [2, 3, 4];
        let mut y = Wrapper::from(&mut x);
        *y.get_mut(0).unwrap() = 5;
        *y.get_mut(1).unwrap() = 6;
        *y.get_mut(2).unwrap() = 7;
        assert!(y.get_mut(3).is_none());
        assert_eq!(x, [5, 6, 7]);
    }

    #[test]
    fn rget_mut() {
        let mut x = [2, 3, 4];
        let mut y = Wrapper::from(&mut x);
        *y.rget_mut(0).unwrap() = 7;
        *y.rget_mut(1).unwrap() = 6;
        *y.rget_mut(2).unwrap() = 5;
        assert!(y.rget_mut(3).is_none());
        assert_eq!(x, [5, 6, 7]);
    }

    #[test]
    fn first_mut() {
        let mut x = [2, 3, 4];
        let mut y = Wrapper::from(&mut x);
        *y.first_mut().unwrap() = 5;
        assert_eq!(x, [5, 3, 4]);
        let mut z: Wrapper<[usize; 0], _> = Wrapper::from([]);
        assert_eq!(z.first_mut(), None);
    }

    #[test]
    fn last_mut() {
        let mut x = [2, 3, 4];
        let mut y = Wrapper::from(&mut x);
        *y.last_mut().unwrap() = 7;
        assert_eq!(x, [2, 3, 7]);
        let mut z: Wrapper<[usize; 0], _> = Wrapper::from([]);
        assert_eq!(z.last_mut(), None);
    }

    #[test]
    fn iter() {
        assert!(Wrapper::from(2..5).iter().eq(2..5));
    }

    #[test]
    fn iter_mut() {
        let mut x = [2, 3, 4];
        Wrapper::from(&mut x).iter_mut().for_each(|v| *v += 3);
        assert!(x.iter().eq([&5, &6, &7]));
    }

    #[test]
    fn min() {
        assert_eq!(Wrapper::from(2..5).min(), Some(2));
        assert_eq!(Wrapper::from(2..2).min(), None);
    }

    #[test]
    fn max() {
        assert_eq!(Wrapper::from(2..5).max(), Some(4));
        assert_eq!(Wrapper::from(2..2).max(), None);
    }

    #[test]
    fn wrap() {
        struct SmartPointer<T>(T);

        impl<T> core::ops::Deref for SmartPointer<T> {
            type Target = T;

            fn deref(&self) -> &T {
                &self.0
            }
        }

        let x = SmartPointer([2, 3, 4]);
        assert_eq!(Sequence::get(&super::wrap(x), 0), Some(&2));

        let x = SmartPointer([2, 3, 4]);
        let y = SmartPointer(x);
        assert_eq!(Sequence::get(&super::wrap(y), 0), Some(&2));
    }
}