Skip to content

Commit f86ddc3

Browse files
committed
Fix memoryview.obj misimplementation.
The memoryview skeleton did not correctly assign the "obj" attribute; The "obj" attribute was assigned to the memoryview class and not the memryview object, leading to a funny bug that can be reproduced as follows: ```python m1 = memoryview(b'1234') m2 = memoryview(b'abcd') print(m1.obj) ``` the result would be the value inside `m2` instead that of `m1`
1 parent 0c9d3c8 commit f86ddc3

File tree

1 file changed

+23
-17
lines changed

1 file changed

+23
-17
lines changed

vm/src/obj/objmemory.rs

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,36 @@
11
use crate::obj::objbyteinner::try_as_byte;
22
use crate::obj::objtype::PyClassRef;
3-
use crate::pyobject::{PyContext, PyObjectRef, PyRef, PyResult, PyValue};
3+
use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
44
use crate::vm::VirtualMachine;
55

6-
pub type PyMemoryViewRef = PyRef<PyMemoryView>;
76

7+
#[pyclass(name = "memoryview")]
88
#[derive(Debug)]
99
pub struct PyMemoryView {
10-
obj: PyObjectRef,
10+
obj_ref: PyObjectRef,
1111
}
1212

13+
pub type PyMemoryViewRef = PyRef<PyMemoryView>;
14+
15+
16+
#[pyimpl]
1317
impl PyMemoryView {
1418
pub fn get_obj_value(&self) -> Option<Vec<u8>> {
15-
try_as_byte(&self.obj)
19+
try_as_byte(&self.obj_ref)
20+
}
21+
22+
#[pymethod(name = "__new__")]
23+
fn new(
24+
cls: PyClassRef,
25+
bytes_object: PyObjectRef,
26+
vm: &VirtualMachine,
27+
) -> PyResult<PyMemoryViewRef> {
28+
PyMemoryView { obj_ref: bytes_object.clone() }.into_ref_with_type(vm, cls)
29+
}
30+
31+
#[pyproperty]
32+
fn obj(&self, __vm: &VirtualMachine) -> PyObjectRef {
33+
self.obj_ref.clone()
1634
}
1735
}
1836

@@ -22,18 +40,6 @@ impl PyValue for PyMemoryView {
2240
}
2341
}
2442

25-
pub fn new_memory_view(
26-
cls: PyClassRef,
27-
bytes_object: PyObjectRef,
28-
vm: &VirtualMachine,
29-
) -> PyResult<PyMemoryViewRef> {
30-
vm.set_attr(cls.as_object(), "obj", bytes_object.clone())?;
31-
PyMemoryView { obj: bytes_object }.into_ref_with_type(vm, cls)
32-
}
33-
3443
pub fn init(ctx: &PyContext) {
35-
let memoryview_type = &ctx.memoryview_type;
36-
extend_class!(ctx, memoryview_type, {
37-
"__new__" => ctx.new_rustfunc(new_memory_view)
38-
});
44+
PyMemoryView::extend_class(ctx, &ctx.memoryview_type)
3945
}

0 commit comments

Comments
 (0)