mfixalloc.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Fixed-size object allocator. Returned memory is not zeroed.
  5. //
  6. // See malloc.h for overview.
  7. #include "runtime.h"
  8. #include "arch.h"
  9. #include "malloc.h"
  10. // Initialize f to allocate objects of the given size,
  11. // using the allocator to obtain chunks of memory.
  12. void
  13. runtime_FixAlloc_Init(FixAlloc *f, uintptr size, void (*first)(void*, byte*), void *arg, uint64 *stat)
  14. {
  15. f->size = size;
  16. f->first = first;
  17. f->arg = arg;
  18. f->list = nil;
  19. f->chunk = nil;
  20. f->nchunk = 0;
  21. f->inuse = 0;
  22. f->stat = stat;
  23. }
  24. void*
  25. runtime_FixAlloc_Alloc(FixAlloc *f)
  26. {
  27. void *v;
  28. if(f->size == 0) {
  29. runtime_printf("runtime: use of FixAlloc_Alloc before FixAlloc_Init\n");
  30. runtime_throw("runtime: internal error");
  31. }
  32. if(f->list) {
  33. v = f->list;
  34. f->list = *(void**)f->list;
  35. f->inuse += f->size;
  36. return v;
  37. }
  38. if(f->nchunk < f->size) {
  39. f->chunk = runtime_persistentalloc(FixAllocChunk, 0, f->stat);
  40. f->nchunk = FixAllocChunk;
  41. }
  42. v = f->chunk;
  43. if(f->first)
  44. f->first(f->arg, v);
  45. f->chunk += f->size;
  46. f->nchunk -= f->size;
  47. f->inuse += f->size;
  48. return v;
  49. }
  50. void
  51. runtime_FixAlloc_Free(FixAlloc *f, void *p)
  52. {
  53. f->inuse -= f->size;
  54. *(void**)p = f->list;
  55. f->list = p;
  56. }