Debian Codegraph @

rust-ext/src/compressor_multi.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::{
9 buffers::{BufferSegment, ZstdBufferWithSegments, ZstdBufferWithSegmentsCollection},
10 compression_dict::ZstdCompressionDict,
11 compression_parameters::CCtxParams,
12 exceptions::ZstdError,
13 zstd_safe::CCtx,
14 },
15 pyo3::{
16 buffer::PyBuffer,
17 exceptions::{PyTypeError, PyValueError},
18 prelude::*,
19 types::{PyBytes, PyList, PyTuple},
20 },
21 rayon::prelude::*,
22 };
23
24 struct DataSource<'a> {
25 data: &'a [u8],
26 }
27
28 pub fn multi_compress_to_buffer(
29 py: Python,
30 params: &CCtxParams,
31 dict: &Option<Py<ZstdCompressionDict>>,
32 data: &Bound<'_, PyAny>,
33 threads: isize,
34 ) -> PyResult<ZstdBufferWithSegmentsCollection> {
35 let threads = if threads < 0 {
36 num_cpus::get()
37 } else if threads < 2 {
38 1
39 } else {
40 threads as _
41 };
42
43 let mut sources = vec![];
44 let mut total_source_size = 0;
45
46 if let Ok(buffer) = data.downcast::<ZstdBufferWithSegments>() {
47 sources.reserve_exact(buffer.borrow().segments.len());
48
49 let borrow = buffer.borrow();
50
51 for i in 0..borrow.segments.len() {
52 let slice = borrow.get_segment_slice(py, i);
53
54 sources.push(DataSource { data: slice });
55 total_source_size += slice.len();
56 }
57 } else if let Ok(collection) = data.downcast::<ZstdBufferWithSegmentsCollection>() {
58 sources.reserve_exact(collection.len()?);
59
60 for buffer_obj in &collection.borrow().buffers {
61 let buffer = buffer_obj.downcast_bound::<ZstdBufferWithSegments>(py)?;
62 let borrow = buffer.borrow();
63
64 for i in 0..borrow.segments.len() {
65 let slice = borrow.get_segment_slice(py, i);
66
67 sources.push(DataSource { data: slice });
68 total_source_size += slice.len();
69 }
70 }
71 } else if let Ok(list) = data.extract::<Bound<'_, PyList>>() {
72 sources.reserve_exact(list.len());
73
74 for (i, item) in list.iter().enumerate() {
75 let buffer: PyBuffer<u8> = PyBuffer::get(&item.as_borrowed())
76 .map_err(|_| PyTypeError::new_err(format!("item {} not a bytes like object", i)))?;
77
78 let slice = unsafe {
79 std::slice::from_raw_parts(buffer.buf_ptr() as *const _, buffer.len_bytes())
80 };
81
82 sources.push(DataSource { data: slice });
83 total_source_size += slice.len();
84 }
85 } else {
86 return Err(PyTypeError::new_err(
87 "argument must be list of BufferWithSegments",
88 ));
89 }
90
91 if sources.is_empty() {
92 return Err(PyValueError::new_err("no source elements found"));
93 }
94
95 if total_source_size == 0 {
96 return Err(PyValueError::new_err("source elements are empty"));
97 }
98
99 compress_from_datasources(py, params, dict, sources, threads)
100 }
101
102 /// Holds results of an individual compression operation.
103 struct WorkerResult {
104 source_offset: usize,
105 error: Option<&'static str>,
106 data: Option<Vec<u8>>,
107 }
108
109 fn compress_from_datasources(
110 py: Python,
111 params: &CCtxParams,
112 dict: &Option<Py<ZstdCompressionDict>>,
113 sources: Vec<DataSource>,
114 thread_count: usize,
115 ) -> PyResult<ZstdBufferWithSegmentsCollection> {
116 // More threads than inputs makes no sense.
117 let thread_count = std::cmp::min(thread_count, sources.len());
118
119 // TODO lower thread count when input size is too small and threads
120 // would add overhead.
121
122 let mut cctxs = Vec::with_capacity(thread_count);
123 let results = std::sync::Mutex::new(Vec::with_capacity(sources.len()));
124
125 // TODO there are tons of inefficiencies in this implementation compared
126 // to the C backend.
127
128 for _ in 0..thread_count {
129 let cctx = CCtx::new().map_err(|msg| ZstdError::new_err(msg))?;
130
131 cctx.set_parameters(params).map_err(|msg| {
132 ZstdError::new_err(format!("could not set compression parameters: {}", msg))
133 })?;
134
135 if let Some(dict) = dict {
136 dict.borrow(py).load_into_cctx(&cctx)?;
137 }
138
139 cctxs.push(cctx);
140 }
141
142 let pool = rayon::ThreadPoolBuilder::new()
143 .num_threads(thread_count)
144 .build()
145 .map_err(|err| ZstdError::new_err(format!("error initializing thread pool: {}", err)))?;
146
147 pool.install(|| {
148 sources.par_iter().enumerate().for_each(|(index, source)| {
149 let thread_index = pool.current_thread_index().unwrap();
150
151 let cctx = &cctxs[thread_index];
152
153 let mut result = WorkerResult {
154 source_offset: index,
155 error: None,
156 data: None,
157 };
158
159 match cctx.compress(source.data) {
160 Ok(chunk) => {
161 result.data = Some(chunk);
162 }
163 Err(msg) => {
164 result.error = Some(msg);
165 }
166 }
167
168 // TODO we can do better than a shared lock.
169 results.lock().unwrap().push(result);
170 });
171 });
172
173 // Need to sort results by their input order or else results aren't
174 // deterministic.
175 results
176 .lock()
177 .unwrap()
178 .sort_by(|a, b| a.source_offset.cmp(&b.source_offset));
179
180 // TODO this is horribly inefficient due to memory copies.
181 let els = PyTuple::new(
182 py,
183 results
184 .lock()
185 .unwrap()
186 .iter()
187 .map(|result| {
188 if let Some(msg) = result.error {
189 return Err(ZstdError::new_err(format!(
190 "error compressing item {}: {}",
191 result.source_offset, msg
192 )));
193 }
194
195 let data = result.data.as_ref().unwrap();
196 let chunk = PyBytes::new(py, data);
197 let segments = vec![BufferSegment {
198 offset: 0,
199 length: data.len() as _,
200 }];
201
202 let segments = unsafe {
203 PyBytes::from_ptr(
204 py,
205 segments.as_ptr() as *const _,
206 segments.len() * std::mem::size_of::<BufferSegment>(),
207 )
208 };
209 let segments_buffer = PyBuffer::get(&segments)?;
210
211 Py::new(
212 py,
213 ZstdBufferWithSegments::new(py, &chunk, segments_buffer)?,
214 )
215 })
216 .collect::<PyResult<Vec<_>>>()?,
217 )?;
218
219 ZstdBufferWithSegmentsCollection::new(py, &els)
220 }