Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

go api: reduce allocations in deck decompression #19

Merged
merged 3 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 54 additions & 35 deletions backend/api/deck.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package api

import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
"strings"

"github.com/gin-gonic/gin"
Expand All @@ -13,6 +13,19 @@ import (

const WILDCARDS = "0123456789abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTVWXYZ_`[]/^%?@><=-+*:;,.()#$!'{}~"

var compressionWildcardRegex []*regexp.Regexp

func init() {
escapeRegex := regexp.MustCompile(`[-\/\\^$*+?.()|[\]{}]`)

compressionWildcardRegex = make([]*regexp.Regexp, 0, len(WILDCARDS))
for i := range WILDCARDS {
wildCard := fmt.Sprintf("&%c", WILDCARDS[i])
escaped := escapeRegex.ReplaceAllString(wildCard, "\\$&")
compressionWildcardRegex = append(compressionWildcardRegex, regexp.MustCompile(escaped))
}
}

func (a *API) getDeckHandler(c *gin.Context) {
name := c.Param("name")
name = strings.ToLower(name)
Expand Down Expand Up @@ -60,11 +73,6 @@ func (a *API) getDeckHandler(c *gin.Context) {
c.Data(200, "text/plain", []byte(result.String()))
}

func escapeRegexp(s string) string {
r := regexp.MustCompile(`[-\/\\^$*+?.()|[\]{}]`)
return r.ReplaceAllString(s, "\\$&")
}

func decompress(s string) (string, error) {
parts := strings.Split(s, "||")
if len(parts) < 2 {
Expand All @@ -76,51 +84,58 @@ func decompress(s string) (string, error) {

for i := len(compressionDict) - 1; i >= 0; i-- {
word := compressionDict[i]
wildCard := fmt.Sprintf("&%c", WILDCARDS[i])
r, err := regexp.Compile(escapeRegexp(wildCard))
if err != nil {
return "", err
}
text = r.ReplaceAllString(text, word)
text = compressionWildcardRegex[i].ReplaceAllString(text, word)
}
return text, nil
}

func parseCommaDelimitedIntegerArray(s string) ([]int, error) {
if s == "-" {
return make([]int, 0), nil
return nil, nil
}

currIndex := 0
result := make([]int, 0, strings.Count(s, ",")+1)
for currIndex < len(s) {
nextIndex := currIndex + strings.Index(s[currIndex:], ",")
if nextIndex < currIndex {
nextIndex = len(s)
}

resultVal, err := strconv.ParseInt(s[currIndex:nextIndex], 10, 64)
if err != nil {
return nil, err
}

currIndex = nextIndex + 1
result = append(result, int(resultVal))
}
//nolint:prealloc
var result []int
err := json.Unmarshal([]byte(fmt.Sprintf("[%s]", s)), &result)
return result, err
return result, nil
}

func splitSemicolonDelimited2DArray(s string) [][]string {
func splitDoubleSemicolonArray(s string) []string {
if s == "-" {
return make([][]string, 0)
return nil
}

//nolint:prealloc
var result [][]string
split := strings.Split(s, ";;")
for _, element := range split {
result = append(result, strings.Split(element, ";"))
}
return result
return strings.Split(s, ";;")
}

func parseCards(cards [][]string) []string {
//nolint:prealloc
var result []string
for _, card := range cards {
result = append(result, parseCard(card))
func parseCards(cardSections []string) []string {
result := make([]string, 0, len(cardSections))
for _, cardSection := range cardSections {
result = append(result, parseCard(cardSection))
}
return result
}

func parseCard(c []string) string {
return c[0]
func parseCard(cardSection string) string {
sectionEnd := strings.Index(cardSection, ";")
if sectionEnd == -1 {
return cardSection
}

return cardSection[:sectionEnd]
}

func decompressDeck(deck string) (map[string]int, error) {
Expand All @@ -134,10 +149,14 @@ func decompressDeck(deck string) (map[string]int, error) {
if err != nil {
return nil, err
}
cards := parseCards(splitSemicolonDelimited2DArray(parts[1]))
cards := parseCards(splitDoubleSemicolonArray(parts[1]))

deckDict := make(map[string]int)
deckDict := make(map[string]int, len(cards))
for _, idx := range d {
if idx < 0 || idx >= len(cards) {
return nil, errors.New("card index out of bounds")
}

name := cards[idx]
deckDict[name]++
}
Expand Down
Loading
Loading