michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim: set ts=8 sts=2 et sw=2 tw=80: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: /* michael@0: * An allocation policy concept, usable for structures and algorithms to michael@0: * control how memory is allocated and how failures are handled. michael@0: */ michael@0: michael@0: #ifndef mozilla_AllocPolicy_h michael@0: #define mozilla_AllocPolicy_h michael@0: michael@0: #include michael@0: #include michael@0: michael@0: namespace mozilla { michael@0: michael@0: /* michael@0: * Allocation policies are used to implement the standard allocation behaviors michael@0: * in a customizable way. Additionally, custom behaviors may be added to these michael@0: * behaviors, such as additionally reporting an error through an out-of-band michael@0: * mechanism when OOM occurs. The concept modeled here is as follows: michael@0: * michael@0: * - public copy constructor, assignment, destructor michael@0: * - void* malloc_(size_t) michael@0: * Responsible for OOM reporting when null is returned. michael@0: * - void* calloc_(size_t) michael@0: * Responsible for OOM reporting when null is returned. michael@0: * - void* realloc_(void*, size_t, size_t) michael@0: * Responsible for OOM reporting when null is returned. The *used* bytes michael@0: * of the previous buffer is passed in (rather than the old allocation michael@0: * size), in addition to the *new* allocation size requested. michael@0: * - void free_(void*) michael@0: * - void reportAllocOverflow() const michael@0: * Called on allocation overflow (that is, an allocation implicitly tried michael@0: * to allocate more than the available memory space -- think allocating an michael@0: * array of large-size objects, where N * size overflows) before null is michael@0: * returned. michael@0: * michael@0: * mfbt provides (and typically uses by default) only MallocAllocPolicy, which michael@0: * does nothing more than delegate to the malloc/alloc/free functions. michael@0: */ michael@0: michael@0: /* michael@0: * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no michael@0: * extra behaviors. michael@0: */ michael@0: class MallocAllocPolicy michael@0: { michael@0: public: michael@0: void* malloc_(size_t bytes) { return malloc(bytes); } michael@0: void* calloc_(size_t bytes) { return calloc(bytes, 1); } michael@0: void* realloc_(void* p, size_t oldBytes, size_t bytes) { return realloc(p, bytes); } michael@0: void free_(void* p) { free(p); } michael@0: void reportAllocOverflow() const {} michael@0: }; michael@0: michael@0: michael@0: } // namespace mozilla michael@0: michael@0: #endif /* mozilla_AllocPolicy_h */