• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2023, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14  */
15 
16 use crate::{CSlice, ForeignType};
17 
18 pub(crate) struct BigNum {
19     ptr: *mut bssl_sys::BIGNUM,
20 }
21 
22 // Safety: Implementation ensures `from_ptr(x).as_ptr() == x`
23 unsafe impl ForeignType for BigNum {
24     type CType = bssl_sys::BIGNUM;
25 
from_ptr(ptr: *mut Self::CType) -> Self26     unsafe fn from_ptr(ptr: *mut Self::CType) -> Self {
27         Self { ptr }
28     }
29 
as_ptr(&self) -> *mut Self::CType30     fn as_ptr(&self) -> *mut Self::CType {
31         self.ptr
32     }
33 }
34 
35 impl BigNum {
new() -> Self36     pub(crate) fn new() -> Self {
37         // Safety: There are no preconditions for BN_new()
38         unsafe { Self::from_ptr(bssl_sys::BN_new()) }
39     }
40 }
41 
42 impl From<&[u8]> for BigNum {
from(value: &[u8]) -> Self43     fn from(value: &[u8]) -> Self {
44         let value_ffi = CSlice(value);
45         // Safety:
46         // - `value` is a CSlice from safe Rust.
47         // - The `ret` argument can be null to request allocating a new result.
48         let ptr = unsafe {
49             bssl_sys::BN_bin2bn(value_ffi.as_ptr(), value_ffi.len(), core::ptr::null_mut())
50         };
51         assert!(!ptr.is_null());
52         Self { ptr }
53     }
54 }
55 
56 impl Drop for BigNum {
drop(&mut self)57     fn drop(&mut self) {
58         // Safety: `self.ptr` is owned by `self`.
59         unsafe { bssl_sys::BN_free(self.ptr) }
60     }
61 }
62