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_
10 #include "mojo/public/cpp/environment/logging.h"
11 #include "mojo/public/cpp/system/macros.h"
16 template <typename Struct>
19 template <typename Ptr>
20 static void Initialize(Ptr* ptr) { ptr->Initialize(); }
23 } // namespace internal
25 template <typename Struct>
27 MOJO_MOVE_ONLY_TYPE_FOR_CPP_03(StructPtr, RValue);
29 typedef typename Struct::Data_ Data_;
31 StructPtr() : ptr_(NULL) {}
36 StructPtr(RValue other) : ptr_(NULL) { Take(other.object); }
37 StructPtr& operator=(RValue other) {
44 return TypeConverter<U, StructPtr>::Convert(*this);
54 bool is_null() const { return ptr_ == NULL; }
56 Struct& operator*() const {
60 Struct* operator->() const {
64 Struct* get() const { return ptr_; }
66 void Swap(StructPtr* other) {
67 std::swap(ptr_, other->ptr_);
71 typedef Struct* StructPtr::*Testable;
74 operator Testable() const { return ptr_ ? &StructPtr::ptr_ : 0; }
77 friend class internal::StructHelper<Struct>;
83 void Take(StructPtr* other) {
91 // Designed to be used when Struct is small and copyable.
92 template <typename Struct>
93 class InlinedStructPtr {
94 MOJO_MOVE_ONLY_TYPE_FOR_CPP_03(InlinedStructPtr, RValue);
96 typedef typename Struct::Data_ Data_;
98 InlinedStructPtr() : is_null_(true) {}
99 ~InlinedStructPtr() {}
101 InlinedStructPtr(RValue other) : is_null_(true) { Take(other.object); }
102 InlinedStructPtr& operator=(RValue other) {
107 template <typename U>
109 return TypeConverter<U, InlinedStructPtr>::Convert(*this);
115 new (&value_) Struct();
118 bool is_null() const { return is_null_; }
120 Struct& operator*() const {
121 MOJO_DCHECK(!is_null_);
124 Struct* operator->() const {
125 MOJO_DCHECK(!is_null_);
128 Struct* get() const { return &value_; }
130 void Swap(InlinedStructPtr* other) {
131 std::swap(value_, other->value_);
132 std::swap(is_null_, other->is_null_);
136 typedef Struct InlinedStructPtr::*Testable;
139 operator Testable() const { return is_null_ ? 0 : &InlinedStructPtr::value_; }
142 friend class internal::StructHelper<Struct>;
143 void Initialize() { is_null_ = false; }
145 void Take(InlinedStructPtr* other) {
150 mutable Struct value_;
156 #endif // MOJO_PUBLIC_CPP_BINDINGS_STRUCT_PTR_H_