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.

iterator.go 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 boltdb
  15. import (
  16. "bytes"
  17. bolt "go.etcd.io/bbolt"
  18. )
  19. type Iterator struct {
  20. store *Store
  21. tx *bolt.Tx
  22. cursor *bolt.Cursor
  23. prefix []byte
  24. start []byte
  25. end []byte
  26. valid bool
  27. key []byte
  28. val []byte
  29. }
  30. func (i *Iterator) updateValid() {
  31. i.valid = (i.key != nil)
  32. if i.valid {
  33. if i.prefix != nil {
  34. i.valid = bytes.HasPrefix(i.key, i.prefix)
  35. } else if i.end != nil {
  36. i.valid = bytes.Compare(i.key, i.end) < 0
  37. }
  38. }
  39. }
  40. func (i *Iterator) Seek(k []byte) {
  41. if i.start != nil && bytes.Compare(k, i.start) < 0 {
  42. k = i.start
  43. }
  44. if i.prefix != nil && !bytes.HasPrefix(k, i.prefix) {
  45. if bytes.Compare(k, i.prefix) < 0 {
  46. k = i.prefix
  47. } else {
  48. i.valid = false
  49. return
  50. }
  51. }
  52. i.key, i.val = i.cursor.Seek(k)
  53. i.updateValid()
  54. }
  55. func (i *Iterator) Next() {
  56. i.key, i.val = i.cursor.Next()
  57. i.updateValid()
  58. }
  59. func (i *Iterator) Current() ([]byte, []byte, bool) {
  60. return i.key, i.val, i.valid
  61. }
  62. func (i *Iterator) Key() []byte {
  63. return i.key
  64. }
  65. func (i *Iterator) Value() []byte {
  66. return i.val
  67. }
  68. func (i *Iterator) Valid() bool {
  69. return i.valid
  70. }
  71. func (i *Iterator) Close() error {
  72. return nil
  73. }