Skip to content

Commit d3e229c

Browse files
Merge #58
58: Add accessor to get the sign of a Mpi r=Goirad a=jack-fortanix Co-authored-by: Jack Lloyd <[email protected]>
2 parents 3bb19d8 + b520d96 commit d3e229c

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

mbedtls/src/bignum/mod.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,13 @@ impl ::core::str::FromStr for Mpi {
8080
}
8181
}
8282

83+
#[derive(Debug,Copy,Clone,Eq,PartialEq)]
84+
pub enum Sign {
85+
Negative,
86+
Zero,
87+
Positive,
88+
}
89+
8390
impl Clone for Mpi {
8491
fn clone(&self) -> Self {
8592
Mpi::copy(&self.handle()).expect("copy succeeded")
@@ -140,6 +147,17 @@ impl Mpi {
140147
Ok(self.get_limb(0) as u32)
141148
}
142149

150+
pub fn sign(&self) -> Sign {
151+
let cmp = unsafe { mpi_cmp_int(&self.inner, 0) };
152+
if cmp < 0 {
153+
Sign::Negative
154+
} else if cmp == 0 {
155+
Sign::Zero
156+
} else {
157+
Sign::Positive
158+
}
159+
}
160+
143161
pub fn to_string_radix(&self, radix: i32) -> Result<String> {
144162
let mut olen = 0;
145163
let r =

mbedtls/tests/bignum.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
extern crate mbedtls;
1010

11-
use mbedtls::bignum::Mpi;
11+
use mbedtls::bignum::{Mpi, Sign};
1212

1313
#[cfg(feature = "std")]
1414
#[test]
@@ -130,8 +130,10 @@ fn bignum_op_assign() {
130130
x *= 2;
131131
assert_eq!(format!("{}", x), "360");
132132

133+
assert_eq!(x.sign(), Sign::Positive);
133134
x *= Mpi::new(-2).unwrap();
134135
assert_eq!(format!("{}", x), "-720");
136+
assert_eq!(x.sign(), Sign::Negative);
135137

136138
x /= Mpi::new(-3).unwrap();
137139
assert_eq!(format!("{}", x), "240");
@@ -354,6 +356,7 @@ const BASE58_ALPHABET: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmno
354356

355357
fn base58_encode(bits: &[u8]) -> mbedtls::Result<String> {
356358
let zero = Mpi::new(0)?;
359+
assert_eq!(zero.sign(), Sign::Zero);
357360
let mut n = Mpi::from_binary(bits)?;
358361
let radix: i64 = 58;
359362

0 commit comments

Comments
 (0)