Skip to content

Commit

Permalink
Implement OpenSSL::BN#abs
Browse files Browse the repository at this point in the history
Provides an efficant way to garentee positive values
  • Loading branch information
Rick Mark committed Mar 30, 2021
1 parent d9e5cbf commit 49f5ee2
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@
ext/openssl/mkmf.log
ext/openssl/Makefile
ext/openssl/extconf.h
.DS_Store
.idea/
24 changes: 24 additions & 0 deletions ext/openssl/ossl_bn.c
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,29 @@ ossl_bn_uminus(VALUE self)
return obj;
}

/*
* call-seq:
* bn.abs -> aBN
*/
static VALUE
ossl_bn_abs(VALUE self)
{
VALUE obj;
BIGNUM *bn1, *bn2;

GetBN(self, bn1);
if (BN_is_negative(bn1)) {
obj = NewBN(cBN);
bn2 = BN_dup(bn1);
if (!bn2) { ossl_raise(eBNError, "BN_dup"); }
SetBN(obj, bn2);
BN_set_negative(bn2, 0);
return obj;
} else {
return self;
}
}

#define BIGNUM_CMP(func) \
static VALUE \
ossl_bn_##func(VALUE self, VALUE other) \
Expand Down Expand Up @@ -1176,6 +1199,7 @@ Init_ossl_bn(void)

rb_define_method(cBN, "+@", ossl_bn_uplus, 0);
rb_define_method(cBN, "-@", ossl_bn_uminus, 0);
rb_define_method(cBN, "abs", ossl_bn_abs, 0);

rb_define_method(cBN, "+", ossl_bn_add, 1);
rb_define_method(cBN, "-", ossl_bn_sub, 1);
Expand Down
13 changes: 13 additions & 0 deletions test/openssl/test_bn.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,19 @@ def test_sqr
assert_equal(100, 10.to_bn.sqr)
end

def test_abs
assert_equal(@e1, @e2.abs)
assert_equal(@e3, @e4.abs)
assert_not_equal(@e2, @e2.abs)
assert_not_equal(@e4, @e4.abs)
assert_false(@e2.abs.negative?)
assert_false(@e4.abs.negative?)
assert_true((-@e1.abs).negative?)
assert_true((-@e2.abs).negative?)
assert_true((-@e3.abs).negative?)
assert_true((-@e4.abs).negative?)
end

def test_four_ops
assert_equal(3, 1.to_bn + 2)
assert_equal(-1, 1.to_bn + -2)
Expand Down

0 comments on commit 49f5ee2

Please sign in to comment.