FreeBASIC  0.91.0
pool.bas
Go to the documentation of this file.
1 '' memory pools
2 ''
3 '' chng: may/2006 written [v1ctor]
4 ''
5 
6 #include once "pool.bi"
7 
8 const MIN_SIZE = 4
9 
10 '':::::
11 sub poolInit _
12  ( _
13  byval pool as TPOOL ptr, _
14  byval items as integer, _
15  byval minlen as integer, _
16  byval maxlen as integer _
17  )
18 
19  minlen = (minlen + (MIN_SIZE-1)) and (not (MIN_SIZE-1))
20  maxlen = (maxlen + (MIN_SIZE-1)) and (not (MIN_SIZE-1))
21 
22  pool->chunks = (maxlen + (minlen-1)) \ minlen
23  pool->chunksize = minlen
24 
25  pool->chunktb = xallocate( len( TLIST ) * pool->chunks )
26 
27  dim as integer len_ = minlen
28  for i as integer = 0 to pool->chunks-1
29  listInit( @pool->chunktb[i], items, len_, LIST_FLAGS_LINKFREENODES )
30  len_ += pool->chunksize
31  next
32 
33 end sub
34 
35 sub poolEnd(byval pool as TPOOL ptr)
36  for i as integer = 0 to pool->chunks-1
37  listEnd( @pool->chunktb[i] )
38  next
39  deallocate( pool->chunktb )
40 end sub
41 
42 '':::::
43 function poolNewItem _
44  ( _
45  byval pool as TPOOL ptr, _
46  byval len_ as integer _
47  ) as any ptr static
48 
49  dim as TPOOLITEM ptr item
50  dim as integer idx
51 
52  if( len_ <= 0 ) then
53  return NULL
54  end if
55 
56  idx = (len_ - 1) \ pool->chunksize
57 
58  if( idx >= pool->chunks ) then
59  item = xallocate( len_ + len( TPOOLITEM ) )
60  else
61  item = listNewNode( @pool->chunktb[idx] )
62  end if
63 
64  item->idx = idx
65 
66  function = cast( byte ptr, item ) + len( TPOOLITEM )
67 
68 end function
69 
70 '':::::
71 sub poolDelItem _
72  ( _
73  byval pool as TPOOL ptr, _
74  byval node as any ptr _
75  ) static
76 
77  dim as TPOOLITEM ptr item
78 
79  if( node = NULL ) then
80  exit sub
81  end if
82 
83  item = cast( TPOOLITEM ptr, cast( byte ptr, node ) - len( TPOOLITEM ) )
84 
85  if( item->idx >= pool->chunks ) then
86  deallocate( item )
87  else
88  listDelNode( @pool->chunktb[item->idx], item )
89  end if
90 
91 end sub
92 
93 
94