ufotofu 0.10.1

Abstractions for lazily consuming and producing 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
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
use core::cmp::min;

use alloc::{boxed::Box, vec::Vec};

use arbitrary::{size_hint, Arbitrary};
use derive_builder::Builder;

use crate::{consumer::compat, prelude::*, test_yielder::TestYielder};

/// Returns a [`TestConsumerBuilder`] for building a consumer with fully configurable observable behaviour.
///
/// See the [fuzz-testing tutorial](crate::fuzz_testing_tutorial) for typical usage.
///
/// ```
/// use ufotofu::prelude::*;
/// # pollster::block_on(async{
/// let mut c = build_test_consumer::<u32, (), char>()
///     .err('z')
///     .consumptions_until_error(2)
///     .build().unwrap();
///
/// c.consume_item(1).await?;
/// c.consume_item(2).await?;
/// assert_eq!(c.consume_item(4).await, Err('z'));
///
/// assert_eq!(c.as_slice(), &[1, 2]);
/// assert_eq!(c.peek_final(), None);
/// # Result::<(), char>::Ok(())
/// # });
/// ```
///
/// <br/>Counterpart: the [`producer::build_test_producer`] function.
pub fn build_test_consumer<Item, Final, Error>() -> TestConsumerBuilder<Item, Final, Error>
where
    Item: Clone,
    Final: Clone,
    Error: Clone,
{
    TestConsumerBuilder::create_empty()
}

impl<Item, Final, Error> TestConsumerBuilder<Item, Final, Error> {
    /// Configures the number of item slots the built [`TestConsumer`] will expose on each call to `expose_slots`; the built consumer will cycle through this vec of sizes.
    ///
    /// Entries of `0` will be ignored. If all entries are zero, a single `usize::MAX` is used as the pattern.
    ///
    /// ```
    /// use ufotofu::prelude::*;
    /// # pollster::block_on(async{
    /// let mut c = build_test_consumer::<u32, (), char>()
    ///     .err('z')
    ///     .consumptions_until_error(999)
    ///     .exposed_slots_sizes(vec![1, 2])
    ///     .build().unwrap();
    ///
    /// // The pattern starts with `1`, so one slots is exposed.
    /// c.expose_slots(async |items| {
    ///     assert_eq!(items.len(), 1);
    ///     (0, ()) // Report back that zero items should be considered consumed.
    /// }).await?;
    ///
    /// // The pattern continues with `2`, so two slots are exposed.
    /// c.expose_slots(async |items| {
    ///     assert_eq!(items.len(), 2);
    ///     (0, ()) // Report back that zero items should be considered consumed.
    /// }).await?;
    ///
    /// // The pattern loops back to its start, so one item is exposed.
    /// c.expose_slots(async |items| {
    ///     assert_eq!(items.len(), 1);
    ///     (0, ()) // Report back that zero items should be considered consumed.
    /// }).await?;
    /// # Result::<(), char>::Ok(())
    /// # });
    /// ```
    ///
    /// If you do not call this method, the built consumer will expose unspecified sizes of item slots strictly less than 65536.
    ///
    /// <br/>Counterpart: the [`TestProducerBuilder::exposed_items_sizes`](producer::TestProducerBuilder::exposed_items_sizes) method.
    pub fn exposed_slots_sizes<VALUE: Into<Vec<usize>>>(&mut self, value: VALUE) -> &mut Self {
        let mut the_sizes: Vec<usize> = value.into().into_iter().filter(|size| *size > 0).collect();

        if the_sizes.is_empty() {
            the_sizes.push(65535);
        }

        let new = self;
        new.exposed_slots_sizes = Some(the_sizes.into_boxed_slice());
        new
    }

    /// Sets a pattern to control whether the built [`TestConsumer`] will immediately complete asynchronous methods, or whether it will yield back to the task executor first.
    ///
    /// If you do not call this method, the built consumer will complete all its methods immediately without unnecessary yielding.
    ///
    /// If all booleans are `true`, a single `false` is automatically appended (otherwise, the producer would always yield and never progress).
    ///
    /// <br/>Counterpart: the [`TestProducerBuilder::yield_pattern`](producer::TestProducerBuilder::yield_pattern) method.
    pub fn yield_pattern<VALUE: Into<Vec<bool>>>(&mut self, value: VALUE) -> &mut Self {
        let new = self;
        new.yielder = Some(TestYielder::new(value.into().into_boxed_slice()));
        new
    }
}

/// A consumer with fully configurable observable behaviour, intended for testing other code.
///
/// See the [fuzz-testing tutorial](crate::fuzz_testing_tutorial) for typical usage.
///
/// ```
/// use ufotofu::prelude::*;
/// # pollster::block_on(async{
/// let mut c = build_test_consumer::<u32, (), char>()
///     .err('z')
///     .consumptions_until_error(2)
///     .build().unwrap();
///
/// c.consume_item(1).await?;
/// c.consume_item(2).await?;
/// assert_eq!(c.consume_item(4).await, Err('z'));
///
/// assert_eq!(c.as_slice(), &[1, 2]);
/// assert_eq!(c.peek_final(), None);
/// # Result::<(), char>::Ok(())
/// # });
/// ```
///
/// <br/>Counterpart: the [`TestProducer`](producer::TestProducer) type.
#[derive(Debug, Clone, Builder)]
#[builder(no_std)]
pub struct TestConsumer<Item, Final, Error> {
    #[builder(default = "alloc::vec![].into_consumer()")]
    #[builder(setter(skip))]
    inner: compat::vec::IntoConsumer<Item>,
    #[builder(setter(skip))]
    fin: Option<Final>,
    /// Configures the error which the built [`TestConsumer`] will emit.
    ///
    /// See [`TestConsumerBuilder::consumptions_until_error`] for how to set *when* the error will be emitted.
    ///
    /// ```
    /// use ufotofu::prelude::*;
    /// # pollster::block_on(async{
    /// let mut c = build_test_consumer::<u32, (), char>()
    ///     .err('z')
    ///     .consumptions_until_error(2)
    ///     .build().unwrap();
    ///
    /// c.consume_item(1).await?;
    /// c.consume_item(2).await?;
    /// assert_eq!(c.consume_item(4).await, Err('z'));
    ///
    /// assert_eq!(c.as_slice(), &[1, 2]);
    /// assert_eq!(c.peek_final(), None);
    /// # Result::<(), char>::Ok(())
    /// # });
    /// ```
    #[builder(setter(strip_option))]
    err: Option<Error>,
    /// Configures after how many consumed items the built [`TestConsumer`] will emit [its error](TestConsumerBuilder::err).
    ///
    /// See [`TestConsumerBuilder::err`] for how to set *which* error will be emitted.
    ///
    /// ```
    /// use ufotofu::prelude::*;
    /// # pollster::block_on(async{
    /// let mut c = build_test_consumer::<u32, (), char>()
    ///     .err('z')
    ///     .consumptions_until_error(2)
    ///     .build().unwrap();
    ///
    /// c.consume_item(1).await?;
    /// c.consume_item(2).await?;
    /// assert_eq!(c.consume_item(4).await, Err('z'));
    ///
    /// assert_eq!(c.as_slice(), &[1, 2]);
    /// assert_eq!(c.peek_final(), None);
    /// # Result::<(), char>::Ok(())
    /// # });
    /// ```
    #[builder(default)]
    consumptions_until_error: usize,
    #[builder(default = "alloc::vec![usize::MAX].into_boxed_slice()")]
    #[builder(setter(custom))]
    exposed_slots_sizes: Box<[usize]>,
    #[builder(setter(skip))]
    exposed_slots_sizes_index: usize,
    #[builder(default)]
    #[builder(setter(custom))]
    yielder: TestYielder,
}

impl<Item, Final, Error> TestConsumer<Item, Final, Error> {
    /// Returns the regular items the consumer has already consumed.
    ///
    /// ```
    /// use ufotofu::prelude::*;
    /// # pollster::block_on(async{
    /// let mut c = build_test_consumer::<u32, (), char>()
    ///     .err('z')
    ///     .consumptions_until_error(2)
    ///     .build().unwrap();
    ///
    /// assert_eq!(c.as_slice(), &[]);
    /// c.consume_item(1).await?;
    /// assert_eq!(c.as_slice(), &[1]);
    /// c.consume_item(2).await?;
    /// assert_eq!(c.as_slice(), &[1, 2]);
    /// assert_eq!(c.consume_item(4).await, Err('z'));
    /// assert_eq!(c.as_slice(), &[1, 2]);
    /// # Result::<(), char>::Ok(())
    /// # });
    /// ```
    ///
    /// <br/>Counterpart: the [`TestProducer::as_slice`](producer::TestProducer::as_slice) method.
    pub fn as_slice(&self) -> &[Item] {
        self.inner.as_slice()
    }

    /// Returns a reference to the final value the consumer has been closed with, or `None` if it has not yet been closed.
    ///
    /// ```
    /// use ufotofu::prelude::*;
    /// # pollster::block_on(async{
    /// let mut c = build_test_consumer::<u32, f32, char>()
    ///     .err('z')
    ///     .consumptions_until_error(2)
    ///     .build().unwrap();
    ///
    /// assert_eq!(c.peek_final(), None);
    /// c.consume_item(1).await?;
    /// assert_eq!(c.peek_final(), None);
    /// c.consume_final(5.2).await?;
    /// assert_eq!(c.peek_final(), Some(&5.2));
    /// # Result::<(), char>::Ok(())
    /// # });
    /// ```
    ///
    /// <br/>Counterpart: the [`TestProducer::peek_last`](producer::TestProducer::peek_last) method (when it returns an `Ok` value).
    pub fn peek_final(&self) -> Option<&Final> {
        self.fin.as_ref()
    }

    /// Returns whether the consumer has been closed already.
    ///
    /// ```
    /// use ufotofu::prelude::*;
    /// # pollster::block_on(async{
    /// let mut c = build_test_consumer::<u32, f32, char>()
    ///     .err('z')
    ///     .consumptions_until_error(2)
    ///     .build().unwrap();
    ///
    /// assert_eq!(c.is_closed(), false);
    /// c.consume_item(1).await?;
    /// assert_eq!(c.is_closed(), false);
    /// c.consume_final(5.2).await?;
    /// assert_eq!(c.is_closed(), true);
    /// # Result::<(), char>::Ok(())
    /// # });
    /// ```
    ///
    /// <br/>Counterpart: the [`TestProducer::did_already_emit_last`](producer::TestProducer::did_already_emit_last) method.
    pub fn is_closed(&self) -> bool {
        self.fin.is_some()
    }

    /// Drops the consumer and returns ownership of the items it has consumed and the final value it has been closed with (if any).
    ///
    /// ```
    /// use ufotofu::prelude::*;
    /// # pollster::block_on(async{
    /// let mut c = build_test_consumer::<u32, f32, char>()
    ///     .err('z')
    ///     .consumptions_until_error(2)
    ///     .build().unwrap();
    ///
    /// c.consume_item(1).await?;
    /// c.consume_final(5.2).await?;
    ///
    /// let (items, fin) = c.into_consumed();
    /// assert_eq!(items, vec![1]);
    /// assert_eq!(fin, Some(5.2));
    /// # Result::<(), char>::Ok(())
    /// # });
    /// ```
    ///
    /// <br/>Counterpart: the [`TestProducer::into_not_yet_produced`](producer::TestProducer::into_not_yet_produced) method.
    pub fn into_consumed(self) -> (Vec<Item>, Option<Final>) {
        (self.inner.into(), self.fin)
    }

    /// Returns a reference to the error the consumer will eventually emit, or `None` if it has been emitted already.
    ///
    /// ```
    /// use ufotofu::prelude::*;
    /// # pollster::block_on(async{
    /// let mut c = build_test_consumer::<u32, (), char>()
    ///     .err('z')
    ///     .consumptions_until_error(2)
    ///     .build().unwrap();
    ///
    /// assert_eq!(c.peek_error(), Some(&'z'));
    /// c.consume_item(1).await?;
    /// assert_eq!(c.peek_error(), Some(&'z'));
    /// c.consume_item(2).await?;
    /// assert_eq!(c.peek_error(), Some(&'z'));
    /// assert_eq!(c.consume_item(4).await, Err('z'));
    /// assert_eq!(c.peek_error(), None);
    /// # Result::<(), char>::Ok(())
    /// # });
    /// ```
    ///
    /// <br/>Counterpart: the [`TestProducer::peek_last`](producer::TestProducer::peek_last) method (when it returns an `Ok` value).
    pub fn peek_error(&self) -> Option<&Error> {
        self.err.as_ref()
    }

    /// Returns whether the consumer has emitted its error already.
    ///
    /// ```
    /// use ufotofu::prelude::*;
    /// # pollster::block_on(async{
    /// let mut c = build_test_consumer::<u32, (), char>()
    ///     .err('z')
    ///     .consumptions_until_error(2)
    ///     .build().unwrap();
    ///
    /// assert_eq!(c.did_already_error(), false);
    /// c.consume_item(1).await?;
    /// assert_eq!(c.did_already_error(), false);
    /// c.consume_item(2).await?;
    /// assert_eq!(c.did_already_error(), false);
    /// assert_eq!(c.consume_item(4).await, Err('z'));
    /// assert_eq!(c.did_already_error(), true);
    /// # Result::<(), char>::Ok(())
    /// # });
    /// ```
    ///
    /// <br/>Counterpart: the [`TestProducer::peek_last`](producer::TestProducer::peek_last) method (when it returns an `Ok` value).
    pub fn did_already_error(&self) -> bool {
        self.err.is_none()
    }

    fn check_error(&mut self) -> Result<(), Error> {
        if self.consumptions_until_error == 0 {
            Err(self
                .err
                .take()
                .expect("Must not call Consumer methods after the consumer has emitted an error."))
        } else {
            Ok(())
        }
    }

    async fn maybe_yield(&mut self) {
        self.yielder.maybe_yield().await
    }
}

impl<Item, Final, Error> Consumer for TestConsumer<Item, Final, Error> {
    type Item = Item;
    type Final = Final;
    type Error = Error;

    async fn consume(&mut self, val: Either<Self::Item, Self::Final>) -> Result<(), Self::Error> {
        self.maybe_yield().await;
        self.check_error()?;

        match val {
            Left(item) => {
                Consumer::consume(&mut self.inner, Left(item))
                    .await
                    .unwrap(); // may unwrap because Err<!>
                self.consumptions_until_error -= 1;
                Ok(())
            }

            Right(fin) => {
                self.fin = Some(fin);

                Ok(())
            }
        }
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        self.maybe_yield().await;
        self.check_error()?;

        Consumer::flush(&mut self.inner).await.unwrap(); // may unwrap because Err<!>
        Ok(())
    }
}

impl<Item, Final, Error> BulkConsumer for TestConsumer<Item, Final, Error>
where
    Item: Default,
{
    async fn expose_slots_gracefully<F, R>(&mut self, f: F) -> Result<R, (F, Self::Error)>
    where
        F: AsyncFnOnce(&mut [Self::Item]) -> (usize, R),
    {
        self.maybe_yield().await;
        if let Err(err) = self.check_error() {
            return Err((f, err));
        }

        let max_len: usize = min(
            self.consumptions_until_error,
            self.exposed_slots_sizes[self.exposed_slots_sizes_index],
        );
        self.exposed_slots_sizes_index =
            (self.exposed_slots_sizes_index + 1) % self.exposed_slots_sizes.len();

        self.inner.prepare_slots(max_len);

        self.inner
            .expose_slots_gracefully(async |inner_slots| {
                let inner_len = inner_slots.len();

                let (amount, ret) = f(&mut inner_slots[..min(inner_len, max_len)]).await;
                self.consumptions_until_error -= amount;
                (amount, ret)
            })
            .await
            .map_err(|_| unreachable!("Inner consumer is infallible"))
    }
}

/// Generates almost completely random [`TestConsumer`], the only exception is that no individual slot_size is greater than 65535 (because arbitrarily large slot_sizes yield in running out of memory on bulk consumption).
impl<'a, Item: Arbitrary<'a>, Final: Arbitrary<'a>, Error: Arbitrary<'a>> Arbitrary<'a>
    for TestConsumer<Item, Final, Error>
where
    Item: Clone,
    Final: Clone,
    Error: Clone,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        let err = Error::arbitrary(u)?;
        let consumptions_until_error = usize::arbitrary(u)?;
        let mut slot_sizes = Vec::<usize>::arbitrary(u)?;
        let yield_pattern = Vec::<bool>::arbitrary(u)?;

        for n in slot_sizes.iter_mut() {
            *n %= 65536;
        }

        let ret = build_test_consumer()
            .err(err)
            .consumptions_until_error(consumptions_until_error)
            .exposed_slots_sizes(slot_sizes)
            .yield_pattern(yield_pattern)
            .build();

        Ok(ret.unwrap())
    }

    fn size_hint(depth: usize) -> (usize, Option<usize>) {
        size_hint::and_all(&[
            Error::size_hint(depth),
            usize::size_hint(depth),
            Vec::<usize>::size_hint(depth),
            Vec::<bool>::size_hint(depth),
        ])
    }
}

/// This implementation considers only the values that have been consumed so far. That is, two `TestConsumer`s are considered equal if they were supplied with equal items and final values (or no final value for both), irrespective of the details of how many item slots they had exposed with their `expose_items` calls, and irrespective of the pattern in which their async methods have yielded. In particular, it does not matter which future behaviour they will display either.
///
/// ```
/// use ufotofu::prelude::*;
/// # pollster::block_on(async{
/// let mut c1 = build_test_consumer::<u32, (), char>()
///     .err('z')
///     .consumptions_until_error(2)
///     .build().unwrap();
///
/// let mut c2 = build_test_consumer::<u32, (), char>()
///     .err('z')
///     .consumptions_until_error(999)
///     .build().unwrap();
///
/// assert_eq!(c1 == c2, true);
/// c1.consume_item(1).await?;
/// assert_eq!(c1 == c2, false);
/// c2.consume_item(1).await?;
/// assert_eq!(c1 == c2, true);
/// # Result::<(), char>::Ok(())
/// # });
/// ```
impl<Item: PartialEq, Final: PartialEq, Error: PartialEq> PartialEq
    for TestConsumer<Item, Final, Error>
{
    fn eq(&self, other: &Self) -> bool {
        self.as_slice() == other.as_slice() && self.peek_final() == other.peek_final()
    }
}

impl<Item: Eq, Final: Eq, Error: Eq> Eq for TestConsumer<Item, Final, Error> {}