-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathencoding_csv.go
More file actions
45 lines (42 loc) · 808 Bytes
/
encoding_csv.go
File metadata and controls
45 lines (42 loc) · 808 Bytes
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
package stable
import (
"encoding/csv"
"errors"
"io"
"strings"
)
var (
// ErrMalformedCSV malformed csv
ErrMalformedCSV error = errors.New("'stable' error. malformed csv")
)
// CSVToTable convert csv encoded string to *STable
func CSVToTable(data string) (*STable, error) {
if len(data) == 0 {
return nil, ErrMalformedCSV
}
r := csv.NewReader(strings.NewReader(data))
lines := make([][]string, 0, 16)
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
lines = append(lines, record)
}
if len(lines) < 1 {
return nil, ErrMalformedCSV
}
t := New("csv")
t.AddFields(lines[0]...)
for _, r := range lines[1:] {
inter := make([]interface{}, len(r))
for i, v := range r {
inter[i] = v
}
t.Row(inter...)
}
return t, nil
}