1 // Copyright 2023, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Helpers for using BoringSSL CBB (crypto byte builder) objects.
16 
17 use bssl_sys::{CBB_init_fixed, CBB};
18 use core::marker::PhantomData;
19 use core::mem::MaybeUninit;
20 
21 /// Wraps a CBB that references a existing fixed-sized buffer; no memory is allocated, but the
22 /// buffer cannot grow.
23 pub struct CbbFixed<'a> {
24     cbb: CBB,
25     /// The CBB contains a mutable reference to the buffer, disguised as a pointer.
26     /// Make sure the borrow checker knows that.
27     _buffer: PhantomData<&'a mut [u8]>,
28 }
29 
30 impl<'a> CbbFixed<'a> {
31     /// Create a new CBB that writes to the given buffer.
new(buffer: &'a mut [u8]) -> Self32     pub fn new(buffer: &'a mut [u8]) -> Self {
33         let mut cbb = MaybeUninit::uninit();
34         // SAFETY: `CBB_init_fixed()` is infallible and always returns one.
35         // The buffer remains valid during the lifetime of `cbb`.
36         unsafe { CBB_init_fixed(cbb.as_mut_ptr(), buffer.as_mut_ptr(), buffer.len()) };
37         // SAFETY: `cbb` has just been initialized by `CBB_init_fixed()`.
38         let cbb = unsafe { cbb.assume_init() };
39         Self { cbb, _buffer: PhantomData }
40     }
41 }
42 
43 impl<'a> AsRef<CBB> for CbbFixed<'a> {
as_ref(&self) -> &CBB44     fn as_ref(&self) -> &CBB {
45         &self.cbb
46     }
47 }
48 
49 impl<'a> AsMut<CBB> for CbbFixed<'a> {
as_mut(&mut self) -> &mut CBB50     fn as_mut(&mut self) -> &mut CBB {
51         &mut self.cbb
52     }
53 }
54