Skip to content

Commit

Permalink
Merge pull request openssl#430 from rickmark/rickmark/bn_abs
Browse files Browse the repository at this point in the history
Implement OpenSSL::BN#abs
  • Loading branch information
rhenium committed Apr 2, 2021
2 parents 69f89d4 + 0321b1e commit 485a6d6
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
31 changes: 30 additions & 1 deletion ext/openssl/ossl_bn.c
Original file line number Diff line number Diff line change
Expand Up @@ -936,7 +936,17 @@ ossl_bn_copy(VALUE self, VALUE other)
static VALUE
ossl_bn_uplus(VALUE self)
{
return self;
VALUE obj;
BIGNUM *bn1, *bn2;

GetBN(self, bn1);
obj = NewBN(cBN);
bn2 = BN_dup(bn1);
if (!bn2)
ossl_raise(eBNError, "BN_dup");
SetBN(obj, bn2);

return obj;
}

/*
Expand All @@ -960,6 +970,24 @@ ossl_bn_uminus(VALUE self)
return obj;
}

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

GetBN(self, bn1);
if (BN_is_negative(bn1)) {
return ossl_bn_uminus(self);
}
else {
return ossl_bn_uplus(self);
}
}

#define BIGNUM_CMP(func) \
static VALUE \
ossl_bn_##func(VALUE self, VALUE other) \
Expand Down Expand Up @@ -1176,6 +1204,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
21 changes: 21 additions & 0 deletions test/openssl/test_bn.rb
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,27 @@ def test_unary_plus_minus
assert_equal(-999, +@e2)
assert_equal(-999, -@e1)
assert_equal(+999, -@e2)

# These methods create new BN instances due to BN mutability
# Ensure that the instance isn't the same
e1_plus = +@e1
e1_minus = -@e1
assert_equal(false, @e1.equal?(e1_plus))
assert_equal(true, @e1 == e1_plus)
assert_equal(false, @e1.equal?(e1_minus))
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_equal(false, @e2.abs.negative?)
assert_equal(false, @e4.abs.negative?)
assert_equal(true, (-@e1.abs).negative?)
assert_equal(true, (-@e2.abs).negative?)
assert_equal(true, (-@e3.abs).negative?)
assert_equal(true, (-@e4.abs).negative?)
end

def test_mod
Expand Down

0 comments on commit 485a6d6

Please sign in to comment.