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
use csv::StringRecordIter;
use std::cmp::PartialEq;
use std::collections::HashMap;

use crate::Row;

/// A structure for keeping relationship between the headers and their positions
#[derive(Debug, Clone, PartialEq)]
pub struct Headers {
    indexes: HashMap<String, usize>,
    names: Row,
}

impl Headers {
    /// Creates an empty Headers object.
    pub fn new() -> Headers {
        Headers {
            indexes: HashMap::new(),
            names: Row::new(),
        }
    }

    /// Retrieves a field from a row given it's header name
    ///
    /// ```rust
    /// use csvsc::{Headers, Row};
    ///
    /// let headers: Headers = Row::from(vec!["id", "val"]).into();
    /// let row = Row::from(vec!["1", "40"]);
    ///
    /// assert_eq!(headers.get_field(&row, "id"), Some("1"));
    /// assert_eq!(headers.get_field(&row, "val"), Some("40"));
    /// assert_eq!(headers.get_field(&row, "foo"), None);
    /// ```
    pub fn get_field<'r>(&self, row: &'r Row, field: &str) -> Option<&'r str> {
        self.index(field).and_then(|i| row.get(i))
    }

    /// Adds a new header.
    ///
    /// Returns wether the header was added or not.
    ///
    /// ```rust
    /// use csvsc::{Headers, Row};
    ///
    /// let mut h: Headers = Row::from(vec!["name"]).into();
    ///
    /// h.add("value");
    ///
    /// assert_eq!(h, Row::from(vec!["name", "value"]).into());
    ///
    /// assert!(!h.add("name"));
    /// assert_eq!(h, Row::from(vec!["name", "value"]).into());
    /// ```
    pub fn add(&mut self, colname: &str) -> bool {
        if self.indexes.contains_key(colname) {
            return false;
        }

        self.names.push_field(colname);
        self.indexes
            .insert(colname.to_string(), self.names.len() - 1);

        true
    }

    pub fn len(&self) -> usize {
        self.names.len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn as_row(&self) -> &Row {
        &self.names
    }

    /// Consumes this Headers object and returns the underlaying Row containing
    /// the names.
    pub fn into_row(self) -> Row {
        self.names
    }

    /// Obtains the index of the given field in the headers
    pub fn index(&self, field: &str) -> Option<usize> {
        self.indexes.get(field).copied()
    }

    pub fn contains_key(&self, field: &str) -> bool {
        self.indexes.contains_key(field)
    }

    pub fn iter(&self) -> StringRecordIter {
        self.names.iter()
    }
}

impl PartialEq<Headers> for Row {
    fn eq(&self, other: &Headers) -> bool {
        self == other.as_row()
    }
}

impl From<Row> for Headers {
    fn from(row: Row) -> Headers {
        let mut indexes = HashMap::new();

        for (index, entry) in row.iter().enumerate() {
            indexes.insert(entry.to_string(), index);
        }

        Headers {
            indexes,
            names: row,
        }
    }
}

impl Default for Headers {
    fn default() -> Self {
        Self::new()
    }
}