From c4104898cec82bee66ac513322f44b67663e4980 Mon Sep 17 00:00:00 2001 From: Jeff Epler Date: Sun, 23 Apr 2023 09:43:25 -0500 Subject: [PATCH] add additional float validators --- py/argcheck.c | 15 +++++++++++++++ py/runtime.h | 2 ++ 2 files changed, 17 insertions(+) diff --git a/py/argcheck.c b/py/argcheck.c index 465a82c97e..b530d44caa 100644 --- a/py/argcheck.c +++ b/py/argcheck.c @@ -186,6 +186,21 @@ mp_int_t mp_arg_validate_int_range(mp_int_t i, mp_int_t min, mp_int_t max, qstr return i; } +mp_float_t mp_arg_validate_type_float(mp_obj_t obj, qstr arg_name) { + mp_float_t a_float; + if (!mp_obj_get_float_maybe(obj, &a_float)) { + mp_raise_TypeError_varg(translate("%q must be of type %q, not %q"), arg_name, MP_QSTR_float, mp_obj_get_type(obj)->name); + } + return a_float; +} + +void mp_arg_validate_obj_float_range(mp_obj_t float_in, mp_int_t min, mp_int_t max, qstr arg_name) { + const mp_float_t f = mp_arg_validate_type_float(float_in, arg_name); + if (f < (mp_float_t)min || f > (mp_float_t)max) { + mp_raise_ValueError_varg(translate("%q must be %d-%d"), arg_name, min, max); + } +} + mp_float_t mp_arg_validate_obj_float_non_negative(mp_obj_t float_in, mp_float_t default_for_null, qstr arg_name) { const mp_float_t f = (float_in == MP_OBJ_NULL) ? default_for_null diff --git a/py/runtime.h b/py/runtime.h index d154772508..f7b96a27ae 100644 --- a/py/runtime.h +++ b/py/runtime.h @@ -103,6 +103,8 @@ mp_int_t mp_arg_validate_int_max(mp_int_t i, mp_int_t j, qstr arg_name); mp_int_t mp_arg_validate_int_range(mp_int_t i, mp_int_t min, mp_int_t max, qstr arg_name); #if MICROPY_PY_BUILTINS_FLOAT mp_float_t mp_arg_validate_obj_float_non_negative(mp_obj_t float_in, mp_float_t default_for_null, qstr arg_name); +void mp_arg_validate_obj_float_range(mp_obj_t float_in, mp_int_t min, mp_int_t max, qstr arg_name); +mp_float_t mp_arg_validate_type_float(mp_obj_t obj, qstr arg_name); #endif mp_uint_t mp_arg_validate_length_min(mp_uint_t length, mp_uint_t min, qstr arg_name); mp_uint_t mp_arg_validate_length_max(mp_uint_t length, mp_uint_t max, qstr arg_name);