internal: fix MaxSizeSubjectsListForLog off-by-one when maxToDisplay is 0

The loop appended before checking the length, so with maxToDisplay=0
one domain leaked into the output before the break check. Reorder so
the length check comes first.

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
add-tests
Mohammed Al Sahaf 2026-08-30 18:21:59 +03:00
parent 39b87003af
commit af716aa9fb
No known key found for this signature in database
2 changed files with 3 additions and 7 deletions

View File

@ -10,10 +10,10 @@ func MaxSizeSubjectsListForLog(subjects map[string]struct{}, maxToDisplay int) [
numberOfNamesToDisplay := min(len(subjects), maxToDisplay)
domainsToDisplay := make([]string, 0, numberOfNamesToDisplay)
for domain := range subjects {
domainsToDisplay = append(domainsToDisplay, domain)
if len(domainsToDisplay) >= numberOfNamesToDisplay {
break
}
domainsToDisplay = append(domainsToDisplay, domain)
}
if len(subjects) > maxToDisplay {
domainsToDisplay = append(domainsToDisplay, fmt.Sprintf("(and %d more...)", len(subjects)-maxToDisplay))

View File

@ -90,12 +90,8 @@ func TestMaxSizeSubjectsListForLog(t *testing.T) {
"b.com": {},
},
maxToDisplay: 0,
// BUG: When maxToDisplay is 0, code still appends one domain
// because append happens before the break check in the loop.
// Expected behavior: 1 item (just suffix). Actual: 2 items
// (1 leaked domain + suffix).
wantLen: 2,
wantSuffix: true,
wantLen: 1,
wantSuffix: true,
},
{
name: "single subject with max 1",