aboutsummaryrefslogtreecommitdiffstats
path: root/pktline/encoder.go
blob: b439c54210b8eb31db9a829ca9427a145466ff7e (plain) (blame)
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
package pktline

import (
	"errors"
	"fmt"
	"strings"
)

var (
	ErrOverflow = errors.New("unexepected string length")
)

type Encoder struct {
	lines []string
}

func NewEncoder() *Encoder {
	return &Encoder{make([]string, 0)}
}

func (e *Encoder) AddLine(line string) error {
	le, err := EncodeFromString(line + "\n")
	if err != nil {
		return err
	}

	e.lines = append(e.lines, le)
	return nil
}

func (e *Encoder) AddFlush() {
	e.lines = append(e.lines, "0000")
}

func (e *Encoder) GetReader() *strings.Reader {
	data := strings.Join(e.lines, "")

	return strings.NewReader(data)
}

func EncodeFromString(line string) (string, error) {
	return Encode([]byte(line))
}

func Encode(line []byte) (string, error) {
	if line == nil {
		return "0000", nil
	}

	l := len(line) + HEADER_LENGTH
	if l > MAX_LENGTH {
		return "", ErrOverflow
	}

	return fmt.Sprintf("%04x%s", l, line), nil
}