summaryrefslogtreecommitdiff
path: root/vendor/github.com/lunixbochs/vtclean/io.go
blob: 31be0076a3e1ec74d03cf8dce7d230637f281bd6 (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
package vtclean

import (
	"bufio"
	"bytes"
	"io"
)

type reader struct {
	io.Reader
	scanner *bufio.Scanner
	buf     []byte

	color bool
}

func NewReader(r io.Reader, color bool) io.Reader {
	return &reader{Reader: r, color: color}
}

func (r *reader) scan() bool {
	if r.scanner == nil {
		r.scanner = bufio.NewScanner(r.Reader)
	}
	if len(r.buf) > 0 {
		return true
	}
	if r.scanner.Scan() {
		r.buf = []byte(Clean(r.scanner.Text(), r.color) + "\n")
		return true
	}
	return false
}

func (r *reader) fill(p []byte) int {
	n := len(r.buf)
	copy(p, r.buf)
	if len(p) < len(r.buf) {
		r.buf = r.buf[len(p):]
		n = len(p)
	} else {
		r.buf = nil
	}
	return n
}

func (r *reader) Read(p []byte) (int, error) {
	n := r.fill(p)
	if n < len(p) {
		if !r.scan() {
			if n == 0 {
				return 0, io.EOF
			}
			return n, nil
		}
		n += r.fill(p[n:])
	}
	return n, nil
}

type writer struct {
	io.Writer
	buf   []byte
	color bool
}

func NewWriter(w io.Writer, color bool) io.WriteCloser {
	return &writer{Writer: w, color: color}
}

func (w *writer) Write(p []byte) (int, error) {
	buf := append(w.buf, p...)
	lines := bytes.Split(buf, []byte("\n"))
	if len(lines) > 0 {
		last := len(lines) - 1
		w.buf = lines[last]
		count := 0
		for _, line := range lines[:last] {
			n, err := w.Writer.Write([]byte(Clean(string(line), w.color) + "\n"))
			count += n
			if err != nil {
				return count, err
			}
		}
	}
	return len(p), nil
}

func (w *writer) Close() error {
	cl := Clean(string(w.buf), w.color)
	_, err := w.Writer.Write([]byte(cl))
	return err
}