-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
91 lines (67 loc) · 1.9 KB
/
lib.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
//DEBUG:
#![allow(dead_code)]
use anyhow::Result;
use std::fmt;
use std::{fmt::{Display, Formatter}, ops::{Deref, DerefMut}};
use parse::split_columns;
pub mod stdin;
pub mod parse;
// default separator is one or more consecutive space characters
//NOTE: to setup a global var for separator ?
pub const DEFAULT_SEP_PATTERN: &str = r"[\s]+";
// TAB as default separator
// pub const DEFAULT_SEP_PATTERN: &str = r"[\t]+";
//FIX:? fix tests for tab separator pattern and default separator pattern
// pub mod patterns {
// use super::DEFAULT_SEP_PATTERN;
// use std::sync::Arc;
//
// pub static CUR_SEP_PATTERN: Arc<&str> = Arc::new("lol");
// }
pub type Column = Vec<String>;
#[derive(Clone, Debug)]
pub struct Columns(Vec<Column>);
impl Display for Columns {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut res = String::new();
let nrows = self[0].len();
let mut i = 0;
while i < nrows {
for col in self.deref() {
assert!(i < col.len(), "column number mismatch");
res.push_str(&format!("{} ", col[i]))
}
// remove last space
res.pop();
if i < nrows-1 {
res.push('\n');
}
i+=1;
}
write!(f, "{}", res)
}
}
impl DerefMut for Columns {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Deref for Columns {
type Target = Vec<Vec<String>>;
fn deref(&self) -> &Vec<Vec<String>> {
&self.0
}
}
// build Columns from &str
impl TryFrom<&str> for Columns {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self> {
split_columns(value, DEFAULT_SEP_PATTERN)
}
}
impl TryFrom<Vec<Vec<String>>> for Columns {
type Error = anyhow::Error;
fn try_from(value: Vec<Vec<String>>) -> Result<Self> {
Ok(Columns(value))
}
}