Debian Codegraph @

contrib/python-zstandard/rust-ext/src/buffers.rs

raw
1 // Copyright (c) 2021-present, Gregory Szorc
2 // All rights reserved.
3 //
4 // This software may be modified and distributed under the terms
5 // of the BSD license. See the LICENSE file for details.
6
7 use {
8 crate::exceptions::ZstdError,
9 pyo3::{
10 buffer::PyBuffer,
11 exceptions::{PyIndexError, PyTypeError, PyValueError},
12 ffi::Py_buffer,
13 prelude::*,
14 types::{PyBytes, PyTuple},
15 },
16 };
17
18 #[repr(C)]
19 #[derive(Clone, Debug)]
20 pub(crate) struct BufferSegment {
21 pub offset: u64,
22 pub length: u64,
23 }
24
25 #[pyclass(module = "zstandard.backend_rust", name = "BufferSegment")]
26 pub struct ZstdBufferSegment {
27 /// The object backing storage. For reference counting.
28 _parent: PyObject,
29 /// PyBuffer into parent object.
30 buffer: PyBuffer<u8>,
31 /// Offset of segment within data.
32 offset: usize,
33 /// Length of segment within data.
34 len: usize,
35 }
36
37 impl ZstdBufferSegment {
38 pub fn as_slice(&self) -> &[u8] {
39 unsafe {
40 std::slice::from_raw_parts(self.buffer.buf_ptr().add(self.offset) as *const _, self.len)
41 }
42 }
43 }
44
45 #[pymethods]
46 impl ZstdBufferSegment {
47 // PySequenceProtocol.
48 fn __len__(&self) -> usize {
49 self.len
50 }
51
52 // PyBufferProtocol.
53 fn bf_getbuffer(slf: PyRefMut<Self>, view: PyObject, flags: i32) -> PyResult<()> {
54 let slice = slf.as_slice();
55
56 if unsafe {
57 pyo3::ffi::PyBuffer_FillInfo(
58 view.as_ptr() as *mut Py_buffer,
59 slf.as_ptr(),
60 slice.as_ptr() as *mut _,
61 slice.len() as _,
62 1,
63 flags,
64 )
65 } != 0
66 {
67 Err(PyErr::fetch(slf.py()))
68 } else {
69 Ok(())
70 }
71 }
72
73 #[allow(unused_variables)]
74 fn bf_releasebuffer(slf: PyRefMut<Self>, view: PyObject) {}
75
76 // Our methods.
77
78 #[getter]
79 fn offset(&self) -> usize {
80 self.offset
81 }
82
83 fn tobytes<'p>(&self, py: Python<'p>) -> PyResult<Bound<'p, PyBytes>> {
84 Ok(PyBytes::new_bound(py, self.as_slice()))
85 }
86 }
87
88 #[pyclass(module = "zstandard.backend_rust", name = "BufferSegments")]
89 pub struct ZstdBufferSegments {
90 parent: PyObject,
91 }
92
93 #[pymethods]
94 impl ZstdBufferSegments {
95 // PyBufferProtocol.
96 fn bf_getbuffer(slf: PyRefMut<Self>, view: PyObject, flags: i32) -> PyResult<()> {
97 let py = slf.py();
98
99 let parent = slf.parent.downcast_bound::<ZstdBufferWithSegments>(py)?;
100
101 if unsafe {
102 pyo3::ffi::PyBuffer_FillInfo(
103 view.as_ptr() as *mut Py_buffer,
104 slf.as_ptr(),
105 parent.borrow().segments.as_ptr() as *const _ as *mut _,
106 (parent.borrow().segments.len() * std::mem::size_of::<BufferSegment>()) as isize,
107 1,
108 flags,
109 )
110 } != 0
111 {
112 Err(PyErr::fetch(py))
113 } else {
114 Ok(())
115 }
116 }
117
118 #[allow(unused_variables)]
119 fn bf_releasebuffer(slf: PyRefMut<Self>, view: PyObject) {}
120 }
121
122 #[pyclass(module = "zstandard.backend_rust", name = "BufferWithSegments")]
123 pub struct ZstdBufferWithSegments {
124 source: PyObject,
125 pub(crate) buffer: PyBuffer<u8>,
126 pub(crate) segments: Vec<BufferSegment>,
127 }
128
129 impl ZstdBufferWithSegments {
130 fn as_slice(&self) -> &[u8] {
131 unsafe {
132 std::slice::from_raw_parts(self.buffer.buf_ptr() as *const _, self.buffer.len_bytes())
133 }
134 }
135
136 pub fn get_segment_slice<'p>(&self, _py: Python<'p>, i: usize) -> &'p [u8] {
137 let segment = &self.segments[i];
138
139 unsafe {
140 std::slice::from_raw_parts(
141 self.buffer.buf_ptr().add(segment.offset as usize) as *const _,
142 segment.length as usize,
143 )
144 }
145 }
146 }
147
148 #[pymethods]
149 impl ZstdBufferWithSegments {
150 // PySequenceProtocol.
151
152 fn __len__(&self) -> usize {
153 self.segments.len()
154 }
155
156 fn __getitem__(&self, key: isize) -> PyResult<ZstdBufferSegment> {
157 let py = unsafe { Python::assume_gil_acquired() };
158
159 if key < 0 {
160 return Err(PyIndexError::new_err("offset must be non-negative"));
161 }
162
163 let key = key as usize;
164
165 if key >= self.segments.len() {
166 return Err(PyIndexError::new_err(format!(
167 "offset must be less than {}",
168 self.segments.len()
169 )));
170 }
171
172 let segment = &self.segments[key];
173
174 Ok(ZstdBufferSegment {
175 _parent: self.source.clone_ref(py),
176 buffer: PyBuffer::get_bound(self.source.downcast_bound(py)?)?,
177 offset: segment.offset as _,
178 len: segment.length as _,
179 })
180 }
181
182 // PyBufferProtocol.
183 fn bf_getbuffer(slf: PyRefMut<Self>, view: PyObject, flags: i32) -> PyResult<()> {
184 if unsafe {
185 pyo3::ffi::PyBuffer_FillInfo(
186 view.as_ptr() as *mut Py_buffer,
187 slf.as_ptr(),
188 slf.buffer.buf_ptr(),
189 slf.buffer.len_bytes() as _,
190 1,
191 flags,
192 )
193 } != 0
194 {
195 Err(PyErr::fetch(slf.py()))
196 } else {
197 Ok(())
198 }
199 }
200
201 #[allow(unused_variables)]
202 fn bf_releasebuffer(slf: PyRefMut<Self>, view: PyObject) {}
203
204 // Our methods.
205
206 #[new]
207 pub fn new(py: Python, data: &Bound<'_, PyAny>, segments: PyBuffer<u8>) -> PyResult<Self> {
208 let data_buffer = PyBuffer::get_bound(&data.as_borrowed())?;
209
210 if segments.len_bytes() % std::mem::size_of::<BufferSegment>() != 0 {
211 return Err(PyValueError::new_err(format!(
212 "segments array size is not a multiple of {}",
213 std::mem::size_of::<BufferSegment>()
214 )));
215 }
216
217 let segments_slice: &[BufferSegment] = unsafe {
218 std::slice::from_raw_parts(
219 segments.buf_ptr() as *const _,
220 segments.len_bytes() / std::mem::size_of::<BufferSegment>(),
221 )
222 };
223
224 // Make a copy of the segments data. It is cheap to do so and is a
225 // guard against caller changing offsets, which has security implications.
226 let segments = segments_slice.to_vec();
227
228 // Validate segments data, as blindly trusting it could lead to
229 // arbitrary memory access.
230 for segment in &segments {
231 if segment.offset + segment.length > data_buffer.len_bytes() as _ {
232 return Err(PyValueError::new_err(
233 "offset within segments array references memory outside buffer",
234 ));
235 }
236 }
237
238 Ok(Self {
239 source: data.into_py(py),
240 buffer: data_buffer,
241 segments,
242 })
243 }
244
245 #[getter]
246 fn size(&self) -> usize {
247 self.buffer.len_bytes()
248 }
249
250 fn segments(slf: PyRef<Self>, py: Python) -> PyResult<ZstdBufferSegments> {
251 Ok(ZstdBufferSegments {
252 // TODO surely there is a better way to cast self to PyObject?
253 parent: unsafe { Py::from_borrowed_ptr(py, slf.as_ptr()) },
254 })
255 }
256
257 fn tobytes<'p>(&self, py: Python<'p>) -> PyResult<Bound<'p, PyBytes>> {
258 Ok(PyBytes::new_bound(py, self.as_slice()))
259 }
260 }
261
262 #[pyclass(
263 module = "zstandard.backend_rust",
264 name = "BufferWithSegmentsCollection"
265 )]
266 pub struct ZstdBufferWithSegmentsCollection {
267 // Py<ZstdBufferWithSegments>.
268 pub(crate) buffers: Vec<PyObject>,
269 first_elements: Vec<usize>,
270 }
271
272 #[pymethods]
273 impl ZstdBufferWithSegmentsCollection {
274 // PySequenceProtocol.
275
276 fn __len__(&self) -> usize {
277 self.first_elements.last().unwrap().clone()
278 }
279
280 fn __getitem__(&self, key: isize) -> PyResult<ZstdBufferSegment> {
281 let py = unsafe { Python::assume_gil_acquired() };
282
283 if key < 0 {
284 return Err(PyIndexError::new_err("offset must be non-negative"));
285 }
286
287 let key = key as usize;
288
289 if key >= self.__len__() {
290 return Err(PyIndexError::new_err(format!(
291 "offset must be less than {}",
292 self.__len__()
293 )));
294 }
295
296 let mut offset = 0;
297 for (buffer_index, segment) in self.buffers.iter().enumerate() {
298 if key < self.first_elements[buffer_index] {
299 if buffer_index > 0 {
300 offset = self.first_elements[buffer_index - 1];
301 }
302
303 let item = segment.downcast_bound::<ZstdBufferWithSegments>(py)?;
304
305 return item.borrow().__getitem__((key - offset) as isize);
306 }
307 }
308
309 Err(ZstdError::new_err(
310 "error resolving segment; this should not happen",
311 ))
312 }
313
314 #[new]
315 #[pyo3(signature = (* py_args))]
316 pub fn new(py: Python, py_args: &Bound<'_, PyTuple>) -> PyResult<Self> {
317 if py_args.is_empty() {
318 return Err(PyValueError::new_err("must pass at least 1 argument"));
319 }
320
321 let mut buffers = Vec::with_capacity(py_args.len());
322 let mut first_elements = Vec::with_capacity(py_args.len());
323 let mut offset = 0;
324
325 for item in py_args {
326 let item = item.downcast::<ZstdBufferWithSegments>().map_err(|_| {
327 PyTypeError::new_err("arguments must be BufferWithSegments instances")
328 })?;
329 let segment = item.borrow();
330
331 if segment.segments.is_empty() || segment.buffer.len_bytes() == 0 {
332 return Err(PyValueError::new_err(
333 "ZstdBufferWithSegments cannot be empty",
334 ));
335 }
336
337 offset += segment.segments.len();
338
339 buffers.push(item.to_object(py));
340 first_elements.push(offset);
341 }
342
343 Ok(Self {
344 buffers,
345 first_elements,
346 })
347 }
348
349 fn size(&self, py: Python) -> PyResult<usize> {
350 let mut size = 0;
351
352 for buffer in &self.buffers {
353 let item = buffer.downcast_bound::<ZstdBufferWithSegments>(py)?;
354
355 for segment in &item.borrow().segments {
356 size += segment.length as usize;
357 }
358 }
359
360 Ok(size)
361 }
362 }
363
364 pub(crate) fn init_module(module: &Bound<'_, PyModule>) -> PyResult<()> {
365 module.add_class::<ZstdBufferSegment>()?;
366 module.add_class::<ZstdBufferSegments>()?;
367 module.add_class::<ZstdBufferWithSegments>()?;
368 module.add_class::<ZstdBufferWithSegmentsCollection>()?;
369
370 Ok(())
371 }