github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/cmds/core/elvish/eval/vals/index_string.go (about) 1 package vals 2 3 import ( 4 "errors" 5 "unicode/utf8" 6 ) 7 8 var errIndexNotAtRuneBoundary = errors.New("index not at rune boundary") 9 10 func indexString(s string, index interface{}) (string, error) { 11 i, j, err := convertStringIndex(index, s) 12 if err != nil { 13 return "", err 14 } 15 return s[i:j], nil 16 } 17 18 func convertStringIndex(rawIndex interface{}, s string) (int, int, error) { 19 index, err := ConvertListIndex(rawIndex, len(s)) 20 if err != nil { 21 return 0, 0, err 22 } 23 r, size := utf8.DecodeRuneInString(s[index.Lower:]) 24 if r == utf8.RuneError { 25 return 0, 0, errIndexNotAtRuneBoundary 26 } 27 if index.Slice { 28 if r, _ := utf8.DecodeLastRuneInString(s[:index.Upper]); r == utf8.RuneError { 29 return 0, 0, errIndexNotAtRuneBoundary 30 } 31 return index.Lower, index.Upper, nil 32 } 33 return index.Lower, index.Lower + size, nil 34 }