Unverified Commit e3be399d authored by Steven Fackler's avatar Steven Fackler Committed by GitHub
Browse files

Merge pull request #1039 from 1aim/asn1num-from-bn

Add `Asn1Integer::from_bn`
parents 79abbeaa 6378eff9
Loading
Loading
Loading
Loading
+35 −1
Original line number Diff line number Diff line
@@ -33,7 +33,7 @@ use std::slice;
use std::str;

use bio::MemBio;
use bn::BigNum;
use bn::{BigNum, BigNumRef};
use error::ErrorStack;
use nid::Nid;
use string::OpensslString;
@@ -191,6 +191,19 @@ foreign_type_and_impl_send_sync! {
    pub struct Asn1IntegerRef;
}

impl Asn1Integer {
    /// Converts a bignum to an `Asn1Integer`.
    ///
    /// Corresponds to [`BN_to_ASN1_INTEGER`]. Also see
    /// [`BigNumRef::to_asn1_integer`].
    ///
    /// [`BN_to_ASN1_INTEGER`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_to_ASN1_INTEGER.html
    /// [`BigNumRef::to_asn1_integer`]: ../bn/struct.BigNumRef.html#method.to_asn1_integer
    pub fn from_bn(bn: &BigNumRef) -> Result<Self, ErrorStack> {
        bn.to_asn1_integer()
    }
}

impl Asn1IntegerRef {
    #[allow(missing_docs)]
    #[deprecated(since = "0.10.6", note = "use to_bn instead")]
@@ -306,3 +319,24 @@ cfg_if! {
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use bn::BigNum;

    /// Tests conversion between BigNum and Asn1Integer.
    #[test]
    fn bn_cvt() {
        fn roundtrip(bn: BigNum) {
            let large = Asn1Integer::from_bn(&bn).unwrap();
            assert_eq!(large.to_bn().unwrap(), bn);
        }

        roundtrip(BigNum::from_dec_str("1000000000000000000000000000000000").unwrap());
        roundtrip(-BigNum::from_dec_str("1000000000000000000000000000000000").unwrap());
        roundtrip(BigNum::from_u32(1234).unwrap());
        roundtrip(-BigNum::from_u32(1234).unwrap());
    }
}