emote: parse emote structs, not just ids

This commit is contained in:
Branden J Brown 2025-04-19 19:17:35 -04:00
parent 5c530a41fb
commit 76fc85b7c0
2 changed files with 15 additions and 15 deletions

View File

@ -23,23 +23,23 @@ type Emote struct {
//
// Parser assumes that emotes are bound by whitespace.
type Parser struct {
m map[string]string
m map[string]Emote
// TODO(branden): more efficient data structure; trie?
}
// NewParser creates a Parser for the given list of emotes.
func NewParser(emotes ...Emote) Parser {
m := make(map[string]string, len(emotes))
m := make(map[string]Emote, len(emotes))
for _, e := range emotes {
m[e.Name] = e.ID
m[e.Name] = e
}
return Parser{m}
}
// Next parses the next emote instance from the message and returns the
// remainder of the message text following it.
// If there is no emote in the message the returned emote is the empty string.
func (p Parser) Next(text string) (name, id, following string) {
// If there is no emote in the message the returned emote has an empty ID.
func (p Parser) Next(text string) (emote Emote, following string) {
for text != "" {
// First trim any existing space.
text = strings.TrimSpace(text)
@ -54,12 +54,12 @@ func (p Parser) Next(text string) (name, id, following string) {
} else {
following = ""
}
id = p.m[word]
if id != "" {
return word, id, following
em := p.m[word]
if em.ID != "" {
return em, following
}
text = following
}
// No emote found.
return "", "", ""
return Emote{}, ""
}

View File

@ -57,16 +57,16 @@ func TestParser(t *testing.T) {
var got []string
text := c.text
for {
name, id, rest := p.Next(text)
if id == "" {
em, rest := p.Next(text)
if em.ID == "" {
break
}
if name != id {
if em.Name != em.ID {
// Not normally the case, but this test is constructed
// so that it is.
t.Errorf("wrong id %q for name %q", id, name)
t.Errorf("wrong id %q for name %q", em.ID, em.Name)
}
got = append(got, name)
got = append(got, em.Name)
text = rest
}
if diff := cmp.Diff(c.want, got); diff != "" {
@ -103,7 +103,7 @@ func BenchmarkParser(b *testing.B) {
for b.Loop() {
text := c.text
for text != "" {
_, _, text = p.Next(text)
_, text = p.Next(text)
}
}
})