/* ibicc - The Ibi C Compiler Copyright (C) 2004 Antti-Juhani Kaijanaho Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ARENA_H #define ARENA_H #include #define ARENA_ALIGNMENT 4 /* An arena is a mechanism for fast allocation of objects that are * freed together. DON'T TRY TO MALLOC an arena - use arena_init to * give you an arena. arena_fini deallocates the arena and all objects * allocated from it. * * An arena_t object is a pointer and may be assigned at will; this * will effect sharing of the arena (but as with malloc/free, an arena * must not be deallocated twice). * * Arena allocation does not interfere with malloc. */ struct arena { void *buf; size_t capacity; size_t freeinx; }; typedef struct arena *arena_t; arena_t arena_init(void); void arena_more(arena_t); /* Don't call directly. */ void arena_fini(arena_t); /* Usage example: struct obj *o; new(o, arena); allocates *one* struct obj from arena and stores the pointer to o. Allocation failure will call enomem(); new will not return if no memory is available. newa(var,n,arena) is used to allocate an n-element array, the address of which is stored in var. The type of var is used to determine the size of the allocated object(s). */ #define newapad(var,n,arena,pad) do { \ size_t newa__tmp__ = (n)*sizeof *(var) + (pad) + \ (((n)*sizeof *(var) + (pad)) % ARENA_ALIGNMENT == 0 \ ? 0 \ : ARENA_ALIGNMENT - ((n)*sizeof *(var) + (pad)) % ARENA_ALIGNMENT); \ if ((arena)->freeinx + newa__tmp__ > (arena)->capacity) { \ arena_more((arena)); \ } \ assert((arena)->freeinx + newa__tmp__ <= (arena)->capacity); \ (var) = (arena)->buf + (arena)->freeinx; \ (arena)->freeinx += newa__tmp__; \ } while (0) #define newa(var,n,arena) newapad((var),(n),(arena),0) #define new(var,arena) newa((var),1,(arena)) #define newpad(var,arena,pad) newapad((var),1,(arena),(pad)) #endif /* ARENA_H */