blob: a48c714516036b28be6bf1697ba55d1ae0b9cab7 [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.
Alice Wangc8f88f52023-09-25 14:02:17 +000016
Maurice Lam0322b8c2023-12-18 22:13:48 +000017use bssl_sys::{CBB_init_fixed, CBB};
Alan Stokesb1f64ee2023-09-25 10:38:13 +010018use core::marker::PhantomData;
19use 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.
23pub struct CbbFixed<'a> {
24 cbb: CBB,
Alice Wangc8f88f52023-09-25 14:02:17 +000025 /// The CBB contains a mutable reference to the buffer, disguised as a pointer.
26 /// Make sure the borrow checker knows that.
Alan Stokesb1f64ee2023-09-25 10:38:13 +010027 _buffer: PhantomData<&'a mut [u8]>,
28}
29
Alan Stokesd7097e42023-09-26 12:23:10 +010030impl<'a> CbbFixed<'a> {
Alice Wangc8f88f52023-09-25 14:02:17 +000031 /// Create a new CBB that writes to the given buffer.
Alan Stokesd7097e42023-09-26 12:23:10 +010032 pub fn new(buffer: &'a mut [u8]) -> Self {
Alan Stokesb1f64ee2023-09-25 10:38:13 +010033 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
Alan Stokesd7097e42023-09-26 12:23:10 +010043impl<'a> AsRef<CBB> for CbbFixed<'a> {
Alan Stokesb1f64ee2023-09-25 10:38:13 +010044 fn as_ref(&self) -> &CBB {
45 &self.cbb
46 }
47}
48
Alan Stokesd7097e42023-09-26 12:23:10 +010049impl<'a> AsMut<CBB> for CbbFixed<'a> {
Alan Stokesb1f64ee2023-09-25 10:38:13 +010050 fn as_mut(&mut self) -> &mut CBB {
51 &mut self.cbb
52 }
53}