Skip to content

Commit cb4d66b

Browse files
committed
Added bit length method on int type.
1 parent f6cced5 commit cb4d66b

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

tests/snippets/basic_types.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,10 @@
4141
a = complex(2, 4)
4242
assert type(a) is complex
4343
assert type(a + a) is complex
44+
45+
46+
a = 12345
47+
48+
b = a*a*a*a*a*a*a*a
49+
assert b.bit_length() == 109
50+

vm/src/obj/objint.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,13 @@ fn int_and(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
363363
}
364364
}
365365

366+
fn int_bit_length(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
367+
arg_check!(vm, args, required = [(i, Some(vm.ctx.int_type()))]);
368+
let v = get_value(i);
369+
let bits = v.bits();
370+
Ok(vm.ctx.new_int(bits.to_bigint().unwrap()))
371+
}
372+
366373
pub fn init(context: &PyContext) {
367374
let ref int_type = context.int_type;
368375
int_type.set_attr("__eq__", context.new_rustfunc(int_eq));
@@ -385,4 +392,5 @@ pub fn init(context: &PyContext) {
385392
int_type.set_attr("__sub__", context.new_rustfunc(int_sub));
386393
int_type.set_attr("__truediv__", context.new_rustfunc(int_truediv));
387394
int_type.set_attr("__xor__", context.new_rustfunc(int_xor));
395+
int_type.set_attr("bit_length", context.new_rustfunc(int_bit_length));
388396
}

vm/src/stdlib/json.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,10 @@ impl<'s> serde::Serialize for PyObjectSerializer<'s> {
4949
} else if objtype::isinstance(self.pyobject, &self.ctx.bool_type()) {
5050
serializer.serialize_bool(objbool::get_value(self.pyobject))
5151
} else if objtype::isinstance(self.pyobject, &self.ctx.int_type()) {
52-
// TODO: Figure out how to use the serialize trait on BigInt:
53-
serializer.serialize_i32(objint::get_value(self.pyobject).to_i32().unwrap())
52+
let v = objint::get_value(self.pyobject);
53+
serializer.serialize_i64(v.to_i64().unwrap())
54+
// Allthough this may seem nice, it does not give the right result:
55+
// v.serialize(serializer)
5456
} else if objtype::isinstance(self.pyobject, &self.ctx.list_type()) {
5557
let elements = objlist::get_elements(self.pyobject);
5658
serialize_seq_elements(serializer, elements)

0 commit comments

Comments
 (0)