Debian Codegraph @

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