This repository has been archived by the owner on Feb 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 221
/
mmap.rs
327 lines (274 loc) · 9.67 KB
/
mmap.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use std::collections::VecDeque;
use crate::array::{Array, ListArray, Offset};
use crate::datatypes::DataType;
use crate::error::Error;
use crate::io::ipc::read::OutOfSpecKind;
use crate::io::ipc::read::{IpcBuffer, Node};
use crate::types::NativeType;
use super::{try_from, ArrowArray, InternalArrowArray};
#[allow(dead_code)]
struct PrivateData<T> {
// the owner of the pointers' regions
data: T,
buffers_ptr: Box<[*const std::os::raw::c_void]>,
children_ptr: Box<[*mut ArrowArray]>,
dictionary_ptr: Option<*mut ArrowArray>,
}
fn get_buffer_bounds(buffers: &mut VecDeque<IpcBuffer>) -> Result<(usize, usize), Error> {
let buffer = buffers
.pop_front()
.ok_or_else(|| Error::from(OutOfSpecKind::ExpectedBuffer))?;
let offset: usize = buffer
.offset()
.try_into()
.map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;
let length: usize = buffer
.length()
.try_into()
.map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;
Ok((offset, length))
}
fn get_buffer<'a, T: NativeType>(
data: &'a [u8],
block_offset: usize,
buffers: &mut VecDeque<IpcBuffer>,
num_rows: usize,
) -> Result<&'a [u8], Error> {
let (offset, length) = get_buffer_bounds(buffers)?;
// verify that they are in-bounds
let values = data
.get(block_offset + offset..block_offset + offset + length)
.ok_or_else(|| Error::OutOfSpec("buffer out of bounds".to_string()))?;
// validate alignment
let v: &[T] = bytemuck::try_cast_slice(values)
.map_err(|_| Error::OutOfSpec("buffer not aligned for mmap".to_string()))?;
if v.len() < num_rows {
return Err(Error::OutOfSpec(
"buffer's length is too small in mmap".to_string(),
));
}
Ok(values)
}
fn get_validity<'a>(
data: &'a [u8],
block_offset: usize,
buffers: &mut VecDeque<IpcBuffer>,
null_count: usize,
) -> Result<Option<&'a [u8]>, Error> {
let validity = get_buffer_bounds(buffers)?;
let (offset, length) = validity;
Ok(if null_count > 0 {
// verify that they are in-bounds and get its pointer
Some(
data.get(block_offset + offset..block_offset + offset + length)
.ok_or_else(|| Error::OutOfSpec("buffer out of bounds".to_string()))?,
)
} else {
None
})
}
fn create_array<
T: Clone + AsRef<[u8]>,
I: Iterator<Item = Option<*const u8>>,
II: Iterator<Item = ArrowArray>,
>(
data: T,
num_rows: usize,
null_count: usize,
buffers: I,
children: II,
) -> ArrowArray {
let buffers_ptr = buffers
.map(|maybe_buffer| match maybe_buffer {
Some(b) => b as *const std::os::raw::c_void,
None => std::ptr::null(),
})
.collect::<Box<[_]>>();
let n_buffers = buffers_ptr.len() as i64;
let children_ptr = children
.map(|child| Box::into_raw(Box::new(child)))
.collect::<Box<_>>();
let n_children = children_ptr.len() as i64;
let mut private_data = Box::new(PrivateData::<T> {
data,
buffers_ptr,
children_ptr,
dictionary_ptr: None,
});
ArrowArray {
length: num_rows as i64,
null_count: null_count as i64,
offset: 0, // IPC files are by definition not offset
n_buffers,
n_children,
buffers: private_data.buffers_ptr.as_mut_ptr(),
children: private_data.children_ptr.as_mut_ptr(),
dictionary: private_data.dictionary_ptr.unwrap_or(std::ptr::null_mut()),
release: Some(release::<T>),
private_data: Box::into_raw(private_data) as *mut ::std::os::raw::c_void,
}
}
/// callback used to drop [`ArrowArray`] when it is exported
unsafe extern "C" fn release<T>(array: *mut ArrowArray) {
if array.is_null() {
return;
}
let array = &mut *array;
// take ownership of `private_data`, therefore dropping it
let private = Box::from_raw(array.private_data as *mut PrivateData<T>);
/*for child in private.children_ptr.iter() {
let _ = Box::from_raw(*child);
}*/
if let Some(ptr) = private.dictionary_ptr {
let _ = Box::from_raw(ptr);
}
array.release = None;
}
fn mmap_binary<O: Offset, T: Clone + AsRef<[u8]>>(
data: T,
node: &Node,
block_offset: usize,
buffers: &mut VecDeque<IpcBuffer>,
) -> Result<ArrowArray, Error> {
let num_rows: usize = node
.length()
.try_into()
.map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;
let null_count: usize = node
.null_count()
.try_into()
.map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;
let data_ref = data.as_ref();
let validity = get_validity(data_ref, block_offset, buffers, null_count)?.map(|x| x.as_ptr());
let offsets = get_buffer::<O>(data_ref, block_offset, buffers, num_rows + 1)?.as_ptr();
let values = get_buffer::<u8>(data_ref, block_offset, buffers, 0)?.as_ptr();
// NOTE: offsets and values invariants are _not_ validated
Ok(create_array(
data,
num_rows,
null_count,
[validity, Some(offsets), Some(values)].into_iter(),
[].into_iter(),
))
}
fn mmap_boolean<T: Clone + AsRef<[u8]>>(
data: T,
node: &Node,
block_offset: usize,
buffers: &mut VecDeque<IpcBuffer>,
) -> Result<ArrowArray, Error> {
let num_rows: usize = node
.length()
.try_into()
.map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;
let null_count: usize = node
.null_count()
.try_into()
.map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;
let data_ref = data.as_ref();
let validity = get_validity(data_ref, block_offset, buffers, null_count)?.map(|x| x.as_ptr());
let values = get_buffer_bounds(buffers)?;
let (offset, length) = values;
// verify that they are in-bounds and get its pointer
let values = data_ref[block_offset + offset..block_offset + offset + length].as_ptr();
Ok(create_array(
data,
num_rows,
null_count,
[validity, Some(values)].into_iter(),
[].into_iter(),
))
}
fn mmap_primitive<P: NativeType, T: Clone + AsRef<[u8]>>(
data: T,
node: &Node,
block_offset: usize,
buffers: &mut VecDeque<IpcBuffer>,
) -> Result<ArrowArray, Error> {
let data_ref = data.as_ref();
let num_rows: usize = node
.length()
.try_into()
.map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;
let null_count: usize = node
.null_count()
.try_into()
.map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;
let validity = get_validity(data_ref, block_offset, buffers, null_count)?.map(|x| x.as_ptr());
let values = get_buffer::<P>(data_ref, block_offset, buffers, num_rows)?.as_ptr();
Ok(create_array(
data,
num_rows,
null_count,
[validity, Some(values)].into_iter(),
[].into_iter(),
))
}
fn mmap_list<O: Offset, T: Clone + AsRef<[u8]>>(
data: T,
node: &Node,
block_offset: usize,
data_type: &DataType,
field_nodes: &mut VecDeque<Node>,
buffers: &mut VecDeque<IpcBuffer>,
) -> Result<ArrowArray, Error> {
let child = ListArray::<O>::try_get_child(data_type)?.data_type();
let num_rows: usize = node
.length()
.try_into()
.map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;
let null_count: usize = node
.null_count()
.try_into()
.map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;
let data_ref = data.as_ref();
let validity = get_validity(data_ref, block_offset, buffers, null_count)?.map(|x| x.as_ptr());
let offsets = get_buffer::<O>(data_ref, block_offset, buffers, num_rows + 1)?.as_ptr();
let values = get_array(data.clone(), block_offset, child, field_nodes, buffers)?;
// NOTE: offsets and values invariants are _not_ validated
Ok(create_array(
data,
num_rows,
null_count,
[validity, Some(offsets)].into_iter(),
[values].into_iter(),
))
}
fn get_array<T: Clone + AsRef<[u8]>>(
data: T,
block_offset: usize,
data_type: &DataType,
field_nodes: &mut VecDeque<Node>,
buffers: &mut VecDeque<IpcBuffer>,
) -> Result<ArrowArray, Error> {
use crate::datatypes::PhysicalType::*;
let node = field_nodes
.pop_front()
.ok_or_else(|| Error::from(OutOfSpecKind::ExpectedBuffer))?;
match data_type.to_physical_type() {
Boolean => mmap_boolean(data, &node, block_offset, buffers),
Primitive(p) => with_match_primitive_type!(p, |$T| {
mmap_primitive::<$T, _>(data, &node, block_offset, buffers)
}),
Utf8 | Binary => mmap_binary::<i32, _>(data, &node, block_offset, buffers),
LargeBinary | LargeUtf8 => mmap_binary::<i64, _>(data, &node, block_offset, buffers),
List => mmap_list::<i32, _>(data, &node, block_offset, data_type, field_nodes, buffers),
LargeList => {
mmap_list::<i64, _>(data, &node, block_offset, data_type, field_nodes, buffers)
}
_ => todo!(),
}
}
/// Maps a memory region to an [`Array`].
pub(crate) unsafe fn mmap<T: Clone + AsRef<[u8]>>(
data: T,
block_offset: usize,
data_type: DataType,
field_nodes: &mut VecDeque<Node>,
buffers: &mut VecDeque<IpcBuffer>,
) -> Result<Box<dyn Array>, Error> {
let array = get_array(data, block_offset, &data_type, field_nodes, buffers)?;
// The unsafety comes from the fact that `array` is not necessarily valid -
// the IPC file may be corrupted (e.g. invalid offsets or non-utf8 data)
unsafe { try_from(InternalArrowArray::new(array, data_type)) }
}