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
use crate::chopper::chopper::Source;
use crate::chopper::types::FieldType;
use crate::error::{CliResult, Error};
use crate::source::csv_configs::CSVOutputConfig;
use std::collections::HashMap;

pub fn parse_into_delimiter(str: &str) -> CliResult<u8> {
    /* Code in this function was adapted from public domain xsv project. */
    match &*str {
        r"\t" => Ok(b'\t'),
        s => {
            if s.len() != 1 {
                return Err(Error::from(format!(
                    "Error: specified delimiter '{}' is not a single ASCII character.",
                    s
                )));
            }
            let c = s.chars().next().unwrap();
            if c.is_ascii() {
                Ok(c as u8)
            } else {
                Err(Error::from(format!(
                    "Error: specified delimiter '{}' is not an ASCII character.",
                    c
                )))
            }
        }
    }
}

pub fn create_csv_output_config_from_source(
    sources: &mut Vec<Box<dyn Source>>,
    delimiter: &str,
) -> CSVOutputConfig {
    let mut some_sources_have_native_timestamps = false;
    for source in sources {
        if source.has_native_timestamp_column() {
            some_sources_have_native_timestamps = true;
            break;
        }
    }
    CSVOutputConfig::new(delimiter, some_sources_have_native_timestamps)
}

pub fn guess_delimiter(row: &str, possible_delimiters: &[u8]) -> u8 {
    assert_ne!(possible_delimiters.len(), 0);

    let mut counts: HashMap<u8, u32> = HashMap::new();

    for d in possible_delimiters {
        counts.insert(*d, 0);
    }

    for c in row.chars() {
        counts.entry(c as u8).and_modify(|count| *count += 1);
    }

    let mut sorted = possible_delimiters.to_vec();
    sorted.sort_by(|a, b| counts[b].cmp(&counts[a]));

    *sorted.get(0).unwrap()
}

/// we want to be on the conservative side, since we'd rather not silently lose data by
/// skipping the first data row by mistaking it for header;
/// returning false when confused is safest thing - in worst case parsing will fail
/// later and user will have to manually configure the csv file format
pub fn guess_has_header(line1: Option<&String>, line2: Option<&String>, delimiter: u8) -> bool {
    let line1 = match line1 {
        None => return false,
        Some(line) => line,
    };
    let line2 = match line2 {
        None => return false,
        Some(line) => line,
    };

    let line1: Vec<FieldType> = line1
        .split(delimiter as char)
        .map(|s| guess_type(s.trim()))
        .collect();
    let line2: Vec<FieldType> = line2
        .split(delimiter as char)
        .map(|s| guess_type(s.trim()))
        .collect();

    line1 != line2
}

pub fn guess_common_type(field_types: &[FieldType]) -> FieldType {
    if field_types.is_empty() {
        return FieldType::String;
    }

    let mut guess = type_upconvert(field_types[0]);

    for &field_type in field_types {
        if guess == FieldType::String {
            return guess;
        }

        let field_type = type_upconvert(field_type);
        guess = match field_type {
            FieldType::Double => FieldType::Double,
            FieldType::Long => guess, // at this point guess can be only long or double, and we want double to take precedence over long
            _ => return FieldType::String,
        }
    }

    guess
}

fn type_upconvert(field_type: FieldType) -> FieldType {
    match field_type {
        FieldType::Boolean => FieldType::String,
        FieldType::ByteBuf => FieldType::String,
        FieldType::String => FieldType::String,
        FieldType::Byte | FieldType::Char | FieldType::Short | FieldType::Int | FieldType::Long => {
            FieldType::Long
        }
        FieldType::Float | FieldType::Double => FieldType::Double,
    }
}

/// current limitations: only long, double, and string; rust format only
pub fn guess_type(str: &str) -> FieldType {
    if str.parse::<i64>().is_ok() {
        return FieldType::Long;
    };
    if str.parse::<f64>().is_ok() {
        return FieldType::Double;
    }
    FieldType::String
}

#[cfg(test)]
mod tests {
    use crate::chopper::types::FieldType;
    use crate::util::csv_util::{guess_has_header, guess_type};

    #[test]
    fn test_guess_has_header() {
        assert!(guess_has_header(
            Some(&"zzz".to_string()),
            Some(&"123".to_string()),
            b','
        ));
        assert!(!guess_has_header(
            Some(&"zzz".to_string()),
            Some(&"zzz".to_string()),
            b','
        ));
        assert!(!guess_has_header(
            Some(&"123".to_string()),
            Some(&"123".to_string()),
            b','
        ));
        assert!(guess_has_header(
            Some(&"zzz".to_string()),
            Some(&"123".to_string()),
            b','
        ));
        assert!(guess_has_header(
            Some(&"zzz,zzz,zzz,zzz".to_string()),
            Some(&"zzz,zzz,123,zzz".to_string()),
            b','
        ));
        assert!(!guess_has_header(
            Some(&"zzz,zzz,123,zzz".to_string()),
            Some(&"zzz,zzz, 123 ,zzz".to_string()),
            b','
        ));
        assert!(guess_has_header(
            Some(&"123".to_string()),
            Some(&"123.4".to_string()),
            b','
        ));
    }

    #[test]
    fn test_guess_type() {
        assert_eq!(guess_type("zzz"), FieldType::String);
        assert_eq!(guess_type("123"), FieldType::Long);
        assert_eq!(guess_type("123.4"), FieldType::Double);
    }
}