aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/core/lib/gprpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/core/lib/gprpp')
-rw-r--r--src/core/lib/gprpp/README.md16
-rw-r--r--src/core/lib/gprpp/abstract.h34
-rw-r--r--src/core/lib/gprpp/atomic.h30
-rw-r--r--src/core/lib/gprpp/atomic_with_atm.h55
-rw-r--r--src/core/lib/gprpp/atomic_with_std.h33
-rw-r--r--src/core/lib/gprpp/debug_location.h52
-rw-r--r--src/core/lib/gprpp/inlined_vector.h112
-rw-r--r--src/core/lib/gprpp/manual_constructor.h211
-rw-r--r--src/core/lib/gprpp/memory.h100
-rw-r--r--src/core/lib/gprpp/orphanable.h171
-rw-r--r--src/core/lib/gprpp/ref_counted.h133
-rw-r--r--src/core/lib/gprpp/ref_counted_ptr.h99
12 files changed, 1046 insertions, 0 deletions
diff --git a/src/core/lib/gprpp/README.md b/src/core/lib/gprpp/README.md
new file mode 100644
index 0000000000..eab018bb31
--- /dev/null
+++ b/src/core/lib/gprpp/README.md
@@ -0,0 +1,16 @@
+# GPR++ - Google Portable Runtime for C++
+
+The files in this directory contain various utility code for C++ code.
+None of this code is gRPC-specific; anything here may also be useful
+for other open source projects written in C++.
+
+Note that this is one of the few places in src/core where we allow
+the use of portability macros.
+
+Note that this is the only place in src/core where we allow
+use of the C++ standard library (i.e., anything in the `std::`
+namespace). And for now, we require that any use of the
+standard library is build-time-only -- i.e., we do not allow
+run-time dependencies on libstdc++. For more details, see
+[gRFC L6](/grpc/proposal/blob/master/L6-allow-c%2B%2B-in-grpc-core.md) and
+[Moving gRPC core to C++](/grpc/grpc/blob/master/doc/core/moving-to-c%2B%2B.md).
diff --git a/src/core/lib/gprpp/abstract.h b/src/core/lib/gprpp/abstract.h
new file mode 100644
index 0000000000..cc96edc49b
--- /dev/null
+++ b/src/core/lib/gprpp/abstract.h
@@ -0,0 +1,34 @@
+/*
+ *
+ * Copyright 2017 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_ABSTRACT_H
+#define GRPC_CORE_LIB_GPRPP_ABSTRACT_H
+
+// This is needed to support abstract base classes in the c core. Since gRPC
+// doesn't have a c++ runtime, it will hit a linker error on delete unless
+// we define a virtual operator delete. See this blog for more info:
+// https://eli.thegreenplace.net/2015/c-deleting-destructors-and-virtual-operator-delete/
+#define GRPC_ABSTRACT_BASE_CLASS \
+ static void operator delete(void* p) { abort(); }
+
+// gRPC currently can't depend on libstdc++, so we can't use "= 0" for
+// pure virtual methods. Instead, we use this macro.
+#define GRPC_ABSTRACT \
+ { GPR_ASSERT(false); }
+
+#endif /* GRPC_CORE_LIB_GPRPP_ABSTRACT_H */
diff --git a/src/core/lib/gprpp/atomic.h b/src/core/lib/gprpp/atomic.h
new file mode 100644
index 0000000000..8b08fc4e9c
--- /dev/null
+++ b/src/core/lib/gprpp/atomic.h
@@ -0,0 +1,30 @@
+/*
+ *
+ * Copyright 2017 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_ATOMIC_H
+#define GRPC_CORE_LIB_GPRPP_ATOMIC_H
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_HAS_CXX11_ATOMIC
+#include "src/core/lib/gprpp/atomic_with_std.h"
+#else
+#include "src/core/lib/gprpp/atomic_with_atm.h"
+#endif
+
+#endif /* GRPC_CORE_LIB_GPRPP_ATOMIC_H */
diff --git a/src/core/lib/gprpp/atomic_with_atm.h b/src/core/lib/gprpp/atomic_with_atm.h
new file mode 100644
index 0000000000..6abf0bc38d
--- /dev/null
+++ b/src/core/lib/gprpp/atomic_with_atm.h
@@ -0,0 +1,55 @@
+/*
+ *
+ * Copyright 2017 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_ATOMIC_WITH_ATM_H
+#define GRPC_CORE_LIB_GPRPP_ATOMIC_WITH_ATM_H
+
+#include <grpc/support/atm.h>
+
+namespace grpc_core {
+
+enum MemoryOrderRelaxed { memory_order_relaxed };
+
+template <class T>
+class atomic;
+
+template <>
+class atomic<bool> {
+ public:
+ atomic() { gpr_atm_no_barrier_store(&x_, static_cast<gpr_atm>(false)); }
+ explicit atomic(bool x) {
+ gpr_atm_no_barrier_store(&x_, static_cast<gpr_atm>(x));
+ }
+
+ bool compare_exchange_strong(bool& expected, bool update, MemoryOrderRelaxed,
+ MemoryOrderRelaxed) {
+ if (!gpr_atm_no_barrier_cas(&x_, static_cast<gpr_atm>(expected),
+ static_cast<gpr_atm>(update))) {
+ expected = gpr_atm_no_barrier_load(&x_) != 0;
+ return false;
+ }
+ return true;
+ }
+
+ private:
+ gpr_atm x_;
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_ATOMIC_WITH_ATM_H */
diff --git a/src/core/lib/gprpp/atomic_with_std.h b/src/core/lib/gprpp/atomic_with_std.h
new file mode 100644
index 0000000000..83322b81c1
--- /dev/null
+++ b/src/core/lib/gprpp/atomic_with_std.h
@@ -0,0 +1,33 @@
+/*
+ *
+ * Copyright 2017 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_ATOMIC_WITH_STD_H
+#define GRPC_CORE_LIB_GPRPP_ATOMIC_WITH_STD_H
+
+#include <atomic>
+
+namespace grpc_core {
+
+template <class T>
+using atomic = std::atomic<T>;
+
+typedef std::memory_order memory_order;
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_ATOMIC_WITH_STD_H */
diff --git a/src/core/lib/gprpp/debug_location.h b/src/core/lib/gprpp/debug_location.h
new file mode 100644
index 0000000000..287761beaf
--- /dev/null
+++ b/src/core/lib/gprpp/debug_location.h
@@ -0,0 +1,52 @@
+/*
+ *
+ * Copyright 2017 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_DEBUG_LOCATION_H
+#define GRPC_CORE_LIB_GPRPP_DEBUG_LOCATION_H
+
+namespace grpc_core {
+
+// Used for tracking file and line where a call is made for debug builds.
+// No-op for non-debug builds.
+// Callers can use the DEBUG_LOCATION macro in either case.
+#ifndef NDEBUG
+class DebugLocation {
+ public:
+ DebugLocation(const char* file, int line) : file_(file), line_(line) {}
+ bool Log() const { return true; }
+ const char* file() const { return file_; }
+ int line() const { return line_; }
+
+ private:
+ const char* file_;
+ const int line_;
+};
+#define DEBUG_LOCATION ::grpc_core::DebugLocation(__FILE__, __LINE__)
+#else
+class DebugLocation {
+ public:
+ bool Log() const { return false; }
+ const char* file() const { return nullptr; }
+ int line() const { return -1; }
+};
+#define DEBUG_LOCATION ::grpc_core::DebugLocation()
+#endif
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_DEBUG_LOCATION_H */
diff --git a/src/core/lib/gprpp/inlined_vector.h b/src/core/lib/gprpp/inlined_vector.h
new file mode 100644
index 0000000000..b78f85b893
--- /dev/null
+++ b/src/core/lib/gprpp/inlined_vector.h
@@ -0,0 +1,112 @@
+/*
+ *
+ * Copyright 2017 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_INLINED_VECTOR_H
+#define GRPC_CORE_LIB_GPRPP_INLINED_VECTOR_H
+
+#include <cassert>
+
+#include "src/core/lib/gprpp/memory.h"
+
+namespace grpc_core {
+
+// NOTE: We eventually want to use absl::InlinedVector here. However,
+// there are currently build problems that prevent us from using absl.
+// In the interim, we define a custom implementation as a place-holder,
+// with the intent to eventually replace this with the absl
+// implementation.
+//
+// This place-holder implementation does not implement the full set of
+// functionality from the absl version; it has just the methods that we
+// currently happen to need in gRPC. If additional functionality is
+// needed before this gets replaced with the absl version, it can be
+// added, with the following proviso:
+//
+// ANY METHOD ADDED HERE MUST COMPLY WITH THE INTERFACE IN THE absl
+// IMPLEMENTATION!
+//
+// TODO(ctiller, nnoble, roth): Replace this with absl::InlinedVector
+// once we integrate absl into the gRPC build system in a usable way.
+template <typename T, size_t N>
+class InlinedVector {
+ public:
+ InlinedVector() {}
+ ~InlinedVector() {
+ for (size_t i = 0; i < size_ && i < N; ++i) {
+ T& value = *reinterpret_cast<T*>(inline_ + i);
+ value.~T();
+ }
+ if (size_ > N) { // Avoid subtracting two signed values.
+ for (size_t i = 0; i < size_ - N; ++i) {
+ dynamic_[i].~T();
+ }
+ }
+ gpr_free(dynamic_);
+ }
+
+ // For now, we do not support copying.
+ InlinedVector(const InlinedVector&) = delete;
+ InlinedVector& operator=(const InlinedVector&) = delete;
+
+ T& operator[](size_t offset) {
+ assert(offset < size_);
+ if (offset < N) {
+ return *reinterpret_cast<T*>(inline_ + offset);
+ } else {
+ return dynamic_[offset - N];
+ }
+ }
+
+ template <typename... Args>
+ void emplace_back(Args&&... args) {
+ if (size_ < N) {
+ new (&inline_[size_]) T(std::forward<Args>(args)...);
+ } else {
+ if (size_ - N == dynamic_capacity_) {
+ size_t new_capacity =
+ dynamic_capacity_ == 0 ? 2 : dynamic_capacity_ * 2;
+ T* new_dynamic = static_cast<T*>(gpr_malloc(sizeof(T) * new_capacity));
+ for (size_t i = 0; i < dynamic_capacity_; ++i) {
+ new (&new_dynamic[i]) T(std::move(dynamic_[i]));
+ dynamic_[i].~T();
+ }
+ gpr_free(dynamic_);
+ dynamic_ = new_dynamic;
+ dynamic_capacity_ = new_capacity;
+ }
+ new (&dynamic_[size_ - N]) T(std::forward<Args>(args)...);
+ }
+ ++size_;
+ }
+
+ void push_back(const T& value) { emplace_back(value); }
+
+ void push_back(T&& value) { emplace_back(std::move(value)); }
+
+ size_t size() const { return size_; }
+
+ private:
+ typename std::aligned_storage<sizeof(T)>::type inline_[N];
+ T* dynamic_ = nullptr;
+ size_t size_ = 0;
+ size_t dynamic_capacity_ = 0;
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_INLINED_VECTOR_H */
diff --git a/src/core/lib/gprpp/manual_constructor.h b/src/core/lib/gprpp/manual_constructor.h
new file mode 100644
index 0000000000..cee38abc1b
--- /dev/null
+++ b/src/core/lib/gprpp/manual_constructor.h
@@ -0,0 +1,211 @@
+/*
+ *
+ * Copyright 2016 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_MANUAL_CONSTRUCTOR_H
+#define GRPC_CORE_LIB_GPRPP_MANUAL_CONSTRUCTOR_H
+
+// manually construct a region of memory with some type
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <new>
+#include <type_traits>
+#include <utility>
+
+#include <grpc/support/log.h>
+
+namespace grpc_core {
+
+// this contains templated helpers needed to implement the ManualConstructors
+// in this file.
+namespace manual_ctor_impl {
+
+// is_one_of returns true it a class, Member, is present in a variadic list of
+// classes, List.
+template <class Member, class... List>
+class is_one_of;
+
+template <class Member, class... List>
+class is_one_of<Member, Member, List...> {
+ public:
+ static constexpr const bool value = true;
+};
+
+template <class Member, class A, class... List>
+class is_one_of<Member, A, List...> {
+ public:
+ static constexpr const bool value = is_one_of<Member, List...>::value;
+};
+
+template <class Member>
+class is_one_of<Member> {
+ public:
+ static constexpr const bool value = false;
+};
+
+// max_size_of returns sizeof(Type) for the largest type in the variadic list
+// of classes, Types.
+template <class... Types>
+class max_size_of;
+
+template <class A>
+class max_size_of<A> {
+ public:
+ static constexpr const size_t value = sizeof(A);
+};
+
+template <class A, class... B>
+class max_size_of<A, B...> {
+ public:
+ static constexpr const size_t value = sizeof(A) > max_size_of<B...>::value
+ ? sizeof(A)
+ : max_size_of<B...>::value;
+};
+
+// max_size_of returns alignof(Type) for the largest type in the variadic list
+// of classes, Types.
+template <class... Types>
+class max_align_of;
+
+template <class A>
+class max_align_of<A> {
+ public:
+ static constexpr const size_t value = alignof(A);
+};
+
+template <class A, class... B>
+class max_align_of<A, B...> {
+ public:
+ static constexpr const size_t value = alignof(A) > max_align_of<B...>::value
+ ? alignof(A)
+ : max_align_of<B...>::value;
+};
+
+} // namespace manual_ctor_impl
+
+template <class BaseType, class... DerivedTypes>
+class PolymorphicManualConstructor {
+ public:
+ // No constructor or destructor because one of the most useful uses of
+ // this class is as part of a union, and members of a union could not have
+ // constructors or destructors till C++11. And, anyway, the whole point of
+ // this class is to bypass constructor and destructor.
+
+ BaseType* get() { return reinterpret_cast<BaseType*>(&space_); }
+ const BaseType* get() const {
+ return reinterpret_cast<const BaseType*>(&space_);
+ }
+
+ BaseType* operator->() { return get(); }
+ const BaseType* operator->() const { return get(); }
+
+ BaseType& operator*() { return *get(); }
+ const BaseType& operator*() const { return *get(); }
+
+ template <class DerivedType>
+ void Init() {
+ FinishInit(new (&space_) DerivedType);
+ }
+
+ // Init() constructs the Type instance using the given arguments
+ // (which are forwarded to Type's constructor).
+ //
+ // Note that Init() with no arguments performs default-initialization,
+ // not zero-initialization (i.e it behaves the same as "new Type;", not
+ // "new Type();"), so it will leave non-class types uninitialized.
+ template <class DerivedType, typename... Ts>
+ void Init(Ts&&... args) {
+ FinishInit(new (&space_) DerivedType(std::forward<Ts>(args)...));
+ }
+
+ // Init() that is equivalent to copy and move construction.
+ // Enables usage like this:
+ // ManualConstructor<std::vector<int>> v;
+ // v.Init({1, 2, 3});
+ template <class DerivedType>
+ void Init(const DerivedType& x) {
+ FinishInit(new (&space_) DerivedType(x));
+ }
+ template <class DerivedType>
+ void Init(DerivedType&& x) {
+ FinishInit(new (&space_) DerivedType(std::move(x)));
+ }
+
+ void Destroy() { get()->~BaseType(); }
+
+ private:
+ template <class DerivedType>
+ void FinishInit(DerivedType* p) {
+ static_assert(
+ manual_ctor_impl::is_one_of<DerivedType, DerivedTypes...>::value,
+ "DerivedType must be one of the predeclared DerivedTypes");
+ GPR_ASSERT(reinterpret_cast<BaseType*>(static_cast<DerivedType*>(p)) == p);
+ }
+
+ typename std::aligned_storage<
+ grpc_core::manual_ctor_impl::max_size_of<DerivedTypes...>::value,
+ grpc_core::manual_ctor_impl::max_align_of<DerivedTypes...>::value>::type
+ space_;
+};
+
+template <typename Type>
+class ManualConstructor {
+ public:
+ // No constructor or destructor because one of the most useful uses of
+ // this class is as part of a union, and members of a union could not have
+ // constructors or destructors till C++11. And, anyway, the whole point of
+ // this class is to bypass constructor and destructor.
+
+ Type* get() { return reinterpret_cast<Type*>(&space_); }
+ const Type* get() const { return reinterpret_cast<const Type*>(&space_); }
+
+ Type* operator->() { return get(); }
+ const Type* operator->() const { return get(); }
+
+ Type& operator*() { return *get(); }
+ const Type& operator*() const { return *get(); }
+
+ void Init() { new (&space_) Type; }
+
+ // Init() constructs the Type instance using the given arguments
+ // (which are forwarded to Type's constructor).
+ //
+ // Note that Init() with no arguments performs default-initialization,
+ // not zero-initialization (i.e it behaves the same as "new Type;", not
+ // "new Type();"), so it will leave non-class types uninitialized.
+ template <typename... Ts>
+ void Init(Ts&&... args) {
+ new (&space_) Type(std::forward<Ts>(args)...);
+ }
+
+ // Init() that is equivalent to copy and move construction.
+ // Enables usage like this:
+ // ManualConstructor<std::vector<int>> v;
+ // v.Init({1, 2, 3});
+ void Init(const Type& x) { new (&space_) Type(x); }
+ void Init(Type&& x) { new (&space_) Type(std::move(x)); }
+
+ void Destroy() { get()->~Type(); }
+
+ private:
+ typename std::aligned_storage<sizeof(Type), alignof(Type)>::type space_;
+};
+
+} // namespace grpc_core
+
+#endif
diff --git a/src/core/lib/gprpp/memory.h b/src/core/lib/gprpp/memory.h
new file mode 100644
index 0000000000..17f42f5983
--- /dev/null
+++ b/src/core/lib/gprpp/memory.h
@@ -0,0 +1,100 @@
+/*
+ *
+ * Copyright 2017 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_MEMORY_H
+#define GRPC_CORE_LIB_GPRPP_MEMORY_H
+
+#include <grpc/support/alloc.h>
+
+#include <limits>
+#include <memory>
+#include <utility>
+
+namespace grpc_core {
+
+// Alternative to new, since we cannot use it (for fear of libstdc++)
+template <typename T, typename... Args>
+inline T* New(Args&&... args) {
+ void* p = gpr_malloc(sizeof(T));
+ return new (p) T(std::forward<Args>(args)...);
+}
+
+// Alternative to delete, since we cannot use it (for fear of libstdc++)
+template <typename T>
+inline void Delete(T* p) {
+ p->~T();
+ gpr_free(p);
+}
+
+template <typename T>
+class DefaultDelete {
+ public:
+ void operator()(T* p) { Delete(p); }
+};
+
+template <typename T, typename Deleter = DefaultDelete<T>>
+using UniquePtr = std::unique_ptr<T, Deleter>;
+
+template <typename T, typename... Args>
+inline UniquePtr<T> MakeUnique(Args&&... args) {
+ return UniquePtr<T>(New<T>(std::forward<Args>(args)...));
+}
+
+// an allocator that uses gpr_malloc/gpr_free
+template <class T>
+class Allocator {
+ public:
+ typedef T value_type;
+ typedef T* pointer;
+ typedef const T* const_pointer;
+ typedef T& reference;
+ typedef const T& const_reference;
+ typedef std::size_t size_type;
+ typedef std::ptrdiff_t difference_type;
+ typedef std::false_type propagate_on_container_move_assignment;
+ template <class U>
+ struct rebind {
+ typedef Allocator<U> other;
+ };
+ typedef std::true_type is_always_equal;
+
+ pointer address(reference x) const { return &x; }
+ const_pointer address(const_reference x) const { return &x; }
+ pointer allocate(std::size_t n,
+ std::allocator<void>::const_pointer hint = nullptr) {
+ return static_cast<pointer>(gpr_malloc(n * sizeof(T)));
+ }
+ void deallocate(T* p, std::size_t n) { gpr_free(p); }
+ size_t max_size() const {
+ return std::numeric_limits<size_type>::max() / sizeof(value_type);
+ }
+ void construct(pointer p, const_reference val) { new ((void*)p) T(val); }
+ template <class U, class... Args>
+ void construct(U* p, Args&&... args) {
+ ::new ((void*)p) U(std::forward<Args>(args)...);
+ }
+ void destroy(pointer p) { p->~T(); }
+ template <class U>
+ void destroy(U* p) {
+ p->~U();
+ }
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_MEMORY_H */
diff --git a/src/core/lib/gprpp/orphanable.h b/src/core/lib/gprpp/orphanable.h
new file mode 100644
index 0000000000..50199730c9
--- /dev/null
+++ b/src/core/lib/gprpp/orphanable.h
@@ -0,0 +1,171 @@
+/*
+ *
+ * Copyright 2017 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_ORPHANABLE_H
+#define GRPC_CORE_LIB_GPRPP_ORPHANABLE_H
+
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include <memory>
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/gprpp/abstract.h"
+#include "src/core/lib/gprpp/debug_location.h"
+#include "src/core/lib/gprpp/memory.h"
+
+namespace grpc_core {
+
+// A base class for orphanable objects, which have one external owner
+// but are not necessarily destroyed immediately when the external owner
+// gives up ownership. Instead, the owner calls the object's Orphan()
+// method, and the object then takes responsibility for its own cleanup
+// and destruction.
+class Orphanable {
+ public:
+ // Gives up ownership of the object. The implementation must arrange
+ // to eventually destroy the object without further interaction from the
+ // caller.
+ virtual void Orphan() GRPC_ABSTRACT;
+
+ // Not copyable or movable.
+ Orphanable(const Orphanable&) = delete;
+ Orphanable& operator=(const Orphanable&) = delete;
+
+ GRPC_ABSTRACT_BASE_CLASS
+
+ protected:
+ Orphanable() {}
+ virtual ~Orphanable() {}
+};
+
+template <typename T>
+class OrphanableDelete {
+ public:
+ void operator()(T* p) { p->Orphan(); }
+};
+
+template <typename T, typename Deleter = OrphanableDelete<T>>
+using OrphanablePtr = std::unique_ptr<T, Deleter>;
+
+template <typename T, typename... Args>
+inline OrphanablePtr<T> MakeOrphanable(Args&&... args) {
+ return OrphanablePtr<T>(New<T>(std::forward<Args>(args)...));
+}
+
+// A type of Orphanable with internal ref-counting.
+class InternallyRefCounted : public Orphanable {
+ public:
+ // Not copyable nor movable.
+ InternallyRefCounted(const InternallyRefCounted&) = delete;
+ InternallyRefCounted& operator=(const InternallyRefCounted&) = delete;
+
+ GRPC_ABSTRACT_BASE_CLASS
+
+ protected:
+ InternallyRefCounted() { gpr_ref_init(&refs_, 1); }
+ virtual ~InternallyRefCounted() {}
+
+ void Ref() { gpr_ref(&refs_); }
+
+ void Unref() {
+ if (gpr_unref(&refs_)) {
+ Delete(this);
+ }
+ }
+
+ // Allow Delete() to access destructor.
+ template <typename T>
+ friend void Delete(T*);
+
+ private:
+ gpr_refcount refs_;
+};
+
+// An alternative version of the InternallyRefCounted base class that
+// supports tracing. This is intended to be used in cases where the
+// object will be handled both by idiomatic C++ code using smart
+// pointers and legacy code that is manually calling Ref() and Unref().
+// Once all of our code is converted to idiomatic C++, we may be able to
+// eliminate this class.
+class InternallyRefCountedWithTracing : public Orphanable {
+ public:
+ // Not copyable nor movable.
+ InternallyRefCountedWithTracing(const InternallyRefCountedWithTracing&) =
+ delete;
+ InternallyRefCountedWithTracing& operator=(
+ const InternallyRefCountedWithTracing&) = delete;
+
+ GRPC_ABSTRACT_BASE_CLASS
+
+ protected:
+ // Allow Delete() to access destructor.
+ template <typename T>
+ friend void Delete(T*);
+
+ InternallyRefCountedWithTracing()
+ : InternallyRefCountedWithTracing(static_cast<TraceFlag*>(nullptr)) {}
+
+ explicit InternallyRefCountedWithTracing(TraceFlag* trace_flag)
+ : trace_flag_(trace_flag) {
+ gpr_ref_init(&refs_, 1);
+ }
+
+#ifdef NDEBUG
+ explicit InternallyRefCountedWithTracing(DebugOnlyTraceFlag* trace_flag)
+ : InternallyRefCountedWithTracing() {}
+#endif
+
+ virtual ~InternallyRefCountedWithTracing() {}
+
+ void Ref() { gpr_ref(&refs_); }
+
+ void Ref(const DebugLocation& location, const char* reason) {
+ if (location.Log() && trace_flag_ != nullptr && trace_flag_->enabled()) {
+ gpr_atm old_refs = gpr_atm_no_barrier_load(&refs_.count);
+ gpr_log(GPR_DEBUG, "%s:%p %s:%d ref %" PRIdPTR " -> %" PRIdPTR " %s",
+ trace_flag_->name(), this, location.file(), location.line(),
+ old_refs, old_refs + 1, reason);
+ }
+ Ref();
+ }
+
+ void Unref() {
+ if (gpr_unref(&refs_)) {
+ Delete(this);
+ }
+ }
+
+ void Unref(const DebugLocation& location, const char* reason) {
+ if (location.Log() && trace_flag_ != nullptr && trace_flag_->enabled()) {
+ gpr_atm old_refs = gpr_atm_no_barrier_load(&refs_.count);
+ gpr_log(GPR_DEBUG, "%s:%p %s:%d unref %" PRIdPTR " -> %" PRIdPTR " %s",
+ trace_flag_->name(), this, location.file(), location.line(),
+ old_refs, old_refs - 1, reason);
+ }
+ Unref();
+ }
+
+ private:
+ TraceFlag* trace_flag_ = nullptr;
+ gpr_refcount refs_;
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_ORPHANABLE_H */
diff --git a/src/core/lib/gprpp/ref_counted.h b/src/core/lib/gprpp/ref_counted.h
new file mode 100644
index 0000000000..c68118a71a
--- /dev/null
+++ b/src/core/lib/gprpp/ref_counted.h
@@ -0,0 +1,133 @@
+/*
+ *
+ * Copyright 2017 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_REF_COUNTED_H
+#define GRPC_CORE_LIB_GPRPP_REF_COUNTED_H
+
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/gprpp/abstract.h"
+#include "src/core/lib/gprpp/debug_location.h"
+#include "src/core/lib/gprpp/memory.h"
+
+namespace grpc_core {
+
+// A base class for reference-counted objects.
+// New objects should be created via New() and start with a refcount of 1.
+// When the refcount reaches 0, the object will be deleted via Delete().
+class RefCounted {
+ public:
+ void Ref() { gpr_ref(&refs_); }
+
+ void Unref() {
+ if (gpr_unref(&refs_)) {
+ Delete(this);
+ }
+ }
+
+ // Not copyable nor movable.
+ RefCounted(const RefCounted&) = delete;
+ RefCounted& operator=(const RefCounted&) = delete;
+
+ GRPC_ABSTRACT_BASE_CLASS
+
+ protected:
+ // Allow Delete() to access destructor.
+ template <typename T>
+ friend void Delete(T*);
+
+ RefCounted() { gpr_ref_init(&refs_, 1); }
+
+ virtual ~RefCounted() {}
+
+ private:
+ gpr_refcount refs_;
+};
+
+// An alternative version of the RefCounted base class that
+// supports tracing. This is intended to be used in cases where the
+// object will be handled both by idiomatic C++ code using smart
+// pointers and legacy code that is manually calling Ref() and Unref().
+// Once all of our code is converted to idiomatic C++, we may be able to
+// eliminate this class.
+class RefCountedWithTracing {
+ public:
+ void Ref() { gpr_ref(&refs_); }
+
+ void Ref(const DebugLocation& location, const char* reason) {
+ if (location.Log() && trace_flag_ != nullptr && trace_flag_->enabled()) {
+ gpr_atm old_refs = gpr_atm_no_barrier_load(&refs_.count);
+ gpr_log(GPR_DEBUG, "%s:%p %s:%d ref %" PRIdPTR " -> %" PRIdPTR " %s",
+ trace_flag_->name(), this, location.file(), location.line(),
+ old_refs, old_refs + 1, reason);
+ }
+ Ref();
+ }
+
+ void Unref() {
+ if (gpr_unref(&refs_)) {
+ Delete(this);
+ }
+ }
+
+ void Unref(const DebugLocation& location, const char* reason) {
+ if (location.Log() && trace_flag_ != nullptr && trace_flag_->enabled()) {
+ gpr_atm old_refs = gpr_atm_no_barrier_load(&refs_.count);
+ gpr_log(GPR_DEBUG, "%s:%p %s:%d unref %" PRIdPTR " -> %" PRIdPTR " %s",
+ trace_flag_->name(), this, location.file(), location.line(),
+ old_refs, old_refs - 1, reason);
+ }
+ Unref();
+ }
+
+ // Not copyable nor movable.
+ RefCountedWithTracing(const RefCountedWithTracing&) = delete;
+ RefCountedWithTracing& operator=(const RefCountedWithTracing&) = delete;
+
+ GRPC_ABSTRACT_BASE_CLASS
+
+ protected:
+ // Allow Delete() to access destructor.
+ template <typename T>
+ friend void Delete(T*);
+
+ RefCountedWithTracing()
+ : RefCountedWithTracing(static_cast<TraceFlag*>(nullptr)) {}
+
+ explicit RefCountedWithTracing(TraceFlag* trace_flag)
+ : trace_flag_(trace_flag) {
+ gpr_ref_init(&refs_, 1);
+ }
+
+#ifdef NDEBUG
+ explicit RefCountedWithTracing(DebugOnlyTraceFlag* trace_flag)
+ : RefCountedWithTracing() {}
+#endif
+
+ virtual ~RefCountedWithTracing() {}
+
+ private:
+ TraceFlag* trace_flag_ = nullptr;
+ gpr_refcount refs_;
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_REF_COUNTED_H */
diff --git a/src/core/lib/gprpp/ref_counted_ptr.h b/src/core/lib/gprpp/ref_counted_ptr.h
new file mode 100644
index 0000000000..dda0f00d79
--- /dev/null
+++ b/src/core/lib/gprpp/ref_counted_ptr.h
@@ -0,0 +1,99 @@
+/*
+ *
+ * Copyright 2017 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_REF_COUNTED_PTR_H
+#define GRPC_CORE_LIB_GPRPP_REF_COUNTED_PTR_H
+
+#include <utility>
+
+#include "src/core/lib/gprpp/memory.h"
+
+namespace grpc_core {
+
+// A smart pointer class for objects that provide Ref() and Unref() methods,
+// such as those provided by the RefCounted base class.
+template <typename T>
+class RefCountedPtr {
+ public:
+ RefCountedPtr() {}
+
+ // If value is non-null, we take ownership of a ref to it.
+ explicit RefCountedPtr(T* value) { value_ = value; }
+
+ // Move support.
+ RefCountedPtr(RefCountedPtr&& other) {
+ value_ = other.value_;
+ other.value_ = nullptr;
+ }
+ RefCountedPtr& operator=(RefCountedPtr&& other) {
+ if (value_ != nullptr) value_->Unref();
+ value_ = other.value_;
+ other.value_ = nullptr;
+ return *this;
+ }
+
+ // Copy support.
+ RefCountedPtr(const RefCountedPtr& other) {
+ if (other.value_ != nullptr) other.value_->Ref();
+ value_ = other.value_;
+ }
+ RefCountedPtr& operator=(const RefCountedPtr& other) {
+ // Note: Order of reffing and unreffing is important here in case value_
+ // and other.value_ are the same object.
+ if (other.value_ != nullptr) other.value_->Ref();
+ if (value_ != nullptr) value_->Unref();
+ value_ = other.value_;
+ return *this;
+ }
+
+ ~RefCountedPtr() {
+ if (value_ != nullptr) value_->Unref();
+ }
+
+ // If value is non-null, we take ownership of a ref to it.
+ void reset(T* value = nullptr) {
+ if (value_ != nullptr) value_->Unref();
+ value_ = value;
+ }
+
+ T* get() const { return value_; }
+
+ T& operator*() const { return *value_; }
+ T* operator->() const { return value_; }
+
+ bool operator==(const RefCountedPtr& other) const {
+ return value_ == other.value_;
+ }
+ bool operator==(const T* other) const { return value_ == other; }
+ bool operator!=(const RefCountedPtr& other) const {
+ return value_ != other.value_;
+ }
+ bool operator!=(const T* other) const { return value_ != other; }
+
+ private:
+ T* value_ = nullptr;
+};
+
+template <typename T, typename... Args>
+inline RefCountedPtr<T> MakeRefCounted(Args&&... args) {
+ return RefCountedPtr<T>(New<T>(std::forward<Args>(args)...));
+}
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_REF_COUNTED_PTR_H */