Skip to content

Commit df05b9e

Browse files
author
1911860538
committed
all: replace HasPrefix and slicing with CutPrefix
1 parent 1e756dc commit df05b9e

File tree

19 files changed

+71
-56
lines changed

19 files changed

+71
-56
lines changed

src/archive/zip/reader.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -796,8 +796,8 @@ func toValidName(name string) string {
796796

797797
p = strings.TrimPrefix(p, "/")
798798

799-
for strings.HasPrefix(p, "../") {
800-
p = p[len("../"):]
799+
for cut := true; cut; {
800+
p, cut = strings.CutPrefix(p, "../")
801801
}
802802

803803
return p

src/cmd/cgo/ast.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -288,11 +288,11 @@ func (f *File) saveExport(x interface{}, context astContext) {
288288
return
289289
}
290290
for _, c := range n.Doc.List {
291-
if !strings.HasPrefix(c.Text, "//export ") {
291+
name, cut := strings.CutPrefix(c.Text, "//export ")
292+
if !cut {
292293
continue
293294
}
294295

295-
name := strings.TrimSpace(c.Text[9:])
296296
if name == "" {
297297
error_(c.Pos(), "export missing name")
298298
}

src/cmd/dist/buildtool.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,10 +255,10 @@ func bootstrapBuildTools() {
255255

256256
// Copy binaries into tool binary directory.
257257
for _, name := range bootstrapDirs {
258-
if !strings.HasPrefix(name, "cmd/") {
258+
name, cut := strings.CutPrefix(name, "cmd/")
259+
if !cut {
259260
continue
260261
}
261-
name = name[len("cmd/"):]
262262
if !strings.Contains(name, "/") {
263263
copyfile(pathf("%s/%s%s", tooldir, name, exe), pathf("%s/bin/%s%s", workspace, name, exe), writeExec)
264264
}

src/cmd/go/internal/gover/gomod.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,10 @@ func GoModLookup(gomod []byte, key string) string {
3131
}
3232

3333
func parseKey(line []byte, key string) (string, bool) {
34-
if !strings.HasPrefix(string(line), key) {
34+
s, cut := strings.CutPrefix(string(line), key)
35+
if !cut {
3536
return "", false
3637
}
37-
s := strings.TrimPrefix(string(line), key)
3838
if len(s) == 0 || (s[0] != ' ' && s[0] != '\t') {
3939
return "", false
4040
}

src/cmd/go/internal/load/godebug.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,11 @@ func godebugForGoVersion(v string) map[string]string {
132132
v = v[:j]
133133
}
134134

135-
if !strings.HasPrefix(v, "1.") {
135+
nv, cut := strings.CutPrefix(v, "1.")
136+
if !cut {
136137
return nil
137138
}
138-
n, err := strconv.Atoi(v[len("1."):])
139+
n, err := strconv.Atoi(nv)
139140
if err != nil {
140141
return nil
141142
}

src/cmd/go/internal/modfetch/codehost/git.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -290,10 +290,10 @@ func (r *gitRepo) Tags(ctx context.Context, prefix string) (*Tags, error) {
290290
List: []Tag{},
291291
}
292292
for ref, hash := range refs {
293-
if !strings.HasPrefix(ref, "refs/tags/") {
293+
tag, cut := strings.CutPrefix(ref, "refs/tags/")
294+
if !cut {
294295
continue
295296
}
296-
tag := ref[len("refs/tags/"):]
297297
if !strings.HasPrefix(tag, prefix) {
298298
continue
299299
}
@@ -721,19 +721,19 @@ func (r *gitRepo) RecentTag(ctx context.Context, rev, prefix string, allowed fun
721721
line = strings.TrimSpace(line)
722722
// git do support lstrip in for-each-ref format, but it was added in v2.13.0. Stripping here
723723
// instead gives support for git v2.7.0.
724-
if !strings.HasPrefix(line, "refs/tags/") {
724+
line, cut := strings.CutPrefix(line, "refs/tags/")
725+
if !cut {
725726
continue
726727
}
727-
line = line[len("refs/tags/"):]
728728

729-
if !strings.HasPrefix(line, prefix) {
729+
semtag, cut := strings.CutPrefix(line, prefix)
730+
if !cut {
730731
continue
731732
}
732733
if !allowed(line) {
733734
continue
734735
}
735736

736-
semtag := line[len(prefix):]
737737
if semver.Compare(semtag, highest) > 0 {
738738
highest = semtag
739739
}

src/cmd/go/internal/modfetch/coderepo.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -565,10 +565,10 @@ func (r *codeRepo) convert(ctx context.Context, info *codehost.RevInfo, statVers
565565
// If the tag is invalid, retracted, or a pseudo-version, tagToVersion returns
566566
// an empty version.
567567
tagToVersion := func(tag string) (v string, tagIsCanonical bool) {
568-
if !strings.HasPrefix(tag, tagPrefix) {
568+
trimmed, cut := strings.CutPrefix(tag, tagPrefix)
569+
if !cut {
569570
return "", false
570571
}
571-
trimmed := tag[len(tagPrefix):]
572572
// Tags that look like pseudo-versions would be confusing. Ignore them.
573573
if module.IsPseudoVersion(tag) {
574574
return "", false

src/cmd/go/internal/modindex/build.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,10 +171,11 @@ func (ctxt *Context) hasSubdir(root, dir string) (rel string, ok bool) {
171171
func hasSubdir(root, dir string) (rel string, ok bool) {
172172
root = str.WithFilePathSeparator(filepath.Clean(root))
173173
dir = filepath.Clean(dir)
174-
if !strings.HasPrefix(dir, root) {
174+
path, cut := strings.CutPrefix(dir, root)
175+
if !cut {
175176
return "", false
176177
}
177-
return filepath.ToSlash(dir[len(root):]), true
178+
return filepath.ToSlash(path), true
178179
}
179180

180181
// gopath returns the list of Go path directories.

src/cmd/go/internal/modindex/scan.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,10 @@ func indexModule(modroot string) ([]byte, error) {
6565
if !d.IsDir() {
6666
return nil
6767
}
68-
if !strings.HasPrefix(path, root) {
68+
rel, cut := strings.CutPrefix(path, root)
69+
if !cut {
6970
panic(fmt.Errorf("path %v in walk doesn't have modroot %v as prefix", path, modroot))
7071
}
71-
rel := path[len(root):]
7272
packages = append(packages, importRaw(modroot, rel))
7373
return nil
7474
})

src/cmd/internal/script/scripttest/run.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,10 @@ func RunToolScriptTest(t *testing.T, repls []ToolReplacement, scriptsdir string,
7575
found := false
7676
for k := range env {
7777
ev := env[k]
78-
if !strings.HasPrefix(ev, "PATH=") {
78+
oldpath, cut := strings.CutPrefix(ev, "PATH=")
79+
if !cut {
7980
continue
8081
}
81-
oldpath := ev[5:]
8282
env[k] = "PATH=" + dir + string(filepath.ListSeparator) + oldpath
8383
found = true
8484
break

src/cmd/link/internal/loadpe/ldpe.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -807,10 +807,10 @@ func (state *peLoaderState) preprocessSymbols() error {
807807
// "__imp_XYZ" but no XYZ can be found.
808808
func LookupBaseFromImport(s loader.Sym, ldr *loader.Loader, arch *sys.Arch) (loader.Sym, error) {
809809
sname := ldr.SymName(s)
810-
if !strings.HasPrefix(sname, "__imp_") {
810+
basename, cut := strings.CutPrefix(sname, "__imp_")
811+
if !cut {
811812
return 0, nil
812813
}
813-
basename := sname[len("__imp_"):]
814814
if arch.Family == sys.I386 && basename[0] == '_' {
815815
basename = basename[1:] // _Name => Name
816816
}

src/encoding/json/v2/fields.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -493,11 +493,11 @@ func parseFieldOptions(sf reflect.StructField) (out fieldOptions, ignored bool,
493493
}
494494
switch opt {
495495
case "case":
496-
if !strings.HasPrefix(tag, ":") {
496+
tag, cut := strings.CutPrefix(tag, ":")
497+
if !cut {
497498
err = cmp.Or(err, fmt.Errorf("Go struct field %s is missing value for `case` tag option; specify `case:ignore` or `case:strict` instead", sf.Name))
498499
break
499500
}
500-
tag = tag[len(":"):]
501501
opt, n, err2 := consumeTagOption(tag)
502502
if err2 != nil {
503503
err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed value for `case` tag option: %v", sf.Name, err2))
@@ -527,11 +527,11 @@ func parseFieldOptions(sf reflect.StructField) (out fieldOptions, ignored bool,
527527
case "string":
528528
out.string = true
529529
case "format":
530-
if !strings.HasPrefix(tag, ":") {
530+
tag, cut := strings.CutPrefix(tag, ":")
531+
if !cut {
531532
err = cmp.Or(err, fmt.Errorf("Go struct field %s is missing value for `format` tag option", sf.Name))
532533
break
533534
}
534-
tag = tag[len(":"):]
535535
opt, n, err2 := consumeTagOption(tag)
536536
if err2 != nil {
537537
err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed value for `format` tag option: %v", sf.Name, err2))

src/go/build/constraint/expr.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -178,12 +178,12 @@ func splitGoBuild(line string) (expr string, ok bool) {
178178
return "", false
179179
}
180180

181-
if !strings.HasPrefix(line, "//go:build") {
181+
line, cut := strings.CutPrefix(line, "//go:build")
182+
if !cut {
182183
return "", false
183184
}
184185

185186
line = strings.TrimSpace(line)
186-
line = line[len("//go:build"):]
187187

188188
// If strings.TrimSpace finds more to trim after removing the //go:build prefix,
189189
// it means that the prefix was followed by a space, making this a //go:build line
@@ -373,17 +373,17 @@ func splitPlusBuild(line string) (expr string, ok bool) {
373373
return "", false
374374
}
375375

376-
if !strings.HasPrefix(line, "//") {
376+
line, cut := strings.CutPrefix(line, "//")
377+
if !cut {
377378
return "", false
378379
}
379-
line = line[len("//"):]
380380
// Note the space is optional; "//+build" is recognized too.
381381
line = strings.TrimSpace(line)
382382

383-
if !strings.HasPrefix(line, "+build") {
383+
line, cut = strings.CutPrefix(line, "+build")
384+
if !cut {
384385
return "", false
385386
}
386-
line = line[len("+build"):]
387387

388388
// If strings.TrimSpace finds more to trim after removing the +build prefix,
389389
// it means that the prefix was followed by a space, making this a +build line

src/internal/buildcfg/cfg.go

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,18 +87,27 @@ func gofips140() string {
8787
// isFIPSVersion reports whether v is a valid FIPS version,
8888
// of the form vX.Y.Z.
8989
func isFIPSVersion(v string) bool {
90-
if !strings.HasPrefix(v, "v") {
90+
v, cut := strings.CutPrefix(v, "v")
91+
if !cut {
9192
return false
9293
}
93-
v, ok := skipNum(v[len("v"):])
94-
if !ok || !strings.HasPrefix(v, ".") {
94+
v, ok := skipNum(v)
95+
if !ok {
9596
return false
9697
}
97-
v, ok = skipNum(v[len("."):])
98-
if !ok || !strings.HasPrefix(v, ".") {
98+
v, cut = strings.CutPrefix(v, ".")
99+
if !cut {
99100
return false
100101
}
101-
v, ok = skipNum(v[len("."):])
102+
v, ok = skipNum(v)
103+
if !ok {
104+
return false
105+
}
106+
v, cut = strings.CutPrefix(v, ".")
107+
if !cut {
108+
return false
109+
}
110+
v, ok = skipNum(v)
102111
return ok && v == ""
103112
}
104113

src/internal/trace/raw/textreader.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,11 @@ func NewTextReader(r io.Reader) (*TextReader, error) {
3737
return nil, fmt.Errorf("failed to parse header")
3838
}
3939
gover, line := readToken(line)
40-
if !strings.HasPrefix(gover, "Go1.") {
40+
ver, cut := strings.CutPrefix(gover, "Go1.")
41+
if !cut {
4142
return nil, fmt.Errorf("failed to parse header Go version")
4243
}
43-
rawv, err := strconv.ParseUint(gover[len("Go1."):], 10, 64)
44+
rawv, err := strconv.ParseUint(ver, 10, 64)
4445
if err != nil {
4546
return nil, fmt.Errorf("failed to parse header Go version: %v", err)
4647
}

src/mime/mediatype.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,11 @@ func checkMediaTypeDisposition(s string) error {
103103
if rest == "" {
104104
return nil
105105
}
106-
if !strings.HasPrefix(rest, "/") {
106+
rest, cut := strings.CutPrefix(rest, "/")
107+
if !cut {
107108
return errors.New("mime: expected slash after first token")
108109
}
109-
subtype, rest := consumeToken(rest[1:])
110+
subtype, rest := consumeToken(rest)
110111
if subtype == "" {
111112
return errors.New("mime: expected token after slash")
112113
}
@@ -309,11 +310,11 @@ func consumeValue(v string) (value, rest string) {
309310

310311
func consumeMediaParam(v string) (param, value, rest string) {
311312
rest = strings.TrimLeftFunc(v, unicode.IsSpace)
312-
if !strings.HasPrefix(rest, ";") {
313+
rest, cut := strings.CutPrefix(rest, ";")
314+
if !cut {
313315
return "", "", v
314316
}
315317

316-
rest = rest[1:] // consume semicolon
317318
rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
318319
param, rest = consumeToken(rest)
319320
param = strings.ToLower(param)
@@ -322,10 +323,10 @@ func consumeMediaParam(v string) (param, value, rest string) {
322323
}
323324

324325
rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
325-
if !strings.HasPrefix(rest, "=") {
326+
rest, cut = strings.CutPrefix(rest, "=")
327+
if !cut {
326328
return "", "", v
327329
}
328-
rest = rest[1:] // consume equals sign
329330
rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
330331
value, rest2 := consumeValue(rest)
331332
if value == "" && rest2 == rest {

src/net/http/fs.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1017,12 +1017,13 @@ func parseRange(s string, size int64) ([]httpRange, error) {
10171017
return nil, nil // header not present
10181018
}
10191019
const b = "bytes="
1020-
if !strings.HasPrefix(s, b) {
1020+
s, cut := strings.CutPrefix(s, b)
1021+
if !cut {
10211022
return nil, errors.New("invalid range")
10221023
}
10231024
var ranges []httpRange
10241025
noOverlap := false
1025-
for ra := range strings.SplitSeq(s[len(b):], ",") {
1026+
for ra := range strings.SplitSeq(s, ",") {
10261027
ra = textproto.TrimString(ra)
10271028
if ra == "" {
10281029
continue

src/net/http/h2_bundle.go

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/net/http/httptest/recorder.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -224,14 +224,15 @@ func (rw *ResponseRecorder) Result() *http.Response {
224224
}
225225
}
226226
for k, vv := range rw.HeaderMap {
227-
if !strings.HasPrefix(k, http.TrailerPrefix) {
227+
k, cut := strings.CutPrefix(k, http.TrailerPrefix)
228+
if !cut {
228229
continue
229230
}
230231
if res.Trailer == nil {
231232
res.Trailer = make(http.Header)
232233
}
233234
for _, v := range vv {
234-
res.Trailer.Add(strings.TrimPrefix(k, http.TrailerPrefix), v)
235+
res.Trailer.Add(k, v)
235236
}
236237
}
237238
return res

0 commit comments

Comments
 (0)