BufferAllocator.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #ifndef BufferAllocator_H
  16. #define BufferAllocator_H
  17. #include "memory/Allocator.h"
  18. #include "util/UniqueName.h"
  19. /**
  20. * Create a new Allocator which allocates from to a user supplied buffer.
  21. * This allocator will reset the pointer to the beginning of the buffer when
  22. * free() is called on it, it is up to the user to free their buffer.
  23. * Allocator_child(allocator) always returns NULL.
  24. *
  25. * @param buffer an array to write to.
  26. * @param length the size of the array. If more is written than this length,
  27. * further allocations will fail and return NULL.
  28. */
  29. struct Allocator* BufferAllocator_newWithIdentity(void* buffer,
  30. size_t length,
  31. char* file,
  32. int line);
  33. #define BufferAllocator_new(buffer, length) \
  34. BufferAllocator_newWithIdentity(buffer, length, __FILE__, __LINE__)
  35. // This relies on the fact that UniqueName is only unique on a per-line basis.
  36. #define BufferAllocator_STACK(name, length) \
  37. uint8_t UniqueName_get()[length]; \
  38. name = BufferAllocator_new(UniqueName_get(), length);
  39. /**
  40. * @param bufferAllocator the buffer allocator to set this on.
  41. * @param electronicThumb in an out-of-memory event, this function will be called just
  42. * before the process is aborted.
  43. * @param towel a context which electronicThumb will be called with.
  44. */
  45. void BufferAllocator_onOOM(const struct Allocator* bufferAllocator,
  46. void (* electronicThumb)(void* towel),
  47. void* towel);
  48. #endif