rewrite lang.go format and templateString

surprisingly not much faster than the originals.
pull/75/head
Harvey Tindall 4 years ago
parent a0a25d64f1
commit 2451d69341
No known key found for this signature in database
GPG Key ID: BBC65952848FB1A2

@ -1,9 +1,5 @@
package main package main
import (
"strings"
)
type langMeta struct { type langMeta struct {
Name string `json:"name"` Name string `json:"name"`
} }
@ -123,10 +119,29 @@ type langSection map[string]string
type tmpl map[string]string type tmpl map[string]string
func templateString(text string, vals tmpl) string { func templateString(text string, vals tmpl) string {
for key, val := range vals { start, previousEnd := -1, -1
text = strings.ReplaceAll(text, "{"+key+"}", val) out := ""
for i := range text {
if text[i] == '{' {
start = i
continue
}
if start != -1 && text[i] == '}' {
varName := text[start+1 : i]
val, ok := vals[varName]
if !ok {
start = -1
continue
}
out += text[previousEnd+1:start] + val
previousEnd = i
start = -1
}
}
if previousEnd != len(text)-1 {
out += text[previousEnd+1:]
} }
return text return out
} }
func (el langSection) template(field string, vals tmpl) string { func (el langSection) template(field string, vals tmpl) string {
@ -136,10 +151,27 @@ func (el langSection) template(field string, vals tmpl) string {
func (el langSection) format(field string, vals ...string) string { func (el langSection) format(field string, vals ...string) string {
text := el.get(field) text := el.get(field)
for _, val := range vals { start, previous := -1, -3
text = strings.Replace(text, "{n}", val, 1) out := ""
val := 0
for i := range text {
if i == len(text)-2 { // Check if there's even enough space for a {n}
break
}
if text[i:i+3] == "{n}" {
start = i
out += text[previous+3:start] + vals[val]
previous = start
val++
if val == len(vals) {
break
}
}
}
if previous+2 != len(text)-1 {
out += text[previous+3:]
} }
return text return out
} }
func (el langSection) get(field string) string { func (el langSection) get(field string) string {

@ -24,6 +24,7 @@ type logger struct {
} }
func Lshortfile() string { func Lshortfile() string {
// 0 = This function, 1 = Print/Printf/Println, 2 = Caller of Print/Printf/Println
_, file, line, ok := runtime.Caller(2) _, file, line, ok := runtime.Caller(2)
lineString := strconv.Itoa(line) lineString := strconv.Itoa(line)
if !ok { if !ok {

Loading…
Cancel
Save