From 28271d1fa752a1fc1d4a8fa66ac4e8ba23fe9a03 Mon Sep 17 00:00:00 2001 From: Wei He Date: Tue, 18 Apr 2023 12:21:07 +0900 Subject: [PATCH] Fix slice access out of bound error (#8) --- CHANGELOG.md | 4 ++++ v2/common.go | 7 +++++++ v2/pack.go | 16 +++++++++++++++- v2/pack_test.go | 3 ++- 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 518c564..bf06c4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # CHANGELOG +## 2.0.1 (2023-04-18) + +* Fix slice access out of bound error + ## 2.0.0 (2023-04-14) * Support Go 1.20. diff --git a/v2/common.go b/v2/common.go index f763e38..decf084 100644 --- a/v2/common.go +++ b/v2/common.go @@ -20,6 +20,13 @@ func max[T constraints.Ordered](a T, b T) T { return b } +func min[T constraints.Ordered](a T, b T) T { + if a < b { + return a + } + return b +} + func regularizeHosts(hosts []string) []string { if hosts == nil { return nil diff --git a/v2/pack.go b/v2/pack.go index 1849039..f0c190a 100644 --- a/v2/pack.go +++ b/v2/pack.go @@ -224,13 +224,24 @@ func (h *host) appendToken(token string, digitMode bool) { } func (h *host) Less(rhs *host) bool { - for i := range h.NonDigits { + m := min(len(h.NonDigits), len(rhs.NonDigits)) + for i := 0; i < m; i++ { if h.NonDigits[i] < rhs.NonDigits[i] { return true } if h.NonDigits[i] > rhs.NonDigits[i] { return false } + } + if len(h.NonDigits) < len(rhs.NonDigits) { + return true + } + if len(h.NonDigits) > len(rhs.NonDigits) { + return false + } + + m = min(len(h.Digits), len(rhs.Digits)) + for i := 0; i < m; i++ { if h.Digits[i].Digit < rhs.Digits[i].Digit { return true } @@ -244,6 +255,9 @@ func (h *host) Less(rhs *host) bool { return false } } + if len(h.Digits) < len(rhs.Digits) { + return true + } return false } diff --git a/v2/pack_test.go b/v2/pack_test.go index dbdc4f9..dc0f26a 100644 --- a/v2/pack_test.go +++ b/v2/pack_test.go @@ -17,9 +17,10 @@ func TestPack(t *testing.T) { {[]string{"abc101z", "abc102z"}, []string{"abc[101-102]z"}}, {[]string{"abc103z", "abc102z", "abc101z"}, []string{"abc[101-103]z"}}, {[]string{"abc101z", "abc102z", "abc104z"}, []string{"abc[101-102,104]z"}}, - {[]string{"abc101z", "abc102z", "abc104"}, []string{"abc[101-102]z", "abc104"}}, + {[]string{"abc101z", "abc102z", "abc104"}, []string{"abc104", "abc[101-102]z"}}, {[]string{"abc101z-02", "abc102z-02", "abc102z-03"}, []string{"abc[101-102]z-02", "abc102z-03"}}, {[]string{"abc101z-01", "abc102z-02", "abc102z-03"}, []string{"abc101z-01", "abc102z-[02-03]"}}, + {[]string{"abc101z-01p", "abc101z-01q", "abc102z-01p", "abc102z-01q"}, []string{"abc[101-102]z-01p", "abc[101-102]z-01q"}}, } for _, test := range cases { test := test