Skip to content

Commit

Permalink
Replace explicit int loops with range-over-int (#7434)
Browse files Browse the repository at this point in the history
This adopts modern Go syntax to reduce the chance of off-by-one errors
and remove unnecessary loop variable declarations.

Fixes #7227
  • Loading branch information
aarongable committed Apr 22, 2024
1 parent 89b07f4 commit e05d47a
Show file tree
Hide file tree
Showing 46 changed files with 119 additions and 107 deletions.
7 changes: 4 additions & 3 deletions akamai/cache-client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@ import (
"time"

"github.com/jmhodges/clock"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/ocsp"

"github.com/letsencrypt/boulder/core"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/metrics"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/ocsp"
)

const (
Expand Down Expand Up @@ -279,7 +280,7 @@ func (cpc *CachePurgeClient) authedRequest(endpoint string, body v3PurgeRequest)
// and returning ErrAllRetriesFailed.
func (cpc *CachePurgeClient) Purge(urls []string) error {
successful := false
for i := 0; i <= cpc.retries; i++ {
for i := range cpc.retries + 1 {
cpc.clk.Sleep(core.RetryBackoff(i, cpc.retryBackoff, time.Minute, 1.3))

err := cpc.purgeURLs(urls)
Expand Down
3 changes: 2 additions & 1 deletion akamai/cache-client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"time"

"github.com/jmhodges/clock"

blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/metrics"
"github.com/letsencrypt/boulder/test"
Expand Down Expand Up @@ -247,7 +248,7 @@ func TestBigBatchPurge(t *testing.T) {
test.AssertNotError(t, err, "Failed to create CachePurgeClient")

var urls []string
for i := 0; i < 250; i++ {
for i := range 250 {
urls = append(urls, fmt.Sprintf("http://test.com/%d", i))
}

Expand Down
2 changes: 1 addition & 1 deletion bdns/dns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -827,7 +827,7 @@ func TestRotateServerOnErr(t *testing.T) {
// in the list. Since we configured maxTries to be larger than the number of
// servers *all* queries should eventually succeed by being retried against
// server "[2606:4700:4700::1111]:53".
for i := 0; i < maxTries*2; i++ {
for range maxTries * 2 {
_, resolvers, err := client.LookupTXT(context.Background(), "example.com")
test.AssertEquals(t, len(resolvers), 1)
test.AssertEquals(t, resolvers[0], "[2606:4700:4700::1111]:53")
Expand Down
4 changes: 2 additions & 2 deletions ca/crl.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ func (ci *crlImpl) GenerateCRL(stream capb.CRLGenerator_GenerateCRLServer) error

if len(rcs) > 0 {
builder := strings.Builder{}
for i := 0; i < len(rcs); i += 1 {
for i := range len(rcs) {
if builder.Len() == 0 {
fmt.Fprintf(&builder, "Signing CRL: logID=[%s] entries=[", logID)
}
Expand Down Expand Up @@ -151,7 +151,7 @@ func (ci *crlImpl) GenerateCRL(stream capb.CRLGenerator_GenerateCRLServer) error
logID, len(crlBytes), hash,
)

for i := 0; i < len(crlBytes); i += 1000 {
for i := range len(crlBytes) {
j := i + 1000
if j > len(crlBytes) {
j = len(crlBytes)
Expand Down
2 changes: 1 addition & 1 deletion ca/ocsp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ func TestOcspFlushOnLength(t *testing.T) {
stats := metrics.NoopRegisterer
queue := newOCSPLogQueue(100, 100*time.Millisecond, stats, log)
go queue.loop()
for i := 0; i < 5; i++ {
for range 5 {
queue.enqueue(serial(t), time.Now(), ocsp.Good, ocsp.Unspecified)
}
queue.stop()
Expand Down
2 changes: 1 addition & 1 deletion cmd/admin/key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func TestSPKIHashFromPrivateKey(t *testing.T) {

func TestSPKIHashesFromFile(t *testing.T) {
var spkiHexes []string
for i := 0; i < 10; i++ {
for i := range 10 {
h := sha256.Sum256([]byte(strconv.Itoa(i)))
spkiHexes = append(spkiHexes, hex.EncodeToString(h[:]))
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/akamai-purger/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func TestAkamaiPurgerQueue(t *testing.T) {
}

// Add 250 entries to fill the stack.
for i := 0; i < 250; i++ {
for i := range 250 {
req := akamaipb.PurgeRequest{Urls: []string{fmt.Sprintf("http://test.com/%d", i)}}
_, err := ap.Purge(context.Background(), &req)
test.AssertNotError(t, err, fmt.Sprintf("Purge failed for entry %d.", i))
Expand Down
2 changes: 1 addition & 1 deletion cmd/boulder/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func readAndValidateConfigFile(name, filename string) error {
// getConfigPath returns the path to the config file if it was provided as a
// command line flag. If the flag was not provided, it returns an empty string.
func getConfigPath() string {
for i := 0; i < len(os.Args); i++ {
for i := range len(os.Args) {
arg := os.Args[i]
if arg == "--config" || arg == "-config" {
if i+1 < len(os.Args) {
Expand Down
2 changes: 1 addition & 1 deletion cmd/cert-checker/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -617,7 +617,7 @@ func main() {

fmt.Fprintf(os.Stderr, "# Processing certificates using %d workers\n", config.CertChecker.Workers)
wg := new(sync.WaitGroup)
for i := 0; i < config.CertChecker.Workers; i++ {
for range config.CertChecker.Workers {
wg.Add(1)
go func() {
s := checker.clock.Now()
Expand Down
4 changes: 2 additions & 2 deletions cmd/cert-checker/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func BenchmarkCheckCert(b *testing.B) {
Expires: expiry,
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for range b.N {
checker.checkCert(context.Background(), cert, nil)
}
}
Expand Down Expand Up @@ -355,7 +355,7 @@ func TestGetAndProcessCerts(t *testing.T) {
}
reg := satest.CreateWorkingRegistration(t, isa.SA{Impl: sa})
test.AssertNotError(t, err, "Couldn't create registration")
for i := int64(0); i < 5; i++ {
for range 5 {
rawCert.SerialNumber = big.NewInt(mrand.Int63())
certDER, err := x509.CreateCertificate(rand.Reader, &rawCert, &rawCert, &testKey.PublicKey, testKey)
test.AssertNotError(t, err, "Couldn't create certificate")
Expand Down
9 changes: 5 additions & 4 deletions cmd/expiration-mailer/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ import (
"time"

"github.com/jmhodges/clock"
"github.com/prometheus/client_golang/prometheus"
io_prometheus_client "github.com/prometheus/client_model/go"
"google.golang.org/grpc"

"github.com/letsencrypt/boulder/core"
corepb "github.com/letsencrypt/boulder/core/proto"
"github.com/letsencrypt/boulder/db"
Expand All @@ -30,9 +34,6 @@ import (
"github.com/letsencrypt/boulder/test"
isa "github.com/letsencrypt/boulder/test/inmem/sa"
"github.com/letsencrypt/boulder/test/vars"
"github.com/prometheus/client_golang/prometheus"
io_prometheus_client "github.com/prometheus/client_model/go"
"google.golang.org/grpc"
)

type fakeRegStore struct {
Expand Down Expand Up @@ -100,7 +101,7 @@ func TestSendNagsManyCerts(t *testing.T) {
}

var certs []*x509.Certificate
for i := 0; i < 101; i++ {
for i := range 101 {
certs = append(certs, &x509.Certificate{
SerialNumber: big.NewInt(0x0304),
NotAfter: fc.Now().AddDate(0, 0, 2),
Expand Down
2 changes: 1 addition & 1 deletion cmd/rocsp-tool/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func (cl *client) loadFromDB(ctx context.Context, speed ProcessingSpeed, startFr

results := make(chan processResult, speed.ParallelSigns)
var runningSigners int32
for i := 0; i < speed.ParallelSigns; i++ {
for range speed.ParallelSigns {
atomic.AddInt32(&runningSigners, 1)
go cl.signAndStoreResponses(ctx, statusesToSign, results, &runningSigners)
}
Expand Down
9 changes: 5 additions & 4 deletions cmd/rocsp-tool/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import (
"time"

"github.com/jmhodges/clock"
"github.com/redis/go-redis/v9"
"golang.org/x/crypto/ocsp"
"google.golang.org/grpc"

capb "github.com/letsencrypt/boulder/ca/proto"
"github.com/letsencrypt/boulder/cmd"
"github.com/letsencrypt/boulder/core"
Expand All @@ -17,9 +21,6 @@ import (
"github.com/letsencrypt/boulder/sa"
"github.com/letsencrypt/boulder/test"
"github.com/letsencrypt/boulder/test/vars"
"github.com/redis/go-redis/v9"
"golang.org/x/crypto/ocsp"
"google.golang.org/grpc"
)

func makeClient() (*rocsp.RWClient, clock.Clock) {
Expand Down Expand Up @@ -129,7 +130,7 @@ func TestLoadFromDB(t *testing.T) {

defer test.ResetBoulderTestDatabase(t)

for i := 0; i < 100; i++ {
for i := range 100 {
err = dbMap.Insert(context.Background(), &core.CertificateStatus{
Serial: fmt.Sprintf("%036x", i),
NotAfter: clk.Now().Add(200 * time.Hour),
Expand Down
4 changes: 2 additions & 2 deletions core/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func TestNewToken(t *testing.T) {
// Test for very blatant RNG failures:
// Try 2^20 birthdays in a 2^72 search space...
// our naive collision probability here is 2^-32...
for i := 0; i < 1000000; i++ {
for range 1000000 {
token = NewToken()[:12] // just sample a portion
test.Assert(t, !collider[token], "Token collision!")
collider[token] = true
Expand Down Expand Up @@ -237,7 +237,7 @@ func BenchmarkIsAnyNilOrZero(b *testing.B) {

for _, v := range table {
b.Run(fmt.Sprintf("input_%T_%v", v.input, v.input), func(b *testing.B) {
for i := 0; i < b.N; i++ {
for range b.N {
_ = IsAnyNilOrZero(v.input)
}
})
Expand Down
6 changes: 3 additions & 3 deletions crl/updater/batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,19 +47,19 @@ func (cu *crlUpdater) RunOnce(ctx context.Context) error {

inputs := make(chan workItem)

for i := 0; i < cu.maxParallelism; i++ {
for range cu.maxParallelism {
wg.Add(1)
go shardWorker(inputs)
}

for _, issuer := range cu.issuers {
for i := 1; i <= cu.numShards; i++ {
for i := range cu.numShards {
select {
case <-ctx.Done():
close(inputs)
wg.Wait()
return ctx.Err()
case inputs <- workItem{issuerNameID: issuer.NameID(), shardIdx: i}:
case inputs <- workItem{issuerNameID: issuer.NameID(), shardIdx: i + 1}:
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crl/updater/updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func (cu *crlUpdater) updateShardWithRetry(ctx context.Context, atTime time.Time

crlID := crl.Id(issuerNameID, shardIdx, crl.Number(atTime))

for i := 0; i < cu.maxAttempts; i++ {
for i := range cu.maxAttempts {
// core.RetryBackoff always returns 0 when its first argument is zero.
sleepTime := core.RetryBackoff(i, time.Second, time.Minute, 2)
if i != 0 {
Expand Down
5 changes: 3 additions & 2 deletions ctpolicy/ctpolicy.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import (
"strings"
"time"

"github.com/prometheus/client_golang/prometheus"

"github.com/letsencrypt/boulder/core"
"github.com/letsencrypt/boulder/ctpolicy/loglist"
berrors "github.com/letsencrypt/boulder/errors"
blog "github.com/letsencrypt/boulder/log"
pubpb "github.com/letsencrypt/boulder/publisher/proto"
"github.com/prometheus/client_golang/prometheus"
)

const (
Expand Down Expand Up @@ -169,7 +170,7 @@ func (ctp *CTPolicy) GetSCTs(ctx context.Context, cert core.CertDER, expiration
// goroutine is guaranteed to write one result to the channel.
scts := make(core.SCTDERs, 0)
errs := make([]string, 0)
for i := 0; i < len(ctp.sctLogs); i++ {
for range len(ctp.sctLogs) {
res := <-results
if res.err != nil {
errs = append(errs, res.err.Error())
Expand Down
2 changes: 1 addition & 1 deletion db/gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func NewMappedSelector[T any](executor MappedExecutor) (MappedSelector[T], error
// check should be performed at the time the mapping is declared.
columns := make([]string, 0)
seen := make(map[string]struct{})
for i := 0; i < t.NumField(); i++ {
for i := range t.NumField() {
field := t.Field(i)
if field.Anonymous {
return nil, fmt.Errorf("struct contains anonymous embedded struct %q", field.Name)
Expand Down
2 changes: 1 addition & 1 deletion db/qmarks.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ func QuestionMarks(n int) string {
}
var qmarks strings.Builder
qmarks.Grow(2 * n)
for i := 0; i < n; i++ {
for i := range n {
if i == 0 {
qmarks.WriteString("?")
} else {
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/letsencrypt/boulder

go 1.21
go 1.22.0

require (
github.com/aws/aws-sdk-go-v2 v1.25.0
Expand Down
2 changes: 1 addition & 1 deletion goodkey/good_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ func checkPrimeFactorsTooClose(n *big.Int, rounds int) error {
b2 := new(big.Int)
b2.Mul(a, a).Sub(b2, n)

for i := 0; i < rounds; i++ {
for range rounds {
// To see if b2 is a perfect square, we take its square root, square that,
// and check to see if we got the same result back.
bb.Sqrt(b2).Mul(bb, bb)
Expand Down
2 changes: 1 addition & 1 deletion goodkey/good_key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ func TestCheckPrimeFactorsTooClose(t *testing.T) {
func benchFermat(rounds int, b *testing.B) {
n := big.NewInt(0)
n.SetString("801622717394169050106926578578301725055526605503706912100006286161529273473377413824975745384114446662904851914935980611269769546695796451504160869649117000521094368058953989236438103975426680952076533198797388295193391779933559668812684470909409457778161223896975426492372231040386646816154793996920467596916193680611886097694746368434138296683172992347929528214464827172059378866098534956467670429228681248968588692628197119606249988365750115578731538804653322115223303388019261933988266126675740797091559541980722545880793708750882230374320698192373040882555154628949384420712168289605526223733016176898368282023301917856921049583659644200174763940543991507836551835324807116188739389620816364505209568211448815747330488813651206715564392791134964121857454359816296832013457790067067190116393364546525054134704119475840526673114964766611499226043189928040037210929720682839683846078550615582181112536768195193557758454282232948765374797970874053642822355832904812487562117265271449547063765654262549173209805579494164339236981348054782533307762260970390747872669357067489756517340817289701322583209366268084923373164395703994945233187987667632964509271169622904359262117908604555420100186491963838567445541249128944592555657626247", 10)
for i := 0; i < b.N; i++ {
for range b.N {
if checkPrimeFactorsTooClose(n, rounds) != nil {
b.Fatal("factored the unfactorable!")
}
Expand Down
2 changes: 1 addition & 1 deletion grpc/interceptors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ func TestInFlightRPCStat(t *testing.T) {
c := test_proto.NewChillerClient(conn)

// Fire off a few RPCs. They will block on the blockedServer's roadblock wg
for i := 0; i < numRPCs; i++ {
for range numRPCs {
go func() {
// Ignore errors, just chilllll.
_, _ = c.Chill(context.Background(), &test_proto.Time{})
Expand Down
4 changes: 2 additions & 2 deletions grpc/internal/leakcheck/leakcheck_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func (e *testErrorfer) Errorf(format string, args ...interface{}) {

func TestCheck(t *testing.T) {
const leakCount = 3
for i := 0; i < leakCount; i++ {
for range leakCount {
go func() { time.Sleep(2 * time.Second) }()
}
if ig := interestingGoroutines(); len(ig) == 0 {
Expand All @@ -59,7 +59,7 @@ func ignoredTestingLeak(d time.Duration) {
func TestCheckRegisterIgnore(t *testing.T) {
RegisterIgnoreGoroutine("ignoredTestingLeak")
const leakCount = 3
for i := 0; i < leakCount; i++ {
for range leakCount {
go func() { time.Sleep(2 * time.Second) }()
}
go func() { ignoredTestingLeak(3 * time.Second) }()
Expand Down
Loading

0 comments on commit e05d47a

Please sign in to comment.