You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compare.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package util
  4. import (
  5. "sort"
  6. "strings"
  7. )
  8. // Int64Slice attaches the methods of Interface to []int64, sorting in increasing order.
  9. type Int64Slice []int64
  10. func (p Int64Slice) Len() int { return len(p) }
  11. func (p Int64Slice) Less(i, j int) bool { return p[i] < p[j] }
  12. func (p Int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  13. // IsSliceInt64Eq returns if the two slice has the same elements but different sequences.
  14. func IsSliceInt64Eq(a, b []int64) bool {
  15. if len(a) != len(b) {
  16. return false
  17. }
  18. sort.Sort(Int64Slice(a))
  19. sort.Sort(Int64Slice(b))
  20. for i := 0; i < len(a); i++ {
  21. if a[i] != b[i] {
  22. return false
  23. }
  24. }
  25. return true
  26. }
  27. // ExistsInSlice returns true if string exists in slice.
  28. func ExistsInSlice(target string, slice []string) bool {
  29. i := sort.Search(len(slice),
  30. func(i int) bool { return slice[i] == target })
  31. return i < len(slice)
  32. }
  33. // IsStringInSlice sequential searches if string exists in slice.
  34. func IsStringInSlice(target string, slice []string, insensitive ...bool) bool {
  35. caseInsensitive := false
  36. if len(insensitive) != 0 && insensitive[0] {
  37. caseInsensitive = true
  38. target = strings.ToLower(target)
  39. }
  40. for i := 0; i < len(slice); i++ {
  41. if caseInsensitive {
  42. if strings.ToLower(slice[i]) == target {
  43. return true
  44. }
  45. } else {
  46. if slice[i] == target {
  47. return true
  48. }
  49. }
  50. }
  51. return false
  52. }
  53. // IsInt64InSlice sequential searches if int64 exists in slice.
  54. func IsInt64InSlice(target int64, slice []int64) bool {
  55. for i := 0; i < len(slice); i++ {
  56. if slice[i] == target {
  57. return true
  58. }
  59. }
  60. return false
  61. }
  62. // IsEqualSlice returns true if slices are equal.
  63. func IsEqualSlice(target, source []string) bool {
  64. if len(target) != len(source) {
  65. return false
  66. }
  67. if (target == nil) != (source == nil) {
  68. return false
  69. }
  70. sort.Strings(target)
  71. sort.Strings(source)
  72. for i, v := range target {
  73. if v != source[i] {
  74. return false
  75. }
  76. }
  77. return true
  78. }