aboutsummaryrefslogtreecommitdiffstats
path: root/skate/xio/util.go
blob: 9f6cc26f16bcf33abb8d5be926e48c788189d7ad (plain)
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
package xio

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
	"sync"
)

type Encoder interface {
	Encode(interface{}) error
}

type SafeEncoder struct {
	sync.Mutex
	enc Encoder
}

func NewSafeEncoder(enc Encoder) *SafeEncoder {
	return &SafeEncoder{enc: enc}
}

func (s *SafeEncoder) Encode(v interface{}) error {
	s.Lock()
	defer s.Unlock()
	return s.enc.Encode(v)
}

// SingleWriter makes any writer thread safe.
type SingleWriter struct {
	sync.Mutex
	w io.Writer
}

// NewSingleWriter returns an io.Writer that can be safely accessed by multiple
// goroutines.
func NewSingleWriter(w io.Writer) *SingleWriter {
	return &SingleWriter{w: w}
}

// Write wraps the underlying writer and gives exclusive access.
func (w *SingleWriter) Write(p []byte) (n int, err error) {
	w.Lock()
	defer w.Unlock()
	return w.w.Write(p)
}

// OpenTwo opens two files. The caller needs to check for a single error only.
func OpenTwo(f0, f1 string) (g0, g1 *os.File, err error) {
	if g0, err = os.Open(f0); err != nil {
		return nil, nil, err
	}
	if g1, err = os.Open(f1); err != nil {
		return nil, nil, err
	}
	return g0, g1, nil
}

// TabsToMapFile turns two columns from a tabular file into a map.
func TabsToMapFile(filename, sep string, kCol, vCol int) (map[string]string, error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return TabsToMap(f, sep, kCol, vCol)
}

// TabsToMap read from a reader and turns values from kCol, vCol columns
// (1-indexed) into a map.
func TabsToMap(r io.Reader, sep string, kCol, vCol int) (map[string]string, error) {
	var (
		br         = bufio.NewReader(r)
		m          = make(map[string]string)
		line, k, v string
		fields     []string
		err        error
	)
	for {
		line, err = br.ReadString('\n')
		if err == io.EOF {
			return m, nil
		}
		if err != nil {
			return nil, err
		}
		fields = strings.Split(line, sep)
		if len(fields) > kCol-1 && len(fields) > vCol-1 {
			k = strings.TrimSpace(fields[kCol-1])
			v = strings.TrimSpace(fields[vCol-1])
			m[k] = v
		} else {
			return nil, fmt.Errorf("invalid line: %v (%v fields, %v, %v)", line, len(fields), kCol, vCol)
		}
	}
	return m, nil
}