1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/mfbt/AllocPolicy.h Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,63 @@ 1.4 +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 1.5 +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ 1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.9 + 1.10 +/* 1.11 + * An allocation policy concept, usable for structures and algorithms to 1.12 + * control how memory is allocated and how failures are handled. 1.13 + */ 1.14 + 1.15 +#ifndef mozilla_AllocPolicy_h 1.16 +#define mozilla_AllocPolicy_h 1.17 + 1.18 +#include <stddef.h> 1.19 +#include <stdlib.h> 1.20 + 1.21 +namespace mozilla { 1.22 + 1.23 +/* 1.24 + * Allocation policies are used to implement the standard allocation behaviors 1.25 + * in a customizable way. Additionally, custom behaviors may be added to these 1.26 + * behaviors, such as additionally reporting an error through an out-of-band 1.27 + * mechanism when OOM occurs. The concept modeled here is as follows: 1.28 + * 1.29 + * - public copy constructor, assignment, destructor 1.30 + * - void* malloc_(size_t) 1.31 + * Responsible for OOM reporting when null is returned. 1.32 + * - void* calloc_(size_t) 1.33 + * Responsible for OOM reporting when null is returned. 1.34 + * - void* realloc_(void*, size_t, size_t) 1.35 + * Responsible for OOM reporting when null is returned. The *used* bytes 1.36 + * of the previous buffer is passed in (rather than the old allocation 1.37 + * size), in addition to the *new* allocation size requested. 1.38 + * - void free_(void*) 1.39 + * - void reportAllocOverflow() const 1.40 + * Called on allocation overflow (that is, an allocation implicitly tried 1.41 + * to allocate more than the available memory space -- think allocating an 1.42 + * array of large-size objects, where N * size overflows) before null is 1.43 + * returned. 1.44 + * 1.45 + * mfbt provides (and typically uses by default) only MallocAllocPolicy, which 1.46 + * does nothing more than delegate to the malloc/alloc/free functions. 1.47 + */ 1.48 + 1.49 +/* 1.50 + * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no 1.51 + * extra behaviors. 1.52 + */ 1.53 +class MallocAllocPolicy 1.54 +{ 1.55 + public: 1.56 + void* malloc_(size_t bytes) { return malloc(bytes); } 1.57 + void* calloc_(size_t bytes) { return calloc(bytes, 1); } 1.58 + void* realloc_(void* p, size_t oldBytes, size_t bytes) { return realloc(p, bytes); } 1.59 + void free_(void* p) { free(p); } 1.60 + void reportAllocOverflow() const {} 1.61 +}; 1.62 + 1.63 + 1.64 +} // namespace mozilla 1.65 + 1.66 +#endif /* mozilla_AllocPolicy_h */