Bug 1867190 - Add prefs for PHC probablities r=glandium
[gecko.git] / xpcom / base / nsAutoRef.h
blob9a1f3ddd93e95b601da87ccf09024f32a4add279
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 // NB: This code may be used from non-XPCOM code, in particular, the
8 // Windows Default Browser Agent.
10 #ifndef nsAutoRef_h_
11 #define nsAutoRef_h_
13 #include "mozilla/Attributes.h"
15 template <class T>
16 class nsSimpleRef;
17 template <class T>
18 class nsAutoRefBase;
19 template <class T>
20 class nsReturnRef;
21 template <class T>
22 class nsReturningRef;
24 /**
25 * template <class T> class nsAutoRef
27 * A class that holds a handle to a resource that must be released.
28 * No reference is added on construction.
30 * No copy constructor nor copy assignment operators are available, so the
31 * resource will be held until released on destruction or explicitly
32 * |reset()| or transferred through provided methods.
34 * The publicly available methods are the public methods on this class and its
35 * public base classes |nsAutoRefBase<T>| and |nsSimpleRef<T>|.
37 * For function return values see |nsReturnRef<T>|.
39 * For each class |T|, |nsAutoRefTraits<T>| or |nsSimpleRef<T>| must be
40 * specialized to use |nsAutoRef<T>|.
42 * @param T A class identifying the type of reference held by the
43 * |nsAutoRef<T>| and the unique set methods for managing references
44 * to the resource (defined by |nsAutoRefTraits<T>| or
45 * |nsSimpleRef<T>|).
47 * Often this is the class representing the resource. Sometimes a
48 * new possibly-incomplete class may need to be declared.
51 * Example: An Automatically closing file descriptor
53 * // References that are simple integral types (as file-descriptors are)
54 * // usually need a new class to represent the resource and how to handle its
55 * // references.
56 * class nsRawFD;
58 * // Specializing nsAutoRefTraits<nsRawFD> describes how to manage file
59 * // descriptors, so that nsAutoRef<nsRawFD> provides automatic closing of
60 * // its file descriptor on destruction.
61 * template <>
62 * class nsAutoRefTraits<nsRawFD> {
63 * public:
64 * // The file descriptor is held in an int.
65 * typedef int RawRef;
66 * // -1 means that there is no file associated with the handle.
67 * static int Void() { return -1; }
68 * // The file associated with a file descriptor is released with close().
69 * static void Release(RawRef aFD) { close(aFD); }
70 * };
72 * // A function returning a file descriptor that must be closed.
73 * nsReturnRef<nsRawFD> get_file(const char *filename) {
74 * // Constructing from a raw file descriptor assumes ownership.
75 * nsAutoRef<nsRawFD> fd(open(filename, O_RDONLY));
76 * fcntl(fd, F_SETFD, FD_CLOEXEC);
77 * return fd.out();
78 * }
80 * void f() {
81 * unsigned char buf[1024];
83 * // Hold a file descriptor for /etc/hosts in fd1.
84 * nsAutoRef<nsRawFD> fd1(get_file("/etc/hosts"));
86 * nsAutoRef<nsRawFD> fd2;
87 * fd2.steal(fd1); // fd2 takes the file descriptor from fd1
88 * ssize_t count = read(fd1, buf, 1024); // error fd1 has no file
89 * count = read(fd2, buf, 1024); // reads from /etc/hosts
91 * // If the file descriptor is not stored then it is closed.
92 * get_file("/etc/login.defs"); // login.defs is closed
94 * // Now use fd1 to hold a file descriptor for /etc/passwd.
95 * fd1 = get_file("/etc/passwd");
97 * // The nsAutoRef<nsRawFD> can give up the file descriptor if explicitly
98 * // instructed, but the caller must then ensure that the file is closed.
99 * int rawfd = fd1.disown();
101 * // Assume ownership of another file descriptor.
102 * fd1.own(open("/proc/1/maps");
104 * // On destruction, fd1 closes /proc/1/maps and fd2 closes /etc/hosts,
105 * // but /etc/passwd is not closed.
110 template <class T>
111 class nsAutoRef : public nsAutoRefBase<T> {
112 protected:
113 typedef nsAutoRef<T> ThisClass;
114 typedef nsAutoRefBase<T> BaseClass;
115 typedef nsSimpleRef<T> SimpleRef;
116 typedef typename BaseClass::RawRefOnly RawRefOnly;
117 typedef typename BaseClass::LocalSimpleRef LocalSimpleRef;
119 public:
120 nsAutoRef() = default;
122 // Explicit construction is required so as not to risk unintentionally
123 // releasing the resource associated with a raw ref.
124 explicit nsAutoRef(RawRefOnly aRefToRelease) : BaseClass(aRefToRelease) {}
126 // Construction from a nsReturnRef<T> function return value, which expects
127 // to give up ownership, transfers ownership.
128 // (nsReturnRef<T> is converted to const nsReturningRef<T>.)
129 explicit nsAutoRef(const nsReturningRef<T>& aReturning)
130 : BaseClass(aReturning) {}
132 // The only assignment operator provided is for transferring from an
133 // nsReturnRef smart reference, which expects to pass its ownership to
134 // another object.
136 // With raw references and other smart references, the type of the lhs and
137 // its taking and releasing nature is often not obvious from an assignment
138 // statement. Assignment from a raw ptr especially is not normally
139 // expected to release the reference.
141 // Use |steal| for taking ownership from other smart refs.
143 // For raw references, use |own| to indicate intention to have the
144 // resource released.
146 ThisClass& operator=(const nsReturningRef<T>& aReturning) {
147 BaseClass::steal(aReturning.mReturnRef);
148 return *this;
151 // Conversion to a raw reference allow the nsAutoRef<T> to often be used
152 // like a raw reference.
153 operator typename SimpleRef::RawRef() const { return this->get(); }
155 explicit operator bool() const { return this->HaveResource(); }
157 // Transfer ownership from another smart reference.
158 void steal(ThisClass& aOtherRef) { BaseClass::steal(aOtherRef); }
160 // Assume ownership of a raw ref.
162 // |own| has similar function to |steal|, and is useful for receiving
163 // ownership from a return value of a function. It is named differently
164 // because |own| requires more care to ensure that the function intends to
165 // give away ownership, and so that |steal| can be safely used, knowing
166 // that it won't steal ownership from any methods returning raw ptrs to
167 // data owned by a foreign object.
168 void own(RawRefOnly aRefToRelease) { BaseClass::own(aRefToRelease); }
170 // Exchange ownership with |aOther|
171 void swap(ThisClass& aOther) {
172 LocalSimpleRef temp;
173 temp.SimpleRef::operator=(*this);
174 SimpleRef::operator=(aOther);
175 aOther.SimpleRef::operator=(temp);
178 // Release the reference now.
179 void reset() {
180 this->SafeRelease();
181 LocalSimpleRef empty;
182 SimpleRef::operator=(empty);
185 // Pass out the reference for a function return values.
186 nsReturnRef<T> out() { return nsReturnRef<T>(this->disown()); }
188 // operator->() and disown() are provided by nsAutoRefBase<T>.
189 // The default nsSimpleRef<T> provides get().
191 // No copy constructor
192 explicit nsAutoRef(const ThisClass& aRefToSteal) = delete;
196 * template <class T> class nsReturnRef
198 * A type for function return values that hold a reference to a resource that
199 * must be released. See also |nsAutoRef<T>::out()|.
202 template <class T>
203 class nsReturnRef : public nsAutoRefBase<T> {
204 protected:
205 typedef nsAutoRefBase<T> BaseClass;
206 typedef typename BaseClass::RawRefOnly RawRefOnly;
208 public:
209 // For constructing a return value with no resource
210 nsReturnRef() = default;
212 // For returning a smart reference from a raw reference that must be
213 // released. Explicit construction is required so as not to risk
214 // unintentionally releasing the resource associated with a raw ref.
215 MOZ_IMPLICIT nsReturnRef(RawRefOnly aRefToRelease)
216 : BaseClass(aRefToRelease) {}
218 // Move construction transfers ownership
219 nsReturnRef(nsReturnRef<T>&& aRefToSteal) = default;
221 MOZ_IMPLICIT nsReturnRef(const nsReturningRef<T>& aReturning)
222 : BaseClass(aReturning) {}
224 // Conversion to a temporary (const) object referring to this object so
225 // that the reference may be passed from a function return value
226 // (temporary) to another smart reference. There is no need to use this
227 // explicitly. Simply assign a nsReturnRef<T> function return value to a
228 // smart reference.
229 operator nsReturningRef<T>() { return nsReturningRef<T>(*this); }
231 // No conversion to RawRef operator is provided on nsReturnRef, to ensure
232 // that the return value is not carelessly assigned to a raw ptr (and the
233 // resource then released). If passing to a function that takes a raw
234 // ptr, use get or disown as appropriate.
238 * template <class T> class nsReturningRef
240 * A class to allow ownership to be transferred from nsReturnRef function
241 * return values.
243 * It should not be necessary for clients to reference this
244 * class directly. Simply pass an nsReturnRef<T> to a parameter taking an
245 * |nsReturningRef<T>|.
247 * The conversion operator on nsReturnRef constructs a temporary wrapper of
248 * class nsReturningRef<T> around a non-const reference to the nsReturnRef.
249 * The wrapper can then be passed as an rvalue parameter.
252 template <class T>
253 class nsReturningRef {
254 private:
255 friend class nsReturnRef<T>;
257 explicit nsReturningRef(nsReturnRef<T>& aReturnRef)
258 : mReturnRef(aReturnRef) {}
260 public:
261 nsReturnRef<T>& mReturnRef;
265 * template <class T> class nsAutoRefTraits
267 * A class describing traits of references managed by the default
268 * |nsSimpleRef<T>| implementation and thus |nsAutoRef<T>|.
269 * The default |nsSimpleRef<T> is suitable for resources with handles that
270 * have a void value. (If there is no such void value for a handle,
271 * specialize |nsSimpleRef<T>|.)
273 * Specializations must be provided for each class |T| according to the
274 * following pattern:
276 * // The template parameter |T| should be a class such that the set of fields
277 * // in class nsAutoRefTraits<T> is unique for class |T|. Usually the
278 * // resource object class is sufficient. For handles that are simple
279 * // integral typedefs, a new unique possibly-incomplete class may need to be
280 * // declared.
282 * template <>
283 * class nsAutoRefTraits<T>
285 * // Specializations must provide a typedef for RawRef, describing the
286 * // type of the handle to the resource.
287 * typedef <handle-type> RawRef;
289 * // Specializations should define Void(), a function returning a value
290 * // suitable for a handle that does not have an associated resource.
291 * //
292 * // The return type must be a suitable as the parameter to a RawRef
293 * // constructor and operator==.
294 * //
295 * // If this method is not accessible then some limited nsAutoRef
296 * // functionality will still be available, but the default constructor,
297 * // |reset|, and most transfer of ownership methods will not be available.
298 * static <return-type> Void();
300 * // Specializations must define Release() to properly finalize the
301 * // handle to a non-void custom-deleted or reference-counted resource.
302 * static void Release(RawRef aRawRef);
303 * };
305 * See nsPointerRefTraits for example specializations for simple pointer
306 * references. See nsAutoRef for an example specialization for a non-pointer
307 * reference.
310 template <class T>
311 class nsAutoRefTraits;
314 * template <class T> class nsPointerRefTraits
316 * A convenience class useful as a base class for specializations of
317 * |nsAutoRefTraits<T>| where the handle to the resource is a pointer to |T|.
318 * By inheriting from this class, definitions of only Release(RawRef) and
319 * possibly AddRef(RawRef) need to be added.
321 * Examples of use:
323 * template <>
324 * class nsAutoRefTraits<PRFileDesc> : public nsPointerRefTraits<PRFileDesc>
326 * public:
327 * static void Release(PRFileDesc *ptr) { PR_Close(ptr); }
328 * };
330 * template <>
331 * class nsAutoRefTraits<FcPattern> : public nsPointerRefTraits<FcPattern>
333 * public:
334 * static void Release(FcPattern *ptr) { FcPatternDestroy(ptr); }
335 * static void AddRef(FcPattern *ptr) { FcPatternReference(ptr); }
336 * };
339 template <class T>
340 class nsPointerRefTraits {
341 public:
342 // The handle is a pointer to T.
343 typedef T* RawRef;
344 // A nullptr does not have a resource.
345 static RawRef Void() { return nullptr; }
349 * template <class T> class nsSimpleRef
351 * Constructs a non-smart reference, and provides methods to test whether
352 * there is an associated resource and (if so) get its raw handle.
354 * A default implementation is suitable for resources with handles that have a
355 * void value. This is not intended for direct use but used by |nsAutoRef<T>|.
357 * Specialize this class if there is no particular void value for the resource
358 * handle. A specialized implementation must also provide Release(RawRef),
361 template <class T>
362 class nsSimpleRef : protected nsAutoRefTraits<T> {
363 protected:
364 // The default implementation uses nsAutoRefTrait<T>.
365 // Specializations need not define this typedef.
366 typedef nsAutoRefTraits<T> Traits;
367 // The type of the handle to the resource.
368 // A specialization must provide a typedef for RawRef.
369 typedef typename Traits::RawRef RawRef;
371 // Construct with no resource.
373 // If this constructor is not accessible then some limited nsAutoRef
374 // functionality will still be available, but the default constructor,
375 // |reset|, and most transfer of ownership methods will not be available.
376 nsSimpleRef() : mRawRef(Traits::Void()) {}
377 // Construct with a handle to a resource.
378 // A specialization must provide this.
379 explicit nsSimpleRef(RawRef aRawRef) : mRawRef(aRawRef) {}
381 // Test whether there is an associated resource. A specialization must
382 // provide this. The function is permitted to always return true if the
383 // default constructor is not accessible, or if Release (and AddRef) can
384 // deal with void handles.
385 bool HaveResource() const { return mRawRef != Traits::Void(); }
387 public:
388 // A specialization must provide get() or loose some functionality. This
389 // is inherited by derived classes and the specialization may choose
390 // whether it is public or protected.
391 RawRef get() const { return mRawRef; }
393 private:
394 RawRef mRawRef;
398 * template <class T> class nsAutoRefBase
400 * Internal base class for |nsAutoRef<T>| and |nsReturnRef<T>|.
401 * Adds release on destruction to a |nsSimpleRef<T>|.
404 template <class T>
405 class nsAutoRefBase : public nsSimpleRef<T> {
406 protected:
407 typedef nsAutoRefBase<T> ThisClass;
408 typedef nsSimpleRef<T> SimpleRef;
409 typedef typename SimpleRef::RawRef RawRef;
411 nsAutoRefBase() = default;
413 // A type for parameters that should be passed a raw ref but should not
414 // accept implicit conversions (from another smart ref). (The only
415 // conversion to this type is from a raw ref so only raw refs will be
416 // accepted.)
417 class RawRefOnly {
418 public:
419 MOZ_IMPLICIT RawRefOnly(RawRef aRawRef) : mRawRef(aRawRef) {}
420 operator RawRef() const { return mRawRef; }
422 private:
423 RawRef mRawRef;
426 // Construction from a raw ref assumes ownership
427 explicit nsAutoRefBase(RawRefOnly aRefToRelease) : SimpleRef(aRefToRelease) {}
429 // Constructors that steal ownership
430 nsAutoRefBase(ThisClass&& aRefToSteal) : SimpleRef(aRefToSteal.disown()) {}
431 explicit nsAutoRefBase(const nsReturningRef<T>& aReturning)
432 : SimpleRef(aReturning.mReturnRef.disown()) {}
434 ~nsAutoRefBase() { SafeRelease(); }
436 // An internal class providing access to protected nsSimpleRef<T>
437 // constructors for construction of temporary simple references (that are
438 // not ThisClass).
439 class LocalSimpleRef : public SimpleRef {
440 public:
441 LocalSimpleRef() = default;
442 explicit LocalSimpleRef(RawRef aRawRef) : SimpleRef(aRawRef) {}
445 public:
446 ThisClass& operator=(const ThisClass& aSmartRef) = delete;
448 RawRef operator->() const { return this->get(); }
450 // Transfer ownership to a raw reference.
452 // THE CALLER MUST ENSURE THAT THE REFERENCE IS EXPLICITLY RELEASED.
454 // Is this really what you want to use? Using this removes any guarantee
455 // of release. Use nsAutoRef<T>::out() for return values, or an
456 // nsAutoRef<T> modifiable lvalue for an out parameter. Use disown() when
457 // the reference must be stored in a POD type object, such as may be
458 // preferred for a namespace-scope object with static storage duration,
459 // for example.
460 RawRef disown() {
461 RawRef temp = this->get();
462 LocalSimpleRef empty;
463 SimpleRef::operator=(empty);
464 return temp;
467 protected:
468 // steal and own are protected because they make no sense on nsReturnRef,
469 // but steal is implemented on this class for access to aOtherRef.disown()
470 // when aOtherRef is an nsReturnRef;
472 // Transfer ownership from another smart reference.
473 void steal(ThisClass& aOtherRef) { own(aOtherRef.disown()); }
474 // Assume ownership of a raw ref.
475 void own(RawRefOnly aRefToRelease) {
476 SafeRelease();
477 LocalSimpleRef ref(aRefToRelease);
478 SimpleRef::operator=(ref);
481 // Release a resource if there is one.
482 void SafeRelease() {
483 if (this->HaveResource()) {
484 this->Release(this->get());
489 #endif // !defined(nsAutoRef_h_)