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 CBS (crypto byte string) objects. 16 17 use bssl_sys::{CBS_init, CBS}; 18 use core::marker::PhantomData; 19 use core::mem::MaybeUninit; 20 21 /// CRYPTO ByteString. 22 /// 23 /// Wraps a `CBS` that references an existing fixed-sized buffer; no memory is allocated, but the 24 /// buffer cannot grow. 25 pub struct Cbs<'a> { 26 cbs: CBS, 27 /// The CBS contains a mutable reference to the buffer, disguised as a pointer. 28 /// Make sure the borrow checker knows that. 29 _buffer: PhantomData<&'a [u8]>, 30 } 31 32 impl<'a> Cbs<'a> { 33 /// Creates a new CBS that points to the given buffer. new(buffer: &'a [u8]) -> Self34 pub fn new(buffer: &'a [u8]) -> Self { 35 let mut cbs = MaybeUninit::uninit(); 36 // SAFETY: `CBS_init()` only sets `cbs` to point to `buffer`. It doesn't take ownership 37 // of data. 38 unsafe { CBS_init(cbs.as_mut_ptr(), buffer.as_ptr(), buffer.len()) }; 39 // SAFETY: `cbs` has just been initialized by `CBS_init()`. 40 let cbs = unsafe { cbs.assume_init() }; 41 Self { cbs, _buffer: PhantomData } 42 } 43 } 44 45 impl<'a> AsRef<CBS> for Cbs<'a> { as_ref(&self) -> &CBS46 fn as_ref(&self) -> &CBS { 47 &self.cbs 48 } 49 } 50 51 impl<'a> AsMut<CBS> for Cbs<'a> { as_mut(&mut self) -> &mut CBS52 fn as_mut(&mut self) -> &mut CBS { 53 &mut self.cbs 54 } 55 } 56