Skip to content

Commit 2479811

Browse files
committed
builtin: fix hex formating
1 parent 587ae18 commit 2479811

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

builtin/builtin.go

+10-3
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ package builtin
77

88
import (
99
"bytes"
10-
"strconv"
10+
"fmt"
1111
"unicode"
1212
"unicode/utf8"
1313

@@ -334,8 +334,15 @@ func builtin_ascii(self, o py.Object) (py.Object, error) {
334334
if c <= unicode.MaxASCII {
335335
sb.WriteRune(c)
336336
} else {
337-
s := "\\u" + strconv.FormatInt(int64(c), 16)
338-
sb.WriteString(s)
337+
if c < 0x100 {
338+
fmt.Fprintf(&sb, "\\u%02x", c)
339+
} else if c < 0x1000 {
340+
fmt.Fprintf(&sb, "\\u%03x", c)
341+
} else if c < 0x10000 {
342+
fmt.Fprintf(&sb, "\\u%04x", c)
343+
} else {
344+
fmt.Fprintf(&sb, "\\U%08x", c)
345+
}
339346
}
340347
}
341348

builtin/tests/builtin.py

+3
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ def __repr__(self):
3030
assert ascii('\t\r\n') == "'\\t\\r\\n'"
3131
assert ascii("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F") == "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f'"
3232
assert ascii(B()) == 'repr method'
33+
assert ascii(chr(0x100)) == "'\\u100'"
34+
assert ascii(chr(0x1001)) == "'\\u1001'"
35+
assert ascii(chr(0x10001)) == "'\\U00010001'"
3336

3437
doc="chr"
3538
assert chr(65) == "A"

0 commit comments

Comments
 (0)