From 49f5ee237780efb4006302743aa3df6c7ace5a74 Mon Sep 17 00:00:00 2001 From: Rick Mark Date: Tue, 30 Mar 2021 14:50:42 -0700 Subject: [PATCH] Implement OpenSSL::BN#abs Provides an efficant way to garentee positive values --- .gitignore | 2 ++ ext/openssl/ossl_bn.c | 24 ++++++++++++++++++++++++ test/openssl/test_bn.rb | 13 +++++++++++++ 3 files changed, 39 insertions(+) diff --git a/.gitignore b/.gitignore index 1be08834f..ef5f6582d 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ ext/openssl/mkmf.log ext/openssl/Makefile ext/openssl/extconf.h +.DS_Store +.idea/ \ No newline at end of file diff --git a/ext/openssl/ossl_bn.c b/ext/openssl/ossl_bn.c index 1d43e4572..3e6208f13 100644 --- a/ext/openssl/ossl_bn.c +++ b/ext/openssl/ossl_bn.c @@ -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) \ @@ -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); diff --git a/test/openssl/test_bn.rb b/test/openssl/test_bn.rb index 547d334c6..5f6a4fb47 100644 --- a/test/openssl/test_bn.rb +++ b/test/openssl/test_bn.rb @@ -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)