-
Notifications
You must be signed in to change notification settings - Fork 314
/
util.go
45 lines (38 loc) · 885 Bytes
/
util.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
package util
import (
"bufio"
"bytes"
"encoding/gob"
"os"
"strings"
"github.com/pkg/errors"
)
func ReadLinesFromFile(fh *os.File) ([]string, error) {
lines := []string{}
reader := bufio.NewReader(fh)
line, err := reader.ReadString('\n')
for err == nil {
lines = append(lines, strings.TrimRight(line, "\n"))
line, err = reader.ReadString('\n')
}
return lines, nil
}
func WriteLinesToFile(ofh *os.File, lines []string) error {
for _, line := range lines {
if _, err := ofh.WriteString(line + "\n"); err != nil {
return errors.Wrap(err, "Cannot write output file")
}
}
return nil
}
func LinesToBytes(lines []string) []byte {
buf := &bytes.Buffer{}
gob.NewEncoder(buf).Encode(lines)
return buf.Bytes()
}
func BytesToLines(buf []byte) []string {
reader := bytes.NewReader(buf)
lines := []string{}
gob.NewDecoder(reader).Decode(&lines)
return lines
}