Bumping gaia.json for 7 gaia revision(s) a=gaia-bump
[gecko.git] / mfbt / AllocPolicy.h
blob71aac91d8e6198bcdbcc9774b05bd304f96e9db0
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 /*
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"
17 #include <stddef.h>
18 #include <stdlib.h>
20 namespace mozilla {
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.
36 * - void free_(void*)
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
41 * returned.
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
49 * extra behaviors.
51 class MallocAllocPolicy
53 public:
54 template <typename T>
55 T* pod_malloc(size_t aNumElems)
57 if (aNumElems & mozilla::tl::MulOverflowMask<sizeof(T)>::value) {
58 return nullptr;
60 return static_cast<T*>(malloc(aNumElems * sizeof(T)));
63 template <typename T>
64 T* pod_calloc(size_t aNumElems)
66 return static_cast<T*>(calloc(aNumElems, sizeof(T)));
69 template <typename T>
70 T* pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize)
72 if (aNewSize & mozilla::tl::MulOverflowMask<sizeof(T)>::value) {
73 return nullptr;
75 return static_cast<T*>(realloc(aPtr, aNewSize * sizeof(T)));
78 void free_(void* aPtr)
80 free(aPtr);
83 void reportAllocOverflow() const
88 } // namespace mozilla
90 #endif /* mozilla_AllocPolicy_h */