From 40772dd4bb113f3155b2ba0d6d09abf2262f9213 Mon Sep 17 00:00:00 2001 From: damuzhi0810 Date: Fri, 24 Jan 2025 10:53:33 +0800 Subject: [PATCH] refactor: using slices.Contains to simplify the code Signed-off-by: damuzhi0810 --- cmd/algons/dnsCmd.go | 9 ++------- data/transactions/logic/eval.go | 12 ++++-------- network/requestTracker.go | 8 ++------ network/wsNetwork.go | 15 ++++++--------- network/wsPeer.go | 9 ++------- shared/pingpong/accounts.go | 7 +++---- shared/pingpong/config.go | 10 ++-------- .../block-generator/generator/generator_ledger.go | 10 ++-------- util/codecs/json.go | 12 ++---------- 9 files changed, 25 insertions(+), 67 deletions(-) diff --git a/cmd/algons/dnsCmd.go b/cmd/algons/dnsCmd.go index 28c46427ca..d8d54dfc63 100644 --- a/cmd/algons/dnsCmd.go +++ b/cmd/algons/dnsCmd.go @@ -23,6 +23,7 @@ import ( "net" "os" "regexp" + "slices" "sort" "strings" @@ -439,13 +440,7 @@ func checkedDelete(toDelete []cloudflare.DNSRecordResponseEntry, cloudflareDNS * func getEntries(getNetwork string, recordType string) ([]cloudflare.DNSRecordResponseEntry, error) { recordTypes := []string{"A", "CNAME", "SRV", "TXT"} - isKnown := false - for _, known := range append(recordTypes, "") { - if recordType == known { - isKnown = true - break - } - } + isKnown := slices.Contains(recordTypes, recordType) || recordType == "" if !isKnown { return nil, fmt.Errorf("invalid recordType specified %s", recordType) } diff --git a/data/transactions/logic/eval.go b/data/transactions/logic/eval.go index 9a3927a002..2449b96162 100644 --- a/data/transactions/logic/eval.go +++ b/data/transactions/logic/eval.go @@ -5220,10 +5220,8 @@ func (cx *EvalContext) assignAsset(sv stackValue) (basics.AssetIndex, error) { // an inner static array. func (cx *EvalContext) availableAsset(aid basics.AssetIndex) bool { // Ensure that aid is in Foreign Assets - for _, assetID := range cx.txn.Txn.ForeignAssets { - if assetID == aid { - return true - } + if slices.Contains(cx.txn.Txn.ForeignAssets, aid) { + return true } // or was created in group if cx.version >= createdResourcesVersion { @@ -5264,10 +5262,8 @@ func (cx *EvalContext) assignApp(sv stackValue) (basics.AppIndex, error) { func (cx *EvalContext) availableApp(aid basics.AppIndex) bool { // Ensure that aid is in Foreign Apps - for _, appID := range cx.txn.Txn.ForeignApps { - if appID == aid { - return true - } + if slices.Contains(cx.txn.Txn.ForeignApps, aid) { + return true } // or was created in group if cx.version >= createdResourcesVersion { diff --git a/network/requestTracker.go b/network/requestTracker.go index d318ca2932..3d54cc5048 100644 --- a/network/requestTracker.go +++ b/network/requestTracker.go @@ -21,6 +21,7 @@ import ( "net" "net/http" "net/textproto" + "slices" "sort" "strings" "sync/atomic" @@ -519,10 +520,5 @@ func (rt *RequestTracker) getForwardedConnectionAddress(header http.Header) (ip // isLocalhost returns true if the given host is a localhost address. func isLocalhost(host string) bool { - for _, v := range []string{"localhost", "127.0.0.1", "[::1]", "::1", "[::]"} { - if host == v { - return true - } - } - return false + return slices.Contains([]string{"localhost", "127.0.0.1", "[::1]", "::1", "[::]"}, host) } diff --git a/network/wsNetwork.go b/network/wsNetwork.go index 5dec40f163..fed0635ff0 100644 --- a/network/wsNetwork.go +++ b/network/wsNetwork.go @@ -30,6 +30,7 @@ import ( "path" "regexp" "runtime" + "slices" "strconv" "strings" "sync" @@ -916,19 +917,15 @@ func (wn *WebsocketNetwork) checkProtocolVersionMatch(otherHeaders http.Header) otherAcceptedVersions := otherHeaders[textproto.CanonicalMIMEHeaderKey(ProtocolAcceptVersionHeader)] for _, otherAcceptedVersion := range otherAcceptedVersions { // do we have a matching version ? - for _, supportedProtocolVersion := range wn.supportedProtocolVersions { - if supportedProtocolVersion == otherAcceptedVersion { - matchingVersion = supportedProtocolVersion - return matchingVersion, "" - } + if slices.Contains(wn.supportedProtocolVersions, otherAcceptedVersion) { + matchingVersion = otherAcceptedVersion + return matchingVersion, "" } } otherVersion = otherHeaders.Get(ProtocolVersionHeader) - for _, supportedProtocolVersion := range wn.supportedProtocolVersions { - if supportedProtocolVersion == otherVersion { - return supportedProtocolVersion, otherVersion - } + if slices.Contains(wn.supportedProtocolVersions, otherVersion) { + return otherVersion, otherVersion } return "", filterASCII(otherVersion) diff --git a/network/wsPeer.go b/network/wsPeer.go index 31f22fbe68..bc8f94c285 100644 --- a/network/wsPeer.go +++ b/network/wsPeer.go @@ -24,6 +24,7 @@ import ( "net" "net/http" "runtime" + "slices" "strconv" "strings" "sync" @@ -52,13 +53,7 @@ const averageMessageLength = 2 * 1024 // Most of the messages are smaller tha const msgsInReadBufferPerPeer = 10 func init() { - matched := false - for _, version := range SupportedProtocolVersions { - if version == versionPeerFeatures { - matched = true - } - } - if !matched { + if !slices.Contains(SupportedProtocolVersions, versionPeerFeatures) { panic(fmt.Sprintf("peer features version %s is not supported %v", versionPeerFeatures, SupportedProtocolVersions)) } diff --git a/shared/pingpong/accounts.go b/shared/pingpong/accounts.go index 703afa35a9..953014f4a4 100644 --- a/shared/pingpong/accounts.go +++ b/shared/pingpong/accounts.go @@ -23,6 +23,7 @@ import ( "math/rand" "os" "path/filepath" + "slices" "sort" "strings" "time" @@ -1003,10 +1004,8 @@ func (pps *WorkerState) generateAccounts() { } func uniqueAppend(they []string, x string) []string { - for _, v := range they { - if v == x { - return they - } + if slices.Contains(they, x) { + return they } return append(they, x) } diff --git a/shared/pingpong/config.go b/shared/pingpong/config.go index d4a46c07a3..865c92eacc 100644 --- a/shared/pingpong/config.go +++ b/shared/pingpong/config.go @@ -21,6 +21,7 @@ import ( "fmt" "io" "os" + "slices" "time" "github.com/algorand/go-algorand/util/codecs" @@ -192,14 +193,7 @@ var accountSampleMethods = []string{ // Check returns an error if config is invalid. func (cfg *PpConfig) Check() error { - sampleOk := false - for _, v := range accountSampleMethods { - if v == cfg.GeneratedAccountSampleMethod { - sampleOk = true - break - } - } - if !sampleOk { + if !slices.Contains(accountSampleMethods, cfg.GeneratedAccountSampleMethod) { return fmt.Errorf("unknown GeneratedAccountSampleMethod: %s", cfg.GeneratedAccountSampleMethod) } if cfg.DeterministicKeys && (cfg.GeneratedAccountsOffset+uint64(cfg.NumPartAccounts) > cfg.GeneratedAccountsCount) { diff --git a/tools/block-generator/generator/generator_ledger.go b/tools/block-generator/generator/generator_ledger.go index d1afe7bbb3..b3d5677652 100644 --- a/tools/block-generator/generator/generator_ledger.go +++ b/tools/block-generator/generator/generator_ledger.go @@ -20,6 +20,7 @@ import ( "encoding/binary" "fmt" "os" + "slices" "strings" "time" @@ -333,14 +334,7 @@ func (g *generator) introspectLedgerVsGenerator(roundNumber, intra uint64) (errs generatorExpectedOptinsNotFound := map[uint64][]uint64{} for appId, appOptins := range expectedOptins[appKindBoxes] { for optin := range appOptins { - missing := true - for _, boxOptin := range ledgerBoxEvidence[appId] { - if boxOptin == optin { - missing = false - break - } - } - if missing { + if !slices.Contains(ledgerBoxEvidence[appId], optin) { generatorExpectedOptinsNotFound[appId] = append(generatorExpectedOptinsNotFound[appId], optin) } } diff --git a/util/codecs/json.go b/util/codecs/json.go index d2b3b6ac21..3b48c9b094 100644 --- a/util/codecs/json.go +++ b/util/codecs/json.go @@ -24,6 +24,7 @@ import ( "io" "os" "reflect" + "slices" "strings" ) @@ -123,7 +124,7 @@ func WriteNonDefaultValues(writer io.Writer, object, defaultObject interface{}, return fmt.Errorf("error processing serialized object - should be at EOF: %s", line) } - if inStringArray(valName, ignore) { + if slices.Contains(ignore, valName) { newFile[newIndex] = line newIndex++ continue @@ -183,15 +184,6 @@ func extractValueName(line string) (name string) { return line[start+1 : end] } -func inStringArray(item string, set []string) bool { - for _, s := range set { - if item == s { - return true - } - } - return false -} - func createValueMap(object interface{}) map[string]interface{} { valueMap := make(map[string]interface{})