Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / mojo / public / cpp / bindings / lib / shared_data.h
1 // Copyright 2014 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 MOJO_PUBLIC_CPP_BINDINGS_LIB_SHARED_DATA_H_
6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_SHARED_DATA_H_
7
8 namespace mojo {
9 namespace internal {
10
11 // Used to allocate an instance of T that can be shared via reference counting.
12 template <typename T>
13 class SharedData {
14  public:
15   ~SharedData() {
16     holder_->Release();
17   }
18
19   SharedData() : holder_(new Holder()) {
20   }
21
22   explicit SharedData(const T& value) : holder_(new Holder(value)) {
23   }
24
25   SharedData(const SharedData<T>& other) : holder_(other.holder_) {
26     holder_->Retain();
27   }
28
29   SharedData<T>& operator=(const SharedData<T>& other) {
30     if (other.holder_ == holder_)
31       return *this;
32     holder_->Release();
33     holder_ = other.holder_;
34     holder_->Retain();
35     return *this;
36   }
37
38   void reset() {
39     holder_->Release();
40     holder_ = new Holder();
41   }
42
43   void reset(const T& value) {
44     holder_->Release();
45     holder_ = new Holder(value);
46   }
47
48   void set_value(const T& value) {
49     holder_->value = value;
50   }
51   T* mutable_value() {
52     return &holder_->value;
53   }
54   const T& value() const {
55     return holder_->value;
56   }
57
58  private:
59   class Holder {
60    public:
61     Holder() : value(), ref_count_(1) {
62     }
63     Holder(const T& value) : value(value), ref_count_(1) {
64     }
65
66     void Retain() { ++ref_count_; }
67     void Release() { if (--ref_count_ == 0) delete this; }
68
69     T value;
70
71    private:
72     int ref_count_;
73     MOJO_DISALLOW_COPY_AND_ASSIGN(Holder);
74   };
75
76   Holder* holder_;
77 };
78
79 }  // namespace internal
80 }  // namespace mojo
81
82 #endif  // MOJO_PUBLIC_CPP_BINDINGS_LIB_SHARED_DATA_H_