blob: 93cebe4562b4858f2ee89a195b2c99c115977b0a [file] [log] [blame]
Alan Stokesb1f64ee2023-09-25 10:38:13 +01001// 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.
16use bssl_ffi::{CBB_init_fixed, CBB};
17use core::marker::PhantomData;
18use 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.
22pub 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
29impl CbbFixed<'_> {
30 // Create a new CBB that writes to the given buffer.
31 pub fn new(buffer: &mut [u8]) -> Self {
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
42impl AsRef<CBB> for CbbFixed<'_> {
43 fn as_ref(&self) -> &CBB {
44 &self.cbb
45 }
46}
47
48impl AsMut<CBB> for CbbFixed<'_> {
49 fn as_mut(&mut self) -> &mut CBB {
50 &mut self.cbb
51 }
52}