blob: 497b5bf1325561f4f177316ad9e3fb10e05038d8 [file] [log] [blame]
Russ Coxe29ce172008-12-18 15:42:28 -08001// 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
5// Fixed-size object allocator. Returned memory is not zeroed.
6//
7// See malloc.h for overview.
8
9#include "runtime.h"
Dmitriy Vyukovc14b2682011-10-06 18:42:51 +030010#include "arch.h"
Russ Coxe29ce172008-12-18 15:42:28 -080011#include "malloc.h"
12
13// Initialize f to allocate objects of the given size,
14// using the allocator to obtain chunks of memory.
15void
Russ Cox68b42552010-11-04 14:00:19 -040016runtime·FixAlloc_Init(FixAlloc *f, uintptr size, void *(*alloc)(uintptr), void (*first)(void*, byte*), void *arg)
Russ Coxe29ce172008-12-18 15:42:28 -080017{
18 f->size = size;
19 f->alloc = alloc;
Russ Cox9f726c22009-01-28 15:22:16 -080020 f->first = first;
21 f->arg = arg;
Russ Coxe29ce172008-12-18 15:42:28 -080022 f->list = nil;
23 f->chunk = nil;
24 f->nchunk = 0;
Russ Coxa7098762010-03-29 13:06:26 -070025 f->inuse = 0;
26 f->sys = 0;
Russ Coxe29ce172008-12-18 15:42:28 -080027}
28
29void*
Russ Cox68b42552010-11-04 14:00:19 -040030runtime·FixAlloc_Alloc(FixAlloc *f)
Russ Coxe29ce172008-12-18 15:42:28 -080031{
32 void *v;
33
34 if(f->list) {
35 v = f->list;
36 f->list = *(void**)f->list;
Russ Coxa7098762010-03-29 13:06:26 -070037 f->inuse += f->size;
Russ Coxe29ce172008-12-18 15:42:28 -080038 return v;
39 }
40 if(f->nchunk < f->size) {
Russ Coxa7098762010-03-29 13:06:26 -070041 f->sys += FixAllocChunk;
Russ Coxe29ce172008-12-18 15:42:28 -080042 f->chunk = f->alloc(FixAllocChunk);
43 if(f->chunk == nil)
Russ Cox68b42552010-11-04 14:00:19 -040044 runtime·throw("out of memory (FixAlloc)");
Russ Coxe29ce172008-12-18 15:42:28 -080045 f->nchunk = FixAllocChunk;
46 }
47 v = f->chunk;
Russ Cox9f726c22009-01-28 15:22:16 -080048 if(f->first)
49 f->first(f->arg, v);
Russ Coxe29ce172008-12-18 15:42:28 -080050 f->chunk += f->size;
51 f->nchunk -= f->size;
Russ Coxa7098762010-03-29 13:06:26 -070052 f->inuse += f->size;
Russ Coxe29ce172008-12-18 15:42:28 -080053 return v;
54}
55
56void
Russ Cox68b42552010-11-04 14:00:19 -040057runtime·FixAlloc_Free(FixAlloc *f, void *p)
Russ Coxe29ce172008-12-18 15:42:28 -080058{
Russ Coxa7098762010-03-29 13:06:26 -070059 f->inuse -= f->size;
Russ Coxe29ce172008-12-18 15:42:28 -080060 *(void**)p = f->list;
61 f->list = p;
62}
63