feat: deduplicate ship name on transfer

This commit is contained in:
Ilia Denisov
2026-02-17 22:02:17 +02:00
parent f394c105b0
commit de91d575d0
7 changed files with 100 additions and 30 deletions
+25 -3
View File
@@ -1,12 +1,16 @@
package util
import (
"fmt"
"math/rand"
"strings"
"unicode"
)
// Allowed special characters
const specialChars = "!@#$%^*-_=+~()[]{}"
const (
maxNameLength = 30
specialChars = "!@#$%^*-_=+~()[]{}" // Allowed special characters
)
var allowedSpecialChars map[rune]bool
@@ -28,7 +32,7 @@ func ValidateTypeName(input string) (string, bool) {
runes := []rune(trimmed)
if len(runes) > 30 {
if len(runes) > maxNameLength {
return "", false
}
@@ -75,3 +79,21 @@ func ValidateTypeName(input string) (string, bool) {
// Return the trimmed string and true if all conditions are met
return trimmed, true
}
func AppendRandomSuffix(v string) string {
return AppendRandomSuffixGenerator(v, RandomSuffixGenerator)
}
func AppendRandomSuffixGenerator(v string, s func() string) string {
suffix := []rune(s())
str := []rune(v)
max := maxNameLength - len(suffix)
if len(str) > max {
str = str[:max]
}
return string(append(str, suffix...))
}
func RandomSuffixGenerator() string {
return fmt.Sprintf("%04d", rand.Intn(9999))
}
+52
View File
@@ -1,6 +1,7 @@
package util_test
import (
"strings"
"testing"
"unicode/utf8"
@@ -238,3 +239,54 @@ func FuzzValidateString(f *testing.F) {
}
})
}
func TestAppendRandomSuffixGenerator(t *testing.T) {
tests := []struct {
name string
input string
suffix string
expected string
}{
{
name: "Regular String",
input: "Regular_String",
suffix: "1234",
expected: "Regular_String1234",
},
{
name: "Zero Length String",
input: "",
suffix: "1234",
expected: "1234",
},
{
name: "Edge Case String len=28",
input: "Edge_Case_String_ABCDEFGHIGK",
suffix: "1234",
expected: "Edge_Case_String_ABCDEFGHI1234",
},
{
name: "Extra Long String len=31",
input: "Extra_Long_String_ABCDEFGHIGKLM",
suffix: "1234",
expected: "Extra_Long_String_ABCDEFGH1234",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := util.AppendRandomSuffixGenerator(tt.input, func() string { return tt.suffix })
assert.Equal(t, tt.expected, result)
})
}
}
func TestRandomSuffixGenerator(t *testing.T) {
var last string
for range 100 {
s := util.RandomSuffixGenerator()
assert.Len(t, s, 4)
assert.NotEqual(t, last, s)
assert.True(t, strings.ContainsFunc(s, func(r rune) bool { return r >= '0' && r <= '9' }))
last = s
}
}