• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 PDFium 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 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6 
7 #ifndef CORE_FXCRT_SHARED_COPY_ON_WRITE_H_
8 #define CORE_FXCRT_SHARED_COPY_ON_WRITE_H_
9 
10 #include "core/fxcrt/fx_system.h"
11 #include "core/fxcrt/retain_ptr.h"
12 
13 namespace fxcrt {
14 
15 // A shared object with Copy on Write semantics that makes it appear as
16 // if each one were independent.
17 template <class ObjClass>
18 class SharedCopyOnWrite {
19  public:
SharedCopyOnWrite()20   SharedCopyOnWrite() {}
SharedCopyOnWrite(const SharedCopyOnWrite & other)21   SharedCopyOnWrite(const SharedCopyOnWrite& other)
22       : m_pObject(other.m_pObject) {}
~SharedCopyOnWrite()23   ~SharedCopyOnWrite() {}
24 
25   template <typename... Args>
Emplace(Args...params)26   ObjClass* Emplace(Args... params) {
27     m_pObject.Reset(new ObjClass(params...));
28     return m_pObject.Get();
29   }
30 
31   SharedCopyOnWrite& operator=(const SharedCopyOnWrite& that) {
32     if (*this != that)
33       m_pObject = that.m_pObject;
34     return *this;
35   }
36 
SetNull()37   void SetNull() { m_pObject.Reset(); }
GetObject()38   const ObjClass* GetObject() const { return m_pObject.Get(); }
39 
40   template <typename... Args>
GetPrivateCopy(Args...params)41   ObjClass* GetPrivateCopy(Args... params) {
42     if (!m_pObject)
43       return Emplace(params...);
44     if (!m_pObject->HasOneRef())
45       m_pObject.Reset(new ObjClass(*m_pObject));
46     return m_pObject.Get();
47   }
48 
49   bool operator==(const SharedCopyOnWrite& that) const {
50     return m_pObject == that.m_pObject;
51   }
52   bool operator!=(const SharedCopyOnWrite& that) const {
53     return !(*this == that);
54   }
55   explicit operator bool() const { return !!m_pObject; }
56 
57  private:
58   RetainPtr<ObjClass> m_pObject;
59 };
60 
61 }  // namespace fxcrt
62 
63 using fxcrt::SharedCopyOnWrite;
64 
65 #endif  // CORE_FXCRT_SHARED_COPY_ON_WRITE_H_
66