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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! A [variable-length encoding](https://en.wikipedia.org/wiki/Variable-length_encoding) for unsigned 64 bit integers.
//!
//! The core idea of this encoding scheme is to split the encoding into two parts: a *tag* which indicates how many bytes are used to encode the int, and then the actual *int encoding*, encoded in zero (sufficiently small ints can be inlined into the tag), one, two, four, or eight bytes. You can use tags of any width between two and eight bits — the wider the tag, the more int encodings can be inlined into the tag. The advantage of smaller tags is that multiple of them can fit into a single byte.
//!
//! We have a detailed [writeup on the encoding here](https://willowprotocol.org/specs/encodings/index.html#compact_integers). But to keep things self-contained, here is a precise definition of the possible codes for any `u64` `n` and any number `2 <= tag_width <= 8`:
//!
//! - You can use the numerically greatest possible `tag_width`-bit integer as the *tag*, and the eight-byte big-endian encoding of `n` as the *int encoding*.
//! - If `n < 256^4`, you can use the numerically second-greatest possible `tag_width`-bit integer as the *tag*, and the four-byte big-endian encoding of `n` as the *int encoding*.
//! - If `n < 256^2`, you can use the numerically third-greatest possible `tag_width`-bit integer as the *tag*, and the two-byte big-endian encoding of `n` as the *int encoding*.
//! - If `n < 256`, you can use the numerically third-greatest possible `tag_width`-bit integer as the *tag*, and the one-byte encoding of `n` as the *int encoding*.
//! - If `tag_width > 2`, and if `n` is less than the numerically fourth-greatest `tag_width`-bit integer, you can use the `tag_width`-bit encoding of `n` as the *tag*, and the empty string as the `int encoding`.
//!
//! Our implementation uses the [`codec`] module of [ufotofu](https://worm-blossom.org/ufotofu/) to abstract over actual byte storage.
//!
//! ## Encoding API
//!
//! Use [`write_tag`] to write *tags* at arbitrary offsets into any [`u8`], and use [`cu64_encode`] to write the minimal *int encoding* for any given tag width into a [`BulkConsumer<Item = u8>`](BulkConsumer).
//!
//! ```
//! use ufotofu::codec_prelude::*;
//! use compact_u64::*;
//!
//! // Encode two u64s using two four-bit tags, combining the tags into a single byte.
//! # pollster::block_on(async {
//! let n1 = 258; // Requires two bytes for its int encoding.
//! let n2 = 7; // Can be inlined into the tag.
//! let tag_width1 = 4;
//! let tag_offset1 = 0;
//! let tag_width2 = 4;
//! let tag_offset2 = 4;
//!
//! let mut tag_byte = 0;
//! // Write the four-bit tag for `n1` into `tag_byte`, starting at the most significant bit.
//! write_tag(&mut tag_byte, tag_width1, tag_offset1, n1);
//! // Write the four-bit tag for `n2` into `tag_byte`, starting at the fifth-most significant bit.
//! write_tag(&mut tag_byte, tag_width2, tag_offset2, n2);
//!
//! // First four bits indicate a 2-byte int encoding, remaining four bits inline the integer `7`.
//! assert_eq!(tag_byte, 0xd7);
//!
//! // The buffer into which we will write the encodings.
//! let mut buf = [0; 3];
//! let mut con = (&mut buf).into_consumer();
//!
//! // First write the byte containing the two tags.
//! con.consume_item(tag_byte).await;
//!
//! // Writing the int encoding for `n1` will write the two-byte big-endian code for `n1`.
//! cu64_encode(n1, tag_width1, &mut con).await.unwrap();
//! // Writing the int encoding for `n2` is a no-op, because `n2` is inlined in the tag.
//! cu64_encode(n2, tag_width2, &mut con).await.unwrap();
//!
//! assert_eq!(buf, [0xd7, 1, 2]);
//! # Result::<(), ()>::Ok(())
//! # });
//! ```
//!
//! You can further use [`cu64_len_of_encoding`] to determine the number of bytes an *int encoding* would require for a given *tag*.
//!
//! ## Decoding API
//!
//! Use [`cu64_decode`] to decode the *int encoding* for some given *tag* from a [`BulkProducer<Item = u8>`](BulkProducer). Use [`cu64_decode_canonic`] if you want to reject non-minimal encodings.
//!
//! ```
//! use ufotofu::codec_prelude::*;
//! use compact_u64::*;
//!
//! // We will decode a single byte containing two four-bit tags, and then decode
//! // two int encodings corresponding to the two tags.
//! # pollster::block_on(async {
//! let tag_width1 = 4;
//! let tag_offset1 = 0;
//! let tag_width2 = 4;
//! let tag_offset2 = 4;
//!
//! // The encoding of two four-bit tags followed by two int encodings, for ints `258` and `7`.
//! let mut pro = producer::clone_from_slice(&[0xd7, 1, 2][..]);
//!
//! // Read the byte that combines the two tags from the producer.
//! let mut tag_byte = pro.produce_item().await?;
//!
//! // Decode the two ints.
//! let n1 = cu64_decode(tag_byte, tag_width1, tag_offset1, &mut pro).await?;
//! let n2 = cu64_decode(tag_byte, tag_width2, tag_offset2, &mut pro).await?;
//!
//! assert_eq!(n1, 258);
//! assert_eq!(n2, 7);
//! # Result::<(), DecodeError<(), Infallible, Infallible>>::Ok(())
//! # });
//! ```
//!
//! ## Standalone APIs
//!
//! The previous examples demonstrated the APIs for processing *tags* and *int encodings* separately. For the common case where you use an eight-bit *tag* immediately followed by the corresponding *int encoding*, we offer a more convenient API via [`cu64_encode_standalone`] and [`cu64_decode_standalone`] (and [`cu64_decode_canonic_standalone`] for rejecting non-minimal encodings):
//!
//! ```
//! use ufotofu::codec_prelude::*;
//! use compact_u64::*;
//!
//! # pollster::block_on(async {
//! let mut buf = [0; 3];
//! let mut con = (&mut buf).into_consumer();
//!
//! cu64_encode_standalone(258, &mut con).await.unwrap();
//! assert_eq!(buf, [0xfd, 1, 2]);
//!
//! let n = cu64_decode_standalone(&mut producer::clone_from_slice(&buf[..])).await.unwrap();
//! assert_eq!(n, 258);
//! # });
//! ```
//!
//! The same functionality is also exposed through the [`CompactU64`] type, which is a thin wrapper around `u64` that implements the [`Encodable`], [`EncodableKnownLength`], [`Decodable`], and [`DecodableCanonic`] traits.
//!
//! ```
//! use ufotofu::codec_prelude::*;
//! use compact_u64::*;
//!
//! # pollster::block_on(async {
//! let mut buf = [0; 3];
//! let mut con = (&mut buf).into_consumer();
//!
//! con.consume_encoded(&CompactU64(258)).await.unwrap();
//! assert_eq!(buf, [0xfd, 1, 2]);
//!
//! let n: CompactU64 = producer::clone_from_slice(&buf[..]).produce_decoded().await.unwrap();
//! assert_eq!(n.0, 258);
//! # });
//! ```
//!
//! ## Invalid Parameters
//!
//! The [offset of a tag](TagOffset) must always be a number between zero and seven (inclusive), and the [width of a tag](TagWidth) must always be a number between two and eight (inclusive). When a function takes a [`TagWidth`] and a [`TagOffset`], their sum must be at most eight.
//!
//! All functions in this crate may exhibit unspecified (but always safe) behaviour if these invariants are broken. When debug assertions are enabled, all functions in this crate are guaranteed to panic when these invariants are broken.
use Display;
use Arbitrary;
use *;
/// The width of a *tag* — between two and eight inclusive.
pub type TagWidth = u8;
const
/// The offset of a *tag* within a [`TagByte`] — between zero (most significant) and seven (least significant).
///
/// Zero indicates the most significant bit, seven indicates the least significant bit.
pub type TagOffset = u8;
const
/// A byte storing some number of *tags*.
pub type TagByte = u8;
// Always one of 0, 1, 2, 4, or 8.
type EncodingWidth = usize;
// A byte whose least significant bits store a tag, and whose other bits are set to zero.
type Tag = u8;
/// Writes the minimal tag for the given u64 `n` into the `tag_byte`, for a given [`TagWidth`] and at a given [`TagOffset`].
///
/// Invariant: `tag_width + tag_offset <= 8`, else anything (safe) may happen. When debug assertions are enabled, this function will panic if the invariant is broken.
///
/// ```
/// use compact_u64::write_tag;
///
/// let mut tag_byte1 = 0;
/// write_tag(&mut tag_byte1, 3, 2, u64::MAX);
/// assert_eq!(tag_byte1, 0b0011_1000);
///
/// let mut tag_byte2 = 0;
/// write_tag(&mut tag_byte2, 3, 2, 258);
/// assert_eq!(tag_byte2, 0b0010_1000);
///
/// let mut tag_byte3 = 0;
/// write_tag(&mut tag_byte3, 3, 2, 3);
/// assert_eq!(tag_byte3, 0b0001_1000);
/// ```
/// Writes the *int encoding* of `n` for the minimal *tag* of width `tag_width` into the `consumer`.
///
/// ```
/// use ufotofu::codec_prelude::*;
/// use compact_u64::*;
/// # pollster::block_on(async {
/// let mut buf = [0; 2];
/// let mut con = (&mut buf).into_consumer();
///
/// cu64_encode(258, 8, &mut con).await.unwrap();
/// assert_eq!(buf, [1, 2]);
/// # Result::<(), ()>::Ok(())
/// # });
/// ```
pub async
/// Writes the minimal eight-bit *tag* for `n` and then the corresponding minimal *int encoding* into the `consumer`.
///
/// ```
/// use ufotofu::codec_prelude::*;
/// use compact_u64::*;
///
/// # pollster::block_on(async {
/// let mut buf = [0; 3];
/// let mut con = (&mut buf).into_consumer();
///
/// cu64_encode_standalone(258, &mut con).await.unwrap();
/// assert_eq!(buf, [0xfd, 1, 2]);
/// # });
/// ```
pub async
/// Returns the length of the *int encoding* of `n` when using a minimal *tag* of the given `tag_width`.
///
/// ```
/// use ufotofu::codec_prelude::*;
/// use compact_u64::*;
///
/// assert_eq!(cu64_len_of_encoding(8, 111), 0);
/// assert_eq!(cu64_len_of_encoding(8, 254), 1);
/// assert_eq!(cu64_len_of_encoding(8, 258), 2);
/// ```
pub const
/// Reads the *int encoding* of `n` for the given *tag* from the `producer`.
///
/// The *tag* of width `tag_width` is read at offset `tag_offset` from the `tag_byte`.
///
/// ```
/// use ufotofu::codec_prelude::*;
/// use compact_u64::*;
/// # pollster::block_on(async {
/// let mut buf = [1, 2];
///
/// let n = cu64_decode(
/// 0b0010_1000, // the tag byte, the actual tag being `101` (the outer zeros are ignored)
/// 3, // the tag width
/// 2, // the tag offset
/// &mut producer::clone_from_slice(&buf[..]),
/// ).await.unwrap();
/// assert_eq!(n, 258);
/// # Result::<(), ()>::Ok(())
/// # });
/// ```
pub async
/// Reads an eight-bit *tag* from the `producer`, then reads the corresponding *int encoding* from the `producer`, and returns the decoded [`u64`].
///
/// ```
/// use ufotofu::codec_prelude::*;
/// use compact_u64::*;
///
/// # pollster::block_on(async {
/// let n = cu64_decode_standalone(
/// &mut producer::clone_from_slice(&[0xfd, 1, 2][..]),
/// ).await.unwrap();
///
/// assert_eq!(n, 258);
/// # });
/// ```
pub async
/// Reads the *int encoding* of `n` for the given *tag* from the `producer`, yielding an error if the encoding was not minimal.
///
/// The *tag* of width `tag_width` is read at offset `tag_offset` from the `tag_byte`.
///
/// ```
/// use ufotofu::codec_prelude::*;
/// use compact_u64::*;
/// # pollster::block_on(async {
/// let mut buf = [1, 2];
///
/// let n = cu64_decode_canonic(
/// 0b0010_1000, // the tag byte, the actual tag being `101` (the outer zeros are ignored)
/// 3, // the tag width
/// 2, // the tag offset
/// &mut producer::clone_from_slice(&buf[..]),
/// ).await.unwrap();
/// assert_eq!(n, 258);
///
/// let mut non_minimal_buf = [0, 0, 1, 2];
///
/// assert!(cu64_decode_canonic(
/// 0xfe, // an eight-bit tag indicating an *int encoding* of four bytes
/// 8, // the tag width
/// 0, // the tag offset
/// &mut producer::clone_from_slice(&buf[..]),
/// ).await.is_err());
/// # Result::<(), ()>::Ok(())
/// # });
/// ```
pub async
/// Reads an eight-bit *tag* from the `producer`, then reads the corresponding *int encoding* from the `producer`, and returns the decoded [`u64`], or an error if the encoding was not minimal.
///
/// ```
/// use ufotofu::codec_prelude::*;
/// use compact_u64::*;
///
/// # pollster::block_on(async {
/// let n = cu64_decode_canonic_standalone(
/// &mut producer::clone_from_slice(&[0xfd, 1, 2][..]),
/// ).await.unwrap();
/// assert_eq!(n, 258);
///
/// assert!(cu64_decode_canonic_standalone(
/// &mut producer::clone_from_slice(&[0xfe, 0, 0, 1, 2][..]), // int encoding in four bytes
/// ).await.is_err());
/// # });
/// ```
pub async
/// Returns the least [`EncodingWidth`] a given [`u64`] can be represented in, given a tag of `tag_width` bits.
const
const
/// Returns the maximal tag of the given width as a Tag, i.e., `self.as_u8()` many one bits at the end, and everything else as zero bits. In other words, this computes `2^tag_width - 1`
const
/// An error indicating that a compact u64 encoding was not minimal.
;
/// A wrapper around [`u64`], implementing the [ufotofu codec traits](codec).
///
/// The [encoding relation](codec) implemented by the [`Encodable`], [`EncodableKnownLength`], [`Decodable`], and [`DecodableCanonic`] impls of this type works by first encoding an eight-bit *tag* for the int, followed by the corresponding *int encoding*.
///
/// ```
/// use ufotofu::codec_prelude::*;
/// use compact_u64::*;
///
/// # pollster::block_on(async {
/// let mut buf = [0; 3];
/// let mut con = (&mut buf).into_consumer();
///
/// con.consume_encoded(&CompactU64(258)).await.unwrap();
/// assert_eq!(buf, [0xfd, 1, 2]);
///
/// let n: CompactU64 = producer::clone_from_slice(&buf[..]).produce_decoded().await.unwrap();
/// assert_eq!(n.0, 258);
/// # });
/// ```
;
/// Implements encoding by first encoding a byte storing the minimal 8-bit tag for self, followed by the corresponding compact u64 encoding.
/// Implements decoding by first decoding a byte storing an 8-bit tag, followed by the corresponding compact u64 encoding.
/// Implements decoding by first decoding a byte storing an 8-bit tag, followed by the corresponding compact u64 encoding, and emitting an error if the encoding was not minimal.