aboutsummaryrefslogtreecommitdiffstats
path: root/formats/pktline/encoder.go
blob: bd0ab758d701ff802df363c90c1cea457596a4fc (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
57
58
59
60
61
62
63
64
package pktline

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

var (
	//ErrOverflow happends when the line length exceed the MaxLength
	ErrOverflow = errors.New("unexpected string length (overflow)")
)

// Encoder implements a pkt-line format encoder
type Encoder struct {
	lines []string
}

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

// AddLine encode and adds a line to the encoder
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
}

// AddFlush adds a flush-pkt to the encoder
func (e *Encoder) AddFlush() {
	e.lines = append(e.lines, "0000")
}

// Reader returns a string.Reader over the encoder
func (e *Encoder) Reader() *strings.Reader {
	data := strings.Join(e.lines, "")

	return strings.NewReader(data)
}

// EncodeFromString encodes a string to pkt-line format
func EncodeFromString(line string) (string, error) {
	return Encode([]byte(line))
}

// Encode encodes a byte slice to pkt-line format
func Encode(line []byte) (string, error) {
	if line == nil {
		return "0000", nil
	}

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

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