Skip to content

Commit

Permalink
fix: RGBFromString() maybe input overflow int value
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jul 7, 2022
1 parent 1905566 commit bf93227
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 4 deletions.
8 changes: 4 additions & 4 deletions color_rgb.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,17 +156,17 @@ func RGBFromString(rgb string, isBg ...bool) RGBColor {
return emptyRGBColor
}

var ar [3]int
var ar [3]uint8
for i, val := range ss {
iv, err := strconv.Atoi(val)
if err != nil {
if err != nil || !isValidUint8(iv) {
return emptyRGBColor
}

ar[i] = iv
ar[i] = uint8(iv)
}

return RGB(uint8(ar[0]), uint8(ar[1]), uint8(ar[2]), isBg...)
return RGB(ar[0], ar[1], ar[2], isBg...)
}

// Set terminal by rgb/true color code
Expand Down
3 changes: 3 additions & 0 deletions color_rgb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ func TestRGBFromString(t *testing.T) {

c = RGBFromString("170,187,error")
is.Equal("msg", c.Sprint("msg"))

c = RGBFromString("170,-187,-34")
is.Equal("msg", c.Sprint("msg"))
}

func TestHexToRGB(t *testing.T) {
Expand Down
5 changes: 5 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,11 @@ func debugf(f string, v ...interface{}) {
}
}

// equals: return ok ? val1 : val2
func isValidUint8(val int) bool {
return val >= 0 && val < 256
}

// equals: return ok ? val1 : val2
func compareVal(ok bool, val1, val2 uint8) uint8 {
if ok {
Expand Down

0 comments on commit bf93227

Please sign in to comment.