From 33abe87c5bcf9e3e41ca4030cdce63e7250c6870 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 29 Nov 2017 12:18:03 -0600 Subject: [PATCH] IntInSlice and StringInSlice functions Refs https://github.com/tendermint/tendermint/pull/835 --- common/int.go | 10 ++++++++++ common/int_test.go | 14 ++++++++++++++ common/string.go | 10 ++++++++++ common/string_test.go | 14 ++++++++++++++ 4 files changed, 48 insertions(+) create mode 100644 common/int_test.go create mode 100644 common/string_test.go diff --git a/common/int.go b/common/int.go index 756e38cd..a8a5f1e0 100644 --- a/common/int.go +++ b/common/int.go @@ -53,3 +53,13 @@ func PutInt64BE(dest []byte, i int64) { func GetInt64BE(src []byte) int64 { return int64(binary.BigEndian.Uint64(src)) } + +// IntInSlice returns true if a is found in the list. +func IntInSlice(a int, list []int) bool { + for _, b := range list { + if b == a { + return true + } + } + return false +} diff --git a/common/int_test.go b/common/int_test.go new file mode 100644 index 00000000..1ecc7844 --- /dev/null +++ b/common/int_test.go @@ -0,0 +1,14 @@ +package common + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIntInSlice(t *testing.T) { + assert.True(t, IntInSlice(1, []int{1, 2, 3})) + assert.False(t, IntInSlice(4, []int{1, 2, 3})) + assert.True(t, IntInSlice(0, []int{0})) + assert.False(t, IntInSlice(0, []int{})) +} diff --git a/common/string.go b/common/string.go index 1ab91f15..6924e6a5 100644 --- a/common/string.go +++ b/common/string.go @@ -43,3 +43,13 @@ func StripHex(s string) string { } return s } + +// StringInSlice returns true if a is found the list. +func StringInSlice(a string, list []string) bool { + for _, b := range list { + if b == a { + return true + } + } + return false +} diff --git a/common/string_test.go b/common/string_test.go new file mode 100644 index 00000000..a82f1022 --- /dev/null +++ b/common/string_test.go @@ -0,0 +1,14 @@ +package common + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestStringInSlice(t *testing.T) { + assert.True(t, StringInSlice("a", []string{"a", "b", "c"})) + assert.False(t, StringInSlice("d", []string{"a", "b", "c"})) + assert.True(t, StringInSlice("", []string{""})) + assert.False(t, StringInSlice("", []string{})) +}