[email protected] | 1573267 | 2012-06-20 18:58:26 | [diff] [blame] | 1 | // Copyright (c) 2012 The Chromium 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. |
| 4 | |
| 5 | #ifndef SYNC_SYNCABLE_SCOPED_INDEX_UPDATER_H_ |
| 6 | #define SYNC_SYNCABLE_SCOPED_INDEX_UPDATER_H_ |
| 7 | |
| 8 | #include "sync/syncable/directory.h" |
| 9 | |
[email protected] | 9cfc7c70 | 2012-07-02 22:54:17 | [diff] [blame] | 10 | namespace syncer { |
[email protected] | 1573267 | 2012-06-20 18:58:26 | [diff] [blame] | 11 | namespace syncable { |
| 12 | class ScopedKernelLock; |
| 13 | |
| 14 | // A ScopedIndexUpdater temporarily removes an entry from an index, |
| 15 | // and restores it to the index when the scope exits. This simplifies |
| 16 | // the common pattern where items need to be removed from an index |
| 17 | // before updating the field. |
| 18 | // |
| 19 | // This class is parameterized on the Indexer traits type, which |
| 20 | // must define a Comparator and a static bool ShouldInclude |
| 21 | // function for testing whether the item ought to be included |
| 22 | // in the index. |
| 23 | template<typename Indexer> |
| 24 | class ScopedIndexUpdater { |
| 25 | public: |
| 26 | ScopedIndexUpdater(const ScopedKernelLock& proof_of_lock, |
| 27 | EntryKernel* entry, |
| 28 | typename Index<Indexer>::Set* index) |
| 29 | : entry_(entry), |
| 30 | index_(index) { |
| 31 | // First call to ShouldInclude happens before the field is updated. |
| 32 | if (Indexer::ShouldInclude(entry_)) { |
| 33 | // TODO(lipalani): Replace this CHECK with |SyncAssert| by refactorting |
| 34 | // this class into a function. |
| 35 | CHECK(index_->erase(entry_)); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | ~ScopedIndexUpdater() { |
| 40 | // Second call to ShouldInclude happens after the field is updated. |
| 41 | if (Indexer::ShouldInclude(entry_)) { |
| 42 | // TODO(lipalani): Replace this CHECK with |SyncAssert| by refactorting |
| 43 | // this class into a function. |
| 44 | CHECK(index_->insert(entry_).second); |
| 45 | } |
| 46 | } |
| 47 | private: |
| 48 | // The entry that was temporarily removed from the index. |
| 49 | EntryKernel* entry_; |
| 50 | // The index which we are updating. |
| 51 | typename Index<Indexer>::Set* const index_; |
| 52 | }; |
| 53 | |
| 54 | } // namespace syncable |
[email protected] | 9cfc7c70 | 2012-07-02 22:54:17 | [diff] [blame] | 55 | } // namespace syncer |
[email protected] | 1573267 | 2012-06-20 18:58:26 | [diff] [blame] | 56 | |
| 57 | #endif // SYNC_SYNCABLE_SCOPED_INDEX_UPDATER_H_ |