fbthrift_git/
binary_type.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use std::io::Cursor;
18
19use bytes::Bytes;
20
21use crate::bufext::BufExt;
22
23/// Trait implemented on types that can be used as `binary` types in
24/// thrift.  These types copy data from the Thrift buffer.
25pub 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
35/// Trait for copying from the Thrift buffer.  Special implementations
36/// may do this without actually copying.
37pub 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}