mirror of
https://github.com/micropython/micropython.git
synced 2026-01-05 03:30:14 +01:00
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:
@@ -231,6 +231,15 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) {
|
||||
} else {
|
||||
return MP_OBJ_NEW_SMALL_INT(-val);
|
||||
}
|
||||
case MP_UNARY_OP_ABS:
|
||||
if (val >= 0) {
|
||||
return arg;
|
||||
} else if (val == MP_SMALL_INT_MIN) {
|
||||
// check for overflow
|
||||
return mp_obj_new_int(-val);
|
||||
} else {
|
||||
return MP_OBJ_NEW_SMALL_INT(-val);
|
||||
}
|
||||
default:
|
||||
assert(op == MP_UNARY_OP_INVERT);
|
||||
return MP_OBJ_NEW_SMALL_INT(~val);
|
||||
|
||||
Reference in New Issue
Block a user