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.

91 lines
2.2 KiB

  1. // Copyright (c) 2014 Couchbase, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package collector
  15. import (
  16. "container/heap"
  17. "github.com/blevesearch/bleve/search"
  18. )
  19. type collectStoreHeap struct {
  20. heap search.DocumentMatchCollection
  21. compare collectorCompare
  22. }
  23. func newStoreHeap(cap int, compare collectorCompare) *collectStoreHeap {
  24. rv := &collectStoreHeap{
  25. heap: make(search.DocumentMatchCollection, 0, cap),
  26. compare: compare,
  27. }
  28. heap.Init(rv)
  29. return rv
  30. }
  31. func (c *collectStoreHeap) Add(doc *search.DocumentMatch) {
  32. heap.Push(c, doc)
  33. }
  34. func (c *collectStoreHeap) RemoveLast() *search.DocumentMatch {
  35. return heap.Pop(c).(*search.DocumentMatch)
  36. }
  37. func (c *collectStoreHeap) Final(skip int, fixup collectorFixup) (search.DocumentMatchCollection, error) {
  38. count := c.Len()
  39. size := count - skip
  40. if size <= 0 {
  41. return make(search.DocumentMatchCollection, 0), nil
  42. }
  43. rv := make(search.DocumentMatchCollection, size)
  44. for count > 0 {
  45. count--
  46. if count >= skip {
  47. size--
  48. doc := heap.Pop(c).(*search.DocumentMatch)
  49. rv[size] = doc
  50. err := fixup(doc)
  51. if err != nil {
  52. return nil, err
  53. }
  54. }
  55. }
  56. return rv, nil
  57. }
  58. // heap interface implementation
  59. func (c *collectStoreHeap) Len() int {
  60. return len(c.heap)
  61. }
  62. func (c *collectStoreHeap) Less(i, j int) bool {
  63. so := c.compare(c.heap[i], c.heap[j])
  64. return -so < 0
  65. }
  66. func (c *collectStoreHeap) Swap(i, j int) {
  67. c.heap[i], c.heap[j] = c.heap[j], c.heap[i]
  68. }
  69. func (c *collectStoreHeap) Push(x interface{}) {
  70. c.heap = append(c.heap, x.(*search.DocumentMatch))
  71. }
  72. func (c *collectStoreHeap) Pop() interface{} {
  73. var rv *search.DocumentMatch
  74. rv, c.heap = c.heap[len(c.heap)-1], c.heap[:len(c.heap)-1]
  75. return rv
  76. }