1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style license that can be
5 // found in the LICENSE file.
6 
7 #ifndef BASE_REVOCABLE_STORE_H_
8 #define BASE_REVOCABLE_STORE_H_
9 
10 #include "base/basictypes.h"
11 #include "nsISupportsImpl.h"
12 
13 // |RevocableStore| is a container of items that can be removed from the store.
14 class RevocableStore {
15  public:
16   // A |StoreRef| is used to link the |RevocableStore| to its items.  There is
17   // one StoreRef per store, and each item holds a reference to it.  If the
18   // store wishes to revoke its items, it sets |store_| to null.  Items are
19   // permitted to release their reference to the |StoreRef| when they no longer
20   // require the store.
21   class StoreRef final {
22    public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(StoreRef)23     NS_INLINE_DECL_THREADSAFE_REFCOUNTING(StoreRef)
24     explicit StoreRef(RevocableStore* aStore) : store_(aStore) {}
25 
set_store(RevocableStore * aStore)26     void set_store(RevocableStore* aStore) { store_ = aStore; }
store()27     RevocableStore* store() const { return store_; }
28 
29    protected:
~StoreRef()30     ~StoreRef() {}
31 
32    private:
33     RevocableStore* store_;
34 
35     DISALLOW_EVIL_CONSTRUCTORS(StoreRef);
36   };
37 
38   // An item in the store.  On construction, the object adds itself to the
39   // store.
40   class Revocable {
41    public:
42     explicit Revocable(RevocableStore* store);
43     ~Revocable();
44 
45     // This item has been revoked if it no longer has a pointer to the store.
revoked()46     bool revoked() const { return !store_reference_->store(); }
47 
48    private:
49     // We hold a reference to the store through this ref pointer.  We release
50     // this reference on destruction.
51     RefPtr<StoreRef> store_reference_;
52 
53     DISALLOW_EVIL_CONSTRUCTORS(Revocable);
54   };
55 
56   RevocableStore();
57   ~RevocableStore();
58 
59   // Revokes all the items in the store.
60   void RevokeAll();
61 
62   // Returns true if there are no items in the store.
empty()63   bool empty() const { return count_ == 0; }
64 
65  private:
66   friend class Revocable;
67 
68   // Adds an item to the store.  To add an item to the store, construct it
69   // with a pointer to the store.
70   void Add(Revocable* item);
71 
72   // This is the reference the unrevoked items in the store hold.
73   RefPtr<StoreRef> owning_reference_;
74 
75   // The number of unrevoked items in the store.
76   int count_;
77 
78   DISALLOW_EVIL_CONSTRUCTORS(RevocableStore);
79 };
80 
81 #endif  // BASE_REVOCABLE_STORE_H_
82