Alan Stokes | b1f64ee | 2023-09-25 10:38:13 +0100 | [diff] [blame] | 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 | use bssl_ffi::{CBB_init_fixed, CBB}; |
| 17 | use core::marker::PhantomData; |
| 18 | use core::mem::MaybeUninit; |
| 19 | |
| 20 | /// Wraps a CBB that references a existing fixed-sized buffer; no memory is allocated, but the |
| 21 | /// buffer cannot grow. |
| 22 | pub struct CbbFixed<'a> { |
| 23 | cbb: CBB, |
| 24 | // The CBB contains a mutable reference to the buffer, disguised as a pointer. |
| 25 | // Make sure the borrow checker knows that. |
| 26 | _buffer: PhantomData<&'a mut [u8]>, |
| 27 | } |
| 28 | |
Alan Stokes | d7097e4 | 2023-09-26 12:23:10 +0100 | [diff] [blame^] | 29 | impl<'a> CbbFixed<'a> { |
Alan Stokes | b1f64ee | 2023-09-25 10:38:13 +0100 | [diff] [blame] | 30 | // Create a new CBB that writes to the given buffer. |
Alan Stokes | d7097e4 | 2023-09-26 12:23:10 +0100 | [diff] [blame^] | 31 | pub fn new(buffer: &'a mut [u8]) -> Self { |
Alan Stokes | b1f64ee | 2023-09-25 10:38:13 +0100 | [diff] [blame] | 32 | let mut cbb = MaybeUninit::uninit(); |
| 33 | // SAFETY: `CBB_init_fixed()` is infallible and always returns one. |
| 34 | // The buffer remains valid during the lifetime of `cbb`. |
| 35 | unsafe { CBB_init_fixed(cbb.as_mut_ptr(), buffer.as_mut_ptr(), buffer.len()) }; |
| 36 | // SAFETY: `cbb` has just been initialized by `CBB_init_fixed()`. |
| 37 | let cbb = unsafe { cbb.assume_init() }; |
| 38 | Self { cbb, _buffer: PhantomData } |
| 39 | } |
| 40 | } |
| 41 | |
Alan Stokes | d7097e4 | 2023-09-26 12:23:10 +0100 | [diff] [blame^] | 42 | impl<'a> AsRef<CBB> for CbbFixed<'a> { |
Alan Stokes | b1f64ee | 2023-09-25 10:38:13 +0100 | [diff] [blame] | 43 | fn as_ref(&self) -> &CBB { |
| 44 | &self.cbb |
| 45 | } |
| 46 | } |
| 47 | |
Alan Stokes | d7097e4 | 2023-09-26 12:23:10 +0100 | [diff] [blame^] | 48 | impl<'a> AsMut<CBB> for CbbFixed<'a> { |
Alan Stokes | b1f64ee | 2023-09-25 10:38:13 +0100 | [diff] [blame] | 49 | fn as_mut(&mut self) -> &mut CBB { |
| 50 | &mut self.cbb |
| 51 | } |
| 52 | } |