1 #ifndef _WDL_CHUNKALLOC_H_
2 #define _WDL_CHUNKALLOC_H_
15 int m_chunksize
, m_chunkused
;
19 WDL_ChunkAlloc(int chunksize
=65500) { m_chunks
=NULL
; m_chunkused
=0; m_chunksize
=chunksize
>16?16:chunksize
; }
20 ~WDL_ChunkAlloc() { Free(); }
27 while (a
) { _hdr
*f
=a
; a
=a
->_next
; free(f
); }
30 void *Alloc(int sz
, int align
=0)
32 if (sz
<1) return NULL
;
34 if (align
< 1 || (align
& (align
-1))) align
=1;
39 char *p
= m_chunks
->data
+ m_chunkused
;
40 int a
= ((int) (INT_PTR
)p
) & (align
-1);
46 if (use_sz
<= m_chunksize
- m_chunkused
)
48 m_chunkused
+= use_sz
;
53 // we assume that malloc always gives at least 8 byte alignment, and our _next ptr may offset that by 4,
54 // so no need to allocate extra if less than 4 bytes of alignment requested
55 int use_align
= (align
>=4 ? align
: 0);
56 int alloc_sz
=sz
+use_align
;
57 if (alloc_sz
< m_chunksize
)
59 // if existing chunk has less free space in it than we would at chunksize, allocate chunksize
60 if (!m_chunks
|| m_chunkused
> alloc_sz
) alloc_sz
=m_chunksize
;
62 _hdr
*nc
= (_hdr
*)malloc(sizeof(_hdr
) + alloc_sz
- 16);
67 int a
= ((int) (INT_PTR
)ret
) & (align
-1);
74 if (m_chunks
&& (m_chunksize
-m_chunkused
) >= (alloc_sz
- use_sz
))
76 // current chunk has as much or more free space than our chunk, put our chunk on the list second
77 nc
->_next
= m_chunks
->_next
;
82 // push our chunk to the top of the list
85 m_chunkused
= alloc_sz
>= m_chunksize
? use_sz
: m_chunksize
;