• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15 
16 #include <cstddef>
17 #include <type_traits>
18 #include <utility>
19 
20 #include "pw_allocator/config.h"
21 #include "pw_allocator/internal/managed_ptr.h"
22 #include "pw_preprocessor/compiler.h"
23 
24 namespace pw {
25 
26 /// A `std::unique_ptr<T>`-like type that integrates with `pw::Deallocator`.
27 ///
28 /// This is a RAII smart pointer that deallocates any memory it points to when
29 /// it goes out of scope.
30 ///
31 /// Its most notable difference from `std::unique_ptr<T>` is that it cannot be
32 /// constructed from a `T*`. Use `Allocator::MakeUnique<T>(...)` instead.
33 ///
34 /// @tparam   T   The type being pointed to. This may be an array type, e.g.
35 ///           `pw::UniquePtr<T[]>`.
36 ///
37 /// TODO(b/399441816): This class should be marked final, but at least one
38 /// downstream has extended it. Resolve and mark final.
39 template <typename T>
40 class UniquePtr : public ::pw::allocator::internal::ManagedPtr<T> {
41  private:
42   using Base = ::pw::allocator::internal::ManagedPtr<T>;
43   using Empty = ::pw::allocator::internal::Empty;
44 
45  public:
46   using pointer = typename Base::element_type*;
47   using element_type = typename Base::element_type;
48 
49   /// Creates an empty (`nullptr`) instance.
50   ///
51   /// NOTE: Instances of this type are most commonly constructed using
52   /// `Allocator::MakeUnique`.
UniquePtr()53   constexpr UniquePtr() noexcept {
54     if constexpr (std::is_array_v<T>) {
55       size_ = 0;
56     }
57   }
58 
59   /// Creates an empty (`nullptr`) instance.
60   ///
61   /// NOTE: Instances of this type are most commonly constructed using
62   /// `Allocator::MakeUnique`.
UniquePtr(std::nullptr_t)63   constexpr UniquePtr(std::nullptr_t) noexcept : UniquePtr() {}
64 
65   /// Move-constructs a `UniquePtr<T>` from a `UniquePtr<U>`.
66   ///
67   /// This allows not only pure move construction where `T == U`, but also
68   /// converting construction where `T` is a base class of `U`, like
69   /// `UniquePtr<Base> base(deallocator.MakeUnique<Child>());`.
70   template <typename U>
UniquePtr(UniquePtr<U> && other)71   UniquePtr(UniquePtr<U>&& other) noexcept {
72     *this = std::move(other);
73   }
74 
75   /// Frees any currently-held value.
~UniquePtr()76   ~UniquePtr() { Reset(); }
77 
78   /// Move-assigns a `UniquePtr<T>` from a `UniquePtr<U>`.
79   ///
80   /// This operation frees the value currently stored in `this`.
81   ///
82   /// This allows not only pure move assignment where `T == U`, but also
83   /// converting assignment where `T` is a base class of `U`.
84   template <typename U>
85   UniquePtr& operator=(UniquePtr<U>&& other) noexcept;
86 
87   /// Sets this `UniquePtr` to null, freeing any currently-held value.
88   ///
89   /// After this function returns, this `UniquePtr` will be in an "empty"
90   /// (`nullptr`) state until a new value is assigned.
91   UniquePtr& operator=(std::nullptr_t) noexcept;
92 
93   /// Returns the number of elements allocated.
94   ///
95   /// This will fail to compile if it is called on a non-array type UniquePtr.
size()96   size_t size() const {
97     static_assert(std::is_array_v<T>,
98                   "size() cannot be called with a non-array type");
99     return size_;
100   }
101 
102   /// Returns a pointer to the object that can destroy the value.
deallocator()103   Deallocator* deallocator() const { return deallocator_; }
104 
105   /// Releases a value from the `UniquePtr` without destructing or
106   /// deallocating it.
107   ///
108   /// After this call, the object will have an "empty" (`nullptr`) value.
109   element_type* Release() noexcept;
110 
111   /// Destroys and deallocates any currently-held value.
112   ///
113   /// After this function returns, this `UniquePtr` will be in an "empty"
114   /// (`nullptr`) state until a new value is assigned.
115   void Reset() noexcept;
116 
117   /// Swaps the managed pointer and deallocator of this and another object.
118   void Swap(UniquePtr& other);
119 
120  private:
121   // Allow construction with to the implementation of `MakeUnique`.
122   friend class Deallocator;
123 
124   // Allow UniquePtr<T> to access UniquePtr<U> and vice versa.
125   template <typename>
126   friend class UniquePtr;
127 
128   /// Private constructor that is public only for use with `emplace` and
129   /// other in-place construction functions.
130   ///
131   /// Constructs a `UniquePtr` from an already-allocated value.
132   ///
133   /// NOTE: Instances of this type are most commonly constructed using
134   /// `Deallocator::MakeUnique`.
UniquePtr(element_type * value,Deallocator * deallocator)135   UniquePtr(element_type* value, Deallocator* deallocator)
136       : Base(value), deallocator_(deallocator) {}
137 
138   /// Private constructor that is public only for use with `emplace` and
139   /// other in-place construction functions.
140   ///
141   /// Constructs a `UniquePtr` from an already-allocated value and size.
142   ///
143   /// NOTE: Instances of this type are most commonly constructed using
144   /// `Deallocator::MakeUnique`.
UniquePtr(element_type * value,size_t size,Deallocator * deallocator)145   UniquePtr(element_type* value, size_t size, Deallocator* deallocator)
146       : Base(value), size_(size), deallocator_(deallocator) {}
147 
148   /// Copies details from another object without releasing it.
149   template <typename U>
150   void CopyFrom(const UniquePtr<U>& other);
151 
152   /// The number of elements allocated. This will not be present in the case
153   /// where T is not an array type as this will be the empty struct type
154   /// optimized out.
155   PW_NO_UNIQUE_ADDRESS
156   std::conditional_t<std::is_array_v<T>, size_t, Empty> size_;
157 
158   /// The `deallocator_` which can reclaim the memory for  `value_`.
159   /// This must be tracked in order to deallocate the memory upon destruction.
160   Deallocator* deallocator_ = nullptr;
161 };
162 
163 namespace allocator {
164 
165 // Alias for module consumers using the older name for the above type.
166 template <typename T>
167 using UniquePtr = PW_ALLOCATOR_DEPRECATED ::pw::UniquePtr<T>;
168 
169 }  // namespace allocator
170 
171 // Template method implementations.
172 
173 template <typename T>
174 template <typename U>
175 UniquePtr<T>& UniquePtr<T>::operator=(UniquePtr<U>&& other) noexcept {
176   Reset();
177   CopyFrom(other);
178   other.Release();
179   return *this;
180 }
181 
182 template <typename T>
183 UniquePtr<T>& UniquePtr<T>::operator=(std::nullptr_t) noexcept {
184   Reset();
185   return *this;
186 }
187 
188 template <typename T>
Release()189 typename UniquePtr<T>::element_type* UniquePtr<T>::Release() noexcept {
190   element_type* value = Base::Release();
191   deallocator_ = nullptr;
192   return value;
193 }
194 
195 template <typename T>
Reset()196 void UniquePtr<T>::Reset() noexcept {
197   if (*this == nullptr) {
198     return;
199   }
200   if (!Base::HasCapability(deallocator_, allocator::kSkipsDestroy)) {
201     if constexpr (std::is_array_v<T>) {
202       Base::Destroy(size_);
203     } else {
204       Base::Destroy();
205     }
206   }
207   Deallocator* deallocator = deallocator_;
208   Base::Deallocate(deallocator, Release());
209 }
210 
211 template <typename T>
Swap(UniquePtr<T> & other)212 void UniquePtr<T>::Swap(UniquePtr<T>& other) {
213   Base::Swap(other);
214   if constexpr (std::is_array_v<T>) {
215     std::swap(size_, other.size_);
216   }
217   std::swap(deallocator_, other.deallocator_);
218 }
219 
220 template <typename T>
221 template <typename U>
CopyFrom(const UniquePtr<U> & other)222 void UniquePtr<T>::CopyFrom(const UniquePtr<U>& other) {
223   Base::CopyFrom(other);
224   size_ = other.size_;
225   deallocator_ = other.deallocator_;
226 }
227 
228 }  // namespace pw
229