Skip to content

Commit bce9341

Browse files
authored
Merge pull request RustPython#3728 from rng-dynamics/object-sizeof
Add `object.__sizeof__`
2 parents 59c0aeb + 1c734b0 commit bce9341

File tree

4 files changed

+13
-1
lines changed

4 files changed

+13
-1
lines changed

derive/src/pyclass.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@ fn generate_class_def(
210210
Some(v) => quote!(Some(#v) ),
211211
None => quote!(None),
212212
};
213+
let basicsize = quote!(std::mem::size_of::<#ident>());
213214
let is_pystruct = attrs.iter().any(|attr| {
214215
path_eq(&attr.path, "derive")
215216
&& if let Ok(Meta::List(l)) = attr.parse_meta() {
@@ -259,6 +260,7 @@ fn generate_class_def(
259260
const MODULE_NAME: Option<&'static str> = #module_name;
260261
const TP_NAME: &'static str = #module_class_name;
261262
const DOC: Option<&'static str> = #doc;
263+
const BASICSIZE: usize = #basicsize;
262264
}
263265

264266
impl ::rustpython_vm::class::StaticType for #ident {

vm/src/builtins/object.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,11 @@ impl PyBaseObject {
326326
fn hash(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyHash> {
327327
Self::slot_hash(&zelf, vm)
328328
}
329+
330+
#[pymethod(magic)]
331+
fn sizeof(zelf: PyObjectRef) -> usize {
332+
zelf.class().slots.basicsize
333+
}
329334
}
330335

331336
pub fn object_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyDictRef> {

vm/src/class.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ pub trait PyClassDef {
5858
const MODULE_NAME: Option<&'static str>;
5959
const TP_NAME: &'static str;
6060
const DOC: Option<&'static str> = None;
61+
const BASICSIZE: usize;
6162
}
6263

6364
impl<T> PyClassDef for PyRef<T>
@@ -68,6 +69,7 @@ where
6869
const MODULE_NAME: Option<&'static str> = T::MODULE_NAME;
6970
const TP_NAME: &'static str = T::TP_NAME;
7071
const DOC: Option<&'static str> = T::DOC;
72+
const BASICSIZE: usize = T::BASICSIZE;
7173
}
7274

7375
pub trait PyClassImpl: PyClassDef {
@@ -125,6 +127,7 @@ pub trait PyClassImpl: PyClassDef {
125127
let mut slots = PyTypeSlots {
126128
flags: Self::TP_FLAGS,
127129
name: PyRwLock::new(Some(Self::TP_NAME.to_owned())),
130+
basicsize: Self::BASICSIZE,
128131
doc: Self::DOC,
129132
..Default::default()
130133
};

vm/src/types/slot.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@ use std::{
2323
#[non_exhaustive]
2424
pub struct PyTypeSlots {
2525
pub name: PyRwLock<Option<String>>, // tp_name, not class name
26-
// tp_basicsize, tp_itemsize
26+
27+
pub basicsize: usize,
28+
// tp_itemsize
2729

2830
// Methods to implement standard operations
2931

0 commit comments

Comments
 (0)