Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions vm/src/builtins/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::{
class::PyClassImpl,
function::Either,
function::{FuncArgs, PyArithmeticValue, PyComparisonValue},
types::PyComparisonOp,
types::{PyComparisonOp, SizeOf},
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine,
};

Expand All @@ -25,7 +25,7 @@ impl PyPayload for PyBaseObject {
}
}

#[pyimpl(flags(BASETYPE))]
#[pyimpl(flags(BASETYPE), with(SizeOf))]
impl PyBaseObject {
/// Create and return a new object. See help(type) for accurate signature.
#[pyslot]
Expand Down Expand Up @@ -331,10 +331,11 @@ impl PyBaseObject {
fn hash(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyHash> {
Self::slot_hash(&zelf, vm)
}
}

#[pymethod(magic)]
fn sizeof(zelf: PyObjectRef) -> usize {
zelf.class().slots.basicsize
impl SizeOf for PyBaseObject {
fn sizeof(zelf: &Py<Self>) -> PyResult<usize> {
Ok(zelf.class().slots.basicsize)
}
}

Expand Down
23 changes: 23 additions & 0 deletions vm/src/types/slot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ pub struct PyTypeSlots {
pub iter: AtomicCell<Option<IterFunc>>,
pub iternext: AtomicCell<Option<IterNextFunc>>,

pub sizeof: AtomicCell<Option<SizeOfFunc>>,

// Flags to define presence of optional/expanded features
pub flags: PyTypeFlags,

Expand Down Expand Up @@ -162,6 +164,7 @@ pub(crate) type NewFunc = fn(PyTypeRef, FuncArgs, &VirtualMachine) -> PyResult;
pub(crate) type InitFunc = fn(PyObjectRef, FuncArgs, &VirtualMachine) -> PyResult<()>;
pub(crate) type DelFunc = fn(&PyObject, &VirtualMachine) -> PyResult<()>;
pub(crate) type AsSequenceFunc = fn(&PyObject, &VirtualMachine) -> &'static PySequenceMethods;
pub(crate) type SizeOfFunc = fn(&PyObject, &VirtualMachine) -> PyResult<usize>;

// slot_sq_length
pub(crate) fn slot_length(obj: &PyObject, vm: &VirtualMachine) -> PyResult<usize> {
Expand Down Expand Up @@ -945,3 +948,23 @@ where
unreachable!("slot_iter is implemented");
}
}

#[pyimpl]
pub trait SizeOf: PyPayload {
#[pyslot]
fn slot_sizeof(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<usize> {
if let Some(zelf) = zelf.downcast_ref() {
Self::sizeof(zelf)
} else {
Err(vm.new_type_error("unexpected payload for __sizeof__".to_owned()))
}
}

fn sizeof(zelf: &Py<Self>) -> PyResult<usize>;

#[inline]
#[pymethod]
fn __sizeof__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Self::slot_sizeof(&zelf, vm).to_pyresult(vm)
}
}