1// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
2// Licensed under the MIT License:
3//
4// Permission is hereby granted, free of charge, to any person obtaining a copy
5// of this software and associated documentation files (the "Software"), to deal
6// in the Software without restriction, including without limitation the rights
7// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8// copies of the Software, and to permit persons to whom the Software is
9// furnished to do so, subject to the following conditions:
10//
11// The above copyright notice and this permission notice shall be included in
12// all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20// THE SOFTWARE.
21
22#pragma once
23
24#if defined(__GNUC__) && !KJ_HEADER_WARNINGS
25#pragma GCC system_header
26#endif
27
28#include "common.h"
29
30namespace kj {
31
32namespace _ { // private
33
34template <typename T> struct RefOrVoid_ { typedef T& Type; };
35template <> struct RefOrVoid_<void> { typedef void Type; };
36template <> struct RefOrVoid_<const void> { typedef void Type; };
37
38template <typename T>
39using RefOrVoid = typename RefOrVoid_<T>::Type;
40// Evaluates to T&, unless T is `void`, in which case evaluates to `void`.
41//
42// This is a hack needed to avoid defining Own<void> as a totally separate class.
43
44template <typename T, bool isPolymorphic = __is_polymorphic(T)>
45struct CastToVoid_;
46
47template <typename T>
48struct CastToVoid_<T, false> {
49 static void* apply(T* ptr) {
50 return static_cast<void*>(ptr);
51 }
52 static const void* applyConst(T* ptr) {
53 const T* cptr = ptr;
54 return static_cast<const void*>(cptr);
55 }
56};
57
58template <typename T>
59struct CastToVoid_<T, true> {
60 static void* apply(T* ptr) {
61 return dynamic_cast<void*>(ptr);
62 }
63 static const void* applyConst(T* ptr) {
64 const T* cptr = ptr;
65 return dynamic_cast<const void*>(cptr);
66 }
67};
68
69template <typename T>
70void* castToVoid(T* ptr) {
71 return CastToVoid_<T>::apply(ptr);
72}
73
74template <typename T>
75const void* castToConstVoid(T* ptr) {
76 return CastToVoid_<T>::applyConst(ptr);
77}
78
79} // namespace _ (private)
80
81// =======================================================================================
82// Disposer -- Implementation details.
83
84class Disposer {
85 // Abstract interface for a thing that "disposes" of objects, where "disposing" usually means
86 // calling the destructor followed by freeing the underlying memory. `Own<T>` encapsulates an
87 // object pointer with corresponding Disposer.
88 //
89 // Few developers will ever touch this interface. It is primarily useful for those implementing
90 // custom memory allocators.
91
92protected:
93 // Do not declare a destructor, as doing so will force a global initializer for each HeapDisposer
94 // instance. Eww!
95
96 virtual void disposeImpl(void* pointer) const = 0;
97 // Disposes of the object, given a pointer to the beginning of the object. If the object is
98 // polymorphic, this pointer is determined by dynamic_cast<void*>(). For non-polymorphic types,
99 // Own<T> does not allow any casting, so the pointer exactly matches the original one given to
100 // Own<T>.
101
102public:
103
104 template <typename T>
105 void dispose(T* object) const;
106 // Helper wrapper around disposeImpl().
107 //
108 // If T is polymorphic, calls `disposeImpl(dynamic_cast<void*>(object))`, otherwise calls
109 // `disposeImpl(implicitCast<void*>(object))`.
110 //
111 // Callers must not call dispose() on the same pointer twice, even if the first call throws
112 // an exception.
113
114private:
115 template <typename T, bool polymorphic = __is_polymorphic(T)>
116 struct Dispose_;
117};
118
119template <typename T>
120class DestructorOnlyDisposer: public Disposer {
121 // A disposer that merely calls the type's destructor and nothing else.
122
123public:
124 static const DestructorOnlyDisposer instance;
125
126 void disposeImpl(void* pointer) const override {
127 reinterpret_cast<T*>(pointer)->~T();
128 }
129};
130
131template <typename T>
132const DestructorOnlyDisposer<T> DestructorOnlyDisposer<T>::instance = DestructorOnlyDisposer<T>();
133
134class NullDisposer: public Disposer {
135 // A disposer that does nothing.
136
137public:
138 static const NullDisposer instance;
139
140 void disposeImpl(void* pointer) const override {}
141};
142
143// =======================================================================================
144// Own<T> -- An owned pointer.
145
146template <typename T>
147class Own {
148 // A transferrable title to a T. When an Own<T> goes out of scope, the object's Disposer is
149 // called to dispose of it. An Own<T> can be efficiently passed by move, without relocating the
150 // underlying object; this transfers ownership.
151 //
152 // This is much like std::unique_ptr, except:
153 // - You cannot release(). An owned object is not necessarily allocated with new (see next
154 // point), so it would be hard to use release() correctly.
155 // - The deleter is made polymorphic by virtual call rather than by template. This is much
156 // more powerful -- it allows the use of custom allocators, freelists, etc. This could
157 // _almost_ be accomplished with unique_ptr by forcing everyone to use something like
158 // std::unique_ptr<T, kj::Deleter>, except that things get hairy in the presence of multiple
159 // inheritance and upcasting, and anyway if you force everyone to use a custom deleter
160 // then you've lost any benefit to interoperating with the "standard" unique_ptr.
161
162public:
163 KJ_DISALLOW_COPY(Own);
164 inline Own(): disposer(nullptr), ptr(nullptr) {}
165 inline Own(Own&& other) noexcept
166 : disposer(other.disposer), ptr(other.ptr) { other.ptr = nullptr; }
167 inline Own(Own<RemoveConstOrDisable<T>>&& other) noexcept
168 : disposer(other.disposer), ptr(other.ptr) { other.ptr = nullptr; }
169 template <typename U, typename = EnableIf<canConvert<U*, T*>()>>
170 inline Own(Own<U>&& other) noexcept
171 : disposer(other.disposer), ptr(cast(other.ptr)) {
172 other.ptr = nullptr;
173 }
174 inline Own(T* ptr, const Disposer& disposer) noexcept: disposer(&disposer), ptr(ptr) {}
175
176 ~Own() noexcept(false) { dispose(); }
177
178 inline Own& operator=(Own&& other) {
179 // Move-assingnment operator.
180
181 // Careful, this might own `other`. Therefore we have to transfer the pointers first, then
182 // dispose.
183 const Disposer* disposerCopy = disposer;
184 T* ptrCopy = ptr;
185 disposer = other.disposer;
186 ptr = other.ptr;
187 other.ptr = nullptr;
188 if (ptrCopy != nullptr) {
189 disposerCopy->dispose(const_cast<RemoveConst<T>*>(ptrCopy));
190 }
191 return *this;
192 }
193
194 inline Own& operator=(decltype(nullptr)) {
195 dispose();
196 return *this;
197 }
198
199 template <typename... Attachments>
200 Own<T> attach(Attachments&&... attachments) KJ_WARN_UNUSED_RESULT;
201 // Returns an Own<T> which points to the same object but which also ensures that all values
202 // passed to `attachments` remain alive until after this object is destroyed. Normally
203 // `attachments` are other Own<?>s pointing to objects that this one depends on.
204 //
205 // Note that attachments will eventually be destroyed in the order they are listed. Hence,
206 // foo.attach(bar, baz) is equivalent to (but more efficient than) foo.attach(bar).attach(baz).
207
208 template <typename U>
209 Own<U> downcast() {
210 // Downcast the pointer to Own<U>, destroying the original pointer. If this pointer does not
211 // actually point at an instance of U, the results are undefined (throws an exception in debug
212 // mode if RTTI is enabled, otherwise you're on your own).
213
214 Own<U> result;
215 if (ptr != nullptr) {
216 result.ptr = &kj::downcast<U>(*ptr);
217 result.disposer = disposer;
218 ptr = nullptr;
219 }
220 return result;
221 }
222
223#define NULLCHECK KJ_IREQUIRE(ptr != nullptr, "null Own<> dereference")
224 inline T* operator->() { NULLCHECK; return ptr; }
225 inline const T* operator->() const { NULLCHECK; return ptr; }
226 inline _::RefOrVoid<T> operator*() { NULLCHECK; return *ptr; }
227 inline _::RefOrVoid<const T> operator*() const { NULLCHECK; return *ptr; }
228#undef NULLCHECK
229 inline T* get() { return ptr; }
230 inline const T* get() const { return ptr; }
231 inline operator T*() { return ptr; }
232 inline operator const T*() const { return ptr; }
233
234private:
235 const Disposer* disposer; // Only valid if ptr != nullptr.
236 T* ptr;
237
238 inline explicit Own(decltype(nullptr)): disposer(nullptr), ptr(nullptr) {}
239
240 inline bool operator==(decltype(nullptr)) { return ptr == nullptr; }
241 inline bool operator!=(decltype(nullptr)) { return ptr != nullptr; }
242 // Only called by Maybe<Own<T>>.
243
244 inline void dispose() {
245 // Make sure that if an exception is thrown, we are left with a null ptr, so we won't possibly
246 // dispose again.
247 T* ptrCopy = ptr;
248 if (ptrCopy != nullptr) {
249 ptr = nullptr;
250 disposer->dispose(const_cast<RemoveConst<T>*>(ptrCopy));
251 }
252 }
253
254 template <typename U>
255 static inline T* cast(U* ptr) {
256 static_assert(__is_polymorphic(T),
257 "Casting owned pointers requires that the target type is polymorphic.");
258 return ptr;
259 }
260
261 template <typename U>
262 friend class Own;
263 friend class Maybe<Own<T>>;
264};
265
266template <>
267template <typename U>
268inline void* Own<void>::cast(U* ptr) {
269 return _::castToVoid(ptr);
270}
271
272template <>
273template <typename U>
274inline const void* Own<const void>::cast(U* ptr) {
275 return _::castToConstVoid(ptr);
276}
277
278namespace _ { // private
279
280template <typename T>
281class OwnOwn {
282public:
283 inline OwnOwn(Own<T>&& value) noexcept: value(kj::mv(value)) {}
284
285 inline Own<T>& operator*() & { return value; }
286 inline const Own<T>& operator*() const & { return value; }
287 inline Own<T>&& operator*() && { return kj::mv(value); }
288 inline const Own<T>&& operator*() const && { return kj::mv(value); }
289 inline Own<T>* operator->() { return &value; }
290 inline const Own<T>* operator->() const { return &value; }
291 inline operator Own<T>*() { return value ? &value : nullptr; }
292 inline operator const Own<T>*() const { return value ? &value : nullptr; }
293
294private:
295 Own<T> value;
296};
297
298template <typename T>
299OwnOwn<T> readMaybe(Maybe<Own<T>>&& maybe) { return OwnOwn<T>(kj::mv(maybe.ptr)); }
300template <typename T>
301Own<T>* readMaybe(Maybe<Own<T>>& maybe) { return maybe.ptr ? &maybe.ptr : nullptr; }
302template <typename T>
303const Own<T>* readMaybe(const Maybe<Own<T>>& maybe) { return maybe.ptr ? &maybe.ptr : nullptr; }
304
305} // namespace _ (private)
306
307template <typename T>
308class Maybe<Own<T>> {
309public:
310 inline Maybe(): ptr(nullptr) {}
311 inline Maybe(Own<T>&& t) noexcept: ptr(kj::mv(t)) {}
312 inline Maybe(Maybe&& other) noexcept: ptr(kj::mv(other.ptr)) {}
313
314 template <typename U>
315 inline Maybe(Maybe<Own<U>>&& other): ptr(mv(other.ptr)) {}
316 template <typename U>
317 inline Maybe(Own<U>&& other): ptr(mv(other)) {}
318
319 inline Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {}
320
321 inline operator Maybe<T&>() { return ptr.get(); }
322 inline operator Maybe<const T&>() const { return ptr.get(); }
323
324 inline Maybe& operator=(Maybe&& other) { ptr = kj::mv(other.ptr); return *this; }
325
326 inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; }
327 inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; }
328
329 Own<T>& orDefault(Own<T>& defaultValue) {
330 if (ptr == nullptr) {
331 return defaultValue;
332 } else {
333 return ptr;
334 }
335 }
336 const Own<T>& orDefault(const Own<T>& defaultValue) const {
337 if (ptr == nullptr) {
338 return defaultValue;
339 } else {
340 return ptr;
341 }
342 }
343
344 template <typename Func>
345 auto map(Func&& f) & -> Maybe<decltype(f(instance<Own<T>&>()))> {
346 if (ptr == nullptr) {
347 return nullptr;
348 } else {
349 return f(ptr);
350 }
351 }
352
353 template <typename Func>
354 auto map(Func&& f) const & -> Maybe<decltype(f(instance<const Own<T>&>()))> {
355 if (ptr == nullptr) {
356 return nullptr;
357 } else {
358 return f(ptr);
359 }
360 }
361
362 template <typename Func>
363 auto map(Func&& f) && -> Maybe<decltype(f(instance<Own<T>&&>()))> {
364 if (ptr == nullptr) {
365 return nullptr;
366 } else {
367 return f(kj::mv(ptr));
368 }
369 }
370
371 template <typename Func>
372 auto map(Func&& f) const && -> Maybe<decltype(f(instance<const Own<T>&&>()))> {
373 if (ptr == nullptr) {
374 return nullptr;
375 } else {
376 return f(kj::mv(ptr));
377 }
378 }
379
380private:
381 Own<T> ptr;
382
383 template <typename U>
384 friend class Maybe;
385 template <typename U>
386 friend _::OwnOwn<U> _::readMaybe(Maybe<Own<U>>&& maybe);
387 template <typename U>
388 friend Own<U>* _::readMaybe(Maybe<Own<U>>& maybe);
389 template <typename U>
390 friend const Own<U>* _::readMaybe(const Maybe<Own<U>>& maybe);
391};
392
393namespace _ { // private
394
395template <typename T>
396class HeapDisposer final: public Disposer {
397public:
398 virtual void disposeImpl(void* pointer) const override { delete reinterpret_cast<T*>(pointer); }
399
400 static const HeapDisposer instance;
401};
402
403template <typename T>
404const HeapDisposer<T> HeapDisposer<T>::instance = HeapDisposer<T>();
405
406} // namespace _ (private)
407
408template <typename T, typename... Params>
409Own<T> heap(Params&&... params) {
410 // heap<T>(...) allocates a T on the heap, forwarding the parameters to its constructor. The
411 // exact heap implementation is unspecified -- for now it is operator new, but you should not
412 // assume this. (Since we know the object size at delete time, we could actually implement an
413 // allocator that is more efficient than operator new.)
414
415 return Own<T>(new T(kj::fwd<Params>(params)...), _::HeapDisposer<T>::instance);
416}
417
418template <typename T>
419Own<Decay<T>> heap(T&& orig) {
420 // Allocate a copy (or move) of the argument on the heap.
421 //
422 // The purpose of this overload is to allow you to omit the template parameter as there is only
423 // one argument and the purpose is to copy it.
424
425 typedef Decay<T> T2;
426 return Own<T2>(new T2(kj::fwd<T>(orig)), _::HeapDisposer<T2>::instance);
427}
428
429// =======================================================================================
430// SpaceFor<T> -- assists in manual allocation
431
432template <typename T>
433class SpaceFor {
434 // A class which has the same size and alignment as T but does not call its constructor or
435 // destructor automatically. Instead, call construct() to construct a T in the space, which
436 // returns an Own<T> which will take care of calling T's destructor later.
437
438public:
439 inline SpaceFor() {}
440 inline ~SpaceFor() {}
441
442 template <typename... Params>
443 Own<T> construct(Params&&... params) {
444 ctor(value, kj::fwd<Params>(params)...);
445 return Own<T>(&value, DestructorOnlyDisposer<T>::instance);
446 }
447
448private:
449 union {
450 T value;
451 };
452};
453
454// =======================================================================================
455// Inline implementation details
456
457template <typename T>
458struct Disposer::Dispose_<T, true> {
459 static void dispose(T* object, const Disposer& disposer) {
460 // Note that dynamic_cast<void*> does not require RTTI to be enabled, because the offset to
461 // the top of the object is in the vtable -- as it obviously needs to be to correctly implement
462 // operator delete.
463 disposer.disposeImpl(dynamic_cast<void*>(object));
464 }
465};
466template <typename T>
467struct Disposer::Dispose_<T, false> {
468 static void dispose(T* object, const Disposer& disposer) {
469 disposer.disposeImpl(static_cast<void*>(object));
470 }
471};
472
473template <typename T>
474void Disposer::dispose(T* object) const {
475 Dispose_<T>::dispose(object, *this);
476}
477
478namespace _ { // private
479
480template <typename... T>
481struct OwnedBundle;
482
483template <>
484struct OwnedBundle<> {};
485
486template <typename First, typename... Rest>
487struct OwnedBundle<First, Rest...>: public OwnedBundle<Rest...> {
488 OwnedBundle(First&& first, Rest&&... rest)
489 : OwnedBundle<Rest...>(kj::fwd<Rest>(rest)...), first(kj::fwd<First>(first)) {}
490
491 // Note that it's intentional that `first` is destroyed before `rest`. This way, doing
492 // ptr.attach(foo, bar, baz) is equivalent to ptr.attach(foo).attach(bar).attach(baz) in terms
493 // of destruction order (although the former does fewer allocations).
494 Decay<First> first;
495};
496
497template <typename... T>
498struct DisposableOwnedBundle final: public Disposer, public OwnedBundle<T...> {
499 DisposableOwnedBundle(T&&... values): OwnedBundle<T...>(kj::fwd<T>(values)...) {}
500 void disposeImpl(void* pointer) const override { delete this; }
501};
502
503} // namespace _ (private)
504
505template <typename T>
506template <typename... Attachments>
507Own<T> Own<T>::attach(Attachments&&... attachments) {
508 T* ptrCopy = ptr;
509
510 KJ_IREQUIRE(ptrCopy != nullptr, "cannot attach to null pointer");
511
512 // HACK: If someone accidentally calls .attach() on a null pointer in opt mode, try our best to
513 // accomplish reasonable behavior: We turn the pointer non-null but still invalid, so that the
514 // disposer will still be called when the pointer goes out of scope.
515 if (ptrCopy == nullptr) ptrCopy = reinterpret_cast<T*>(1);
516
517 auto bundle = new _::DisposableOwnedBundle<Own<T>, Attachments...>(
518 kj::mv(*this), kj::fwd<Attachments>(attachments)...);
519 return Own<T>(ptrCopy, *bundle);
520}
521
522} // namespace kj
523