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

fix: ufmt multi-byte fix. #1889

Merged
merged 11 commits into from
Apr 8, 2024
18 changes: 10 additions & 8 deletions examples/gno.land/p/demo/ufmt/ufmt.gno
Original file line number Diff line number Diff line change
Expand Up @@ -52,24 +52,26 @@ func Println(args ...interface{}) {
// %t: formats a boolean value to "true" or "false".
// %%: outputs a literal %. Does not consume an argument.
func Sprintf(format string, args ...interface{}) string {
end := len(format)
// we use runes to handle multi-byte characters
sTor := []rune(format)
end := len(sTor)
argNum := 0
argLen := len(args)
buf := ""

for i := 0; i < end; {
isLast := i == end-1
c := format[i]
c := string(sTor[i])

if isLast || c != '%' {
if isLast || c != "%" {
// we don't check for invalid format like a one ending with "%"
buf += string(c)
i++
continue
}

verb := format[i+1]
if verb == '%' {
verb := string(sTor[i+1])
if verb == "%" {
buf += "%"
i += 2
continue
Expand All @@ -82,7 +84,7 @@ func Sprintf(format string, args ...interface{}) string {
argNum++

switch verb {
case 's':
case "s":
switch v := arg.(type) {
case interface{ String() string }:
buf += v.String()
Expand All @@ -91,7 +93,7 @@ func Sprintf(format string, args ...interface{}) string {
default:
buf += "(unhandled)"
}
case 'd':
case "d":
switch v := arg.(type) {
case int:
buf += strconv.Itoa(v)
Expand All @@ -116,7 +118,7 @@ func Sprintf(format string, args ...interface{}) string {
default:
buf += "(unhandled)"
}
case 't':
case "t":
switch v := arg.(type) {
case bool:
if v {
Expand Down
1 change: 1 addition & 0 deletions examples/gno.land/p/demo/ufmt/ufmt_test.gno
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func TestSprintf(t *testing.T) {
{"no args", nil, "no args"},
{"finish with %", nil, "finish with %"},
{"stringer [%s]", []interface{}{stringer{}}, "stringer [I'm a stringer]"},
{"Hello, World! 😊", nil, "Hello, World! 😊"},
MalekLahbib marked this conversation as resolved.
Show resolved Hide resolved
}

for _, tc := range cases {
Expand Down
Loading