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
mod default;
pub use default::DefaultEntropyScheme;
#[cfg(feature = "alloc")]
use alloc::{ffi::CString, string::String, vec::Vec};
use core::ffi::CStr;
use core::ops::RangeInclusive;
use crate::prelude::*;
use crate::Int;
/// Defines the means by which base types are converted to/from entropy bytes.
///
/// Different entropy schemes can be designed to suit various purposes, such as to guarantee
/// an even distribution of options or to minimize bytes consumed from a [`Source`].
pub trait EntropyScheme: Default + Clone {
/// Constructs a value within the given range from entropy source bytes.
fn get_uniform_range<'a, T: Int, I: Iterator<Item = &'a u8>>(
&mut self,
entropy: &mut I,
range: RangeInclusive<T>,
) -> Result<T, EntropicError>;
/// Converts the value within the given range into bytes and writes them to the sink.
fn put_uniform_range<'a, T: Int, I: Iterator<Item = &'a mut u8>>(
&mut self,
entropy: &mut I,
range: RangeInclusive<T>,
value: T,
) -> Result<usize, EntropicError>;
/// Constructs a value within the given ranges from entropy source bytes.
fn get_uniform_ranges<'a, T: Int, I: Iterator<Item = &'a u8>, const L: usize>(
&mut self,
entropy: &mut I,
ranges: &[RangeInclusive<T>; L],
) -> Result<T, EntropicError>;
/// Converts the value within the given ranges into bytes and writes them to the sink.
fn put_uniform_ranges<'a, T: Int, I: Iterator<Item = &'a mut u8>, const L: usize>(
&mut self,
entropy: &mut I,
range: &[RangeInclusive<T>; L],
value: T,
) -> Result<usize, EntropicError>;
// In general, a uniformly distributed range of values is desired.
// However, there exist cases where a non-uniform distribution is better, such as for
// determining the length of a collection of highly composite objects
// for len fns: min,max,mean,deviation?
// Add size_hint: usize
/// Constructs a length value within the given bound from entropy source bytes.
fn get_bounded_len<'a, I: Iterator<Item = &'a u8>>(
&mut self,
entropy: &mut I,
range: RangeInclusive<usize>,
) -> Result<usize, EntropicError>;
/// Converts the length value within the given bound into bytes and writes them to the sink.
fn put_bounded_len<'a, I: Iterator<Item = &'a mut u8>>(
&mut self,
entropy: &mut I,
range: RangeInclusive<usize>,
value: usize,
) -> Result<usize, EntropicError>;
/// Constructs a length value from entropy source bytes.
fn get_unbounded_len<'a, I: Iterator<Item = &'a u8>>(
&mut self,
entropy: &mut I,
) -> Result<usize, EntropicError>;
/// Converts the length value into bytes and writes them to the sink.
fn put_unbounded_len<'a, I: Iterator<Item = &'a mut u8>>(
&mut self,
entropy: &mut I,
value: usize,
) -> Result<usize, EntropicError>;
/// Chooses an Option/Result choice from entropy source bytes.
fn get_optional<'a, I: Iterator<Item = &'a u8>>(
&mut self,
entropy: &mut I,
) -> Result<bool, EntropicError>;
/// Converts the Option/Result choice into bytes and writes it to the sink.
fn put_optional<'a, I: Iterator<Item = &'a mut u8>>(
&mut self,
entropy: &mut I,
is_some: bool,
) -> Result<usize, EntropicError>;
/// Constructs a boolean value from entropy source bytes.
#[inline]
fn get_bool<'a, I: Iterator<Item = &'a u8>>(
&mut self,
entropy: &mut I,
) -> Result<bool, EntropicError> {
entropy
.next()
.ok_or(EntropicError::InsufficientBytes)
.map(|b| (*b & 0x01) == 1)
}
/// Converts the boolean value into bytes and writes them to the sink.
#[inline]
fn put_bool<'a, I: Iterator<Item = &'a mut u8>>(
&mut self,
entropy: &mut I,
value: bool,
) -> Result<usize, EntropicError> {
match entropy.next() {
Some(b) => {
*b = if value { 0x01 } else { 0x00 };
Ok(1)
}
None => Err(EntropicError::InsufficientBytes),
}
}
/// Constructs a char value from entropy source bytes.
#[inline]
fn get_char<'a, I: Iterator<Item = &'a u8>>(
&mut self,
entropy: &mut I,
) -> Result<char, EntropicError> {
char::from_u32(
self.get_uniform_ranges(entropy, &[0u32..=0xD7FFu32, 0xE000u32..=0x10FFFFu32])?,
)
.ok_or(EntropicError::Internal)
}
/// Converts the char value into bytes and writes them to the sink.
#[inline]
fn put_char<'a, I: Iterator<Item = &'a mut u8>>(
&mut self,
entropy: &mut I,
value: char,
) -> Result<usize, EntropicError> {
self.put_uniform_ranges(
entropy,
&[0u32..=0xD7FFu32, 0xE000u32..=0x10FFFFu32],
value as u32,
)
}
/// Constructs a string value from entropy source bytes.
#[cfg(feature = "alloc")]
#[inline]
fn get_string<'a, I: Iterator<Item = &'a u8>>(
&mut self,
entropy: &mut I,
) -> Result<String, EntropicError> {
let byte_len = self.get_unbounded_len(entropy)?;
let mut str_bytes = Vec::new();
// While there's more bytes left to fill in vec...
while let Some(rem @ 1..) = byte_len.checked_sub(str_bytes.len()) {
let b1 = self.get_byte(entropy)?; // Get first byte of UTF-8
match b1 {
0b1111_0000..=0b1111_0111 if rem >= 4 => {
// 4-byte UTF-8 code point
str_bytes.push(b1);
for _ in 0..3 {
str_bytes.push((self.get_byte(entropy)? & 0b0011_1111) | 0b1000_0000);
}
}
0b1110_0000..=0b1110_1111 if rem >= 3 => {
// 3-byte UTF-8 code point
str_bytes.push(b1);
for _ in 0..2 {
str_bytes.push((self.get_byte(entropy)? & 0b0011_1111) | 0b1000_0000);
}
}
0b1100_0000..=0b1101_1111 if rem >= 2 => {
// 2-byte UTF-8 code point
str_bytes.push(b1);
str_bytes.push((self.get_byte(entropy)? & 0b0011_1111) | 0b1000_0000);
}
// FALL THROUGH: default to 1-byte UTF-8 (slightly favors these characters)
_ => str_bytes.push(b1 & 0b0111_1111), // 1-byte UTF-8 code point
}
}
String::from_utf8(str_bytes).map_err(|_| EntropicError::Internal)
}
/// Converts the String value into bytes and writes them to the sink.
#[cfg(feature = "alloc")]
#[inline]
fn put_string<'a, I: Iterator<Item = &'a mut u8>>(
&mut self,
entropy: &mut I,
value: &str,
) -> Result<usize, EntropicError> {
let mut len = self.put_unbounded_len(entropy, value.as_bytes().len())?;
// While there's more bytes left to fill in vec...
for b in value.as_bytes() {
self.put_byte(entropy, *b)?;
}
len += value.as_bytes().len();
Ok(len)
}
/// Constructs a cstring value from entropy source bytes.
#[cfg(feature = "alloc")]
#[inline]
fn get_cstring<'a, I: Iterator<Item = &'a u8>>(
&mut self,
entropy: &mut I,
) -> Result<CString, EntropicError> {
let byte_len = self.get_unbounded_len(entropy)?;
let mut str_bytes = Vec::new();
// While there's more bytes left to fill in vec...
while let Some(rem @ 1..) = byte_len.checked_sub(str_bytes.len()) {
let b1 = self.get_byte(entropy)?; // Get first byte of UTF-8
match b1 {
0b1111_0000..=0b1111_0111 if rem >= 4 => {
// 4-byte UTF-8 code point
str_bytes.push(b1);
for _ in 0..3 {
str_bytes.push((self.get_byte(entropy)? & 0b0011_1111) | 0b1000_0000);
}
}
0b1110_0000..=0b1110_1111 if rem >= 3 => {
// 3-byte UTF-8 code point
str_bytes.push(b1);
for _ in 0..2 {
str_bytes.push((self.get_byte(entropy)? & 0b0011_1111) | 0b1000_0000);
}
}
0b1100_0000..=0b1101_1111 if rem >= 2 => {
// 2-byte UTF-8 code point
str_bytes.push(b1);
str_bytes.push((self.get_byte(entropy)? & 0b0011_1111) | 0b1000_0000);
}
// Ensure no null terminating bytes exist
0 => str_bytes.push(b'A'),
// FALL THROUGH: default to 1-byte UTF-8 (slightly favors these characters)
_ => str_bytes.push(b1 & 0b0111_1111), // 1-byte UTF-8 code point
}
}
str_bytes.push(0u8);
CString::from_vec_with_nul(str_bytes).map_err(|_| EntropicError::Internal)
}
/// Converts the CString value into bytes and writes them to the sink.
#[cfg(feature = "alloc")]
#[inline]
fn put_cstring<'a, I: Iterator<Item = &'a mut u8>>(
&mut self,
entropy: &mut I,
value: &CStr,
) -> Result<usize, EntropicError> {
let mut len = self.put_unbounded_len(entropy, value.to_bytes().len())?;
for b in value.to_bytes() {
self.put_byte(entropy, *b)?;
}
len += value.to_bytes().len();
Ok(len)
}
/// Constructs a byte value from entropy source bytes.
#[inline]
fn get_byte<'a, I: Iterator<Item = &'a u8>>(
&mut self,
entropy: &mut I,
) -> Result<u8, EntropicError> {
entropy
.next()
.ok_or(EntropicError::InsufficientBytes)
.copied()
}
/// Writes the byte value to the sink.
#[inline]
fn put_byte<'a, I: Iterator<Item = &'a mut u8>>(
&mut self,
entropy: &mut I,
value: u8,
) -> Result<usize, EntropicError> {
match entropy.next() {
Some(b) => {
*b = value;
Ok(1)
}
None => Err(EntropicError::InsufficientBytes),
}
}
/// Constructs a slice of bytes from entropy source bytes.
#[inline]
fn get_slice<'a, I: Iterator<Item = &'a u8>>(
&mut self,
entropy: &mut I,
slice: &mut [u8],
) -> Result<(), EntropicError> {
for byte in slice.iter_mut() {
*byte = match entropy.next() {
Some(b) => *b,
None => return Err(EntropicError::InsufficientBytes),
}
}
Ok(())
}
/// Writes the slice of bytes to the sink.
#[inline]
fn put_slice<'a, I: Iterator<Item = &'a mut u8>>(
&mut self,
entropy: &mut I,
slice: &[u8],
) -> Result<usize, EntropicError> {
for byte in slice.iter() {
match entropy.next() {
Some(b) => *b = *byte,
None => return Err(EntropicError::InsufficientBytes),
}
}
Ok(slice.len())
}
/// Constructs an array of bytes from entropy source bytes.
#[inline]
fn get_bytearray<'a, I: Iterator<Item = &'a u8>, const T: usize>(
&mut self,
entropy: &mut I,
) -> Result<[u8; T], EntropicError> {
let mut res = [0u8; T];
for byte in res.iter_mut() {
*byte = match entropy.next() {
Some(b) => *b,
None => return Err(EntropicError::InsufficientBytes),
}
}
Ok(res)
}
/// Writes the array of bytes to the sink.
#[inline]
fn put_bytearray<'a, I: Iterator<Item = &'a mut u8>, const T: usize>(
&mut self,
entropy: &mut I,
arr: [u8; T],
) -> Result<usize, EntropicError> {
for byte in arr.iter() {
match entropy.next() {
Some(b) => *b = *byte,
None => return Err(EntropicError::InsufficientBytes),
}
}
Ok(T)
}
}