/rust/registry/src/index.crates.io-1949cf8c6b5b557f/aws-lc-rs-1.16.2/src/bn.rs
Line | Count | Source |
1 | | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
2 | | // SPDX-License-Identifier: Apache-2.0 OR ISC |
3 | | |
4 | | use crate::aws_lc::{BN_bin2bn, BN_bn2bin, BN_new, BN_num_bytes, BN_set_u64, BIGNUM}; |
5 | | use crate::ptr::{ConstPointer, DetachableLcPtr, LcPtr}; |
6 | | use core::ptr::null_mut; |
7 | | |
8 | | impl TryFrom<&[u8]> for LcPtr<BIGNUM> { |
9 | | type Error = (); |
10 | | |
11 | 0 | fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> { |
12 | 0 | unsafe { LcPtr::new(BN_bin2bn(bytes.as_ptr(), bytes.len(), null_mut())) } |
13 | 0 | } |
14 | | } |
15 | | |
16 | | impl TryFrom<&[u8]> for DetachableLcPtr<BIGNUM> { |
17 | | type Error = (); |
18 | | |
19 | 0 | fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> { |
20 | 0 | unsafe { DetachableLcPtr::new(BN_bin2bn(bytes.as_ptr(), bytes.len(), null_mut())) } |
21 | 0 | } |
22 | | } |
23 | | |
24 | | impl TryFrom<u64> for DetachableLcPtr<BIGNUM> { |
25 | | type Error = (); |
26 | | |
27 | 0 | fn try_from(value: u64) -> Result<Self, Self::Error> { |
28 | | unsafe { |
29 | 0 | let mut bn = DetachableLcPtr::new(BN_new())?; |
30 | 0 | if 1 != BN_set_u64(bn.as_mut_ptr(), value) { |
31 | 0 | return Err(()); |
32 | 0 | } |
33 | 0 | Ok(bn) |
34 | | } |
35 | 0 | } |
36 | | } |
37 | | |
38 | | impl ConstPointer<'_, BIGNUM> { |
39 | 0 | pub(crate) fn to_be_bytes(&self) -> Vec<u8> { |
40 | | unsafe { |
41 | 0 | let bn_bytes = BN_num_bytes(self.as_const_ptr()); |
42 | 0 | let mut byte_vec = Vec::with_capacity(bn_bytes as usize); |
43 | 0 | let out_bytes = BN_bn2bin(self.as_const_ptr(), byte_vec.as_mut_ptr()); |
44 | 0 | debug_assert_eq!(out_bytes, bn_bytes as usize); |
45 | 0 | byte_vec.set_len(out_bytes); |
46 | 0 | byte_vec |
47 | | } |
48 | 0 | } |
49 | | } |