compiler,runtime: implement []rune to string conversion
This is used by a few packages in the standard library, at least compress/gzip and regexp/syntax.
Этот коммит содержится в:
родитель
fea56d4164
коммит
fd3309afa8
4 изменённых файлов: 33 добавлений и 1 удалений
|
@ -2415,6 +2415,8 @@ func (c *Compiler) parseConvert(typeFrom, typeTo types.Type, value llvm.Value, p
|
|||
switch typeFrom.Elem().(*types.Basic).Kind() {
|
||||
case types.Byte:
|
||||
return c.createRuntimeCall("stringFromBytes", []llvm.Value{value}, ""), nil
|
||||
case types.Rune:
|
||||
return c.createRuntimeCall("stringFromRunes", []llvm.Value{value}, ""), nil
|
||||
default:
|
||||
return llvm.Value{}, c.makeError(pos, "todo: convert to string: "+typeFrom.String())
|
||||
}
|
||||
|
|
|
@ -89,6 +89,30 @@ func stringToBytes(x _string) (slice struct {
|
|||
return
|
||||
}
|
||||
|
||||
// Convert a []rune slice to a string.
|
||||
func stringFromRunes(runeSlice []rune) (s _string) {
|
||||
// Count the number of characters that will be in the string.
|
||||
for _, r := range runeSlice {
|
||||
_, numBytes := encodeUTF8(r)
|
||||
s.length += numBytes
|
||||
}
|
||||
|
||||
// Allocate memory for the string.
|
||||
s.ptr = (*byte)(alloc(s.length))
|
||||
|
||||
// Encode runes to UTF-8 and store the resulting bytes in the string.
|
||||
index := uintptr(0)
|
||||
for _, r := range runeSlice {
|
||||
array, numBytes := encodeUTF8(r)
|
||||
for _, c := range array[:numBytes] {
|
||||
*(*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(s.ptr)) + index)) = c
|
||||
index++
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Convert a string to []rune slice.
|
||||
func stringToRunes(s string) []rune {
|
||||
var n = 0
|
||||
|
|
5
testdata/string.go
предоставленный
5
testdata/string.go
предоставленный
|
@ -13,7 +13,12 @@ func testStringToRunes() {
|
|||
}
|
||||
}
|
||||
|
||||
func testRunesToString(r []rune) {
|
||||
println("string from runes:", string(r))
|
||||
}
|
||||
|
||||
func main() {
|
||||
testRangeString()
|
||||
testStringToRunes()
|
||||
testRunesToString([]rune{97, 98, 99, 252, 162, 8364, 66376, 176, 120})
|
||||
}
|
||||
|
|
1
testdata/string.txt
предоставленный
1
testdata/string.txt
предоставленный
|
@ -16,3 +16,4 @@
|
|||
6 66376
|
||||
7 176
|
||||
8 120
|
||||
string from runes: abcü¢€𐍈°x
|
||||
|
|
Загрузка…
Создание таблицы
Сослаться в новой задаче