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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
|
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: Copyright (c) 2018-2024 luk3yx <https://luk3yx.github.io>
// SPDX-FileCopyrightText: Copyright (c) 2025 Runxi Yu <https://runxiyu.org>
package irc
import (
"bytes"
)
type Message struct {
Command string
Source *Source
Tags map[string]string
Args []string
}
// All strings returned are borrowed from the input byte slice.
func Parse(raw []byte) (msg Message, err error) {
sp := bytes.Split(raw, []byte{' '}) // TODO: Use bytes.Cut instead here
if bytes.HasPrefix(sp[0], []byte{'@'}) { // TODO: Check size manually
if len(sp[0]) < 2 {
err = ErrMalformedMsg
return
}
sp[0] = sp[0][1:]
msg.Tags, err = tagsToMap(sp[0])
if err != nil {
return
}
if len(sp) < 2 {
err = ErrMalformedMsg
return
}
sp = sp[1:]
} else {
msg.Tags = nil // TODO: Is a nil map the correct thing to use here?
}
if bytes.HasPrefix(sp[0], []byte{':'}) { // TODO: Check size manually
if len(sp[0]) < 2 {
err = ErrMalformedMsg
return
}
sp[0] = sp[0][1:]
source := parseSource(sp[0])
msg.Source = &source
if len(sp) < 2 {
err = ErrMalformedMsg
return
}
sp = sp[1:]
}
msg.Command = bytesToString(sp[0])
if len(sp) < 2 {
return
}
sp = sp[1:]
for i := 0; i < len(sp); i++ {
if len(sp[i]) == 0 {
continue
}
if sp[i][0] == ':' {
if len(sp[i]) < 2 {
sp[i] = []byte{}
} else {
sp[i] = sp[i][1:]
}
msg.Args = append(msg.Args, bytesToString(bytes.Join(sp[i:], []byte{' '})))
// TODO: Avoid Join by not using sp in the first place
break
}
msg.Args = append(msg.Args, bytesToString(sp[i]))
}
return
}
var ircv3TagEscapes = map[byte]byte{
':': ';',
's': ' ',
'r': '\r',
'n': '\n',
}
func tagsToMap(raw []byte) (tags map[string]string, err error) {
tags = make(map[string]string)
for rawTag := range bytes.SplitSeq(raw, []byte{';'}) {
key, value, found := bytes.Cut(rawTag, []byte{'='})
if !found {
err = ErrInvalidIRCv3Tag
return
}
if len(value) == 0 {
tags[bytesToString(key)] = ""
} else {
if !bytes.Contains(value, []byte{'\\'}) {
tags[bytesToString(key)] = bytesToString(value)
} else {
valueUnescaped := bytes.NewBuffer(make([]byte, 0, len(value)))
for i := 0; i < len(value); i++ {
if value[i] == '\\' {
i++
byteUnescaped, ok := ircv3TagEscapes[value[i]]
if !ok {
byteUnescaped = value[i]
}
valueUnescaped.WriteByte(byteUnescaped)
} else {
valueUnescaped.WriteByte(value[i])
}
}
tags[bytesToString(key)] = bytesToString(valueUnescaped.Bytes())
}
}
}
return
}
|