From bf93227272fb8d21b8ef98962606e5873e7d1b49 Mon Sep 17 00:00:00 2001 From: Inhere Date: Thu, 7 Jul 2022 17:58:52 +0800 Subject: [PATCH] fix: RGBFromString() maybe input overflow int value --- color_rgb.go | 8 ++++---- color_rgb_test.go | 3 +++ utils.go | 5 +++++ 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/color_rgb.go b/color_rgb.go index cc87a4d..ff3c1bb 100644 --- a/color_rgb.go +++ b/color_rgb.go @@ -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 diff --git a/color_rgb_test.go b/color_rgb_test.go index 930d81b..347eecc 100644 --- a/color_rgb_test.go +++ b/color_rgb_test.go @@ -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) { diff --git a/utils.go b/utils.go index 9b3f0ca..d4bb78d 100644 --- a/utils.go +++ b/utils.go @@ -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 {