blob: f1814cab436aa24a2b89b8dd12850bc57433a345 [file] [log] [blame]
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +00001// 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
5#ifndef STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_
6#define STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_
7
Chris Mumforda75d4352014-12-11 08:02:45 -08008#include "leveldb/iterator.h"
9#include "leveldb/slice.h"
10
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000011namespace leveldb {
12
13// A internal wrapper class with an interface similar to Iterator that
14// caches the valid() and key() results for an underlying iterator.
15// This can help avoid virtual function calls and also gives better
16// cache locality.
17class IteratorWrapper {
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000018 public:
costan09217fd2018-04-10 16:18:06 -070019 IteratorWrapper(): iter_(nullptr), valid_(false) { }
20 explicit IteratorWrapper(Iterator* iter): iter_(nullptr) {
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000021 Set(iter);
22 }
23 ~IteratorWrapper() { delete iter_; }
24 Iterator* iter() const { return iter_; }
25
26 // Takes ownership of "iter" and will delete it when destroyed, or
27 // when Set() is invoked again.
28 void Set(Iterator* iter) {
29 delete iter_;
30 iter_ = iter;
costan09217fd2018-04-10 16:18:06 -070031 if (iter_ == nullptr) {
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000032 valid_ = false;
33 } else {
34 Update();
35 }
36 }
37
38
39 // Iterator interface methods
dgrogan@chromium.orgc4f55142011-06-02 00:00:37 +000040 bool Valid() const { return valid_; }
41 Slice key() const { assert(Valid()); return key_; }
42 Slice value() const { assert(Valid()); return iter_->value(); }
costan09217fd2018-04-10 16:18:06 -070043 // Methods below require iter() != nullptr
dgrogan@chromium.orgc4f55142011-06-02 00:00:37 +000044 Status status() const { assert(iter_); return iter_->status(); }
45 void Next() { assert(iter_); iter_->Next(); Update(); }
46 void Prev() { assert(iter_); iter_->Prev(); Update(); }
47 void Seek(const Slice& k) { assert(iter_); iter_->Seek(k); Update(); }
48 void SeekToFirst() { assert(iter_); iter_->SeekToFirst(); Update(); }
49 void SeekToLast() { assert(iter_); iter_->SeekToLast(); Update(); }
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000050
51 private:
52 void Update() {
53 valid_ = iter_->Valid();
54 if (valid_) {
55 key_ = iter_->key();
56 }
57 }
dgrogan@chromium.org740d8b32011-05-28 00:53:58 +000058
59 Iterator* iter_;
60 bool valid_;
61 Slice key_;
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000062};
63
dgrogan@chromium.org740d8b32011-05-28 00:53:58 +000064} // namespace leveldb
jorlow@chromium.orgf67e15e2011-03-18 22:37:00 +000065
66#endif // STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_