blob: 12671cf882a001f8ef95ce69bc2ecf058d90520e [file] [log] [blame]
Alice Wang000595b2023-10-02 13:46:45 +00001// 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
Maurice Lam0322b8c2023-12-18 22:13:48 +000017use bssl_sys::{CBS_init, CBS};
Alice Wang000595b2023-10-02 13:46:45 +000018use core::marker::PhantomData;
19use 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.
25pub 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
32impl<'a> Cbs<'a> {
33 /// Creates a new CBS that points to the given buffer.
34 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
45impl<'a> AsRef<CBS> for Cbs<'a> {
46 fn as_ref(&self) -> &CBS {
47 &self.cbs
48 }
49}
50
51impl<'a> AsMut<CBS> for Cbs<'a> {
52 fn as_mut(&mut self) -> &mut CBS {
53 &mut self.cbs
54 }
55}