py/modbuiltins: Implement abs() by dispatching to MP_UNARY_OP_ABS.

This allows user classes to implement __abs__ special method, and saves
code size (104 bytes for x86_64), even though during refactor, an issue
was fixed and few optimizations were made:

* abs() of minimum (negative) small int value is calculated properly.
* objint_longlong and objint_mpz avoid allocating new object is the
  argument is already non-negative.
This commit is contained in:
Paul Sokolovsky
2017-09-18 00:06:43 +03:00
parent 72491b3e40
commit 9dce823cfd
10 changed files with 45 additions and 77 deletions

View File

@@ -162,6 +162,15 @@ STATIC mp_obj_t float_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT(mp_float_hash(val));
case MP_UNARY_OP_POSITIVE: return o_in;
case MP_UNARY_OP_NEGATIVE: return mp_obj_new_float(-val);
case MP_UNARY_OP_ABS: {
mp_float_t value = mp_obj_float_get(o_in);
// TODO check for NaN etc
if (value < 0) {
return mp_obj_new_float(-value);
} else {
return o_in;
}
}
default: return MP_OBJ_NULL; // op not supported
}
}