Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement OpenSSL::BN#abs #430

Merged
merged 1 commit into from
Apr 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
rickmark marked this conversation as resolved.
Show resolved Hide resolved
}

#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