diff options
| author | Yukihiro "Matz" Matsumoto <[email protected]> | 2021-03-21 08:30:52 +0900 |
|---|---|---|
| committer | Yukihiro "Matz" Matsumoto <[email protected]> | 2021-03-21 08:30:52 +0900 |
| commit | 73056aeb2b8e67145ee4bf28cd99a6cbb4224231 (patch) | |
| tree | daa94bfcd66a0fc827a56dea4b51fa05446192dd | |
| parent | a6d4477a09ae9ca2af97bdcecd25911da5a75a7c (diff) | |
| download | mruby-73056aeb2b8e67145ee4bf28cd99a6cbb4224231.tar.gz mruby-73056aeb2b8e67145ee4bf28cd99a6cbb4224231.zip | |
complex.c: define `Complex#==` in C.
This change also fixes the error caused by `rational.c` that calls
`mrb_complex_eq()`, which had been undefined.
| -rw-r--r-- | mrbgems/mruby-complex/mrblib/complex.rb | 8 | ||||
| -rw-r--r-- | mrbgems/mruby-complex/src/complex.c | 35 |
2 files changed, 35 insertions, 8 deletions
diff --git a/mrbgems/mruby-complex/mrblib/complex.rb b/mrbgems/mruby-complex/mrblib/complex.rb index 0b5fc8f73..1484ff394 100644 --- a/mrbgems/mruby-complex/mrblib/complex.rb +++ b/mrbgems/mruby-complex/mrblib/complex.rb @@ -52,14 +52,6 @@ class Complex < Numeric end alias_method :quo, :/ - def ==(rhs) - if rhs.is_a? Complex - real == rhs.real && imaginary == rhs.imaginary - elsif rhs.is_a? Numeric - imaginary == 0 && real == rhs - end - end - def abs Math.hypot imaginary, real end diff --git a/mrbgems/mruby-complex/src/complex.c b/mrbgems/mruby-complex/src/complex.c index 8960c0573..67ab9c33d 100644 --- a/mrbgems/mruby-complex/src/complex.c +++ b/mrbgems/mruby-complex/src/complex.c @@ -137,6 +137,40 @@ complex_to_c(mrb_state *mrb, mrb_value self) return self; } +mrb_bool +mrb_complex_eq(mrb_state *mrb, mrb_value x, mrb_value y) +{ + struct mrb_complex *p1 = complex_ptr(mrb, x); + + switch (mrb_type(y)) { + case MRB_TT_COMPLEX: + { + struct mrb_complex *p2 = complex_ptr(mrb, y); + + if (p1->real == p2->real && p1->imaginary == p2->imaginary) { + return TRUE; + } + return FALSE; + } + case MRB_TT_INTEGER: + if (p1->imaginary != 0) return FALSE; + return p1->real == mrb_integer(y); + case MRB_TT_FLOAT: + if (p1->imaginary != 0) return FALSE; + return p1->real == mrb_float(y); + + default: + return mrb_equal(mrb, y, x); + } +} + +static mrb_value +complex_eq(mrb_state *mrb, mrb_value x) +{ + mrb_value y = mrb_get_arg1(mrb); + return mrb_bool_value(mrb_complex_eq(mrb, x, y)); +} + /* Arithmetic on (significand, exponent) pairs avoids premature overflow in complex division */ struct float_pair { @@ -289,6 +323,7 @@ void mrb_mruby_complex_gem_init(mrb_state *mrb) mrb_define_method(mrb, comp, "to_i", complex_to_i, MRB_ARGS_NONE()); mrb_define_method(mrb, comp, "to_c", complex_to_c, MRB_ARGS_NONE()); mrb_define_method(mrb, comp, "__div__", complex_div, MRB_ARGS_REQ(1)); + mrb_define_method(mrb, comp, "==", complex_eq, MRB_ARGS_REQ(1)); #ifndef MRB_USE_RATIONAL mrb_define_method(mrb, mrb->integer_class, "/", int_div, MRB_ARGS_REQ(1)); /* overrride */ mrb_define_method(mrb, mrb->integer_class, "quo", int_quo, MRB_ARGS_REQ(1)); /* overrride */ |
