]> git.lizzy.rs Git - mt.git/blob - itemmeta.go
LICENSE: add my email address to copyright notice
[mt.git] / itemmeta.go
1 package mt
2
3 import "strings"
4
5 type ItemMeta string
6
7 var sanitizer = strings.NewReplacer(
8         string(1), "",
9         string(2), "",
10         string(3), "",
11 )
12
13 func NewItemMeta(fields []Field) ItemMeta {
14         if len(fields) == 0 {
15                 return ""
16         }
17
18         b := new(strings.Builder)
19         b.WriteByte(1)
20         for _, f := range fields {
21                 sanitizer.WriteString(b, f.Name)
22                 b.WriteByte(2)
23                 sanitizer.WriteString(b, f.Value)
24                 b.WriteByte(3)
25         }
26         return ItemMeta(b.String())
27 }
28
29 func (m ItemMeta) Fields() []Field {
30         var f []Field
31         if len(m) > 0 && m[0] == 1 {
32                 m = m[1:]
33                 eat := func(stop byte) string {
34                         if i := strings.IndexByte(string(m), stop); i != -1 {
35                                 defer func() {
36                                         m = m[i+1:]
37                                 }()
38                                 return string(m[:i])
39                         }
40
41                         defer func() {
42                                 m = ""
43                         }()
44                         return string(m)
45                 }
46                 for len(m) > 0 {
47                         f = append(f, Field{eat(2), eat(3)})
48                 }
49                 return f
50         }
51
52         return []Field{{"", string(m)}}
53 }
54
55 func (m ItemMeta) Field(name string) (s string, ok bool) {
56         for _, f := range m.Fields() {
57                 if f.Name == name {
58                         s, ok = f.Value, true
59                 }
60         }
61         return
62 }
63
64 func (m *ItemMeta) SetField(name, value string) {
65         var fields []Field
66         for _, f := range m.Fields() {
67                 if f.Name != name {
68                         fields = append(fields, f)
69                 }
70         }
71         fields = append(fields, Field{name, value})
72         *m = NewItemMeta(fields)
73 }