nip54: improve normalization and add tests.

This commit is contained in:
fiatjaf 2024-03-13 16:36:08 -03:00
parent c0f1c4f510
commit 6f32e4da63
2 changed files with 37 additions and 5 deletions

View File

@ -1,17 +1,26 @@
package nip54
import (
"regexp"
"strings"
"unicode"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
var nonLetter = regexp.MustCompile(`\W`)
func NormalizeIdentifier(name string) string {
name = strings.ToLower(name)
res, _, _ := transform.Bytes(norm.NFKC, []byte(name))
str := nonLetter.ReplaceAllString(string(res), "-")
return strings.ToLower(str)
runes := []rune(string(res))
b := make([]rune, len(runes))
for i, letter := range runes {
if unicode.IsLetter(letter) {
b[i] = letter
} else {
b[i] = '-'
}
}
return string(b)
}

23
nip54/nip54_test.go Normal file
View File

@ -0,0 +1,23 @@
package nip54
import (
"fmt"
"testing"
)
func TestNormalization(t *testing.T) {
for _, vector := range []struct {
before string
after string
}{
{"hello", "hello"},
{"Goodbye", "goodbye"},
{"the long and winding road / that leads to your door", "the-long-and-winding-road---that-leads-to-your-door"},
{"it's 平仮名", "it-s-平仮名"},
} {
if norm := NormalizeIdentifier(vector.before); norm != vector.after {
fmt.Println([]byte(vector.after), []byte(norm))
t.Fatalf("%s: %s != %s", vector.before, norm, vector.after)
}
}
}