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/NullPtr.h"
16 #include "mozilla/TemplateLib.h"
24 * Allocation policies are used to implement the standard allocation behaviors
25 * in a customizable way. Additionally, custom behaviors may be added to these
26 * behaviors, such as additionally reporting an error through an out-of-band
27 * mechanism when OOM occurs. The concept modeled here is as follows:
29 * - public copy constructor, assignment, destructor
30 * - template <typename T> T* pod_malloc(size_t)
31 * Responsible for OOM reporting when null is returned.
32 * - template <typename T> T* pod_calloc(size_t)
33 * Responsible for OOM reporting when null is returned.
34 * - template <typename T> T* pod_realloc(T*, size_t, size_t)
35 * Responsible for OOM reporting when null is returned. The old allocation
36 * size is passed in, in addition to the new allocation size requested.
38 * - void reportAllocOverflow() const
39 * Called on allocation overflow (that is, an allocation implicitly tried
40 * to allocate more than the available memory space -- think allocating an
41 * array of large-size objects, where N * size overflows) before null is
44 * mfbt provides (and typically uses by default) only MallocAllocPolicy, which
45 * does nothing more than delegate to the malloc/alloc/free functions.
49 * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no
52 class MallocAllocPolicy
56 T
* pod_malloc(size_t aNumElems
)
58 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
)
74 return static_cast<T
*>(realloc(aPtr
, aNewSize
* sizeof(T
)));
77 void free_(void* aPtr
)
82 void reportAllocOverflow() const
87 } // namespace mozilla
89 #endif /* mozilla_AllocPolicy_h */