Pārlūkot izejas kodu

BN_min() and BN_abs() utility function.

Tests included.
Michele Orrù 11 gadi atpakaļ
vecāks
revīzija
3ef50e5459

+ 5 - 0
src/questions/include/qarith.h

@@ -5,6 +5,9 @@
 /* shortcut macros. */
 #define BN_uiadd1(a) BN_uadd(a, a, BN_value_one())
 
+#define BN_abs(a)  BN_set_negative(a, 0)
+
+
 /**
  * Fractions made of bignums.
  */
@@ -33,6 +36,8 @@ void cf_free(cf_t* f);
 bigfraction_t* cf_next(cf_t *f);
 
 
+BIGNUM* BN_min(BIGNUM *a, BIGNUM *b);
+
 /* square root calculation */
 int BN_sqrtmod(BIGNUM* dv, BIGNUM* rem, BIGNUM* a, BN_CTX* ctx);
 

+ 5 - 0
src/questions/qarith.c

@@ -217,3 +217,8 @@ RSA* qa_RSA_recover(const RSA *rsapub,
   BN_free(phi);
   return rsapriv;
 }
+
+inline BIGNUM *BN_min(BIGNUM *a, BIGNUM *b)
+{
+  return (BN_cmp(a, b) < 0) ? a : b;
+}

+ 39 - 0
src/questions/tests/test_qarith.c

@@ -206,11 +206,50 @@ test_qa_RSA_recover(void)
   BN_CTX_free(ctx);
 }
 
+
+void
+test_BN_min(void)
+{
+  BIGNUM *a = BN_new();
+  BIGNUM *b = BN_new();
+
+  BN_dec2bn(&a, "10");
+  BN_dec2bn(&b, "11");
+  assert(!BN_cmp(BN_min(a, b), a));
+
+  BN_dec2bn(&a, "-100");
+  BN_dec2bn(&b, "-101");
+  assert(!BN_cmp(BN_min(a, b), b));
+
+  BN_free(a);
+  BN_free(b);
+}
+
+void
+test_BN_abs(void)
+{
+  BIGNUM *a = BN_new();
+  BIGNUM *check = BN_new();
+
+  BN_dec2bn(&a, "-100");
+  BN_dec2bn(&check, "100");
+  BN_abs(a);
+  assert(!BN_cmp(a, check));
+
+  BN_abs(a);
+  assert(!BN_cmp(a, check));
+
+  BN_free(check);
+  BN_free(a);
+}
+
 int main(int argc, char **argv)
 {
   test_cf();
   test_BN_sqrtmod();
   test_qa_RSA_recover();
+  test_BN_min();
+  test_BN_abs();
 
   return 0;