generator_extensions 0.1.1

Basic extensions to Generator types to bring parity with Iterators.
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
//
// Copyright (C) 2020 Nathan Sharp.
//
// This file is available under either the terms of the Apache License, Version
// 2.0 or the MIT License, at your discretion.
//

use core::fmt::{self, Debug, Formatter};
use core::marker::PhantomData;
use core::mem;
use core::num::NonZeroUsize;
use core::ops::{Generator, GeneratorState};
use core::pin::Pin;

use crate::NoData;

/// This trait provides extension methods for generators behind references which
/// allow [resumption].
///
/// This trait is blanket implemented for all suitable references to a
/// generator, namely [`Pin`]`<&mut `[`Generator`]`>` and
/// `&mut `[`Generator`]` + `[`Unpin`].
///
/// To take advantage of these extension methods, simply write:
/// ```
/// use generator_extensions::Resumable;
/// ```
/// Or, preferably:
/// ```
/// use generator_extensions::prelude::*;
/// ```
///
/// [`Generator`]: core::ops::Generator
/// [`Pin`]: core::pin::Pin
/// [resumption]: core::ops::Generator::resume
/// [`Unpin`]: core::marker::Unpin
pub trait Resumable<'a, R, G: Generator<R>> {
    /// Reborrow the pinned generator.
    ///
    /// This method serves the same role as [`Pin::as_mut`].
    ///
    /// [`Pin::as_mut`]: core::pin::Pin::as_mut
    #[must_use]
    fn as_mut(&mut self) -> Pin<&mut G>;

    /// [`Resume`] the pinned generator.
    ///
    /// [`Resume`]: core::ops::Generator::resume
    #[must_use]
    fn resume(&mut self, arg: R) -> GeneratorState<G::Yield, G::Return> {
        self.as_mut().resume(arg)
    }

    /// [`Resume`] the pinned generator and panic if it does not [yield].
    ///
    /// [`Resume`]: core::ops::Generator::resume
    /// [yield]: core::ops::GeneratorState::Yielded
    fn expect_yield(&mut self, arg: R) -> G::Yield {
        match self.resume(arg) {
            GeneratorState::Yielded(item) => item,
            GeneratorState::Complete(..) => panic!("generator completed"),
        }
    }

    /// [`Resume`] the pinned generator and panic if it does not [complete].
    ///
    /// [complete]: core::ops::GeneratorState::Complete
    /// [`Resume`]: core::ops::Generator::resume
    fn expect_complete(&mut self, arg: R) -> G::Return {
        match self.resume(arg) {
            GeneratorState::Yielded(..) => panic!("generator yielded"),
            GeneratorState::Complete(item) => item,
        }
    }

    /// Transforms a pinned generator into an [`Iterator`].
    ///
    /// This method is only available on generators which take `()` as the
    /// argument to [`resume`], and which return `()` on completion. To
    /// transform a generator into this form, consider using the [`unify`]
    /// or [`states`] extensions.
    ///
    /// [`unify`]: Resumable::unify
    /// [`Iterator`]: core::iter::Iterator
    /// [`resume`]: core::ops::Generator::resume
    /// [`states`]: Resumable::states
    #[must_use]
    fn iter(self) -> Iter<'a, G>
    where G: Generator<(), Return = ()>;

    /// Produces a generator which will repeatedly return
    /// [`GeneratorState::Complete`]`(())` instead of panicking, provided that
    /// the generator *has not already completed*.
    ///
    /// The generator type must already [return] `()`.
    ///
    /// [`GeneratorState::Complete`]: core::ops::GeneratorState::Complete
    /// [return]: core::ops::Generator::Return
    #[must_use]
    fn fuse(self) -> Fuse<'a, R, G>
    where G: Generator<R, Return = ()>;

    /// Produces a generator which yields its [states] and then completes with
    /// `()`.
    ///
    /// [states]: core::ops::GeneratorState
    #[must_use]
    fn states(self) -> States<'a, R, G>;

    /// Transforms a pinned generator with identical [`Yield`] and [`Return`]
    /// types into a generator which yields these values and then completes
    /// with `()`.
    ///
    /// [`Yield`]: core::ops::Generator::Yield
    /// [`Return`]: core::ops::Generator::Return
    #[must_use]
    fn unify<T>(self) -> Unify<'a, R, T, G>
    where G: Generator<R, Yield = T, Return = T>;
}

impl<'a, R, G: Generator<R>> Resumable<'a, R, G> for Pin<&'a mut G> {
    fn as_mut(&mut self) -> Pin<&mut G> {
        Pin::as_mut(self)
    }

    fn iter(self) -> Iter<'a, G>
    where G: Generator<(), Return = ()> {
        Iter::new(self)
    }

    fn unify<T>(self) -> Unify<'a, R, T, G>
    where G: Generator<R, Yield = T, Return = T> {
        Unify::new(self)
    }

    fn fuse(self) -> Fuse<'a, R, G>
    where G: Generator<R, Return = ()> {
        Fuse::new(self)
    }

    fn states(self) -> States<'a, R, G> {
        States::new(self)
    }
}

impl<'a, R, G: Generator<R> + Unpin> Resumable<'a, R, G> for &'a mut G {
    fn as_mut(&mut self) -> Pin<&mut G> {
        Pin::new(self)
    }

    fn iter(self) -> Iter<'a, G>
    where G: Generator<(), Return = ()> {
        Iter::new(Pin::new(self))
    }

    fn unify<T>(self) -> Unify<'a, R, T, G>
    where G: Generator<R, Yield = T, Return = T> {
        Unify::new(Pin::new(self))
    }

    fn fuse(self) -> Fuse<'a, R, G>
    where G: Generator<R, Return = ()> {
        Fuse::new(Pin::new(self))
    }

    fn states(self) -> States<'a, R, G> {
        States::new(Pin::new(self))
    }
}

/// The return type of [`Resumable::iter`].
pub struct Iter<'a, G: Generator<()>> {
    pin: Pin<&'a mut G>,
}

impl<'a, G: Generator<(), Return = ()>> Iter<'a, G> {
    /// Creates a new `Iter` from a suitable pinned generator.
    ///
    /// Consider using [`Resumable::iter`] instead.
    #[must_use]
    pub fn new(pin: Pin<&'a mut G>) -> Self {
        Self { pin }
    }

    /// Retrieves the original pinned generator.
    #[must_use]
    pub fn into_inner(self) -> Pin<&'a mut G> {
        self.pin
    }
}

impl<'a, G: Generator<(), Return = ()>> Debug for Iter<'a, G> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("Iter").field("ptr", &(self.pin.as_ref().get_ref() as *const G)).finish()
    }
}

impl<'a, G: Generator<(), Return = ()>> Iterator for Iter<'a, G> {
    type Item = G::Yield;

    fn next(&mut self) -> Option<Self::Item> {
        match self.pin.as_mut().resume(()) {
            GeneratorState::Yielded(item) => Some(item),
            GeneratorState::Complete(()) => None,
        }
    }
}

#[repr(transparent)]
struct TaggedPin<'a, G> {
    ptr: NonZeroUsize,
    _data: PhantomData<Pin<&'a mut G>>,
}

impl<'a, G> TaggedPin<'a, G> {
    #[must_use]
    fn new(pin: Pin<&'a mut G>) -> Self {
        assert!(mem::align_of::<G>() > 1);

        // Safety:
        //     get_unchecked_mut(): We don't move out of G or expose an unpinned
        //     reference.
        //     NonZeroUSize: References are never null, so the pointer will be nonzero.
        unsafe {
            Self {
                ptr: NonZeroUsize::new_unchecked(pin.get_unchecked_mut() as *mut G as usize),
                _data: PhantomData,
            }
        }
    }

    fn get_ptr(&self) -> *mut G {
        (self.ptr.get() & !1) as *mut G
    }

    fn get_pin(&mut self) -> Pin<&'a mut G> {
        // Safety: The returned reference was previously pinned.
        unsafe { Pin::new_unchecked(&mut *self.get_ptr()) }
    }

    fn get_tag(&self) -> bool {
        (self.ptr.get() & 1) != 0
    }

    fn set_tag(&mut self) {
        // Safety: We are setting a bit, so the result cannot be zero. Additionally,
        //         get_ptr() will clear this bit so the returned pointer will remain
        //         valid to dereference.
        self.ptr = unsafe { NonZeroUsize::new_unchecked(self.ptr.get() | 1) };
    }

    fn into_inner(mut self) -> Pin<&'a mut G> {
        self.get_pin()
    }
}

/// The return type of [`Resumable::states`].
pub struct States<'a, R, G: Generator<R>> {
    pin: TaggedPin<'a, G>,
    _arg: NoData<R>,
}

impl<'a, R, G: Generator<R>> States<'a, R, G> {
    /// Creates a new `States` generator from a pinned generator.
    ///
    /// Consider using [`Resumable::states`] instead.
    #[must_use]
    pub fn new(pin: Pin<&'a mut G>) -> Self {
        Self { pin: TaggedPin::new(pin), _arg: NoData::new() }
    }

    /// Retrieves the original pinned generator.
    #[must_use]
    pub fn into_inner(self) -> Pin<&'a mut G> {
        self.pin.into_inner()
    }
}

impl<'a, R, G: Generator<R>> Debug for States<'a, R, G> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("States").field("ptr", &self.pin.get_ptr()).finish()
    }
}

impl<'a, R, G: Generator<R>> Generator<R> for States<'a, R, G> {
    type Yield = GeneratorState<G::Yield, G::Return>;
    type Return = ();

    fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
        if self.pin.get_tag() {
            GeneratorState::Complete(())
        } else {
            match self.pin.get_pin().resume(arg) {
                yielded @ GeneratorState::Yielded(..) => GeneratorState::Yielded(yielded),
                complete @ GeneratorState::Complete(..) => {
                    self.pin.set_tag();
                    GeneratorState::Yielded(complete)
                }
            }
        }
    }
}

/// The return type of [`Resumable::unify`].
pub struct Unify<'a, R, T, G: Generator<R, Yield = T, Return = T>> {
    pin: TaggedPin<'a, G>,
    _arg: NoData<R>,
}

impl<'a, R, T, G: Generator<R, Yield = T, Return = T>> Unify<'a, R, T, G> {
    /// Creates a new `Unify` generator from a pinned generator.
    ///
    /// Consider using [`Resumable::unify`] instead.
    #[must_use]
    pub fn new(pin: Pin<&'a mut G>) -> Self {
        Self { pin: TaggedPin::new(pin), _arg: NoData::new() }
    }

    /// Retrieves the original pinned generator.
    #[must_use]
    pub fn into_inner(self) -> Pin<&'a mut G> {
        self.pin.into_inner()
    }
}

impl<'a, R, T, G: Generator<R, Yield = T, Return = T>> Debug for Unify<'a, R, T, G> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("Unify").field("ptr", &self.pin.get_ptr()).finish()
    }
}

impl<'a, R, T, G: Generator<R, Yield = T, Return = T>> Generator<R> for Unify<'a, R, T, G> {
    type Yield = T;
    type Return = ();

    fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
        if self.pin.get_tag() {
            GeneratorState::Complete(())
        } else {
            match self.pin.get_pin().resume(arg) {
                GeneratorState::Yielded(item) => GeneratorState::Yielded(item),
                GeneratorState::Complete(item) => {
                    self.pin.set_tag();
                    GeneratorState::Yielded(item)
                }
            }
        }
    }
}

/// The return type of [`Resumable::fuse`].
pub struct Fuse<'a, R, G: Generator<R>> {
    pin: TaggedPin<'a, G>,
    _arg: NoData<R>,
}

impl<'a, R, G: Generator<R, Return = ()>> Fuse<'a, R, G> {
    /// Creates a new `Fuse` generator from a pinned generator.
    ///
    /// Consider using [`Resumable::fuse`] instead.
    #[must_use]
    pub fn new(pin: Pin<&'a mut G>) -> Self {
        Self { pin: TaggedPin::new(pin), _arg: NoData::new() }
    }

    /// Returns `true` if the pinned generator has completed.
    ///
    /// # Notes
    /// This method may return `false` even if the generator is complete if
    /// [`new`] was called with a generator which was already complete.
    ///
    /// [`new`]: Fuse::new
    #[must_use]
    pub fn is_complete(&self) -> bool {
        self.pin.get_tag()
    }

    /// Forces the `Fuse` to repeatedly return
    /// [`GeneratorState::Complete`]`(())`, even if the underlying pinned
    /// generator is not yet complete.
    ///
    /// The underlying pinned generator is neither made to complete nor dropped.
    ///
    /// [`GeneratorState::Complete`]: core::ops::GeneratorState::Complete
    pub fn stop(&mut self) {
        self.pin.set_tag()
    }

    /// Retrieves the original pinned generator.
    #[must_use]
    pub fn into_inner(self) -> Pin<&'a mut G> {
        self.pin.into_inner()
    }
}

impl<'a, R, G: Generator<R, Return = ()>> Debug for Fuse<'a, R, G> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("Fuse")
            .field("fuse", &self.pin.get_tag())
            .field("ptr", &self.pin.get_ptr())
            .finish()
    }
}

impl<'a, R, G: Generator<R, Return = ()>> Generator<R> for Fuse<'a, R, G> {
    type Yield = G::Yield;
    type Return = ();

    fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
        if self.pin.get_tag() {
            GeneratorState::Complete(())
        } else {
            match self.pin.get_pin().resume(arg) {
                yielded @ GeneratorState::Yielded(..) => yielded,
                complete @ GeneratorState::Complete(..) => {
                    self.pin.set_tag();
                    complete
                }
            }
        }
    }
}