Permalink
Browse files

Add comparison functions.

  • Loading branch information...
colomon committed Jan 30, 2011
1 parent 1ab9bd0 commit 286b8594745bf6ac4e13e16f9abd06092be9e02b
Showing with 60 additions and 0 deletions.
  1. +36 −0 lib/Math/BigInt.pm
  2. +24 −0 t/04-compare.t
View
@@ -11,6 +11,8 @@ sub bdMultiply(OpaquePointer $w, OpaquePointer $u, OpaquePointer $v) returns Int
sub bdDivide(OpaquePointer $q, OpaquePointer $r, OpaquePointer $u, OpaquePointer $v) returns Int is native("libbd") { ... }
sub bdModulo(OpaquePointer $w, OpaquePointer $u, OpaquePointer $v) returns Int is native("libbd") { ... }
sub bdConvToDecimal(OpaquePointer $bd, OpaquePointer $s, Int $smax) returns Int is native("libbd") { ... }
+sub bdIsEqual(OpaquePointer $a, OpaquePointer $b) returns Int is native("libbd") { ... }
+sub bdCompare(OpaquePointer $a, OpaquePointer $b) returns Int is native("libbd") { ... }
sub malloc(Int $n) returns OpaquePointer is native("libSystem") { ... }
sub free(OpaquePointer $p) is native("libSystem") { ... }
@@ -138,4 +140,38 @@ class Math::BigInt does Real {
bdModulo($result.bd, $a.bd, Math::BigInt.new($b).bd);
$result.Int;
}
+
+ # Comparison operators
+
+ multi sub infix:<cmp>(Math::BigInt $a, Math::BigInt $b) is export(:DEFAULT) {
+ $a <=> $b;
+ }
+
+ multi sub infix:«<=>»(Math::BigInt $a, Math::BigInt $b) is export(:DEFAULT) {
+ bdCompare($a.bd, $b.bd);
+ }
+
+ multi sub infix:«==»(Math::BigInt $a, Math::BigInt $b) is export(:DEFAULT) {
+ ?bdIsEqual($a.bd, $b.bd);
+ }
+
+ multi sub infix:«!=»(Math::BigInt $a, Math::BigInt $b) is export(:DEFAULT) {
+ !bdIsEqual($a.bd, $b.bd);
+ }
+
+ multi sub infix:«<»(Math::BigInt $a, Math::BigInt $b) is export(:DEFAULT) {
+ ($a <=> $b) == -1;
+ }
+
+ multi sub infix:«>»(Math::BigInt $a, Math::BigInt $b) is export(:DEFAULT) {
+ ($a <=> $b) == 1;
+ }
+
+ multi sub infix:«<=»(Math::BigInt $a, Math::BigInt $b) is export(:DEFAULT) {
+ ($a <=> $b) != 1;
+ }
+
+ multi sub infix:«>=»(Math::BigInt $a, Math::BigInt $b) is export(:DEFAULT) {
+ ($a <=> $b) != -1;
+ }
}
View
@@ -0,0 +1,24 @@
+use Math::BigInt;
+use Test;
+
+plan *;
+
+ok 4¹ < "54534624524525325234524354252"¹;
+ok 4¹ <= "54534624524525325234524354252"¹;
+ok 4¹ != "54534624524525325234524354252"¹;
+nok 4¹ > "54534624524525325234524354252"¹;
+nok 4¹ >= "54534624524525325234524354252"¹;
+
+ok 4¹ == 4¹;
+ok 4¹ <= 4¹;
+ok 4¹ >= 4¹;
+nok 4¹ < 4¹;
+nok 4¹ > 4¹;
+
+ok "54534624524525325234524354252"¹ == "54534624524525325234524354252"¹;
+ok "54534624524525325234524354252"¹ <= "54534624524525325234524354252"¹;
+ok "54534624524525325234524354252"¹ >= "54534624524525325234524354252"¹;
+nok "54534624524525325234524354252"¹ < "54534624524525325234524354252"¹;
+nok "54534624524525325234524354252"¹ > "54534624524525325234524354252"¹;
+
+done;

0 comments on commit 286b859

Please sign in to comment.