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
//! Helper functions for [property testing](https://en.wikipedia.org/wiki/Software_testing#Property_testing) of the relative codec traits.
//!
//! Everything in this module is analogous to the functionality provided in the [`codec::proptest`] module.
//!
//! This module provides assertion functions which panic when their arguments constitute a counterexample to the invariants of the relative codec traits. They are intended for property testing, i.e., you are supposed to call them a large number of times with randomly generated arguments. The assertions are:
//!
//! - [`assert_relative_codec`] for checking the invariants of types which implement [`RelativeEncodable`] and [`RelativeDecodable`].
//! - [`assert_relative_codec_known_length`] for checking the invariants of types which implement [`RelativeEncodableKnownLength`] and [`RelativeDecodable`].
//! - [`assert_relative_codec_canonic`] for checking the invariants of types which implement [`RelativeEncodable`] and [`RelativeDecodableCanonic`].
//! - [`assert_relative_codec_canonic_and_known_len`] for checking the invariants of types which implement [`RelativeEncodableKnownLength`] and [`RelativeDecodableCanonic`].

use crate::codec_prelude::*;
use crate::producer::clone_from_slice;

use core::fmt::Debug;
use std::format;
use std::string::ToString;

/// Panics with a diagnostic message if the input values (which should be generated randomly, so you do not need to know what exactly they mean or how they are used) provide a counterexample to any invariant of the [`RelativeEncodable`] or [`RelativeDecodable`] traits.
pub async fn assert_relative_codec<T, RelativeTo, Symbol>(
    rel: &RelativeTo,
    t1: &T,
    t2: &T,
    mut c1: TestConsumer<Symbol, (), ()>,
    mut c2: TestConsumer<Symbol, (), ()>,
    p1: TestProducer<Symbol, (), ()>,
    mut p2: TestProducer<Symbol, (), ()>,
) where
    T: RelativeEncodable<RelativeTo, Symbol>
        + RelativeDecodable<RelativeTo, Symbol>
        + Eq
        + Debug
        + Clone,
    T::ErrorReason: Debug + Eq,
    RelativeTo: Debug,
    Symbol: Debug + Default + PartialEq + Clone,
{
    if !(t1.can_be_encoded_relative_to(rel) && t2.can_be_encoded_relative_to(rel)) {
        return;
    }

    ///////////////////////////////////////////////////////////////////////////////////////
    // Encoding depends only on the sequence of symbols, not on details of the consumer. //
    ///////////////////////////////////////////////////////////////////////////////////////
    let res1 = t1.relative_encode(rel, &mut c1).await;
    let res2 = t1.relative_encode(rel, &mut c2).await;
    let consumed1 = c1.as_slice();
    let consumed2 = c2.as_slice();
    let common_len = core::cmp::min(consumed1.len(), consumed2.len());
    let status = match (res1, res2) {
        (Ok(()), Ok(())) => "Neither consumer errored.".to_string(),
        (Err(()), Ok(())) => format!(
            "First consumer errored after {} symbols, second did not error.",
            consumed1.len()
        ),
        (Ok(()), Err(())) => format!(
            "First consumer did not error, second consumer errored after {} symbols.",
            consumed2.len()
        ),
        (Err(()), Err(())) => format!(
            "First consumer errored after {} symbols, second consumer errored after {} symbols.",
            consumed1.len(),
            consumed2.len()
        ),
    };
    assert_eq!(
        &consumed1[..common_len],
        &consumed2[..common_len],
        "The same value produced two different (prefixes of) encodings for two different test consumers.\n\nValue: {t1:#?}\n\nRelative to: {rel:#?}\n\n{status}\n\n\nFirst Consumer: {c1:#?}\n\nSecond Consumer: {c2:#?}\n\nFirst Encoding: {consumed1:?}\n\nSecond Encoding: {consumed2:?}",
    );

    ///////////////////////////////////////////////////////////
    // Computation results used to check several properties. //
    ///////////////////////////////////////////////////////////

    let enc1 = t1.new_vec_storing_relative_encoding(rel).await;
    let enc2 = t2.new_vec_storing_relative_encoding(rel).await;

    let res1 = T::relative_decode(rel, &mut p1.clone()).await;

    ///////////////////////////////////////////////////////////////////////////////////
    // Relative decoding must yield a value that could be encoded relative to `rel`. //
    ///////////////////////////////////////////////////////////////////////////////////

    if let Ok(decoded) = res1.as_ref() {
        assert!(
            decoded.can_be_encoded_relative_to(rel),
            "When decoding relative to some value rel is successful, the decoded value must be encodable relativ to rel.\n\nDecoded Value: {decoded:#?}\n\nRelative to: {rel:#?}\n\nDecoded from: {:?}",
            p1.as_slice(),
        );
    }

    ///////////////////////////////////////////////
    // Encodings are equal iff values are equal. //
    ///////////////////////////////////////////////

    if t1 == t2 {
        if enc1 != enc2 {
            panic!(
                "Two equal values produced the nonequal encodings.\n\nFirst Value: {:#?}\n\nSecond Value: {:#?}\n\nRelative to: {rel:#?}\n\nFirst encoding: {:?}\n\nSecond encoding: {:?}",
                t1,
                t2,
                enc1,
                enc2,
            );
        }
    } else if enc1 == enc2 {
        panic!(
            "Two nonequal values produced equal encodings.\n\nFirst Value: {:#?}\n\nSecond Value: {:#?}\n\nRelative to: {rel:#?}\n\nFirst encoding: {:?}\n\nSecond encoding: {:?}",
            t1,
            t2,
            enc1,
            enc2,
        );
    }

    ///////////////////////////
    // Codes are prefix-free //
    ///////////////////////////

    if t1 != t2 && enc2.starts_with(&enc1[..]) {
        panic!(
                "The encoding of value one is a prefix of the encoding of value two.\n\nFirst Value: {:#?}\n\nSecond Value: {:#?}\n\nRelative to: {rel:#?}\n\nFirst encoding: {:?}\n\nSecond encoding: {:?}",
                t1,
                t2,
                enc1,
                enc2,
            );
    }

    ///////////////////////////////////////////////////////////////////////////////////////
    // Decoding depends only on the sequence of symbols, not on details of the producer. //
    ///////////////////////////////////////////////////////////////////////////////////////

    if p1 == p2 {
        let res2 = T::relative_decode(rel, &mut p2).await;

        match (&res1, &res2) {
            (Ok(t1), Ok(t2)) => {
                if t1 != t2 {
                    panic!(
                        "Decoded nonequal values from the same sequence of symbols, because exposed item slot sizes and yield patterns of the producers differed.\n\nFirst Value: {:#?}\n\nSecond Value: {:#?}\n\nRelative to: {rel:#?}\n\nFirst TestProducer: {:?}\n\nSecond TestProducer: {:?}",
                        t1,
                        t2,
                        p1,
                        p2,
                    );
                } else {
                    // Yay, this is what it should be!
                }
            }
            (Err(err1), Err(err2)) => {
                if err1 != err2 {
                    panic!(
                        "Got nonequal errors from decoding the same sequence of symbols, because exposed item slot sizes and yield patterns of the producers differed.\n\nFirst Error: {:#?}\n\nSecond Error: {:#?}\n\nRelative to: {rel:#?}\n\nFirst TestProducer: {:?}\n\nSecond TestProducer: {:?}",
                        err1,
                        err2,
                        p1,
                        p2,
                    );
                } else {
                    // Yay, this is what it should be!
                }
            }
            (res1, res2) => panic!(
                "Got different results from decoding the same sequence of symbols, because exposed item slot sizes and yield patterns of the producers differed.\n\nFirst Result: {:#?}\n\nSecond Result: {:#?}\n\nRelative to: {rel:#?}\n\nFirst TestProducer: {:?}\n\nSecond TestProducer: {:?}",
                res1,
                res2,
                p1,
                p2,
            ),
        };
    }

    //////////////////////////////////////////
    // Decoding reads no excessive symbols. //
    //////////////////////////////////////////

    if let Ok(t) = res1 {
        let p1b = p1.clone();
        let hopefully_minimal_enc = p1b.already_produced();
        if hopefully_minimal_enc.len() > 1 {
            let mut p3 =
                clone_from_slice(&hopefully_minimal_enc[..hopefully_minimal_enc.len() - 1]);

            match T::relative_decode(rel, &mut p3).await {
                Err(DecodeError::UnexpectedEndOfInput(())) => {
                    // This is what should happen.
                }
                res => panic!(
                    "Removing the final symbol of a valid encoding and trying to decode again did not yield an UnexpectedEndOfInput error!\n\nRelative to: {rel:#?}\n\nThe Valid Encoding: {:?}\n\nWhat It Decoded To: {:#?}\n\nThe Result After Decoding From One Less Symbol: {:?}",
                    hopefully_minimal_enc,
                    t,
                    res,
                ),
            }
        }
    }

    //////////////////////////////////////////////////////
    // Encoding then decoding yields the original value //
    //////////////////////////////////////////////////////

    match T::relative_decode(rel, &mut clone_from_slice(&enc1[..])).await {
        Ok(dec1) => {
            if dec1 != *t1 {
                panic!(
                    "Encoding and then decoding a value yielded a value not equal to the original value.\n\nOriginal: {:#?}\n\nDecoded: {:#?}Encoding: {:?}\n\nRelative to: {rel:#?}\n\n",
                    t1,
                    dec1,
                    &enc1[..],
                );
            }
        }
        Err(err) => {
            panic!(
                "Encoding and then decoding a value resulted in failure to decode.\n\nOriginal: {:#?}\n\nEncoding: {:?}\n\nDecoding Error: {:#?}\n\nRelative to: {rel:#?}\n\n",
                t1,
                &enc1[..],
                err,
            );
        }
    }
}

async fn assert_known_length_stuff_in_isolation<T, RelativeTo, Symbol>(rel: &RelativeTo, t: &T)
where
    T: RelativeEncodableKnownLength<RelativeTo, Symbol>
        + RelativeEncodableKnownLengthExt<RelativeTo, Symbol>
        + RelativeDecodable<RelativeTo, Symbol>
        + Eq
        + Debug
        + Clone,
    T::ErrorReason: Debug + Eq,
    RelativeTo: Debug,
    Symbol: Debug + Default + PartialEq + Clone,
{
    if !t.can_be_encoded_relative_to(rel) {
        return;
    }

    /////////////////////////////////////////////////////////
    // The length reported by len_of_encoding is accurate. //
    /////////////////////////////////////////////////////////

    let enc = t.new_boxed_slice_storing_relative_encoding(rel).await;

    let claimed_len = t.len_of_relative_encoding(rel);

    if enc.len() != claimed_len {
        panic!(
            "len_of_encoding reported an incorrect len.\n\nValue: {:#?}\n\nRelative to: {rel:#?}\n\nClaimed Length: {:?}\n\nActual Encoding Length: {:?}\n\nFull Encoding: {:?}",
            t,
            claimed_len,
            enc.len(),
            &enc[..],
        );
    }
}

/// Panics with a diagnostic message if the input values (which should be generated randomly, so you do not need to know what exactly they mean or how they are used) provide a counterexample to any invariant of the [`RelativeEncodableKnownLength`] or [`RelativeDecodable`] traits.
pub async fn assert_relative_codec_known_length<T, RelativeTo, Symbol>(
    rel: &RelativeTo,
    t1: &T,
    t2: &T,
    c1: TestConsumer<Symbol, (), ()>,
    c2: TestConsumer<Symbol, (), ()>,
    p1: TestProducer<Symbol, (), ()>,
    p2: TestProducer<Symbol, (), ()>,
) where
    T: RelativeEncodableKnownLength<RelativeTo, Symbol>
        + RelativeEncodableKnownLengthExt<RelativeTo, Symbol>
        + RelativeDecodable<RelativeTo, Symbol>
        + Eq
        + Debug
        + Clone,
    T::ErrorReason: Debug + Eq,
    RelativeTo: Debug,
    Symbol: Debug + Default + PartialEq + Clone,
{
    assert_relative_codec(rel, t1, t2, c1, c2, p1, p2).await;
    assert_known_length_stuff_in_isolation(rel, t1).await;
}

async fn assert_canonic_stuff_in_isolation<T, RelativeTo, Symbol>(
    rel: &RelativeTo,
    mut p1: TestProducer<Symbol, (), ()>,
    mut p2: TestProducer<Symbol, (), ()>,
) where
    T: RelativeEncodable<RelativeTo, Symbol>
        + RelativeDecodableCanonic<RelativeTo, Symbol>
        + Eq
        + Debug
        + Clone,
    T::ErrorReason: Debug + Eq,
    T::ErrorCanonic: Debug + Eq,
    RelativeTo: Debug,
    Symbol: Debug + Default + PartialEq + Clone,
{
    let mut p1b = p1.clone();
    let mut p1c = p1.clone();
    let mut p1d = p1.clone();
    let mut p1e = p1.clone();
    let mut p1f = p1.clone();

    ////////////////////////////////////////////////////////////////
    // Nonequal codecs do not canonically decode to equal values. //
    ////////////////////////////////////////////////////////////////

    if let (Ok(t1), Ok(t2)) = (
        T::relative_decode_canonic(rel, &mut p1).await,
        T::relative_decode_canonic(rel, &mut p2).await,
    ) {
        if p1.already_produced() != p2.already_produced() && t1 == t2 {
            panic!(
                "Canonically decoding two non-equal sequences of symbols resulted in equal values.\n\nRelative to: {rel:#?}\n\nFirst Sequence: {:?}\n\nSecond Sequence: {:?}\n\nFirst Decoded: {:#?}\n\nSecond Decoded: {:#?}",
                p1.already_produced(), p2.already_produced(), t1, t2);
        }
    }

    //////////////////////////////////////
    // Roundtrip with canonic decoding. //
    //////////////////////////////////////

    if let Ok(t) = T::relative_decode_canonic(rel, &mut p1b).await {
        if t.can_be_encoded_relative_to(rel) {
            let reencoding = t.new_vec_storing_relative_encoding(rel).await;

            if p1b.already_produced() != &reencoding[..] {
                panic!(
                "Successfully canonically decoding a sequence of symbols and then reencoding did not yield the original sequence of symbols.\n\nRelative to: {rel:#?}\n\nOriginal sequence: {:?}\n\nDecoded: {:#?}\n\nReencoded symbols: {:?}",
                p1b.already_produced(),
                t,
                &reencoding[..],
            );
            }
        }
    }

    ////////////////////////////////////////////////////
    // Canonic decoding specialises regular decoding. //
    ////////////////////////////////////////////////////

    if let Ok(t_canonic) = T::relative_decode_canonic(rel, &mut p1c).await {
        let res = T::relative_decode(rel, &mut p1d).await;

        match res {
            Ok(t_general) => {
                if t_canonic != t_general {
                    panic!(
                        "Successful canonic decoding and successful general decoding of the same sequence of symbols did not produce equal values.\n\nRelative to: {rel:#?}\n\nThe Encoding: {:?}\n\nCanonically Decoded: {:#?}\n\nGenerally Decoded: {:#?}",
                        p1c.already_produced(),
                        t_canonic,
                        t_general,
                    );
                }
            }
            Err(err) => {
                panic!(
                    "Canonic decoding succeeded but general decoding failed for the same sequence of code symbols.\n\nRelative to: {rel:#?}\n\nThe Encoding: {:?}\n\nCanonically Decoded: {:#?}\n\nGenerally Decoded Error: {:#?}",
                    p1c.already_produced(),
                    t_canonic,
                    err,
                );
            }
        }
    }

    ///////////////////////////////////////////////////////////////
    // If regular decoding fails, then so does canonic decoding. //
    ///////////////////////////////////////////////////////////////

    if let Err(err_regular) = T::relative_decode(rel, &mut p1e).await {
        if let Ok(t_decoded_canonic) = T::relative_decode_canonic(rel, &mut p1f).await {
            panic!(
                "Regular decoding succeeded but canonic decoding failed for the same sequence of code symbols.\n\nRelative to: {rel:#?}\n\nThe Encoding: {:?}\n\nCanonically Decoded: {:#?}\n\nRegular Decoding Error: {:#?}",
                p1e.already_produced(),
                t_decoded_canonic,
                err_regular,
            );
        }
    }
}

/// Panics with a diagnostic message if the input values (which should be generated randomly, so you do not need to know what exactly they mean or how they are used) provide a counterexample to any invariant of the [`RelativeEncodable`] or [`RelativeDecodableCanonic`] traits.
pub async fn assert_relative_codec_canonic<T, RelativeTo, Symbol>(
    rel: &RelativeTo,
    t1: &T,
    t2: &T,
    c1: TestConsumer<Symbol, (), ()>,
    c2: TestConsumer<Symbol, (), ()>,
    p1: TestProducer<Symbol, (), ()>,
    p2: TestProducer<Symbol, (), ()>,
) where
    T: RelativeEncodable<RelativeTo, Symbol>
        + RelativeDecodableCanonic<RelativeTo, Symbol>
        + Eq
        + Debug
        + Clone,
    T::ErrorReason: Debug + Eq,
    T::ErrorCanonic: Debug + Eq,
    RelativeTo: Debug,
    Symbol: Debug + Default + PartialEq + Clone,
{
    assert_relative_codec(rel, t1, t2, c1, c2, p1.clone(), p2.clone()).await;
    assert_canonic_stuff_in_isolation::<T, RelativeTo, Symbol>(rel, p1, p2).await;
}

/// Panics with a diagnostic message if the input values (which should be generated randomly, so you do not need to know what exactly they mean or how they are used) provide a counterexample to any invariant of the [`RelativeEncodableKnownLength`] or [`RelativeDecodableCanonic`] traits.
pub async fn assert_relative_codec_canonic_and_known_len<T, RelativeTo, Symbol>(
    rel: &RelativeTo,
    t1: &T,
    t2: &T,
    c1: TestConsumer<Symbol, (), ()>,
    c2: TestConsumer<Symbol, (), ()>,
    p1: TestProducer<Symbol, (), ()>,
    p2: TestProducer<Symbol, (), ()>,
) where
    T: RelativeEncodableKnownLength<RelativeTo, Symbol>
        + RelativeEncodableKnownLengthExt<RelativeTo, Symbol>
        + RelativeDecodableCanonic<RelativeTo, Symbol>
        + Eq
        + Debug
        + Clone,
    T::ErrorReason: Debug + Eq,
    T::ErrorCanonic: Debug + Eq,
    RelativeTo: Debug,
    Symbol: Debug + Default + PartialEq + Clone,
{
    assert_relative_codec(rel, t1, t2, c1, c2, p1.clone(), p2.clone()).await;
    assert_known_length_stuff_in_isolation(rel, t1).await;
    assert_canonic_stuff_in_isolation::<T, RelativeTo, Symbol>(rel, p1, p2).await;
}