sort.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package collate
  5. import (
  6. "bytes"
  7. "sort"
  8. )
  9. const (
  10. maxSortBuffer = 40960
  11. maxSortEntries = 4096
  12. )
  13. type swapper interface {
  14. Swap(i, j int)
  15. }
  16. type sorter struct {
  17. buf *Buffer
  18. keys [][]byte
  19. src swapper
  20. }
  21. func (s *sorter) init(n int) {
  22. if s.buf == nil {
  23. s.buf = &Buffer{}
  24. s.buf.init()
  25. }
  26. if cap(s.keys) < n {
  27. s.keys = make([][]byte, n)
  28. }
  29. s.keys = s.keys[0:n]
  30. }
  31. func (s *sorter) sort(src swapper) {
  32. s.src = src
  33. sort.Sort(s)
  34. }
  35. func (s sorter) Len() int {
  36. return len(s.keys)
  37. }
  38. func (s sorter) Less(i, j int) bool {
  39. return bytes.Compare(s.keys[i], s.keys[j]) == -1
  40. }
  41. func (s sorter) Swap(i, j int) {
  42. s.keys[i], s.keys[j] = s.keys[j], s.keys[i]
  43. s.src.Swap(i, j)
  44. }
  45. // A Lister can be sorted by Collator's Sort method.
  46. type Lister interface {
  47. Len() int
  48. Swap(i, j int)
  49. // Bytes returns the bytes of the text at index i.
  50. Bytes(i int) []byte
  51. }
  52. // Sort uses sort.Sort to sort the strings represented by x using the rules of c.
  53. func (c *Collator) Sort(x Lister) {
  54. n := x.Len()
  55. c.sorter.init(n)
  56. for i := 0; i < n; i++ {
  57. c.sorter.keys[i] = c.Key(c.sorter.buf, x.Bytes(i))
  58. }
  59. c.sorter.sort(x)
  60. }
  61. // SortStrings uses sort.Sort to sort the strings in x using the rules of c.
  62. func (c *Collator) SortStrings(x []string) {
  63. c.sorter.init(len(x))
  64. for i, s := range x {
  65. c.sorter.keys[i] = c.KeyFromString(c.sorter.buf, s)
  66. }
  67. c.sorter.sort(sort.StringSlice(x))
  68. }