Skip to content

Commit

Permalink
all: use min/max functions
Browse files Browse the repository at this point in the history
They are shorter, more readable, and don't require temp vars.
  • Loading branch information
dvyukov committed Jan 17, 2025
1 parent f9e07a6 commit 5d04aae
Show file tree
Hide file tree
Showing 39 changed files with 93 additions and 296 deletions.
10 changes: 2 additions & 8 deletions dashboard/app/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,7 @@ func dropEntities(c context.Context, keys []*db.Key, dryRun bool) error {
return nil
}
for len(keys) != 0 {
batch := 100
if batch > len(keys) {
batch = len(keys)
}
batch := min(len(keys), 100)
if err := db.DeleteMulti(c, keys[:batch]); err != nil {
return err
}
Expand Down Expand Up @@ -383,10 +380,7 @@ func updateHeadReproLevel(c context.Context, w http.ResponseWriter, r *http.Requ

func updateBatch[T any](c context.Context, keys []*db.Key, transform func(key *db.Key, item *T)) error {
for len(keys) != 0 {
batchSize := 20
if batchSize > len(keys) {
batchSize = len(keys)
}
batchSize := min(len(keys), 20)
batchKeys := keys[:batchSize]
keys = keys[batchSize:]

Expand Down
32 changes: 8 additions & 24 deletions dashboard/app/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -906,12 +906,8 @@ func reportCrash(c context.Context, build *Build, req *dashapi.Crash) (*Bug, err
bug.NumRepro++
bug.LastReproTime = now
}
if bug.ReproLevel < reproLevel {
bug.ReproLevel = reproLevel
}
if bug.HeadReproLevel < reproLevel {
bug.HeadReproLevel = reproLevel
}
bug.ReproLevel = max(bug.ReproLevel, reproLevel)
bug.HeadReproLevel = max(bug.HeadReproLevel, reproLevel)
if len(req.Report) != 0 {
bug.HasReport = true
}
Expand Down Expand Up @@ -1231,28 +1227,16 @@ func apiManagerStats(c context.Context, ns string, payload io.Reader) (interface
mgr.Link = req.Addr
mgr.LastAlive = now
mgr.CurrentUpTime = req.UpTime
if cur := int64(req.Corpus); cur > stats.MaxCorpus {
stats.MaxCorpus = cur
}
if cur := int64(req.PCs); cur > stats.MaxPCs {
stats.MaxPCs = cur
}
if cur := int64(req.Cover); cur > stats.MaxCover {
stats.MaxCover = cur
}
if cur := int64(req.CrashTypes); cur > stats.CrashTypes {
stats.CrashTypes = cur
}
stats.MaxCorpus = max(stats.MaxCorpus, int64(req.Corpus))
stats.MaxPCs = max(stats.MaxPCs, int64(req.PCs))
stats.MaxCover = max(stats.MaxCover, int64(req.Cover))
stats.CrashTypes = max(stats.CrashTypes, int64(req.CrashTypes))
stats.TotalFuzzingTime += req.FuzzingTime
stats.TotalCrashes += int64(req.Crashes)
stats.SuppressedCrashes += int64(req.SuppressedCrashes)
stats.TotalExecs += int64(req.Execs)
if cur := int64(req.TriagedCoverage); cur > stats.TriagedCoverage {
stats.TriagedCoverage = cur
}
if cur := int64(req.TriagedPCs); cur > stats.TriagedPCs {
stats.TriagedPCs = cur
}
stats.TriagedCoverage = max(stats.TriagedCoverage, int64(req.TriagedCoverage))
stats.TriagedPCs = max(stats.TriagedPCs, int64(req.TriagedPCs))
return nil
})
return nil, err
Expand Down
18 changes: 5 additions & 13 deletions dashboard/app/graphs.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,13 +295,8 @@ func createBugsGraph(c context.Context, bugs []*Bug) *uiGraph {
m := make(map[int]*BugStats)
maxWeek := 0
bugStatsFor := func(t time.Time) *BugStats {
week := int(now.Sub(t) / (30 * 24 * time.Hour))
if week < 0 {
week = 0
}
if maxWeek < week {
maxWeek = week
}
week := max(0, int(now.Sub(t)/(30*24*time.Hour)))
maxWeek = max(maxWeek, week)
bs := m[week]
if bs == nil {
bs = new(BugStats)
Expand Down Expand Up @@ -564,22 +559,19 @@ func createManagersGraph(c context.Context, ns string, selManagers, selMetrics [
// comparable across different managers.
if len(selMetrics) > 1 {
for metricIndex := range selMetrics {
max := float32(1)
maxVal := float32(1)
for col := range graph.Columns {
for mgrIndex := range selManagers {
item := graph.Columns[col].Vals[mgrIndex*len(selMetrics)+metricIndex]
if item.IsNull {
continue
}
val := item.Val
if max < val {
max = val
}
maxVal = max(maxVal, item.Val)
}
}
for col := range graph.Columns {
for mgrIndex := range selManagers {
graph.Columns[col].Vals[mgrIndex*len(selMetrics)+metricIndex].Val /= max * 100
graph.Columns[col].Vals[mgrIndex*len(selMetrics)+metricIndex].Val /= maxVal * 100
}
}
}
Expand Down
4 changes: 1 addition & 3 deletions dashboard/app/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -1991,9 +1991,7 @@ func mergeUIBug(c context.Context, bug *uiBug, dup *Bug) {
if bug.LastTime.Before(dup.LastTime) {
bug.LastTime = dup.LastTime
}
if bug.ReproLevel < dup.ReproLevel {
bug.ReproLevel = dup.ReproLevel
}
bug.ReproLevel = max(bug.ReproLevel, dup.ReproLevel)
updateBugBadness(c, bug)
}

Expand Down
18 changes: 6 additions & 12 deletions dashboard/app/reporting.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,20 +366,16 @@ func (bug *Bug) obsoletePeriod(c context.Context) time.Duration {
days = days * 3
period = time.Hour * time.Duration(24*days)
}
min, max := config.Obsoleting.MinPeriod, config.Obsoleting.MaxPeriod
minVal, maxVal := config.Obsoleting.MinPeriod, config.Obsoleting.MaxPeriod
if config.Obsoleting.NonFinalMinPeriod != 0 &&
bug.Reporting[len(bug.Reporting)-1].Reported.IsZero() {
min, max = config.Obsoleting.NonFinalMinPeriod, config.Obsoleting.NonFinalMaxPeriod
minVal, maxVal = config.Obsoleting.NonFinalMinPeriod, config.Obsoleting.NonFinalMaxPeriod
}
if mgr := bug.managerConfig(c); mgr != nil && mgr.ObsoletingMinPeriod != 0 {
min, max = mgr.ObsoletingMinPeriod, mgr.ObsoletingMaxPeriod
}
if period < min {
period = min
}
if period > max {
period = max
minVal, maxVal = mgr.ObsoletingMinPeriod, mgr.ObsoletingMaxPeriod
}
period = max(period, minVal)
period = min(period, maxVal)
return period
}

Expand Down Expand Up @@ -1042,9 +1038,7 @@ func incomingCommandUpdate(c context.Context, now time.Time, cmd *dashapi.BugUpd
merged := email.MergeEmailLists(strings.Split(bugReporting.CC, "|"), cmd.CC)
bugReporting.CC = strings.Join(merged, "|")
}
if bugReporting.ReproLevel < cmd.ReproLevel {
bugReporting.ReproLevel = cmd.ReproLevel
}
bugReporting.ReproLevel = max(bugReporting.ReproLevel, cmd.ReproLevel)
if bug.Status != BugStatusDup {
bug.DupOf = ""
}
Expand Down
4 changes: 1 addition & 3 deletions dashboard/app/reporting_lists.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,9 +289,7 @@ func querySubsystemReport(c context.Context, subsystem *Subsystem, reporting *Re
if takeNoRepro+len(withRepro) < config.BugsInReport {
takeNoRepro = config.BugsInReport - len(withRepro)
}
if takeNoRepro > len(noRepro) {
takeNoRepro = len(noRepro)
}
takeNoRepro = min(takeNoRepro, len(noRepro))
sort.Slice(noRepro, func(i, j int) bool {
return noRepro[i].NumCrashes > noRepro[j].NumCrashes
})
Expand Down
5 changes: 1 addition & 4 deletions dashboard/app/stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,7 @@ func allBugInputs(c context.Context, ns string) ([]*bugInput, error) {
func getAllMulti[T any](c context.Context, keys []*db.Key, objects []*T) (*db.Key, error) {
const step = 1000
for from := 0; from < len(keys); from += step {
to := from + step
if to > len(keys) {
to = len(keys)
}
to := min(from+step, len(keys))
err := db.GetMulti(c, keys[from:to], objects[from:to])
if err == nil {
continue
Expand Down
4 changes: 1 addition & 3 deletions pkg/ast/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,7 @@ func (n *Struct) serialize(w io.Writer) {
maxTabs := 0
for _, f := range n.Fields {
tabs := (len(f.Name.Name) + tabWidth) / tabWidth
if maxTabs < tabs {
maxTabs = tabs
}
maxTabs = max(maxTabs, tabs)
}
for _, f := range n.Fields {
if f.NewBlock {
Expand Down
16 changes: 2 additions & 14 deletions pkg/bisect/bisect.go
Original file line number Diff line number Diff line change
Expand Up @@ -928,9 +928,7 @@ func (env *env) postTestResult(res *testResult) {
// Let's be conservative and only decrease our reproduction likelihood estimate.
// As the estimate of each test() can also be flaky, only partially update the result.
avg := (env.reproChance + res.badRatio) / 2.0
if env.reproChance > avg {
env.reproChance = avg
}
env.reproChance = min(env.reproChance, avg)
}
}

Expand Down Expand Up @@ -1086,7 +1084,7 @@ func pickReleaseTags(all []string) []string {
}
var ret []string
// Take 2 latest sub releases.
takeSubReleases := minInts(2, len(subReleases))
takeSubReleases := min(2, len(subReleases))
ret = append(ret, subReleases[:takeSubReleases]...)
// If there are a lot of sub releases, also take the middle one.
if len(subReleases) > 5 {
Expand All @@ -1107,13 +1105,3 @@ func pickReleaseTags(all []string) []string {
}
return ret
}

func minInts(vals ...int) int {
ret := vals[0]
for i := 1; i < len(vals); i++ {
if vals[i] < ret {
ret = vals[i]
}
}
return ret
}
5 changes: 1 addition & 4 deletions pkg/bisect/minimize/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,10 +257,7 @@ func splitChunk[T any](chunk []T, parts int) [][]T {
}
var ret [][]T
for i := 0; i < len(chunk); i += chunkSize {
end := i + chunkSize
if end > len(chunk) {
end = len(chunk)
}
end := min(i+chunkSize, len(chunk))
ret = append(ret, chunk[i:end])
}
return ret
Expand Down
12 changes: 3 additions & 9 deletions pkg/compiler/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,9 +284,7 @@ func (comp *compiler) layoutUnion(t *prog.UnionType) {
" which is less than field %v size %v",
structNode.Name.Name, sizeAttr, fld.Type.Name(), sz)
}
if t.TypeSize < sz {
t.TypeSize = sz
}
t.TypeSize = max(t.TypeSize, sz)
}
if hasSize {
t.TypeSize = sizeAttr
Expand All @@ -313,9 +311,7 @@ func (comp *compiler) layoutStruct(t *prog.StructType) {
size = 0
}
size += f.Size()
if t.TypeSize < size {
t.TypeSize = size
}
t.TypeSize = max(t.TypeSize, size)
}
sizeAttr, hasSize := attrs[attrSize]
if hasSize {
Expand Down Expand Up @@ -348,9 +344,7 @@ func (comp *compiler) layoutStructFields(t *prog.StructType, varlen, packed bool
fieldAlign := uint64(1)
if !packed {
fieldAlign = f.Alignment()
if structAlign < fieldAlign {
structAlign = fieldAlign
}
structAlign = max(structAlign, fieldAlign)
}
fullBitOffset := byteOffset*8 + bitOffset
var fieldOffset uint64
Expand Down
9 changes: 2 additions & 7 deletions pkg/compiler/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -1007,9 +1007,7 @@ func init() {
case *prog.UnionType:
typ1.Fields = fields
for _, f := range fields {
if a := f.Type.Alignment(); typ1.TypeAlign < a {
typ1.TypeAlign = a
}
typ1.TypeAlign = max(typ1.TypeAlign, f.Type.Alignment())
}
case *prog.StructType:
typ1.Fields = fields
Expand All @@ -1028,10 +1026,7 @@ func init() {
typ1.TypeAlign = 1
} else {
for _, f := range fields {
a := f.Type.Alignment()
if typ1.TypeAlign < a {
typ1.TypeAlign = a
}
typ1.TypeAlign = max(typ1.TypeAlign, f.Type.Alignment())
}
}
}
Expand Down
18 changes: 4 additions & 14 deletions pkg/cover/backend/dwarf.go
Original file line number Diff line number Diff line change
Expand Up @@ -405,21 +405,14 @@ func readTextRanges(debugInfo *dwarf.Data, module *vminfo.KernelModule, pcFix pc

func symbolizeModule(target *targets.Target, interner *symbolizer.Interner, objDir, srcDir, buildDir string,
splitBuildDelimiters []string, mod *vminfo.KernelModule, pcs []uint64) ([]Frame, error) {
procs := runtime.GOMAXPROCS(0) / 2
if need := len(pcs) / 1000; procs > need {
procs = need
}
procs := min(runtime.GOMAXPROCS(0)/2, len(pcs)/1000)
const (
minProcs = 1
maxProcs = 4
)
// addr2line on a beefy vmlinux takes up to 1.6GB of RAM, so don't create too many of them.
if procs > maxProcs {
procs = maxProcs
}
if procs < minProcs {
procs = minProcs
}
procs = min(procs, maxProcs)
procs = max(procs, minProcs)
type symbolizerResult struct {
frames []symbolizer.Frame
err error
Expand Down Expand Up @@ -449,10 +442,7 @@ func symbolizeModule(target *targets.Target, interner *symbolizer.Interner, objD
}()
}
for i := 0; i < len(pcs); {
end := i + 100
if end > len(pcs) {
end = len(pcs)
}
end := min(i+100, len(pcs))
pcchan <- pcs[i:end]
i = end
}
Expand Down
19 changes: 4 additions & 15 deletions pkg/cover/html.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,7 @@ func fileLineContents(file *file, lines [][]byte) lineCoverExport {
start := 0
cover := append(lineCover[i+1], lineCoverChunk{End: backend.LineEnd})
for _, cov := range cover {
end := cov.End - 1
if end > len(ln) {
end = len(ln)
}
end := min(cov.End-1, len(ln))
if end == start {
continue
}
Expand Down Expand Up @@ -661,10 +658,7 @@ func fileContents(file *file, lines [][]byte, haveProgs bool) string {
start := 0
cover := append(lineCover[i+1], lineCoverChunk{End: backend.LineEnd})
for _, cov := range cover {
end := cov.End - 1
if end > len(ln) {
end = len(ln)
}
end := min(cov.End-1, len(ln))
if end == start {
continue
}
Expand Down Expand Up @@ -708,9 +702,7 @@ func perLineCoverage(covered, uncovered []backend.Range) map[int][]lineCoverChun

func mergeRange(lines map[int][]lineCoverChunk, r backend.Range, covered bool) {
// Don't panic on broken debug info, it is frequently broken.
if r.EndLine < r.StartLine {
r.EndLine = r.StartLine
}
r.EndLine = max(r.EndLine, r.StartLine)
if r.EndLine == r.StartLine && r.EndCol <= r.StartCol {
r.EndCol = backend.LineEnd
}
Expand Down Expand Up @@ -750,10 +742,7 @@ func mergeLine(chunks []lineCoverChunk, start, end int, covered bool) []lineCove
if chunkStart < start {
res = append(res, lineCoverChunk{start, chunk.Covered, chunk.Uncovered})
}
mid := end
if mid > chunk.End {
mid = chunk.End
}
mid := min(end, chunk.End)
res = append(res, lineCoverChunk{mid, chunk.Covered || covered, chunk.Uncovered || !covered})
if chunk.End > end {
res = append(res, lineCoverChunk{chunk.End, chunk.Covered, chunk.Uncovered})
Expand Down
4 changes: 1 addition & 3 deletions pkg/instance/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,9 +273,7 @@ func (env *env) Test(numVMs int, reproSyz, reproOpts, reproC []byte) ([]EnvTestR
return nil, fmt.Errorf("failed to create VM pool: %w", err)
}
defer vmPool.Close()
if n := vmPool.Count(); numVMs > n {
numVMs = n
}
numVMs = min(numVMs, vmPool.Count())
res := make(chan EnvTestResult, numVMs)
for i := 0; i < numVMs; i++ {
inst := &inst{
Expand Down
Loading

0 comments on commit 5d04aae

Please sign in to comment.