tower_web/util/buf_stream/from.rs
1use super::SizeHint;
2
3use bytes::{Buf, BufMut, Bytes, BytesMut};
4
5/// Conversion from a `BufStream`.
6///
7/// By implementing `FromBufStream` for a type, you define how it will be
8/// created from a buf stream. This is common for types which describe byte
9/// storage of some kind.
10///
11/// `FromBufStream` is rarely called explicitly, and it is instead used through
12/// `BufStream`'s `collect` method.
13pub trait FromBufStream {
14 /// Type that is used to build `Self` while the `BufStream` is being
15 /// consumed.
16 type Builder;
17
18 /// Create a new, empty, builder. The provided `hint` can be used to inform
19 /// reserving capacity.
20 fn builder(hint: &SizeHint) -> Self::Builder;
21
22 /// Extend the builder with the `Buf`.
23 ///
24 /// This method is called whenever a new `Buf` value is obtained from the
25 /// buf stream.
26 fn extend<T: Buf>(builder: &mut Self::Builder, buf: &mut T);
27
28 /// Finalize the building of `Self`.
29 ///
30 /// Called once the buf stream is fully consumed.
31 fn build(builder: Self::Builder) -> Self;
32}
33
34impl FromBufStream for Vec<u8> {
35 type Builder = Vec<u8>;
36
37 fn builder(hint: &SizeHint) -> Vec<u8> {
38 Vec::with_capacity(hint.lower())
39 }
40
41 fn extend<T: Buf>(builder: &mut Self, buf: &mut T) {
42 builder.put(buf);
43 }
44
45 fn build(builder: Self) -> Self {
46 builder
47 }
48}
49
50impl FromBufStream for Bytes {
51 type Builder = BytesMut;
52
53 fn builder(hint: &SizeHint) -> BytesMut {
54 BytesMut::with_capacity(hint.lower())
55 }
56
57 fn extend<T: Buf>(builder: &mut Self::Builder, buf: &mut T) {
58 builder.put(buf);
59 }
60
61 fn build(builder: Self::Builder) -> Self {
62 builder.freeze()
63 }
64}