From 6a0352da389af334d333018d1574e5da42a6a0b2 Mon Sep 17 00:00:00 2001 From: Nguyen Ba Tam Date: Tue, 6 Nov 2018 14:14:40 +0700 Subject: [PATCH 1/2] fix error panic in func RemoveItemFromArray --- common/types.go | 10 +++++++++- common/types_test.go | 6 +++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/common/types.go b/common/types.go index 8877b5bd1a..54658709ac 100644 --- a/common/types.go +++ b/common/types.go @@ -249,12 +249,20 @@ func RemoveItemFromArray(array []Address, items []Address) []Address { if items == nil { return array } - for i, value := range array { + i := 0; + for i < len(array) { + value := array[i] + remove := false for _, item := range items { if value == item { array = append(array[:i], array[i+1:]...) + remove = true + break } } + if !remove { + i++ + } } return array } diff --git a/common/types_test.go b/common/types_test.go index 4b01bc275d..e481db96c3 100644 --- a/common/types_test.go +++ b/common/types_test.go @@ -151,10 +151,10 @@ func BenchmarkAddressHex(b *testing.B) { } func TestRemoveItemInArray(t *testing.T) { - array := []Address{HexToAddress("0x0000000"), HexToAddress("0x0000001"), HexToAddress("0x0000002")} - remove := []Address{HexToAddress("0x0000000"), HexToAddress("0x0000004"), HexToAddress("0x0000003")} + array := []Address{HexToAddress("0x0000003"),HexToAddress("0x0000001"), HexToAddress("0x0000002"),HexToAddress("0x0000003")} + remove := []Address{HexToAddress("0x0000002"), HexToAddress("0x0000004"), HexToAddress("0x0000003")} array = RemoveItemFromArray(array, remove) - if len(array) != 2 { + if len(array) != 1 { t.Error("fail remove item from array address") } } From 942893594dacf121c3d43256c15dd7fd753a5d14 Mon Sep 17 00:00:00 2001 From: Tuna Date: Sat, 10 Nov 2018 10:15:43 +0700 Subject: [PATCH 2/2] refactor RemoveItemFromArray --- common/types.go | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/common/types.go b/common/types.go index 54658709ac..95ea6bc17b 100644 --- a/common/types.go +++ b/common/types.go @@ -246,24 +246,18 @@ func (a UnprefixedAddress) MarshalText() ([]byte, error) { // Extract validators from byte array. func RemoveItemFromArray(array []Address, items []Address) []Address { - if items == nil { + if len(items) == 0 { return array } - i := 0; - for i < len(array) { - value := array[i] - remove := false - for _, item := range items { - if value == item { + + for _, item := range items { + for i := len(array) - 1; i >= 0; i-- { + if array[i] == item { array = append(array[:i], array[i+1:]...) - remove = true - break } } - if !remove { - i++ - } } + return array }