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
use aliasable::boxed::AliasableBox;
use core::{fmt, ops::ControlFlow};
use maybe_dangling::MaybeDangling;
use crate::{
DoubleEndedFallibleLender, ExactSizeFallibleLender, FallibleLend, FallibleLender,
FallibleLending, FusedFallibleLender,
try_trait_v2::{FromResidual, Try},
};
/// A fallible lender with a [`peek()`](Peekable::peek) method
/// that returns an optional reference to the next element.
///
/// This `struct` is created by the
/// [`peekable()`](crate::FallibleLender::peekable) method on
/// [`FallibleLender`]. See its documentation for more.
#[must_use = "lenders are lazy and do nothing unless consumed"]
pub struct Peekable<'this, L>
where
L: FallibleLender,
{
// MaybeDangling wraps the peeked value to indicate it may reference data
// from the lender. AliasableBox eliminates noalias retagging that would
// invalidate the peeked reference when the struct is moved.
// Field order ensures lender drops last.
//
// See https://github.com/WanderLanz/Lender/issues/34
peeked: MaybeDangling<Option<Option<FallibleLend<'this, L>>>>,
lender: AliasableBox<L>,
}
impl<'this, L> Peekable<'this, L>
where
L: FallibleLender,
{
#[inline(always)]
pub(crate) fn new(lender: L) -> Peekable<'this, L> {
let _ = L::__check_covariance(crate::CovariantProof::new());
Peekable {
peeked: MaybeDangling::new(None),
lender: AliasableBox::from_unique(alloc::boxed::Box::new(lender)),
}
}
/// Returns the inner lender.
#[inline(always)]
pub fn into_inner(self) -> L {
*AliasableBox::into_unique(self.lender)
}
/// Returns a reference to the next element without advancing the lender.
///
/// Like [`next`](FallibleLender::next), if there is a
/// next value, it is borrowed from the underlying lender
/// and cached. Calling `peek()` multiple times without
/// advancing the lender returns the same cached element.
///
/// # Errors
///
/// Returns an error if the underlying lender produces an error.
///
/// # Examples
///
/// ```
/// # use lender::prelude::*;
/// # use std::convert::Infallible;
/// # fn main() -> Result<(), Infallible> {
/// let mut lender = [1, 2, 3].iter().into_lender()
/// .into_fallible()
/// .peekable();
///
/// assert_eq!(lender.peek()?, Some(&&1));
/// assert_eq!(lender.peek()?, Some(&&1)); // Doesn't advance
/// assert_eq!(lender.next()?, Some(&1));
/// assert_eq!(lender.peek()?, Some(&&2));
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn peek(&mut self) -> Result<Option<&'_ FallibleLend<'_, L>>, L::Error> {
let lender = &mut self.lender;
if self.peeked.is_none() {
// SAFETY: Extends the lend's lifetime to store it in `self.peeked`.
// Safe because the lender is boxed (stable address) and only one lend
// is alive at a time.
*self.peeked = Some(unsafe {
core::mem::transmute::<Option<FallibleLend<'_, L>>, Option<FallibleLend<'this, L>>>(
lender.next()?,
)
});
}
// SAFETY: Ties the lend's lifetime to the borrow of `self`, preventing it
// from escaping. Safe because `L::Lend` is covariant in its lifetime
// (required by FallibleLender). The `unwrap_unchecked` is safe because
// `self.peeked` was set to `Some` above if it was `None`.
Ok(unsafe {
core::mem::transmute::<
Option<&'_ FallibleLend<'this, L>>,
Option<&'_ FallibleLend<'_, L>>,
>(self.peeked.as_mut().unwrap_unchecked().as_ref())
})
}
/// Returns a mutable reference to the next element without advancing the lender.
///
/// Like [`peek`](Self::peek), if there is a next value, it is borrowed from the
/// underlying lender and cached. The returned mutable reference allows modifying
/// the peeked value.
///
/// # Errors
///
/// Returns an error if the underlying lender produces an error.
///
/// # Examples
///
/// ```
/// # use lender::prelude::*;
/// # use std::convert::Infallible;
/// # fn main() -> Result<(), Infallible> {
/// let mut lender = [1, 2, 3].iter().into_lender()
/// .into_fallible()
/// .peekable();
///
/// if let Some(p) = lender.peek_mut()? {
/// // p is &mut &i32, so we replace the reference
/// *p = &10;
/// }
/// assert_eq!(lender.next()?, Some(&10));
/// assert_eq!(lender.next()?, Some(&2));
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn peek_mut(&mut self) -> Result<Option<&'_ mut FallibleLend<'this, L>>, L::Error> {
let lender = &mut self.lender;
if self.peeked.is_none() {
*self.peeked = Some(
// SAFETY: The lend is manually guaranteed to be the only one alive
unsafe {
core::mem::transmute::<
Option<FallibleLend<'_, L>>,
Option<FallibleLend<'this, L>>,
>(lender.next()?)
},
);
}
Ok(
// SAFETY: a `None` variant for `self` would have been replaced by a `Some`
// variant in the code above.
unsafe { self.peeked.as_mut().unwrap_unchecked().as_mut() },
)
}
/// Consumes and returns the next element if the given predicate is true.
///
/// If `f(&next_element)` returns `true`, consumes and returns the next element.
/// Otherwise, returns `Ok(None)` and the element remains peeked.
///
/// # Errors
///
/// Returns an error if the underlying lender produces an error.
///
/// # Examples
///
/// ```
/// # use lender::prelude::*;
/// # use std::convert::Infallible;
/// # fn main() -> Result<(), Infallible> {
/// let mut lender = [1, 2, 3].iter().into_lender()
/// .into_fallible()
/// .peekable();
///
/// // Consume 1 since it's odd
/// assert_eq!(lender.next_if(|&x| *x % 2 == 1)?, Some(&1));
/// // Don't consume 2 since it's not odd
/// assert_eq!(lender.next_if(|&x| *x % 2 == 1)?, None);
/// // 2 is still there
/// assert_eq!(lender.next()?, Some(&2));
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn next_if<F>(&mut self, f: F) -> Result<Option<FallibleLend<'_, L>>, L::Error>
where
F: FnOnce(&FallibleLend<'_, L>) -> bool,
{
// Get the next value by inlining the logic of next() to avoid borrow conflicts
let v = match self.peeked.take() {
// SAFETY: The lend is manually guaranteed to be the only one alive
Some(peeked) => unsafe {
core::mem::transmute::<Option<FallibleLend<'this, L>>, Option<FallibleLend<'_, L>>>(
peeked,
)
},
None => self.lender.next()?,
};
match v {
Some(v) if f(&v) => Ok(Some(v)),
v => {
// SAFETY: The lend is manually guaranteed to be the only one alive
*self.peeked = Some(unsafe {
core::mem::transmute::<
Option<FallibleLend<'_, L>>,
Option<FallibleLend<'this, L>>,
>(v)
});
Ok(None)
}
}
}
/// Consumes and returns the next element if it equals the given value.
///
/// If the next element equals `t`, consumes and returns it. Otherwise,
/// returns `Ok(None)` and the element remains peeked.
///
/// # Errors
///
/// Returns an error if the underlying lender produces an error.
///
/// # Examples
///
/// ```
/// # use lender::prelude::*;
/// # use std::convert::Infallible;
/// # fn main() -> Result<(), Infallible> {
/// let mut lender = [1, 2, 3].iter().into_lender()
/// .into_fallible()
/// .peekable();
///
/// // Consume 1 since it equals 1
/// assert_eq!(lender.next_if_eq(&&1)?, Some(&1));
/// // Don't consume 2 since it doesn't equal 1
/// assert_eq!(lender.next_if_eq(&&1)?, None);
/// // 2 is still there
/// assert_eq!(lender.next()?, Some(&2));
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn next_if_eq<'a, T>(&'a mut self, t: &T) -> Result<Option<FallibleLend<'a, L>>, L::Error>
where
T: for<'all> PartialEq<FallibleLend<'all, L>>,
{
self.next_if(|v| t == v)
}
}
// Clone is not implemented for Peekable because the peeked value borrows from
// the lender's AliasableBox allocation; a clone would need its own allocation,
// leaving the cloned peeked value dangling.
impl<'this, L> fmt::Debug for Peekable<'this, L>
where
L: FallibleLender + fmt::Debug,
FallibleLend<'this, L>: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Peekable")
.field("lender", &self.lender)
.field("peeked", &self.peeked)
.finish()
}
}
impl<'lend, L> FallibleLending<'lend> for Peekable<'_, L>
where
L: FallibleLender,
{
type Lend = FallibleLend<'lend, L>;
}
impl<'this, L> FallibleLender for Peekable<'this, L>
where
L: FallibleLender,
{
type Error = L::Error;
// SAFETY: the lend is that of L
crate::unsafe_assume_covariance_fallible!();
#[inline]
fn next(&mut self) -> Result<Option<FallibleLend<'_, Self>>, Self::Error> {
match self.peeked.take() {
Some(peeked) => Ok(
// SAFETY: The lend is manually guaranteed to be the only one alive
unsafe {
core::mem::transmute::<
Option<FallibleLend<'this, Self>>,
Option<FallibleLend<'_, Self>>,
>(peeked)
},
),
None => self.lender.next(),
}
}
#[inline]
fn count(mut self) -> Result<usize, Self::Error> {
let lender = *AliasableBox::into_unique(self.lender);
match self.peeked.take() {
Some(None) => Ok(0),
Some(Some(_)) => Ok(1 + lender.count()?),
None => lender.count(),
}
}
#[inline]
fn nth(&mut self, n: usize) -> Result<Option<FallibleLend<'_, Self>>, Self::Error> {
match self.peeked.take() {
Some(None) => Ok(None),
Some(v @ Some(_)) if n == 0 => Ok(unsafe {
// SAFETY: The lend is manually guaranteed to be the only one alive
core::mem::transmute::<
Option<FallibleLend<'this, Self>>,
Option<FallibleLend<'_, Self>>,
>(v)
}),
Some(Some(_)) => self.lender.nth(n - 1),
None => self.lender.nth(n),
}
}
#[inline]
fn last<'a>(&'a mut self) -> Result<Option<FallibleLend<'a, Self>>, Self::Error>
where
Self: Sized,
{
let peek_opt = match self.peeked.take() {
Some(None) => return Ok(None),
Some(v) =>
// SAFETY: 'this: 'a
unsafe {
core::mem::transmute::<
Option<FallibleLend<'this, Self>>,
Option<FallibleLend<'a, Self>>,
>(v)
},
None => None,
};
Ok(self.lender.last()?.or(peek_opt))
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let peek_len = match *self.peeked {
Some(None) => return (0, Some(0)),
Some(Some(_)) => 1,
None => 0,
};
let (l, r) = self.lender.size_hint();
(
l.saturating_add(peek_len),
r.and_then(|r| r.checked_add(peek_len)),
)
}
#[inline]
fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> Result<R, Self::Error>
where
Self: Sized,
F: FnMut(B, FallibleLend<'_, Self>) -> Result<R, Self::Error>,
R: Try<Output = B>,
{
let acc = match self.peeked.take() {
Some(None) => return Ok(Try::from_output(init)),
Some(Some(v)) => match f(init, v)?.branch() {
ControlFlow::Break(b) => return Ok(FromResidual::from_residual(b)),
ControlFlow::Continue(a) => a,
},
None => init,
};
self.lender.try_fold(acc, f)
}
#[inline]
fn fold<B, F>(mut self, init: B, mut f: F) -> Result<B, Self::Error>
where
Self: Sized,
F: FnMut(B, FallibleLend<'_, Self>) -> Result<B, Self::Error>,
{
match self.peeked.take() {
Some(None) => Ok(init),
Some(Some(v)) => {
// Manual loop instead of lender.fold() to avoid
// consuming the lender before v is used: v borrows
// from the AliasableBox allocation, which must stay
// alive until f(acc, v) completes.
let mut acc = f(init, v)?;
while let Some(x) = self.lender.next()? {
acc = f(acc, x)?;
}
Ok(acc)
}
None => {
let lender = *AliasableBox::into_unique(self.lender);
lender.fold(init, f)
}
}
}
}
impl<'this, L: DoubleEndedFallibleLender> DoubleEndedFallibleLender for Peekable<'this, L> {
#[inline]
fn next_back(&mut self) -> Result<Option<FallibleLend<'_, Self>>, Self::Error> {
match self.peeked.as_mut() {
Some(v @ Some(_)) => match self.lender.next_back()? {
Some(next) => Ok(Some(next)),
None => Ok(
// SAFETY: The lend is manually guaranteed to be the only one alive
unsafe {
core::mem::transmute::<
Option<FallibleLend<'this, Self>>,
Option<FallibleLend<'_, Self>>,
>(v.take())
},
),
},
Some(None) => Ok(None),
None => self.lender.next_back(),
}
}
#[inline]
fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> Result<R, Self::Error>
where
Self: Sized,
F: FnMut(B, FallibleLend<'_, Self>) -> Result<R, Self::Error>,
R: Try<Output = B>,
{
match self.peeked.take() {
None => self.lender.try_rfold(init, f),
Some(None) => Ok(Try::from_output(init)),
Some(Some(v)) => match self.lender.try_rfold(init, &mut f)?.branch() {
ControlFlow::Continue(acc) => f(acc, v),
ControlFlow::Break(r) => {
*self.peeked = Some(Some(v));
Ok(FromResidual::from_residual(r))
}
},
}
}
#[inline]
fn rfold<B, F>(mut self, init: B, mut f: F) -> Result<B, Self::Error>
where
Self: Sized,
F: FnMut(B, FallibleLend<'_, Self>) -> Result<B, Self::Error>,
{
match self.peeked.take() {
None => {
let lender = *AliasableBox::into_unique(self.lender);
lender.rfold(init, f)
}
Some(None) => Ok(init),
Some(Some(v)) => {
// Manual loop instead of lender.rfold() to avoid
// consuming the lender before v is used: v borrows
// from the AliasableBox allocation, which must stay
// alive until f(acc, v) completes.
let mut acc = init;
while let Some(x) = self.lender.next_back()? {
acc = f(acc, x)?;
}
f(acc, v)
}
}
}
}
impl<'this, L> ExactSizeFallibleLender for Peekable<'this, L> where L: ExactSizeFallibleLender {}
impl<'this, L> FusedFallibleLender for Peekable<'this, L> where L: FusedFallibleLender {}
#[cfg(test)]
mod test {
use core::convert::Infallible;
use super::*;
use crate::{IntoFallible, Lend, Lender, Lending};
struct ArrayLender {
array: [i32; 4],
}
impl<'lend> Lending<'lend> for ArrayLender {
type Lend = &'lend i32;
}
impl Lender for ArrayLender {
crate::check_covariance!();
fn next(&mut self) -> Option<Lend<'_, Self>> {
Some(&self.array[0])
}
}
// This test will fail if Peekable stores L instead of Box<L>. In that case,
// when Peekable<ArrayLender> is moved, the array inside ArrayLender is
// moved, too, but Peekable.peeked will still contain a reference to the
// previous location.
#[test]
fn test_peekable() -> Result<(), Infallible> {
let lender = ArrayLender {
array: [-1, 1, 2, 3],
};
let mut peekable = lender.into_fallible().peekable();
assert_eq!(**peekable.peek()?.unwrap(), -1);
assert_eq!(
peekable.peeked.unwrap().unwrap() as *const _,
&peekable.lender.lender.array[0] as *const _
);
moved_peekable(peekable);
Ok(())
}
fn moved_peekable(peekable: Peekable<IntoFallible<ArrayLender>>) {
let peeked = peekable.peeked.unwrap().unwrap() as *const _;
let array = &peekable.lender.lender.array[0] as *const _;
assert_eq!(
peeked, array,
"Peeked element pointer should point to the first element of the array"
);
}
}