list.go 1001 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // This file is subject to a 1-clause BSD license.
  2. // Its contents can be found in the enclosed LICENSE file.
  3. package cmd
  4. import (
  5. "strings"
  6. )
  7. // List defines a list of commands, sortable by name.
  8. type List []*Command
  9. func (cl List) Len() int { return len(cl) }
  10. func (cl List) Less(i, j int) bool { return cl[i].Name < cl[j].Name }
  11. func (cl List) Swap(i, j int) { cl[i], cl[j] = cl[j], cl[i] }
  12. // Find finds the command for the given name.
  13. // Returns nil if it was not found.
  14. func (cl List) Find(name string) *Command {
  15. idx := cl.Index(name)
  16. if idx > -1 {
  17. return cl[idx]
  18. }
  19. return nil
  20. }
  21. // Index returns the index of the command for the given name.
  22. // Returns -1 if it was not found.
  23. func (cl List) Index(name string) int {
  24. var lo int
  25. hi := len(cl) - 1
  26. name = strings.ToLower(name)
  27. for lo < hi {
  28. mid := lo + ((hi - lo) / 2)
  29. if cl[mid].Name < name {
  30. lo = mid + 1
  31. } else {
  32. hi = mid
  33. }
  34. }
  35. if hi == lo && cl[lo].Name == name {
  36. return lo
  37. }
  38. return -1
  39. }