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.
5 #ifndef MOJO_PUBLIC_CPP_BINDINGS_STRUCT_PTR_H_
6 #define MOJO_PUBLIC_CPP_BINDINGS_STRUCT_PTR_H_
12 #include "mojo/public/cpp/system/macros.h"
17 template <typename Struct>
20 template <typename Ptr>
21 static void Initialize(Ptr* ptr) { ptr->Initialize(); }
24 } // namespace internal
26 template <typename Struct>
28 MOJO_MOVE_ONLY_TYPE_FOR_CPP_03(StructPtr, RValue);
30 typedef typename Struct::Data_ Data_;
32 StructPtr() : ptr_(NULL) {}
37 StructPtr(RValue other) : ptr_(NULL) { Take(other.object); }
38 StructPtr& operator=(RValue other) {
45 return TypeConverter<StructPtr, U>::ConvertTo(*this);
55 bool is_null() const { return ptr_ == NULL; }
57 Struct& operator*() const {
61 Struct* operator->() const {
65 Struct* get() const { return ptr_; }
67 void Swap(StructPtr* other) {
68 std::swap(ptr_, other->ptr_);
72 typedef Struct* StructPtr::*Testable;
75 operator Testable() const { return ptr_ ? &StructPtr::ptr_ : 0; }
78 friend class internal::StructHelper<Struct>;
79 void Initialize() { assert(!ptr_); ptr_ = new Struct(); }
81 void Take(StructPtr* other) {
89 // Designed to be used when Struct is small and copyable.
90 template <typename Struct>
91 class InlinedStructPtr {
92 MOJO_MOVE_ONLY_TYPE_FOR_CPP_03(InlinedStructPtr, RValue);
94 typedef typename Struct::Data_ Data_;
96 InlinedStructPtr() : is_null_(true) {}
97 ~InlinedStructPtr() {}
99 InlinedStructPtr(RValue other) : is_null_(true) { Take(other.object); }
100 InlinedStructPtr& operator=(RValue other) {
105 template <typename U>
107 return TypeConverter<InlinedStructPtr, U>::ConvertTo(*this);
113 new (&value_) Struct();
116 bool is_null() const { return is_null_; }
118 Struct& operator*() const {
122 Struct* operator->() const {
126 Struct* get() const { return &value_; }
128 void Swap(InlinedStructPtr* other) {
129 std::swap(value_, other->value_);
130 std::swap(is_null_, other->is_null_);
134 typedef Struct InlinedStructPtr::*Testable;
137 operator Testable() const { return is_null_ ? 0 : &InlinedStructPtr::value_; }
140 friend class internal::StructHelper<Struct>;
141 void Initialize() { is_null_ = false; }
143 void Take(InlinedStructPtr* other) {
148 mutable Struct value_;
154 #endif // MOJO_PUBLIC_CPP_BINDINGS_STRUCT_PTR_H_