1
\ *****************************************************************************
2
\ * Copyright (c) 2004, 2008 IBM Corporation
3
\ * All rights reserved.
4
\ * This program and the accompanying materials
5
\ * are made available under the terms of the BSD License
6
\ * which accompanies this distribution, and is available at
7
\ * http://www.opensource.org/licenses/bsd-license.php
10
\ * IBM Corporation - initial implementation
11
\ ****************************************************************************/
14
\ Memory "heap" (de-)allocation.
16
\ Keep a linked list of free blocks per power-of-two size.
17
\ Never coalesce entries when freed; split blocks when needed while allocating.
19
\ 3f CONSTANT (max-heads#)
20
heap-end heap-start - log2 1+ CONSTANT (max-heads#)
22
CREATE heads (max-heads#) cells allot
23
heads (max-heads#) cells erase
26
: size>head ( size -- headptr ) log2 3 max cells heads + ;
29
\ Allocate a memory block
30
: alloc-mem ( len -- a-addr )
32
1 over log2 3 max ( len 1 log_len )
33
dup (max-heads#) >= IF cr ." Out of internal memory." cr 3drop 0 EXIT THEN
34
lshift >r ( len R: 1<<log_len )
36
dup @ dup >r @ swap ! r> r> drop EXIT
37
THEN ( headptr R: 1<<log_len)
38
r@ 2* recurse dup ( headptr a-addr2 a-addr2 R: 1<<log_len)
39
dup 0= IF r> 2drop 2drop 0 EXIT THEN
40
r> + >r 0 over ! swap ! r>
46
: free-mem ( a-addr len -- )
47
dup 0= IF 2drop EXIT THEN size>head 2dup @ swap ! !
52
@ 0 BEGIN over WHILE 1+ swap @ swap REPEAT nip
58
heads i cells + #links dup IF
59
cr dup . ." * " 1 i lshift dup . ." = " * dup .
67
\ Start with just one free block.
68
heap-start heap-end heap-start - free-mem
71
\ : free-mem ( a-addr len -- ) 2drop ;
73
\ Uncomment the following line for debugging:
74
\ #include <alloc-mem-debug.fs>