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
//! Octets Builders
//!
//! Octets builders, i.e., anything that implements the [`OctetsBuilder`]
//! trait, represent a buffer to which octets can be appended.
//! Whether the buffer can grow to accommodate appended data depends on the
//! underlying type.
//!
//! The [`OctetsBuilder`] trait only provides methods to append data to the
//! builder. Implementations may, however, provide more functionality. They
//! do so by implementing additional traits. Conversely, if additional
//! functionality is needed from a builder, this can be expressed by
//! adding trait bounds.
//!
//! Some examples are:
//!
//! * creating an empty octets builder from scratch is provided by the
//!   [`EmptyBuilder`] trait,
//! * looking at already assembled octets is done via `AsRef<[u8]>`,
//! * manipulation of already assembled octets requires `AsMut<[u8]>`, and
//! * truncating the sequence of assembled octets happens through
//!   [`Truncate`].

use core::fmt;
use core::convert::Infallible;
#[cfg(feature = "bytes")] use bytes::{Bytes, BytesMut};
#[cfg(feature = "std")] use std::borrow::Cow;
#[cfg(feature = "std")] use std::vec::Vec;


//------------ OctetsBuilder -------------------------------------------------

/// A buffer to construct an octet sequence.
///
/// Octet builders represent a buffer of space available for building an
/// octets sequence by appending the contents of octet slices. The buffers
/// may consist of a predefined amount of space or grow as needed.
///
/// Octet builders provide access to the already assembled data through
/// octet slices via their implementations of `AsRef<[u8]>` and
/// `AsMut<[u8]>`.
pub trait OctetsBuilder {
    /// The error type when appending data fails.
    ///
    /// There are exactly two options for this type: Builders where appending
    /// never fails use `Infallible`. Builders with a limited buffer which 
    /// may have insufficient space for appending use [`ShortBuf`].
    ///
    /// The trait bound on the type allows upgrading the error to [`ShortBuf`]
    /// even for builders with unlimited space. This way, an error type for
    /// operations that use a builder doesn’t need to be generic over the
    /// append error type and can simply use a variant for anything
    /// `Into<ShortBuf>` instead.
    type AppendError: Into<ShortBuf>;

    /// Appends the content of a slice to the builder.
    ///
    /// If there isn’t enough space available for appending the slice,
    /// returns an error and leaves the builder alone.
    fn append_slice(
        &mut self, slice: &[u8]
    ) -> Result<(), Self::AppendError>;
}

impl<'a, T: OctetsBuilder> OctetsBuilder for &'a mut T {
    type AppendError = T::AppendError;

    fn append_slice(
        &mut self, slice: &[u8]
    ) -> Result<(), Self::AppendError> {
        (*self).append_slice(slice)
    }
}

#[cfg(feature = "std")]
impl OctetsBuilder for Vec<u8> {
    type AppendError = Infallible;

    fn append_slice(
        &mut self, slice: &[u8]
    ) -> Result<(), Self::AppendError> {
        self.extend_from_slice(slice);
        Ok(())
    }
}

#[cfg(feature = "std")]
impl<'a> OctetsBuilder for Cow<'a, [u8]> {
    type AppendError = Infallible;

    fn append_slice(
        &mut self, slice: &[u8]
    ) -> Result<(), Self::AppendError> {
        if let Cow::Owned(ref mut vec) = *self {
            vec.extend_from_slice(slice);
        } else {
            let mut vec = std::mem::replace(
                self, Cow::Borrowed(b"")
            ).into_owned();
            vec.extend_from_slice(slice);
            *self = Cow::Owned(vec);
        }
        Ok(())
    }
}

#[cfg(feature = "bytes")]
impl OctetsBuilder for BytesMut {
    type AppendError = Infallible;

    fn append_slice(
        &mut self, slice: &[u8]
    ) -> Result<(), Self::AppendError> {
        self.extend_from_slice(slice);
        Ok(())
    }
}

#[cfg(feature = "smallvec")]
impl<A: smallvec::Array<Item = u8>> OctetsBuilder for smallvec::SmallVec<A> {
    type AppendError = Infallible;

    fn append_slice(
        &mut self, slice: &[u8]
    ) -> Result<(), Self::AppendError> {
        self.extend_from_slice(slice);
        Ok(())
    }
}

#[cfg(feature = "heapless")]
impl<const N: usize> OctetsBuilder for heapless::Vec<u8, N> {
    type AppendError = ShortBuf;

    fn append_slice(
        &mut self, slice: &[u8]
    ) -> Result<(), Self::AppendError> {
        self.extend_from_slice(slice).map_err(|_| ShortBuf)
    }
}


//------------ Truncate ------------------------------------------------------

/// An octet sequence that can be shortened.
pub trait Truncate {
    /// Truncate the sequence to `len` octets.
    ///
    /// If `len` is larger than the length of the sequence, nothing happens.
    fn truncate(&mut self, len: usize);
}

impl<'a, T: Truncate> Truncate for &'a mut T {
    fn truncate(&mut self, len: usize) {
        (*self).truncate(len)
    }
}

impl<'a> Truncate for &'a [u8] {
    fn truncate(&mut self, len: usize) {
        if len < self.len() {
            *self = &self[..len]
        }
    }
}

#[cfg(feature = "std")]
impl<'a> Truncate for Cow<'a, [u8]> {
    fn truncate(&mut self, len: usize) {
        match *self {
            Cow::Borrowed(ref mut slice) => *slice = &slice[..len],
            Cow::Owned(ref mut vec) => vec.truncate(len),
        }
    }
}

#[cfg(feature = "std")]
impl Truncate for Vec<u8> {
    fn truncate(&mut self, len: usize) {
        self.truncate(len)
    }
}

#[cfg(feature = "bytes")]
impl Truncate for Bytes {
    fn truncate(&mut self, len: usize) {
        self.truncate(len)
    }
}

#[cfg(feature = "bytes")]
impl Truncate for BytesMut {
    fn truncate(&mut self, len: usize) {
        self.truncate(len)
    }
}

#[cfg(feature = "smallvec")]
impl<A: smallvec::Array<Item = u8>> Truncate for smallvec::SmallVec<A> {
    fn truncate(&mut self, len: usize) {
        self.truncate(len)
    }
}

#[cfg(feature = "heapless")]
impl<const N: usize> Truncate for heapless::Vec<u8, N> {
    fn truncate(&mut self, len: usize) {
        self.truncate(len)
    }
}


//------------ EmptyBuilder --------------------------------------------------

/// An octets builder that can be newly created empty.
pub trait EmptyBuilder {
    /// Creates a new empty octets builder with a default size.
    fn empty() -> Self;

    /// Creates a new empty octets builder with a suggested initial size.
    ///
    /// The builder may or may not use the size provided by `capacity` as the
    /// initial size of the buffer. It may very well be possibly that the
    /// builder is never able to grow to this capacity at all. Therefore,
    /// even if you create a builder for your data size via this function,
    /// appending may still fail.
    fn with_capacity(capacity: usize) -> Self;
}

#[cfg(feature = "std")]
impl EmptyBuilder for Vec<u8> {
    fn empty() -> Self {
        Vec::new()
    }

    fn with_capacity(capacity: usize) -> Self {
        Vec::with_capacity(capacity)
    }
}

#[cfg(feature = "bytes")]
impl EmptyBuilder for BytesMut {
    fn empty() -> Self {
        BytesMut::new()
    }

    fn with_capacity(capacity: usize) -> Self {
        BytesMut::with_capacity(capacity)
    }
}

#[cfg(feature = "smallvec")]
impl<A: smallvec::Array<Item = u8>> EmptyBuilder for smallvec::SmallVec<A> {
    fn empty() -> Self {
        smallvec::SmallVec::new()
    }

    fn with_capacity(capacity: usize) -> Self {
        smallvec::SmallVec::with_capacity(capacity)
    }
}

#[cfg(feature = "heapless")]
impl<const N: usize> EmptyBuilder for heapless::Vec<u8, N> {
    fn empty() -> Self {
        Self::new()
    }

    fn with_capacity(capacity: usize) -> Self {
        debug_assert!(capacity <= N);
        Self::with_capacity(capacity)
    }
}


//------------ FreezeBuilder -------------------------------------------------

/// An octets builder that can be frozen into a imutable octets sequence.
pub trait FreezeBuilder {
    /// The type of octets sequence to builder will be frozen into.
    type Octets;

    /// Converts the octets builder into an imutable octets sequence.
    fn freeze(self) -> Self::Octets;
}

#[cfg(feature = "std")]
impl FreezeBuilder for Vec<u8> {
    type Octets = Self;

    fn freeze(self) -> Self::Octets {
        self
    }
}

#[cfg(feature = "std")]
impl<'a> FreezeBuilder for Cow<'a, [u8]> {
    type Octets = Self;

    fn freeze(self) -> Self::Octets {
        self
    }
}

#[cfg(feature = "bytes")]
impl FreezeBuilder for BytesMut {
    type Octets = Bytes;

    fn freeze(self) -> Self::Octets {
        BytesMut::freeze(self)
    }
}

#[cfg(feature = "smallvec")]
impl<A: smallvec::Array<Item = u8>> FreezeBuilder for smallvec::SmallVec<A> {
    type Octets = Self;

    fn freeze(self) -> Self::Octets {
        self
    }
}

#[cfg(feature = "heapless")]
impl<const N: usize> FreezeBuilder for heapless::Vec<u8, N> {
    type Octets = Self;

    fn freeze(self) -> Self::Octets {
        self
    }
}


//------------ IntoBuilder ---------------------------------------------------

/// An octets type that can be converted into an octets builder.
pub trait IntoBuilder {
    /// The type of octets builder this octets type can be converted into.
    type Builder: OctetsBuilder;

    /// Converts an octets value into an octets builder.
    fn into_builder(self) -> Self::Builder;
}

#[cfg(feature = "std")]
impl IntoBuilder for Vec<u8> {
    type Builder = Self;

    fn into_builder(self) -> Self::Builder {
        self
    }
}

#[cfg(feature = "std")]
impl<'a> IntoBuilder for &'a [u8] {
    type Builder = Vec<u8>;

    fn into_builder(self) -> Self::Builder {
        self.into()
    }
}

#[cfg(feature = "std")]
impl<'a> IntoBuilder for Cow<'a, [u8]> {
    type Builder = Self;

    fn into_builder(self) -> Self::Builder {
        self
    }
}

#[cfg(feature = "bytes")]
impl IntoBuilder for Bytes {
    type Builder = BytesMut;

    fn into_builder(self) -> Self::Builder {
        // XXX Currently, we need to copy to do this. If bytes gains a way
        //     to convert from Bytes to BytesMut for non-shared data without
        //     copying, we should change this.
        BytesMut::from(self.as_ref())
    }
}

#[cfg(feature = "smallvec")]
impl<A: smallvec::Array<Item = u8>> IntoBuilder for smallvec::SmallVec<A> {
    type Builder = Self;

    fn into_builder(self) -> Self::Builder {
        self
    }
}

#[cfg(feature = "heapless")]
impl<const N: usize> IntoBuilder for heapless::Vec<u8, N> {
    type Builder = Self;

    fn into_builder(self) -> Self::Builder {
        self
    }
}


//------------ FromBuilder ---------------------------------------------------

/// An octets type that can be created from an octets builder.
pub trait FromBuilder: AsRef<[u8]> + Sized {
    /// The type of builder this octets type can be created from.
    type Builder: OctetsBuilder + FreezeBuilder<Octets = Self>;

    /// Creates an octets value from an octets builder.
    fn from_builder(builder: Self::Builder) -> Self;
}

#[cfg(feature = "std")]
impl FromBuilder for Vec<u8> {
    type Builder = Self;

    fn from_builder(builder: Self::Builder) -> Self {
        builder
    }
}

#[cfg(feature = "std")]
impl<'a> FromBuilder for Cow<'a, [u8]> {
    type Builder = Self;

    fn from_builder(builder: Self::Builder) -> Self {
        builder
    }
}

#[cfg(feature = "bytes")]
impl FromBuilder for Bytes {
    type Builder = BytesMut;

    fn from_builder(builder: Self::Builder) -> Self {
        builder.freeze()
    }
}

#[cfg(feature = "smallvec")]
impl<A: smallvec::Array<Item = u8>> FromBuilder for smallvec::SmallVec<A> {
    type Builder = Self;

    fn from_builder(builder: Self::Builder) -> Self {
        builder
    }
}

#[cfg(feature = "heapless")]
impl<const N: usize> FromBuilder for heapless::Vec<u8, N> {
    type Builder = Self;

    fn from_builder(builder: Self::Builder) -> Self {
        builder
    }
}


//------------ BuilderAppendError --------------------------------------------

/// A type alias resolving into the `AppendError` of an octets type’s builder.
///
/// This alias can be used rather than spelling out the complete litany in
/// result types.
pub type BuilderAppendError<Octets>
    = <<Octets as FromBuilder>::Builder as OctetsBuilder>::AppendError;


//============ Error Handling ================================================

//------------ ShortBuf ------------------------------------------------------

/// An attempt was made to write beyond the end of a buffer.
///
/// This type is returned as an error by all functions and methods that append
/// data to an [octets builder] when the buffer size of the builder is not
/// sufficient to append the data.
///
/// [octets builder]: trait.OctetsBuilder.html
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ShortBuf;


//--- From

impl From<Infallible> for ShortBuf {
    fn from(_: Infallible) -> ShortBuf {
        unreachable!()
    }
}


//--- Display and Error

impl fmt::Display for ShortBuf {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("buffer size exceeded")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ShortBuf {}


//------------ Functions for Infallible --------------------------------------

/// Erases an error for infallible results.
///
/// This function can be used in place of the still unstable
/// `Result::into_ok` for operations on infallible octets builders.
///
/// If you perform multiple operations, [`with_infallible`] allows you to
/// use the question mark operator on them before erasing the error.
pub fn infallible<T, E: Into<Infallible>>(src: Result<T, E>) -> T {
    match src {
        Ok(ok) => ok,
        Err(_) => unreachable!(),
    }
}

/// Erases an error for a closure returning an infallible results.
///
/// This function can be used for a sequence of operations on an infallible
/// octets builder. By wrapping these operations in a closure, you can still
/// use the question mark operator rather than having to wrap each individual
/// operation in [`infallible`].
pub fn with_infallible<F, T, E>(op: F) -> T
where
    F: FnOnce() -> Result<T, E>,
    E: Into<Infallible>,
{
    infallible(op())
}