|
4 | 4 | #include "PyFloat.hpp" |
5 | 5 | #include "TypeError.hpp" |
6 | 6 | #include "ValueError.hpp" |
7 | | -#include "interpreter/Interpreter.hpp" |
| 7 | +#include "runtime/PyByteArray.hpp" |
8 | 8 | #include "runtime/PyObject.hpp" |
9 | 9 | #include "runtime/Value.hpp" |
10 | 10 | #include "types/api.hpp" |
11 | 11 | #include "types/builtin.hpp" |
12 | | -#include "utilities.hpp" |
13 | 12 | #include "vm/VM.hpp" |
14 | 13 |
|
| 14 | +#include <gmpxx.h> |
| 15 | + |
15 | 16 | namespace py { |
16 | 17 |
|
17 | 18 | template<> PyInteger *as(PyObject *obj) |
@@ -266,6 +267,24 @@ PyResult<PyObject *> PyInteger::from_bytes(PyType *type, PyTuple *args, PyDict * |
266 | 267 | return result; |
267 | 268 | } |
268 | 269 |
|
| 270 | +PyResult<PyObject *> PyInteger::__round__(PyObject *ndigits_obj) const |
| 271 | +{ |
| 272 | + if (!ndigits_obj || ndigits_obj == py_none()) { return PyInteger::create(as_big_int()); } |
| 273 | + |
| 274 | + if (!ndigits_obj->type()->issubclass(types::integer())) { |
| 275 | + return Err(type_error( |
| 276 | + "'{}' object cannot be interpreted as an integer", ndigits_obj->type()->name())); |
| 277 | + } |
| 278 | + |
| 279 | + auto ndigits = static_cast<const PyInteger &>(*ndigits_obj).as_big_int(); |
| 280 | + |
| 281 | + if (ndigits >= 0) { return PyInteger::create(as_big_int()); } |
| 282 | + |
| 283 | + auto result = m_value - (m_value % Number{ BigIntType{ 10 } }.exp(Number{ -ndigits })); |
| 284 | + |
| 285 | + return PyInteger::create(std::visit([](auto el) { return BigIntType{ el }; }, result.value)); |
| 286 | +} |
| 287 | + |
269 | 288 | int64_t PyInteger::as_i64() const |
270 | 289 | { |
271 | 290 | ASSERT(std::holds_alternative<BigIntType>(m_value.value)); |
@@ -298,6 +317,7 @@ namespace { |
298 | 317 | .def("bit_length", &PyInteger::bit_length) |
299 | 318 | .def("bit_count", &PyInteger::bit_count) |
300 | 319 | .def("to_bytes", &PyInteger::to_bytes) |
| 320 | + .def("__round__", &PyInteger::__round__) |
301 | 321 | .classmethod("from_bytes", &PyInteger::from_bytes) |
302 | 322 | .type); |
303 | 323 | } |
|
0 commit comments