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
use crate::csv::CsvEncoding;
use crate::csv_core::parser::next_line_position;
use lazy_static::lazy_static;
use polars_core::datatypes::PlHashSet;
use polars_core::prelude::*;
use regex::{Regex, RegexBuilder};
use std::borrow::Cow;
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
pub(crate) fn init_csv_reader<R: Read>(
reader: R,
has_header: bool,
delimiter: u8,
comment_char: Option<u8>,
) -> csv::Reader<R> {
let mut reader_builder = csv::ReaderBuilder::new();
reader_builder.has_headers(has_header);
reader_builder.delimiter(delimiter);
reader_builder.comment(comment_char);
reader_builder.flexible(true);
reader_builder.from_reader(reader)
}
pub(crate) fn get_file_chunks(
bytes: &[u8],
n_threads: usize,
expected_fields: usize,
delimiter: u8,
) -> Vec<(usize, usize)> {
let mut last_pos = 0;
let total_len = bytes.len();
let chunk_size = total_len / n_threads;
let mut offsets = Vec::with_capacity(n_threads);
for _ in 0..n_threads {
let search_pos = last_pos + chunk_size;
if search_pos >= bytes.len() {
break;
}
let end_pos = match next_line_position(&bytes[search_pos..], expected_fields, delimiter) {
Some(pos) => search_pos + pos,
None => {
break;
}
};
offsets.push((last_pos, end_pos + 1));
last_pos = end_pos;
}
offsets.push((last_pos, total_len));
offsets
}
lazy_static! {
static ref DECIMAL_RE: Regex = Regex::new(r"^\s*-?(\d+\.\d+)$").unwrap();
static ref INTEGER_RE: Regex = Regex::new(r"^\s*-?(\d+)$").unwrap();
static ref BOOLEAN_RE: Regex = RegexBuilder::new(r"^\s*(true)$|^(false)$")
.case_insensitive(true)
.build()
.unwrap();
}
fn infer_field_schema(string: &str) -> DataType {
if string.starts_with('"') {
return DataType::Utf8;
}
if BOOLEAN_RE.is_match(string) {
DataType::Boolean
} else if DECIMAL_RE.is_match(string) {
DataType::Float64
} else if INTEGER_RE.is_match(string) {
DataType::Int64
} else {
DataType::Utf8
}
}
#[inline]
pub(crate) fn parse_bytes_with_encoding(bytes: &[u8], encoding: CsvEncoding) -> Result<Cow<str>> {
let s = match encoding {
CsvEncoding::Utf8 => std::str::from_utf8(bytes)
.map_err(anyhow::Error::from)?
.into(),
CsvEncoding::LossyUtf8 => String::from_utf8_lossy(bytes),
};
Ok(s)
}
pub fn infer_file_schema<R: Read + Seek>(
reader: &mut R,
delimiter: u8,
max_read_records: Option<usize>,
has_header: bool,
schema_overwrite: Option<&Schema>,
skip_rows: usize,
comment_char: Option<u8>,
) -> Result<(Schema, usize)> {
let mut reader = BufReader::new(reader);
let mut line = String::new();
for _ in 0..skip_rows {
reader.read_line(&mut line)?;
line.clear()
}
let encoding = CsvEncoding::LossyUtf8;
let csv_reader = init_csv_reader(reader, false, delimiter, comment_char);
let mut records = csv_reader.into_byte_records();
let header_length;
let headers: Vec<String> = if let Some(byterecord) = records.next() {
let byterecord = byterecord.map_err(anyhow::Error::from)?;
header_length = byterecord.len();
if has_header {
byterecord
.iter()
.map(|slice| {
let s = parse_bytes_with_encoding(slice, encoding)?;
Ok(s.into())
})
.collect::<Result<_>>()?
} else {
(0..header_length)
.map(|i| format!("column_{}", i + 1))
.collect()
}
} else {
return Err(PolarsError::NoData("empty csv".into()));
};
let mut column_types: Vec<PlHashSet<DataType>> = vec![PlHashSet::new(); header_length];
let mut nulls: Vec<bool> = vec![false; header_length];
let mut records_count = 0;
let mut fields = Vec::with_capacity(header_length);
let records_ref = &mut records;
for result in records_ref.take(max_read_records.unwrap_or(usize::MAX)) {
let record = result.map_err(anyhow::Error::from)?;
records_count += 1;
for i in 0..header_length {
if let Some(slice) = record.get(i) {
if slice.is_empty() {
nulls[i] = true;
} else {
let s = parse_bytes_with_encoding(slice, encoding)?;
column_types[i].insert(infer_field_schema(&s));
}
}
}
}
for i in 0..header_length {
let possibilities = &column_types[i];
let field_name = &headers[i];
if let Some(schema_overwrite) = schema_overwrite {
if let Ok(field_ovw) = schema_overwrite.field_with_name(field_name) {
fields.push(field_ovw.clone());
continue;
}
}
match possibilities.len() {
1 => {
for dtype in possibilities.iter() {
fields.push(Field::new(field_name, dtype.clone()));
}
}
2 => {
if possibilities.contains(&DataType::Int64)
&& possibilities.contains(&DataType::Float64)
{
fields.push(Field::new(field_name, DataType::Float64));
} else {
fields.push(Field::new(field_name, DataType::Utf8));
}
}
_ => fields.push(Field::new(field_name, DataType::Utf8)),
}
}
let csv_reader = records.into_reader();
csv_reader.into_inner().seek(SeekFrom::Start(0))?;
Ok((Schema::new(fields), records_count))
}
#[cfg(feature = "decompress")]
pub(crate) fn decompress(bytes: &[u8]) -> Option<Vec<u8>> {
let gzip: [u8; 2] = [31, 139];
let zlib0: [u8; 2] = [0x78, 0x01];
let zlib1: [u8; 2] = [0x78, 0x9C];
let zlib2: [u8; 2] = [0x78, 0xDA];
if bytes.starts_with(&gzip) {
let mut out = Vec::with_capacity(bytes.len());
let mut decoder = flate2::read::GzDecoder::new(bytes);
decoder.read_to_end(&mut out).ok()?;
Some(out)
} else if bytes.starts_with(&zlib0) || bytes.starts_with(&zlib1) || bytes.starts_with(&zlib2) {
let mut out = Vec::with_capacity(bytes.len());
let mut decoder = flate2::read::ZlibDecoder::new(bytes);
decoder.read_to_end(&mut out).ok()?;
Some(out)
} else {
None
}
}
#[cfg(feature = "decompress")]
pub(crate) fn bytes_to_schema(
bytes: &[u8],
delimiter: u8,
has_header: bool,
skip_rows: usize,
comment_char: Option<u8>,
) -> Result<SchemaRef> {
let mut r = std::io::Cursor::new(&bytes);
Ok(Arc::from(
infer_file_schema(
&mut r,
delimiter,
Some(100),
has_header,
None,
skip_rows,
comment_char,
)?
.0,
))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_get_file_chunks() {
let path = "../../examples/aggregate_multiple_files_in_chunks/datasets/foods1.csv";
let s = std::fs::read_to_string(path).unwrap();
let bytes = s.as_bytes();
assert!((get_file_chunks(bytes, 10, 4, b',').len() as i32 - 10).abs() <= 1);
assert!((get_file_chunks(bytes, 8, 4, b',').len() as i32 - 8).abs() <= 1);
}
}