This repository has been archived by the owner on Aug 24, 2021. It is now read-only.
/
csv.go
125 lines (101 loc) · 1.97 KB
/
csv.go
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
package csv
import (
"fmt"
"io"
"unsafe"
"github.com/353solutions/carrow"
)
/*
#cgo pkg-config: arrow plasma
#include "csv.h"
*/
import "C"
var (
reg = &Registry{reg: make(map[int]*inStream)}
)
type inStream struct {
rdr io.Reader
pos int
buf []byte
closed bool
}
type Registry struct {
reg map[int]*inStream
nextID int
}
func (r *Registry) Alloc(is *inStream) int {
id := r.nextID
r.nextID++
r.reg[id] = is
return id
}
func (r *Registry) Get(id int) *inStream {
return r.reg[id]
}
func (r *Registry) Release(id int) {
delete(r.reg, id)
}
//export istream_read
func istream_read(id int, size int) C.csv_res_t {
res := C.csv_res_t{nil, 0, nil}
is := reg.Get(id)
if is == nil {
err := fmt.Sprintf("%d: unknown id", id)
res.err = C.CString(err)
return res
}
if size > len(is.buf) {
is.buf = make([]byte, size)
}
n, err := is.rdr.Read(is.buf)
if err != nil {
if err == io.EOF {
is.closed = true
} else {
res.err = C.CString(err.Error())
return res
}
}
res.size = C.ulonglong(n)
res.data = C.CBytes(is.buf[:n])
return res
}
//export istream_tell
func istream_tell(id int) C.csv_res_t {
res := C.csv_res_t{nil, 0, nil}
is := reg.Get(id)
if is == nil {
err := fmt.Sprintf("%d: unknown id", id)
res.err = C.CString(err)
return res
}
res.size = C.ulonglong(is.pos)
return res
}
//export istream_closed
func istream_closed(id int) C.csv_res_t {
res := C.csv_res_t{nil, 0, nil}
is := reg.Get(id)
if is == nil {
err := fmt.Sprintf("%d: unknown id", id)
res.err = C.CString(err)
return res
}
if is.closed {
res.size = 1
}
return res
}
// Reads a CSV data from rdr, returns a *carrow.Table
func Read(rdr io.Reader) (*carrow.Table, error) {
is := &inStream{rdr: rdr}
id := reg.Alloc(is)
defer reg.Release(id)
res := C.csv_read(C.longlong(id))
if res.err != nil {
// TODO: Free res.err?
return nil, fmt.Errorf(C.GoString(res.err))
}
ptr := unsafe.Pointer(res.table)
return carrow.NewTableFromPtr(ptr), nil
}