github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/util/compare.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 The Gitea Authors. All rights reserved. 3 // Use of this source code is governed by a MIT-style 4 // license that can be found in the LICENSE file. 5 6 package util 7 8 import ( 9 "sort" 10 "strings" 11 ) 12 13 // Int64Slice attaches the methods of Interface to []int64, sorting in increasing order. 14 type Int64Slice []int64 15 16 func (p Int64Slice) Len() int { return len(p) } 17 func (p Int64Slice) Less(i, j int) bool { return p[i] < p[j] } 18 func (p Int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 19 20 // IsSliceInt64Eq returns if the two slice has the same elements but different sequences. 21 func IsSliceInt64Eq(a, b []int64) bool { 22 if len(a) != len(b) { 23 return false 24 } 25 sort.Sort(Int64Slice(a)) 26 sort.Sort(Int64Slice(b)) 27 for i := 0; i < len(a); i++ { 28 if a[i] != b[i] { 29 return false 30 } 31 } 32 return true 33 } 34 35 // ExistsInSlice returns true if string exists in slice. 36 func ExistsInSlice(target string, slice []string) bool { 37 i := sort.Search(len(slice), 38 func(i int) bool { return slice[i] == target }) 39 return i < len(slice) 40 } 41 42 // IsStringInSlice sequential searches if string exists in slice. 43 func IsStringInSlice(target string, slice []string, insensitive ...bool) bool { 44 caseInsensitive := false 45 if len(insensitive) != 0 && insensitive[0] { 46 caseInsensitive = true 47 target = strings.ToLower(target) 48 } 49 50 for i := 0; i < len(slice); i++ { 51 if caseInsensitive { 52 if strings.ToLower(slice[i]) == target { 53 return true 54 } 55 } else { 56 if slice[i] == target { 57 return true 58 } 59 } 60 } 61 return false 62 } 63 64 // IsInt64InSlice sequential searches if int64 exists in slice. 65 func IsInt64InSlice(target int64, slice []int64) bool { 66 for i := 0; i < len(slice); i++ { 67 if slice[i] == target { 68 return true 69 } 70 } 71 return false 72 } 73 74 // IsEqualSlice returns true if slices are equal. 75 func IsEqualSlice(target, source []string) bool { 76 if len(target) != len(source) { 77 return false 78 } 79 80 if (target == nil) != (source == nil) { 81 return false 82 } 83 84 sort.Strings(target) 85 sort.Strings(source) 86 87 for i, v := range target { 88 if v != source[i] { 89 return false 90 } 91 } 92 93 return true 94 }