aboutsummaryrefslogtreecommitdiffstats
path: root/common/infostring/infostring.go
blob: 114058ad87a8ce7f7506bbeeb486f9d3dafed17f (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
65
66
67
68
69
70
71
72
package infostring

import (
	"strings"

	"github.com/osm/quake/common/buffer"
)

type InfoString struct {
	Info []Info
}

type Info struct {
	Key   string
	Value string
}

func New(opts ...Option) *InfoString {
	var infoString InfoString

	for _, opt := range opts {
		opt(&infoString)
	}

	return &infoString
}

func (is *InfoString) Bytes() []byte {
	buf := buffer.New()

	buf.PutByte(byte('"'))

	for i := 0; i < len(is.Info); i++ {
		buf.PutBytes([]byte("\\" + is.Info[i].Key))
		buf.PutBytes([]byte("\\" + is.Info[i].Value))
	}

	buf.PutByte(byte('"'))

	return buf.Bytes()
}

func Parse(input string) *InfoString {
	var ret InfoString

	trimmed := strings.Trim(input, "\"")
	parts := strings.Split(trimmed, "\\")

	for i := 1; i < len(parts)-1; i += 2 {
		ret.Info = append(ret.Info, Info{parts[i], parts[i+1]})
	}

	return &ret
}

func (is *InfoString) Get(key string) string {
	for i := 0; i < len(is.Info); i++ {
		if is.Info[i].Key == key {
			return is.Info[i].Value
		}
	}

	return ""
}

func (is *InfoString) Set(key, value string) {
	for i := 0; i < len(is.Info); i++ {
		if is.Info[i].Key == key {
			is.Info[i].Value = value
		}
	}
}