作者: 韩晨旭 10225101440 李畅 10225102463
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

92 righe
2.1 KiB

  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #ifndef STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_
  5. #define STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_
  6. #include "leveldb/iterator.h"
  7. #include "leveldb/slice.h"
  8. namespace leveldb {
  9. // A internal wrapper class with an interface similar to Iterator that
  10. // caches the valid() and key() results for an underlying iterator.
  11. // This can help avoid virtual function calls and also gives better
  12. // cache locality.
  13. class IteratorWrapper {
  14. public:
  15. IteratorWrapper() : iter_(nullptr), valid_(false) {}
  16. explicit IteratorWrapper(Iterator* iter) : iter_(nullptr) { Set(iter); }
  17. ~IteratorWrapper() { delete iter_; }
  18. Iterator* iter() const { return iter_; }
  19. // Takes ownership of "iter" and will delete it when destroyed, or
  20. // when Set() is invoked again.
  21. void Set(Iterator* iter) {
  22. delete iter_;
  23. iter_ = iter;
  24. if (iter_ == nullptr) {
  25. valid_ = false;
  26. } else {
  27. Update();
  28. }
  29. }
  30. // Iterator interface methods
  31. bool Valid() const { return valid_; }
  32. Slice key() const {
  33. assert(Valid());
  34. return key_;
  35. }
  36. Slice value() const {
  37. assert(Valid());
  38. return iter_->value();
  39. }
  40. // Methods below require iter() != nullptr
  41. Status status() const {
  42. assert(iter_);
  43. return iter_->status();
  44. }
  45. void Next() {
  46. assert(iter_);
  47. iter_->Next();
  48. Update();
  49. }
  50. void Prev() {
  51. assert(iter_);
  52. iter_->Prev();
  53. Update();
  54. }
  55. void Seek(const Slice& k) {
  56. assert(iter_);
  57. iter_->Seek(k);
  58. Update();
  59. }
  60. void SeekToFirst() {
  61. assert(iter_);
  62. iter_->SeekToFirst();
  63. Update();
  64. }
  65. void SeekToLast() {
  66. assert(iter_);
  67. iter_->SeekToLast();
  68. Update();
  69. }
  70. private:
  71. void Update() {
  72. valid_ = iter_->Valid();
  73. if (valid_) {
  74. key_ = iter_->key();
  75. }
  76. }
  77. Iterator* iter_;
  78. bool valid_;
  79. Slice key_;
  80. };
  81. } // namespace leveldb
  82. #endif // STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_