Importing Upstream version 4.8.2
[platform/upstream/gcc48.git] / libgo / runtime / mfixalloc.c
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
5 // Fixed-size object allocator.  Returned memory is not zeroed.
6 //
7 // See malloc.h for overview.
8
9 #include "runtime.h"
10 #include "arch.h"
11 #include "malloc.h"
12
13 // Initialize f to allocate objects of the given size,
14 // using the allocator to obtain chunks of memory.
15 void
16 runtime_FixAlloc_Init(FixAlloc *f, uintptr size, void *(*alloc)(uintptr), void (*first)(void*, byte*), void *arg)
17 {
18         f->size = size;
19         f->alloc = alloc;
20         f->first = first;
21         f->arg = arg;
22         f->list = nil;
23         f->chunk = nil;
24         f->nchunk = 0;
25         f->inuse = 0;
26         f->sys = 0;
27 }
28
29 void*
30 runtime_FixAlloc_Alloc(FixAlloc *f)
31 {
32         void *v;
33         
34         if(f->size == 0) {
35                 runtime_printf("runtime: use of FixAlloc_Alloc before FixAlloc_Init\n");
36                 runtime_throw("runtime: internal error");
37         }
38
39         if(f->list) {
40                 v = f->list;
41                 f->list = *(void**)f->list;
42                 f->inuse += f->size;
43                 return v;
44         }
45         if(f->nchunk < f->size) {
46                 f->sys += FixAllocChunk;
47                 f->chunk = f->alloc(FixAllocChunk);
48                 if(f->chunk == nil)
49                         runtime_throw("out of memory (FixAlloc)");
50                 f->nchunk = FixAllocChunk;
51         }
52         v = f->chunk;
53         if(f->first)
54                 f->first(f->arg, v);
55         f->chunk += f->size;
56         f->nchunk -= f->size;
57         f->inuse += f->size;
58         return v;
59 }
60
61 void
62 runtime_FixAlloc_Free(FixAlloc *f, void *p)
63 {
64         f->inuse -= f->size;
65         *(void**)p = f->list;
66         f->list = p;
67 }
68