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
21 * Allocation policies are used to implement the standard allocation behaviors
22 * in a customizable way. Additionally, custom behaviors may be added to these
23 * behaviors, such as additionally reporting an error through an out-of-band
24 * mechanism when OOM occurs. The concept modeled here is as follows:
26 * - public copy constructor, assignment, destructor
27 * - void* malloc_(size_t)
28 * Responsible for OOM reporting when null is returned.
29 * - void* calloc_(size_t)
30 * Responsible for OOM reporting when null is returned.
31 * - void* realloc_(void*, size_t, size_t)
32 * Responsible for OOM reporting when null is returned. The *used* bytes
33 * of the previous buffer is passed in (rather than the old allocation
34 * size), in addition to the *new* allocation size requested.
36 * - void reportAllocOverflow() const
37 * Called on allocation overflow (that is, an allocation implicitly tried
38 * to allocate more than the available memory space -- think allocating an
39 * array of large-size objects, where N * size overflows) before null is
42 * mfbt provides (and typically uses by default) only MallocAllocPolicy, which
43 * does nothing more than delegate to the malloc/alloc/free functions.
47 * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no
50 class MallocAllocPolicy
53 void* malloc_(size_t aBytes
)
55 return malloc(aBytes
);
58 void* calloc_(size_t aBytes
)
60 return calloc(aBytes
, 1);
63 void* realloc_(void* aPtr
, size_t aOldBytes
, size_t aBytes
)
65 return realloc(aPtr
, aBytes
);
68 void free_(void* aPtr
)
73 void reportAllocOverflow() const
78 } // namespace mozilla
80 #endif /* mozilla_AllocPolicy_h */