Skip to content

Commit f7fd4ef

Browse files
committed
cmd/stringer: omit negative bounds check from String() for unsigned integers
Commit 82041a1 ("cmd/stringer: fix bounds checking for integer types spanning full range") introduced a universal lower bounds check for all integers, including unsigned ints. Unfortunately, performing a <0 bounds check on a uint gets flagged by static analysis tools like staticcheck. This commit only emits the bounds check if the type in question is either signed or has a non-zero minimum value, in which case the bounds check is necessary for unsigned types as well. Signed-off-by: Timo Beckers <timo@incline.eu>
1 parent d2096d1 commit f7fd4ef

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

cmd/stringer/stringer.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -641,14 +641,35 @@ func (g *Generator) buildOneRun(runs [][]Value, typeName string) {
641641
values := runs[0]
642642
g.Printf("\n")
643643
g.declareIndexAndNameVar(values, typeName)
644-
g.Printf(stringOneRun, typeName, values[0].String())
644+
645+
if values[0].signed || values[0].String() != "0" {
646+
g.Printf(stringOneRunSigned, typeName, values[0].String())
647+
} else {
648+
g.Printf(stringOneRun, typeName, values[0].String())
649+
}
645650
}
646651

647652
// Arguments to format are:
648653
//
649654
// [1]: type name
650655
// [2]: lowest defined value for type, as a string
651656
const stringOneRun = `func (i %[1]s) String() string {
657+
idx := int(i) - %[2]s
658+
if idx >= len(_%[1]s_index)-1 {
659+
return "%[1]s(" + strconv.FormatInt(int64(i), 10) + ")"
660+
}
661+
return _%[1]s_name[_%[1]s_index[idx] : _%[1]s_index[idx+1]]
662+
}
663+
`
664+
665+
// Arguments to format are:
666+
//
667+
// [1]: type name
668+
// [2]: lowest defined value for type, as a string
669+
//
670+
// This is the signed version of [stringOneRun] with an extra bounds check for
671+
// negative values.
672+
const stringOneRunSigned = `func (i %[1]s) String() string {
652673
idx := int(i) - %[2]s
653674
if i < %[2]s || idx >= len(_%[1]s_index)-1 {
654675
return "%[1]s(" + strconv.FormatInt(int64(i), 10) + ")"

0 commit comments

Comments
 (0)