Merge companion and firmware notes, and get them from the server (#5530)
[opentx.git] / radio / src / bin_allocator.h
blobc47597f2a3ceef4372ad4c9a5066604acece3da1
1 /*
2 * Copyright (C) OpenTX
4 * Based on code named
5 * th9x - http://code.google.com/p/th9x
6 * er9x - http://code.google.com/p/er9x
7 * gruvin9x - http://code.google.com/p/gruvin9x
9 * License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2 as
13 * published by the Free Software Foundation.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
21 #ifndef _BIN_ALLOCATOR_H_
22 #define _BIN_ALLOCATOR_H_
24 #include "debug.h"
26 template <int SIZE_SLOT, int NUM_BINS> class BinAllocator {
27 private:
28 PACK(struct Bin {
29 char data[SIZE_SLOT];
30 bool Used;
31 });
32 struct Bin Bins[NUM_BINS];
33 int NoUsedBins;
34 public:
35 BinAllocator() : NoUsedBins(0) {
36 memclear(Bins, sizeof(Bins));
38 bool free(void * ptr) {
39 for (size_t n = 0; n < NUM_BINS; ++n) {
40 if (ptr == Bins[n].data) {
41 Bins[n].Used = false;
42 --NoUsedBins;
43 // TRACE("\tBinAllocator<%d> free %lu ------", SIZE_SLOT, n);
44 return true;
47 return false;
49 bool is_member(void * ptr) {
50 return (ptr >= Bins[0].data && ptr <= Bins[NUM_BINS-1].data);
52 void * malloc(size_t size) {
53 if (size > SIZE_SLOT) {
54 // TRACE("BinAllocator<%d> malloc [%lu] size > SIZE_SLOT", SIZE_SLOT, size);
55 return 0;
57 if (NoUsedBins >= NUM_BINS) {
58 // TRACE("BinAllocator<%d> malloc [%lu] no free slots", SIZE_SLOT, size);
59 return 0;
61 for (size_t n = 0; n < NUM_BINS; ++n) {
62 if (!Bins[n].Used) {
63 Bins[n].Used = true;
64 ++NoUsedBins;
65 // TRACE("\tBinAllocator<%d> malloc %lu[%lu]", SIZE_SLOT, n, size);
66 return Bins[n].data;
69 // TRACE("BinAllocator<%d> malloc [%lu] no free slots", SIZE_SLOT , size);
70 return 0;
72 size_t size(void * ptr) {
73 return is_member(ptr) ? SIZE_SLOT : 0;
75 bool can_fit(void * ptr, size_t size) {
76 return is_member(ptr) && size <= SIZE_SLOT; //todo is_member check is redundant
78 unsigned int capacity() { return NUM_BINS; }
79 unsigned int size() { return NoUsedBins; }
82 #if defined(SIMU)
83 typedef BinAllocator<39,300> BinAllocator_slots1;
84 typedef BinAllocator<79,100> BinAllocator_slots2;
85 #else
86 typedef BinAllocator<29,200> BinAllocator_slots1;
87 typedef BinAllocator<91,50> BinAllocator_slots2;
88 #endif
90 #if defined(USE_BIN_ALLOCATOR)
91 extern BinAllocator_slots1 slots1;
92 extern BinAllocator_slots2 slots2;
94 // wrapper for our BinAllocator for Lua
95 void *bin_l_alloc (void *ud, void *ptr, size_t osize, size_t nsize);
96 #endif //#if defined(USE_BIN_ALLOCATOR)
98 #endif // _BIN_ALLOCATOR_H_