xref: /aosp_15_r20/external/pdfium/core/fxcrt/scoped_set_insertion.h (revision 3ac0a46f773bac49fa9476ec2b1cf3f8da5ec3a4)
1 // Copyright 2021 The PDFium Authors
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 CORE_FXCRT_SCOPED_SET_INSERTION_H_
6 #define CORE_FXCRT_SCOPED_SET_INSERTION_H_
7 
8 #include <set>
9 #include <utility>
10 
11 #include "core/fxcrt/fx_memory.h"
12 #include "core/fxcrt/unowned_ptr.h"
13 #include "third_party/base/check.h"
14 
15 namespace fxcrt {
16 
17 // Track the addition of an object to a set, removing it automatically when
18 // the ScopedSetInsertion goes out of scope.
19 template <typename T>
20 class ScopedSetInsertion {
21  public:
22   FX_STACK_ALLOCATED();
23 
ScopedSetInsertion(std::set<T> * org_set,const T & elem)24   ScopedSetInsertion(std::set<T>* org_set, const T& elem)
25       : set_(org_set), insert_results_(set_->insert(elem)) {
26     CHECK(insert_results_.second);
27   }
28   ScopedSetInsertion(const ScopedSetInsertion&) = delete;
29   ScopedSetInsertion& operator=(const ScopedSetInsertion&) = delete;
~ScopedSetInsertion()30   ~ScopedSetInsertion() { set_->erase(insert_results_.first); }
31 
32  private:
33   UnownedPtr<std::set<T>> const set_;
34   const std::pair<typename std::set<T>::iterator, bool> insert_results_;
35 };
36 
37 }  // namespace fxcrt
38 
39 using fxcrt::ScopedSetInsertion;
40 
41 #endif  // CORE_FXCRT_SCOPED_SET_INSERTION_H_
42