golang.org/x/build@v0.0.0-20240506185731-218518f32b70/internal/foreach/foreach.go (about) 1 // Copyright 2019 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package foreach provides allocation-conscious helpers 6 // for iterating over lines of text. 7 // 8 // They're factored out into a separate small package primarily 9 // to allow them to have allocation-measuring tests that need 10 // to run without interference from other goroutine-leaking tests. 11 package foreach 12 13 import ( 14 "bytes" 15 "strings" 16 ) 17 18 // Line calls f on each line in v, without the trailing '\n'. 19 // The final line need not include a trailing '\n'. 20 // Returns first non-nil error returned by f. 21 func Line(v []byte, f func([]byte) error) error { 22 for len(v) > 0 { 23 i := bytes.IndexByte(v, '\n') 24 if i < 0 { 25 return f(v) 26 } 27 if err := f(v[:i]); err != nil { 28 return err 29 } 30 v = v[i+1:] 31 } 32 return nil 33 } 34 35 // LineStr calls f on each line in s, without the trailing '\n'. 36 // The final line need not include a trailing '\n'. 37 // Returns first non-nil error returned by f. 38 // 39 // LineStr is the string variant of Line. 40 func LineStr(s string, f func(string) error) error { 41 for len(s) > 0 { 42 i := strings.IndexByte(s, '\n') 43 if i < 0 { 44 return f(s) 45 } 46 if err := f(s[:i]); err != nil { 47 return err 48 } 49 s = s[i+1:] 50 } 51 return nil 52 }