Skip to content

Commit 3f2b050

Browse files
committed
memoryview validation
1 parent 42b9462 commit 3f2b050

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

vm/src/builtins/memory.rs

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,24 @@ impl SlotConstructor for PyMemoryView {
5858

5959
#[pyimpl(with(Hashable, Comparable, AsBuffer, SlotConstructor))]
6060
impl PyMemoryView {
61+
#[cfg(debug_assertions)]
62+
fn validate(self) -> Self {
63+
let options = &self.buffer.options;
64+
let bytes_len = options.len * options.itemsize;
65+
let buffer_len = self.buffer.internal.obj_bytes().len();
66+
let t1 = self.range.len() == bytes_len;
67+
let t2 = buffer_len >= self.range.end;
68+
let t3 = buffer_len >= self.range.start + bytes_len;
69+
assert!(t1);
70+
assert!(t2);
71+
assert!(t3);
72+
self
73+
}
74+
#[cfg(not(debug_assertions))]
75+
fn validate(self) -> Self {
76+
self
77+
}
78+
6179
fn parse_format(format: &str, vm: &VirtualMachine) -> PyResult<FormatSpec> {
6280
FormatSpec::parse(format, vm)
6381
}
@@ -77,7 +95,8 @@ impl PyMemoryView {
7795
step: 1,
7896
format_spec,
7997
hash: OnceCell::new(),
80-
})
98+
}
99+
.validate())
81100
}
82101

83102
pub fn from_buffer_range(
@@ -96,7 +115,8 @@ impl PyMemoryView {
96115
step: 1,
97116
format_spec,
98117
hash: OnceCell::new(),
99-
})
118+
}
119+
.validate())
100120
}
101121

102122
fn as_contiguous(&self) -> Option<BorrowedValue<[u8]>> {
@@ -270,6 +290,7 @@ impl PyMemoryView {
270290
format_spec,
271291
hash: OnceCell::new(),
272292
}
293+
.validate()
273294
.into_object(vm));
274295
}
275296

@@ -315,6 +336,7 @@ impl PyMemoryView {
315336
format_spec,
316337
hash: OnceCell::new(),
317338
}
339+
.validate()
318340
.into_object(vm));
319341
};
320342

@@ -345,6 +367,7 @@ impl PyMemoryView {
345367
format_spec,
346368
hash: OnceCell::new(),
347369
}
370+
.validate()
348371
.into_object(vm))
349372
}
350373

@@ -538,6 +561,7 @@ impl PyMemoryView {
538561
hash: OnceCell::new(),
539562
..*zelf
540563
}
564+
.validate()
541565
.into_ref(vm))
542566
}
543567

@@ -607,6 +631,7 @@ impl PyMemoryView {
607631
hash: OnceCell::new(),
608632
..*zelf
609633
}
634+
.validate()
610635
.into_ref(vm))
611636
}
612637

0 commit comments

Comments
 (0)