blob: 531a1184d2a152d08a8988755814127802c73820 (
plain)
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
|
import {Option, none, some} from 'fp-ts/lib/Option.js';
import Prando from 'prando';
// a shrinkable generator needs to maintain some state,
// namely the sequence of generated values in order to be
// able to backtrack and shrink.
type GenMode = 'gen' | 'shrink';
export interface Gen<A> {
generate(): A;
generateN(n: number): A[];
}
export interface GenBytes {
generate(n: number): number[];
}
export class BytesGen implements GenBytes {
prng: Prando;
bytes: number[][]; // the internal sequence of generated values
constructor(prng: Prando) {
this.prng = prng;
this.bytes = [];
}
generate(n: number): number[] {
if (n <= 0) {
throw new Error('n must be greater than 0');
}
return this.generateBytes(n);
}
generateBytes(n: number): number[] {
const gens = [];
for (let i = 0; i < n; i++) {
gens.push(this.prng.nextInt(0, 255));
}
this.bytes.push([...gens]);
return gens;
}
replay(): GenBytes {
return new ReplayBytes(this.bytes);
}
}
export class ReplayBytes implements GenBytes {
bytes: number[][]; // the internal sequence of generated values
index: number = 0; // the current index in the sequence of generated values
constructor(bytes: number[][]) {
this.bytes = bytes;
this.index = 0;
}
generate(n: number): number[] {
if (this.index >= this.bytes.length) {
throw new Error('No more bytes to shrink');
}
const chunk = [...this.bytes[this.index++]];
if (chunk.length < n) {
const zeros = new Array(n - chunk.length).fill(0);
chunk.unshift(...zeros);
}
return chunk;
}
}
|