From 595f64bca6492a75a96c0a0c5435adc26b04c58d Mon Sep 17 00:00:00 2001 From: Matt Quinn Date: Sun, 11 Oct 2015 10:29:53 -0700 Subject: [PATCH] Adding to_i32 and from_i32 functions to RecoveryId in order to give library users the ability to create RecoveryId objects and convert them to i32 equivalents, without allowing users to create invalid ones. --- src/lib.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 0ab38b5..43fe897 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -66,6 +66,23 @@ pub struct Signature(ffi::Signature); #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct RecoverableSignature(ffi::RecoverableSignature); +impl RecoveryId { + #[inline] + /// Allows library users to create valid recovery IDs from i32. + pub fn from_i32(id: i32) -> Result { + match id { + 0 | 1 | 2 | 3 => Ok(RecoveryId(id)), + _ => Err(Error::InvalidRecoveryId) + } + } + + #[inline] + /// Allows library users to convert recovery IDs to i32. + pub fn to_i32(&self) -> i32 { + self.0 + } +} + impl Signature { #[inline] /// Converts a DER-encoded byte slice to a signature @@ -243,6 +260,8 @@ pub enum Error { InvalidSignature, /// Bad secret key InvalidSecretKey, + /// Bad recovery id + InvalidRecoveryId, /// Boolean-returning function returned the wrong boolean Unknown } @@ -734,6 +753,20 @@ mod tests { assert_eq!(recid_in, recid_out); assert_eq!(&bytes_in[..], &bytes_out[..]); } + + #[test] + fn test_recov_id_conversion_between_i32() { + assert!(RecoveryId::from_i32(-1).is_err()); + assert!(RecoveryId::from_i32(0).is_ok()); + assert!(RecoveryId::from_i32(1).is_ok()); + assert!(RecoveryId::from_i32(2).is_ok()); + assert!(RecoveryId::from_i32(3).is_ok()); + assert!(RecoveryId::from_i32(4).is_err()); + let id0 = RecoveryId::from_i32(0).unwrap(); + assert_eq!(id0.to_i32(), 0); + let id1 = RecoveryId(1); + assert_eq!(id1.to_i32(), 1); + } } #[cfg(all(test, feature = "unstable"))]