Skip to content

all: replace HasPrefix and slicing with CutPrefix #73756

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/archive/zip/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -796,8 +796,8 @@ func toValidName(name string) string {

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

for strings.HasPrefix(p, "../") {
p = p[len("../"):]
for cut := true; cut; {
p, cut = strings.CutPrefix(p, "../")
}

return p
Expand Down
5 changes: 3 additions & 2 deletions src/cmd/cgo/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,11 +288,12 @@ func (f *File) saveExport(x interface{}, context astContext) {
return
}
for _, c := range n.Doc.List {
if !strings.HasPrefix(c.Text, "//export ") {
name, cut := strings.CutPrefix(c.Text, "//export ")
if !cut {
continue
}

name := strings.TrimSpace(c.Text[9:])
name = strings.TrimSpace(name)
if name == "" {
error_(c.Pos(), "export missing name")
}
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/dist/buildtool.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,10 +255,10 @@ func bootstrapBuildTools() {

// Copy binaries into tool binary directory.
for _, name := range bootstrapDirs {
if !strings.HasPrefix(name, "cmd/") {
name, cut := strings.CutPrefix(name, "cmd/")
if !cut {
continue
}
name = name[len("cmd/"):]
if !strings.Contains(name, "/") {
copyfile(pathf("%s/%s%s", tooldir, name, exe), pathf("%s/bin/%s%s", workspace, name, exe), writeExec)
}
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/go/internal/gover/gomod.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ func GoModLookup(gomod []byte, key string) string {
}

func parseKey(line []byte, key string) (string, bool) {
if !strings.HasPrefix(string(line), key) {
s, cut := strings.CutPrefix(string(line), key)
if !cut {
return "", false
}
s := strings.TrimPrefix(string(line), key)
if len(s) == 0 || (s[0] != ' ' && s[0] != '\t') {
return "", false
}
Expand Down
5 changes: 3 additions & 2 deletions src/cmd/go/internal/load/godebug.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,11 @@ func godebugForGoVersion(v string) map[string]string {
v = v[:j]
}

if !strings.HasPrefix(v, "1.") {
nv, cut := strings.CutPrefix(v, "1.")
if !cut {
return nil
}
n, err := strconv.Atoi(v[len("1."):])
n, err := strconv.Atoi(nv)
if err != nil {
return nil
}
Expand Down
12 changes: 6 additions & 6 deletions src/cmd/go/internal/modfetch/codehost/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,10 +290,10 @@ func (r *gitRepo) Tags(ctx context.Context, prefix string) (*Tags, error) {
List: []Tag{},
}
for ref, hash := range refs {
if !strings.HasPrefix(ref, "refs/tags/") {
tag, cut := strings.CutPrefix(ref, "refs/tags/")
if !cut {
continue
}
tag := ref[len("refs/tags/"):]
if !strings.HasPrefix(tag, prefix) {
continue
}
Expand Down Expand Up @@ -721,19 +721,19 @@ func (r *gitRepo) RecentTag(ctx context.Context, rev, prefix string, allowed fun
line = strings.TrimSpace(line)
// git do support lstrip in for-each-ref format, but it was added in v2.13.0. Stripping here
// instead gives support for git v2.7.0.
if !strings.HasPrefix(line, "refs/tags/") {
line, cut := strings.CutPrefix(line, "refs/tags/")
if !cut {
continue
}
line = line[len("refs/tags/"):]

if !strings.HasPrefix(line, prefix) {
semtag, cut := strings.CutPrefix(line, prefix)
if !cut {
continue
}
if !allowed(line) {
continue
}

semtag := line[len(prefix):]
if semver.Compare(semtag, highest) > 0 {
highest = semtag
}
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/go/internal/modfetch/coderepo.go
Original file line number Diff line number Diff line change
Expand Up @@ -565,10 +565,10 @@ func (r *codeRepo) convert(ctx context.Context, info *codehost.RevInfo, statVers
// If the tag is invalid, retracted, or a pseudo-version, tagToVersion returns
// an empty version.
tagToVersion := func(tag string) (v string, tagIsCanonical bool) {
if !strings.HasPrefix(tag, tagPrefix) {
trimmed, cut := strings.CutPrefix(tag, tagPrefix)
if !cut {
return "", false
}
trimmed := tag[len(tagPrefix):]
// Tags that look like pseudo-versions would be confusing. Ignore them.
if module.IsPseudoVersion(tag) {
return "", false
Expand Down
5 changes: 3 additions & 2 deletions src/cmd/go/internal/modindex/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,11 @@ func (ctxt *Context) hasSubdir(root, dir string) (rel string, ok bool) {
func hasSubdir(root, dir string) (rel string, ok bool) {
root = str.WithFilePathSeparator(filepath.Clean(root))
dir = filepath.Clean(dir)
if !strings.HasPrefix(dir, root) {
path, cut := strings.CutPrefix(dir, root)
if !cut {
return "", false
}
return filepath.ToSlash(dir[len(root):]), true
return filepath.ToSlash(path), true
}

// gopath returns the list of Go path directories.
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/go/internal/modindex/scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,10 @@ func indexModule(modroot string) ([]byte, error) {
if !d.IsDir() {
return nil
}
if !strings.HasPrefix(path, root) {
rel, cut := strings.CutPrefix(path, root)
if !cut {
panic(fmt.Errorf("path %v in walk doesn't have modroot %v as prefix", path, modroot))
}
rel := path[len(root):]
packages = append(packages, importRaw(modroot, rel))
return nil
})
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/internal/script/scripttest/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,10 @@ func RunToolScriptTest(t *testing.T, repls []ToolReplacement, scriptsdir string,
found := false
for k := range env {
ev := env[k]
if !strings.HasPrefix(ev, "PATH=") {
oldpath, cut := strings.CutPrefix(ev, "PATH=")
if !cut {
continue
}
oldpath := ev[5:]
env[k] = "PATH=" + dir + string(filepath.ListSeparator) + oldpath
found = true
break
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/link/internal/loadpe/ldpe.go
Original file line number Diff line number Diff line change
Expand Up @@ -807,10 +807,10 @@ func (state *peLoaderState) preprocessSymbols() error {
// "__imp_XYZ" but no XYZ can be found.
func LookupBaseFromImport(s loader.Sym, ldr *loader.Loader, arch *sys.Arch) (loader.Sym, error) {
sname := ldr.SymName(s)
if !strings.HasPrefix(sname, "__imp_") {
basename, cut := strings.CutPrefix(sname, "__imp_")
if !cut {
return 0, nil
}
basename := sname[len("__imp_"):]
if arch.Family == sys.I386 && basename[0] == '_' {
basename = basename[1:] // _Name => Name
}
Expand Down
8 changes: 4 additions & 4 deletions src/encoding/json/v2/fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -493,11 +493,11 @@ func parseFieldOptions(sf reflect.StructField) (out fieldOptions, ignored bool,
}
switch opt {
case "case":
if !strings.HasPrefix(tag, ":") {
tag, cut := strings.CutPrefix(tag, ":")
if !cut {
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))
break
}
tag = tag[len(":"):]
opt, n, err2 := consumeTagOption(tag)
if err2 != nil {
err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed value for `case` tag option: %v", sf.Name, err2))
Expand Down Expand Up @@ -527,11 +527,11 @@ func parseFieldOptions(sf reflect.StructField) (out fieldOptions, ignored bool,
case "string":
out.string = true
case "format":
if !strings.HasPrefix(tag, ":") {
tag, cut := strings.CutPrefix(tag, ":")
if !cut {
err = cmp.Or(err, fmt.Errorf("Go struct field %s is missing value for `format` tag option", sf.Name))
break
}
tag = tag[len(":"):]
opt, n, err2 := consumeTagOption(tag)
if err2 != nil {
err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed value for `format` tag option: %v", sf.Name, err2))
Expand Down
12 changes: 6 additions & 6 deletions src/go/build/constraint/expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,12 +178,12 @@ func splitGoBuild(line string) (expr string, ok bool) {
return "", false
}

if !strings.HasPrefix(line, "//go:build") {
line, cut := strings.CutPrefix(line, "//go:build")
if !cut {
return "", false
}

line = strings.TrimSpace(line)
line = line[len("//go:build"):]

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

if !strings.HasPrefix(line, "//") {
line, cut := strings.CutPrefix(line, "//")
if !cut {
return "", false
}
line = line[len("//"):]
// Note the space is optional; "//+build" is recognized too.
line = strings.TrimSpace(line)

if !strings.HasPrefix(line, "+build") {
line, cut = strings.CutPrefix(line, "+build")
if !cut {
return "", false
}
line = line[len("+build"):]

// If strings.TrimSpace finds more to trim after removing the +build prefix,
// it means that the prefix was followed by a space, making this a +build line
Expand Down
21 changes: 15 additions & 6 deletions src/internal/buildcfg/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,18 +87,27 @@ func gofips140() string {
// isFIPSVersion reports whether v is a valid FIPS version,
// of the form vX.Y.Z.
func isFIPSVersion(v string) bool {
if !strings.HasPrefix(v, "v") {
v, cut := strings.CutPrefix(v, "v")
if !cut {
return false
}
v, ok := skipNum(v[len("v"):])
if !ok || !strings.HasPrefix(v, ".") {
v, ok := skipNum(v)
if !ok {
return false
}
v, ok = skipNum(v[len("."):])
if !ok || !strings.HasPrefix(v, ".") {
v, cut = strings.CutPrefix(v, ".")
if !cut {
return false
}
v, ok = skipNum(v[len("."):])
v, ok = skipNum(v)
if !ok {
return false
}
v, cut = strings.CutPrefix(v, ".")
if !cut {
return false
}
v, ok = skipNum(v)
return ok && v == ""
}

Expand Down
5 changes: 3 additions & 2 deletions src/internal/trace/raw/textreader.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,11 @@ func NewTextReader(r io.Reader) (*TextReader, error) {
return nil, fmt.Errorf("failed to parse header")
}
gover, line := readToken(line)
if !strings.HasPrefix(gover, "Go1.") {
ver, cut := strings.CutPrefix(gover, "Go1.")
if !cut {
return nil, fmt.Errorf("failed to parse header Go version")
}
rawv, err := strconv.ParseUint(gover[len("Go1."):], 10, 64)
rawv, err := strconv.ParseUint(ver, 10, 64)
if err != nil {
return nil, fmt.Errorf("failed to parse header Go version: %v", err)
}
Expand Down
13 changes: 7 additions & 6 deletions src/mime/mediatype.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,11 @@ func checkMediaTypeDisposition(s string) error {
if rest == "" {
return nil
}
if !strings.HasPrefix(rest, "/") {
rest, cut := strings.CutPrefix(rest, "/")
if !cut {
return errors.New("mime: expected slash after first token")
}
subtype, rest := consumeToken(rest[1:])
subtype, rest := consumeToken(rest)
if subtype == "" {
return errors.New("mime: expected token after slash")
}
Expand Down Expand Up @@ -309,11 +310,11 @@ func consumeValue(v string) (value, rest string) {

func consumeMediaParam(v string) (param, value, rest string) {
rest = strings.TrimLeftFunc(v, unicode.IsSpace)
if !strings.HasPrefix(rest, ";") {
rest, cut := strings.CutPrefix(rest, ";")
if !cut {
return "", "", v
}

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

rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
if !strings.HasPrefix(rest, "=") {
rest, cut = strings.CutPrefix(rest, "=")
if !cut {
return "", "", v
}
rest = rest[1:] // consume equals sign
rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
value, rest2 := consumeValue(rest)
if value == "" && rest2 == rest {
Expand Down
5 changes: 3 additions & 2 deletions src/net/http/fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -1017,12 +1017,13 @@ func parseRange(s string, size int64) ([]httpRange, error) {
return nil, nil // header not present
}
const b = "bytes="
if !strings.HasPrefix(s, b) {
s, cut := strings.CutPrefix(s, b)
if !cut {
return nil, errors.New("invalid range")
}
var ranges []httpRange
noOverlap := false
for ra := range strings.SplitSeq(s[len(b):], ",") {
for ra := range strings.SplitSeq(s, ",") {
ra = textproto.TrimString(ra)
if ra == "" {
continue
Expand Down
4 changes: 2 additions & 2 deletions src/net/http/h2_bundle.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions src/net/http/httptest/recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,14 +224,15 @@ func (rw *ResponseRecorder) Result() *http.Response {
}
}
for k, vv := range rw.HeaderMap {
if !strings.HasPrefix(k, http.TrailerPrefix) {
k, cut := strings.CutPrefix(k, http.TrailerPrefix)
if !cut {
continue
}
if res.Trailer == nil {
res.Trailer = make(http.Header)
}
for _, v := range vv {
res.Trailer.Add(strings.TrimPrefix(k, http.TrailerPrefix), v)
res.Trailer.Add(k, v)
}
}
return res
Expand Down