| 1 | // -*- C++ -*- |
| 2 | |
| 3 | /* |
| 4 | |
| 5 | Heap Layers: An Extensible Memory Allocation Infrastructure |
| 6 | |
| 7 | Copyright (C) 2000-2020 by Emery Berger |
| 8 | http://www.emeryberger.com |
| 9 | [email protected] |
| 10 | |
| 11 | Heap Layers is distributed under the terms of the Apache 2.0 license. |
| 12 | |
| 13 | You may obtain a copy of the License at |
| 14 | http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | |
| 16 | */ |
| 17 | |
| 18 | #pragma once |
| 19 | |
| 20 | #if !defined(HL_BINSPOW2_H) |
| 21 | #define HL_BINSPOW2_H |
| 22 | |
| 23 | #include <stdlib.h> |
| 24 | #include <assert.h> |
| 25 | #include <stddef.h> |
| 26 | |
| 27 | #include "bins.h" |
| 28 | #include "ilog2.h" |
| 29 | |
| 30 | namespace HL { |
| 31 | |
| 32 | template <size_t MaxSize> |
| 33 | class bins_pow2 { |
| 34 | public: |
| 35 | |
| 36 | bins_pow2() |
| 37 | { |
| 38 | static_assert(BIG_OBJECT > 0, "BIG_OBJECT must be positive."); |
| 39 | static_assert(getClassSize(0) < getClassSize(1), "Need distinct size classes."); |
| 40 | static_assert(getSizeClass(getClassSize(0)) == 0, "Size class computation error."); |
| 41 | static_assert(getSizeClass(0) >= getSizeClass(sizeof(max_align_t)), "Min size must be at least max_align_t."); |
| 42 | static_assert(getSizeClass(0) >= getSizeClass(alignof(max_align_t)), "Min size must be at least alignof(max_align_t)."); |
| 43 | #ifndef NDEBUG |
| 44 | for (unsigned long i = sizeof(max_align_t); i < BIG_OBJECT; i++) { |
| 45 | int sc = getSizeClass(i); |
| 46 | assert (getClassSize(sc) >= i); |
| 47 | assert (sc == 0 ? true : (getClassSize(sc-1) < i)); |
| 48 | assert (getSizeClass(getClassSize(sc)) == sc); |
| 49 | } |
| 50 | #endif |
| 51 | } |
| 52 | |
| 53 | private: |
| 54 | |
| 55 | static constexpr inline unsigned int ilog2_constexpr (size_t v) { |
| 56 | unsigned int log = 0; |
| 57 | unsigned int value = 1; |
| 58 | while (value < v) { |
| 59 | value <<= 1; |
| 60 | log++; |
| 61 | } |
| 62 | return log; |
| 63 | } |
| 64 | |
| 65 | public: |
| 66 | |
| 67 | enum { BIG_OBJECT = MaxSize }; |
| 68 | enum { MaxObjectSize = BIG_OBJECT }; |
| 69 | enum { NUM_BINS = HL::ilog2(MaxSize) - HL::ilog2(sizeof(max_align_t)) + 1 }; |
| 70 | enum { NumBins = NUM_BINS }; |
| 71 | |
| 72 | static inline constexpr int getSizeClass (size_t sz) { |
| 73 | sz = (sz < sizeof(max_align_t)) ? sizeof(max_align_t) : sz; |
| 74 | return static_cast<int>(HL::ilog2(sz) - HL::ilog2(sizeof(max_align_t))); |
| 75 | } |
| 76 | |
| 77 | static constexpr inline size_t getClassSize (int i) { |
| 78 | return (sizeof(max_align_t) << i); |
| 79 | } |
| 80 | |
| 81 | static constexpr inline size_t getClassMaxSize(int i) { |
| 82 | return getClassSize(i); |
| 83 | } |
| 84 | }; |
| 85 | |
| 86 | } |
| 87 | |
| 88 | |
| 89 | |
| 90 | #endif |