github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/database/leveldb.chai2010/include/table/iterator_wrapper.h (about)

     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  
     5  #ifndef STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_
     6  #define STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_
     7  
     8  namespace leveldb {
     9  
    10  // A internal wrapper class with an interface similar to Iterator that
    11  // caches the valid() and key() results for an underlying iterator.
    12  // This can help avoid virtual function calls and also gives better
    13  // cache locality.
    14  class IteratorWrapper {
    15   public:
    16    IteratorWrapper(): iter_(NULL), valid_(false) { }
    17    explicit IteratorWrapper(Iterator* iter): iter_(NULL) {
    18      Set(iter);
    19    }
    20    ~IteratorWrapper() { delete iter_; }
    21    Iterator* iter() const { return iter_; }
    22  
    23    // Takes ownership of "iter" and will delete it when destroyed, or
    24    // when Set() is invoked again.
    25    void Set(Iterator* iter) {
    26      delete iter_;
    27      iter_ = iter;
    28      if (iter_ == NULL) {
    29        valid_ = false;
    30      } else {
    31        Update();
    32      }
    33    }
    34  
    35  
    36    // Iterator interface methods
    37    bool Valid() const        { return valid_; }
    38    Slice key() const         { assert(Valid()); return key_; }
    39    Slice value() const       { assert(Valid()); return iter_->value(); }
    40    // Methods below require iter() != NULL
    41    Status status() const     { assert(iter_); return iter_->status(); }
    42    void Next()               { assert(iter_); iter_->Next();        Update(); }
    43    void Prev()               { assert(iter_); iter_->Prev();        Update(); }
    44    void Seek(const Slice& k) { assert(iter_); iter_->Seek(k);       Update(); }
    45    void SeekToFirst()        { assert(iter_); iter_->SeekToFirst(); Update(); }
    46    void SeekToLast()         { assert(iter_); iter_->SeekToLast();  Update(); }
    47  
    48   private:
    49    void Update() {
    50      valid_ = iter_->Valid();
    51      if (valid_) {
    52        key_ = iter_->key();
    53      }
    54    }
    55  
    56    Iterator* iter_;
    57    bool valid_;
    58    Slice key_;
    59  };
    60  
    61  }  // namespace leveldb
    62  
    63  #endif  // STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_