Upstream version 7.35.144.0
[platform/framework/web/crosswalk.git] / src / ppapi / cpp / extensions / optional.h
1 // Copyright (c) 2013 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 PPAPI_CPP_EXTENSIONS_OPTIONAL_H_
6 #define PPAPI_CPP_EXTENSIONS_OPTIONAL_H_
7
8 namespace pp {
9 namespace ext {
10
11 template <class T>
12 class Optional {
13  public:
14   Optional() : value_(NULL) {
15   }
16   // Takes ownership of |value|.
17   explicit Optional(T* value) : value_(value) {
18   }
19   Optional(const T& value) : value_(new T(value)) {
20   }
21   Optional(const Optional<T>& other)
22       : value_(other.value_ ? new T(*other.value_) : NULL) {
23   }
24
25   ~Optional() {
26     Reset();
27   }
28
29   Optional<T>& operator=(const T& other) {
30     if (value_ == &other)
31       return *this;
32
33     Reset();
34     value_ = new T(other);
35
36     return *this;
37   }
38
39   Optional<T>& operator=(const Optional<T>& other) {
40     if (value_ == other.value_)
41       return *this;
42
43     Reset();
44     if (other.value_)
45       value_ = new T(*other.value_);
46
47     return *this;
48   }
49
50   bool IsSet() const {
51     return !!value_;
52   }
53
54   T* Get() const {
55     return value_;
56   }
57
58   // Should only be used when IsSet() is true.
59   T& operator*() const {
60     return *value_;
61   }
62
63   // Should only be used when IsSet() is true.
64   T* operator->() const {
65     PP_DCHECK(value_);
66     return value_;
67   }
68
69   // Takes ownership of |value|.
70   void Set(T* value) {
71     if (value == value_)
72       return;
73
74     Reset();
75     *value_ = value;
76   }
77
78   void Reset() {
79     T* value = value_;
80     value_ = NULL;
81     delete value;
82   }
83
84   void Swap(Optional<T>* other) {
85     T* temp = value_;
86     value_ = other->value_;
87     other->value_ = temp;
88   }
89
90  private:
91   T* value_;
92 };
93
94 }  // namespace ext
95 }  // namespace pp
96
97 #endif  // PPAPI_CPP_EXTENSIONS_OPTIONAL_H_