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/. */
8 * An allocation policy concept, usable for structures and algorithms to
9 * control how memory is allocated and how failures are handled.
12 #ifndef mozilla_AllocPolicy_h
13 #define mozilla_AllocPolicy_h
15 #include "mozilla/TemplateLib.h"
23 * Allocation policies are used to implement the standard allocation behaviors
24 * in a customizable way. Additionally, custom behaviors may be added to these
25 * behaviors, such as additionally reporting an error through an out-of-band
26 * mechanism when OOM occurs. The concept modeled here is as follows:
28 * - public copy constructor, assignment, destructor
29 * - template <typename T> T* pod_malloc(size_t)
30 * Responsible for OOM reporting when null is returned.
31 * - template <typename T> T* pod_calloc(size_t)
32 * Responsible for OOM reporting when null is returned.
33 * - template <typename T> T* pod_realloc(T*, size_t, size_t)
34 * Responsible for OOM reporting when null is returned. The old allocation
35 * size is passed in, in addition to the new allocation size requested.
37 * - void reportAllocOverflow() const
38 * Called on allocation overflow (that is, an allocation implicitly tried
39 * to allocate more than the available memory space -- think allocating an
40 * array of large-size objects, where N * size overflows) before null is
43 * mfbt provides (and typically uses by default) only MallocAllocPolicy, which
44 * does nothing more than delegate to the malloc/alloc/free functions.
48 * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no
51 class MallocAllocPolicy
55 T
* pod_malloc(size_t aNumElems
)
57 if (aNumElems
& mozilla::tl::MulOverflowMask
<sizeof(T
)>::value
) {
60 return static_cast<T
*>(malloc(aNumElems
* sizeof(T
)));
64 T
* pod_calloc(size_t aNumElems
)
66 return static_cast<T
*>(calloc(aNumElems
, sizeof(T
)));
70 T
* pod_realloc(T
* aPtr
, size_t aOldSize
, size_t aNewSize
)
72 if (aNewSize
& mozilla::tl::MulOverflowMask
<sizeof(T
)>::value
) {
75 return static_cast<T
*>(realloc(aPtr
, aNewSize
* sizeof(T
)));
78 void free_(void* aPtr
)
83 void reportAllocOverflow() const
88 } // namespace mozilla
90 #endif /* mozilla_AllocPolicy_h */