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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
use crate::parsers::parse_line_with_schema;
use crate::schema::DataType;
use deepsize::DeepSizeOf;
use serde::{Deserialize, Serialize};
use std::convert::{From, TryFrom};
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader, Seek, SeekFrom, Split};
use std::thread;
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, DeepSizeOf)]
pub enum Column {
Int(Vec<Option<i64>>),
Bool(Vec<Option<bool>>),
Float(Vec<Option<f64>>),
String(Vec<Option<String>>),
}
impl Column {
pub fn len(&self) -> usize {
match &self {
&Column::Bool(col) => col.len(),
&Column::Int(col) => col.len(),
&Column::Float(col) => col.len(),
&Column::String(col) => col.len(),
}
}
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, DeepSizeOf)]
pub enum Data {
String(String),
Int(i64),
Float(f64),
Bool(bool),
Null,
}
impl Data {
pub fn unwrap_string(&self) -> String {
match self {
Data::String(s) => s.clone(),
_ => panic!("unwrap error"),
}
}
pub fn unwrap_int(&self) -> i64 {
match self {
Data::Int(n) => *n,
_ => panic!("unwrap error"),
}
}
pub fn unwrap_float(&self) -> f64 {
match self {
Data::Float(n) => *n,
_ => panic!("unwrap error"),
}
}
pub fn unwrap_bool(&self) -> bool {
match self {
Data::Bool(n) => *n,
_ => panic!("unwrap error"),
}
}
}
fn init_columnar(schema: &[DataType]) -> Vec<Column> {
let mut result = Vec::with_capacity(schema.len() + 1);
for t in schema {
match t {
DataType::Bool => result.push(Column::Bool(Vec::new())),
DataType::Int => result.push(Column::Int(Vec::new())),
DataType::Float => result.push(Column::Float(Vec::new())),
DataType::String => result.push(Column::String(Vec::new())),
}
}
result
}
pub fn from_file(
file_path: &str,
schema: Vec<DataType>,
from: usize,
len: usize,
num_threads: usize,
) -> Vec<Column> {
let num_chars = if len == std::usize::MAX {
(std::fs::metadata(file_path).unwrap().len() - from as u64) as f64
} else {
len as f64
};
let step = (num_chars / num_threads as f64).ceil() as usize;
let f: File = File::open(file_path).unwrap();
let mut reader = BufReader::new(f);
let mut work: Vec<(usize, usize)> = Vec::with_capacity(num_threads + 1);
work.push((from, step));
let mut so_far = from;
let mut buffer = Vec::new();
for i in 1..num_threads {
so_far += step;
reader.seek(SeekFrom::Start(so_far as u64)).unwrap();
reader.read_until(b'\n', &mut buffer).unwrap();
work.push((so_far, step));
work.get_mut(i - 1).unwrap().1 += buffer.len() as usize + 1;
buffer.clear();
}
let mut threads = Vec::new();
for w in work {
let new_schema = schema.clone();
let f: File = File::open(file_path.clone()).unwrap();
let mut r = BufReader::new(f);
threads.push(thread::spawn(move || {
read_chunk(new_schema, &mut r, w.0, w.1)
}));
}
let mut parsed_data: Vec<Column> = init_columnar(&schema);
for t in threads {
let mut x: Vec<Column> = t.join().unwrap();
let iter = parsed_data.iter_mut().zip(x.iter_mut());
for (complete, partial) in iter {
match (complete, partial) {
(Column::Bool(c1), Column::Bool(c2)) => c1.append(c2),
(Column::Int(c1), Column::Int(c2)) => c1.append(c2),
(Column::Float(c1), Column::Float(c2)) => c1.append(c2),
(Column::String(c1), Column::String(c2)) => c1.append(c2),
_ => panic!("Unexpected result from thread"),
}
}
}
parsed_data
}
pub fn get(d: &[Column], col_idx: usize, row_idx: usize) -> Data {
match &d[col_idx] {
Column::Bool(b) => {
if let Some(val) = &b[row_idx] {
Data::Bool(*val)
} else {
Data::Null
}
}
Column::Int(b) => {
if let Some(val) = &b[row_idx] {
Data::Int(*val)
} else {
Data::Null
}
}
Column::Float(b) => {
if let Some(val) = &b[row_idx] {
Data::Float(*val)
} else {
Data::Null
}
}
Column::String(b) => {
if let Some(val) = &b[row_idx] {
Data::String(val.clone())
} else {
Data::Null
}
}
}
}
fn read_chunk<T>(
schema: Vec<DataType>,
reader: &mut T,
from: usize,
len: usize,
) -> Vec<Column>
where
T: BufRead + Seek,
{
reader.seek(SeekFrom::Start(from as u64)).unwrap();
let mut buffer = Vec::new();
let mut so_far = if from != 0 {
let l1_len = reader.read_until(b'\n', &mut buffer).unwrap();
buffer.clear();
l1_len
} else {
0
};
let mut parsed_data = init_columnar(&schema);
loop {
let line_len = reader.read_until(b'\n', &mut buffer).unwrap();
so_far += line_len;
if line_len == 0 || so_far >= len {
break;
}
match parse_line_with_schema(&buffer[..], &schema) {
None => {
buffer.clear();
continue;
}
Some(data) => {
let iter = data.iter().zip(parsed_data.iter_mut());
for (d, col) in iter {
match (d, col) {
(Data::Bool(b), Column::Bool(c)) => c.push(Some(*b)),
(Data::Int(i), Column::Int(c)) => c.push(Some(*i)),
(Data::Float(f), Column::Float(c)) => c.push(Some(*f)),
(Data::String(s), Column::String(c)) => {
c.push(Some(s.clone()))
}
(Data::Null, Column::Bool(c)) => c.push(None),
(Data::Null, Column::Int(c)) => c.push(None),
(Data::Null, Column::Float(c)) => c.push(None),
(Data::Null, Column::String(c)) => c.push(None),
_ => panic!("Parser Failed"),
}
}
}
}
buffer.clear();
}
parsed_data
}
pub struct SorTerator {
buf_reader: Split<BufReader<File>>,
chunk_size: usize,
schema: Vec<DataType>,
empty_col: Column,
}
impl SorTerator {
pub fn new(
file_name: &str,
schema: Vec<DataType>,
chunk_size: usize,
) -> Self {
SorTerator {
buf_reader: BufReader::new(File::open(file_name).unwrap())
.split(b'\n'),
empty_col: Column::Bool(Vec::new()),
chunk_size,
schema,
}
}
}
impl Iterator for SorTerator {
type Item = Vec<Column>;
fn next(&mut self) -> Option<Self::Item> {
let mut parsed_data = init_columnar(&self.schema);
while let Some(Ok(line)) = self.buf_reader.next() {
match parse_line_with_schema(&line, &self.schema) {
None => continue,
Some(data) => {
let iter = data.iter().zip(parsed_data.iter_mut());
for (d, col) in iter {
match (d, col) {
(Data::Bool(b), Column::Bool(c)) => {
c.push(Some(*b))
}
(Data::Int(i), Column::Int(c)) => c.push(Some(*i)),
(Data::Float(f), Column::Float(c)) => {
c.push(Some(*f))
}
(Data::String(s), Column::String(c)) => {
c.push(Some(s.clone()))
}
(Data::Null, Column::Bool(c)) => c.push(None),
(Data::Null, Column::Int(c)) => c.push(None),
(Data::Null, Column::Float(c)) => c.push(None),
(Data::Null, Column::String(c)) => c.push(None),
_ => panic!("Parser Failed"),
}
}
}
}
if let Some(column) = parsed_data.get(0) {
if column.len() == self.chunk_size {
return Some(parsed_data);
}
}
}
if parsed_data.get(0).unwrap_or(&self.empty_col).len() > 0 {
Some(parsed_data)
} else {
None
}
}
}
impl From<Vec<Option<bool>>> for Column {
fn from(v: Vec<Option<bool>>) -> Column {
Column::Bool(v)
}
}
impl From<Vec<Option<i64>>> for Column {
fn from(v: Vec<Option<i64>>) -> Column {
Column::Int(v)
}
}
impl From<Vec<Option<f64>>> for Column {
fn from(v: Vec<Option<f64>>) -> Column {
Column::Float(v)
}
}
impl From<Vec<Option<String>>> for Column {
fn from(v: Vec<Option<String>>) -> Column {
Column::String(v)
}
}
impl TryFrom<Column> for Vec<Option<bool>> {
type Error = &'static str;
fn try_from(c: Column) -> Result<Self, Self::Error> {
match c {
Column::Bool(col) => Ok(col),
_ => Err("The given column was not of type bool"),
}
}
}
impl TryFrom<Column> for Vec<Option<i64>> {
type Error = &'static str;
fn try_from(c: Column) -> Result<Self, Self::Error> {
match c {
Column::Int(col) => Ok(col),
_ => Err("The given column was not of type int"),
}
}
}
impl TryFrom<Column> for Vec<Option<f64>> {
type Error = &'static str;
fn try_from(c: Column) -> Result<Self, Self::Error> {
match c {
Column::Float(col) => Ok(col),
_ => Err("The given column was not of type float"),
}
}
}
impl TryFrom<Column> for Vec<Option<String>> {
type Error = &'static str;
fn try_from(c: Column) -> Result<Self, Self::Error> {
match c {
Column::String(col) => Ok(col),
_ => Err("The given column was not of type String"),
}
}
}
impl fmt::Display for Data {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Data::String(s) => write!(f, "\"{}\"", s),
Data::Int(n) => write!(f, "{}", n),
Data::Float(fl) => write!(f, "{}", fl),
Data::Bool(true) => write!(f, "1"),
Data::Bool(false) => write!(f, "0"),
Data::Null => write!(f, "Missing Value"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn test_read_file() {
let schema = vec![DataType::String, DataType::Bool];
let expected_col1 = Column::String(vec![
Some("1".to_string()),
Some("a".to_string()),
Some("1.2".to_string()),
]);
let expected_col2 = Column::Bool(vec![Some(true), Some(false), None]);
let expected = vec![expected_col1, expected_col2];
let mut input = Cursor::new(b"<1><1>\n<a><0>\n<1.2><>");
let parsed1: Vec<Column> =
read_chunk(schema.clone(), &mut input, 0, 26);
assert_eq!(parsed1, expected.clone());
let mut larger_input = Cursor::new(b"<1><1>\n<a><0>\n<1.2><>\n<no><1>");
let parsed2: Vec<Column> =
read_chunk(schema.clone(), &mut larger_input, 0, 27);
assert_eq!(parsed2, expected.clone());
let mut input_skipped_l1 =
Cursor::new(b"<b><1>\n<1><1>\n<a><0>\n<1.2><>");
let parsed3: Vec<Column> =
read_chunk(schema.clone(), &mut input_skipped_l1, 3, 26);
assert_eq!(parsed3, expected.clone());
let mut input_with_invalid =
Cursor::new(b"<1><1>\n<a><0>\n<c><1.2>\n<1.2><>");
let parsed4: Vec<Column> =
read_chunk(schema.clone(), &mut input_with_invalid, 0, 32);
assert_eq!(parsed4, expected.clone());
}
#[test]
fn test_sor_terator() {
let schema = vec![
DataType::Bool,
DataType::Int,
DataType::Float,
DataType::String,
];
let mut sor_terator =
SorTerator::new("tests/sor_terator.sor", schema, 10);
let mut chunk = sor_terator.next();
assert_eq!(chunk.unwrap().get(0).unwrap().len(), 10);
chunk = sor_terator.next();
assert_eq!(chunk.unwrap().get(0).unwrap().len(), 5);
chunk = sor_terator.next();
assert!(chunk.is_none());
}
}