img_mem.c 812 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /* Bump allocator over a caller-provided arena (see img.h). */
  2. #include "img.h"
  3. void img_mem_init(struct img_mem *m, void *base, unsigned int size)
  4. {
  5. m->base = (unsigned char *)base;
  6. m->size = size;
  7. m->used = 0;
  8. }
  9. unsigned int img_mem_mark(const struct img_mem *m)
  10. {
  11. return m->used;
  12. }
  13. int img_mem_rewind(struct img_mem *m, unsigned int mark)
  14. {
  15. if (mark > m->used)
  16. return -1;
  17. m->used = mark;
  18. return 0;
  19. }
  20. void *img_mem_alloc(struct img_mem *m, unsigned int bytes, unsigned int align)
  21. {
  22. unsigned int start, end;
  23. if (!m || !m->base || bytes == 0)
  24. return 0;
  25. if (align < 1)
  26. align = 1;
  27. if (align & (align - 1))
  28. return 0;
  29. start = (m->used + align - 1) & ~(align - 1);
  30. if (start > m->size || bytes > m->size - start)
  31. return 0;
  32. end = start + bytes;
  33. m->used = end;
  34. return m->base + start;
  35. }