fbthrift_git/
binary_type.rs1use std::io::Cursor;
18
19use bytes::Bytes;
20
21use crate::bufext::BufExt;
22
23pub trait BinaryType: Sized {
26 fn with_capacity(capacity: usize) -> Self;
27 fn extend_from_slice(&mut self, other: &[u8]);
28 fn from_vec(vec: Vec<u8>) -> Self {
29 let mut binary = Self::with_capacity(vec.len());
30 binary.extend_from_slice(&vec);
31 binary
32 }
33}
34
35pub trait CopyFromBuf: Sized {
38 fn copy_from_buf<B: BufExt>(buffer: &mut B, len: usize) -> Self;
39 fn from_vec(vec: Vec<u8>) -> Self {
40 Self::copy_from_buf(&mut Cursor::new(&vec), vec.len())
41 }
42}
43
44impl BinaryType for Vec<u8> {
45 fn with_capacity(capacity: usize) -> Self {
46 Vec::with_capacity(capacity)
47 }
48 fn extend_from_slice(&mut self, other: &[u8]) {
49 Vec::extend_from_slice(self, other);
50 }
51 fn from_vec(vec: Vec<u8>) -> Self {
52 vec
53 }
54}
55
56impl<T: BinaryType> CopyFromBuf for T {
57 fn copy_from_buf<B: BufExt>(buffer: &mut B, len: usize) -> Self {
58 assert!(buffer.remaining() >= len);
59 let mut result = T::with_capacity(len);
60 let mut remaining = len;
61
62 while remaining > 0 {
63 let part = buffer.chunk();
64 let part_len = part.len().min(remaining);
65 result.extend_from_slice(&part[..part_len]);
66 remaining -= part_len;
67 buffer.advance(part_len);
68 }
69
70 result
71 }
72 fn from_vec(vec: Vec<u8>) -> Self {
73 BinaryType::from_vec(vec)
74 }
75}
76
77pub(crate) struct Discard;
78
79impl CopyFromBuf for Discard {
80 fn copy_from_buf<B: BufExt>(buffer: &mut B, len: usize) -> Self {
81 buffer.advance(len);
82 Discard
83 }
84}
85
86impl CopyFromBuf for Bytes {
87 fn copy_from_buf<B: BufExt>(buffer: &mut B, len: usize) -> Self {
88 buffer.copy_or_reuse_bytes(len)
89 }
90 fn from_vec(vec: Vec<u8>) -> Self {
91 vec.into()
92 }
93}