From 7461c298dd35c7e8634bc9205f501da7a4b88885 Mon Sep 17 00:00:00 2001 From: Michael Teichgraeber Date: Sun, 27 Jan 2019 00:08:23 +0100 Subject: [PATCH] runtime: make stringNext use byteindex only, fix index offset Use stringIterator.byteindex as the loop index, and remove stringIterator.rangeindex, as "the index of the loop is the starting position of the current rune, measured in bytes". This patch also fixes the current loop index returned by stringNext, using `it.byteindex' before - not after - `length' is added. --- src/runtime/string.go | 7 +++---- testdata/rangestring.go | 11 +++++++++++ testdata/rangestring.txt | 9 +++++++++ 3 files changed, 23 insertions(+), 4 deletions(-) create mode 100644 testdata/rangestring.go create mode 100644 testdata/rangestring.txt diff --git a/src/runtime/string.go b/src/runtime/string.go index e1142034..70507861 100644 --- a/src/runtime/string.go +++ b/src/runtime/string.go @@ -14,8 +14,7 @@ type _string struct { // The iterator state for a range over a string. type stringIterator struct { - byteindex uintptr - rangeindex uintptr + byteindex uintptr } // Return true iff the strings match. @@ -105,10 +104,10 @@ func stringNext(s string, it *stringIterator) (bool, int, rune) { if len(s) <= int(it.byteindex) { return false, 0, 0 } + i := int(it.byteindex) r, length := decodeUTF8(s, it.byteindex) it.byteindex += length - it.rangeindex += 1 - return true, int(it.rangeindex), r + return true, i, r } // Convert a Unicode code point into an array of bytes and its length. diff --git a/testdata/rangestring.go b/testdata/rangestring.go new file mode 100644 index 00000000..32401c2c --- /dev/null +++ b/testdata/rangestring.go @@ -0,0 +1,11 @@ +package main + +func testRangeString() { + for i, c := range "abcü¢€𐍈°x" { + println(i, c) + } +} + +func main() { + testRangeString() +} diff --git a/testdata/rangestring.txt b/testdata/rangestring.txt new file mode 100644 index 00000000..e3318b41 --- /dev/null +++ b/testdata/rangestring.txt @@ -0,0 +1,9 @@ +0 97 +1 98 +2 99 +3 252 +5 162 +7 8364 +10 66376 +14 176 +16 120