/rust/registry/src/index.crates.io-1949cf8c6b5b557f/aws-lc-rs-1.12.4/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<u64> for LcPtr<BIGNUM> { |
17 | | type Error = (); |
18 | | |
19 | 0 | fn try_from(value: u64) -> Result<Self, Self::Error> { |
20 | | unsafe { |
21 | 0 | let mut bn = LcPtr::new(BN_new())?; |
22 | 0 | if 1 != BN_set_u64(*bn.as_mut(), value) { |
23 | 0 | return Err(()); |
24 | 0 | } |
25 | 0 | Ok(bn) |
26 | | } |
27 | 0 | } |
28 | | } |
29 | | |
30 | | impl TryFrom<&[u8]> for DetachableLcPtr<BIGNUM> { |
31 | | type Error = (); |
32 | | |
33 | 0 | fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> { |
34 | 0 | unsafe { DetachableLcPtr::new(BN_bin2bn(bytes.as_ptr(), bytes.len(), null_mut())) } |
35 | 0 | } |
36 | | } |
37 | | |
38 | | impl TryFrom<u64> for DetachableLcPtr<BIGNUM> { |
39 | | type Error = (); |
40 | | |
41 | 0 | fn try_from(value: u64) -> Result<Self, Self::Error> { |
42 | | unsafe { |
43 | 0 | let bn = DetachableLcPtr::new(BN_new())?; |
44 | 0 | if 1 != BN_set_u64(*bn, value) { |
45 | 0 | return Err(()); |
46 | 0 | } |
47 | 0 | Ok(bn) |
48 | | } |
49 | 0 | } |
50 | | } |
51 | | |
52 | | impl ConstPointer<BIGNUM> { |
53 | 0 | pub(crate) fn to_be_bytes(&self) -> Vec<u8> { |
54 | | unsafe { |
55 | 0 | let bn_bytes = BN_num_bytes(**self); |
56 | 0 | let mut byte_vec = Vec::with_capacity(bn_bytes as usize); |
57 | 0 | let out_bytes = BN_bn2bin(**self, byte_vec.as_mut_ptr()); |
58 | 0 | debug_assert_eq!(out_bytes, bn_bytes as usize); |
59 | 0 | byte_vec.set_len(out_bytes); |
60 | 0 | byte_vec |
61 | | } |
62 | 0 | } |
63 | | } |