1
/* ocache.h -- a minimal object caching implementation. */
3
/* Copyright (C) 2002 Free Software Foundation, Inc.
5
This file is part of GNU Bash, the Bourne Again SHell.
7
Bash is free software: you can redistribute it and/or modify
8
it under the terms of the GNU General Public License as published by
9
the Free Software Foundation, either version 3 of the License, or
10
(at your option) any later version.
12
Bash is distributed in the hope that it will be useful,
13
but WITHOUT ANY WARRANTY; without even the implied warranty of
14
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
GNU General Public License for more details.
17
You should have received a copy of the GNU General Public License
18
along with Bash. If not, see <http://www.gnu.org/licenses/>.
21
#if !defined (_OCACHE_H_)
26
#if defined (__STDC__)
34
#define OC_MEMSET(memp, xch, nbytes) \
36
if ((nbytes) <= 32) { \
37
register char * mzp = (char *)(memp); \
38
unsigned long mctmp = (nbytes); \
40
if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp &= 7; } \
42
case 0: for(;;) { *mzp++ = xch; \
43
case 7: *mzp++ = xch; \
44
case 6: *mzp++ = xch; \
45
case 5: *mzp++ = xch; \
46
case 4: *mzp++ = xch; \
47
case 3: *mzp++ = xch; \
48
case 2: *mzp++ = xch; \
49
case 1: *mzp++ = xch; if(mcn <= 0) break; mcn--; } \
52
memset ((memp), (xch), (nbytes)); \
55
typedef struct objcache {
57
int cs; /* cache size, number of objects */
58
int nc; /* number of cache entries */
61
/* Create an object cache C of N pointers to OTYPE. */
62
#define ocache_create(c, otype, n) \
64
(c).data = xmalloc((n) * sizeof (otype *)); \
69
/* Destroy an object cache C. */
70
#define ocache_destroy(c) \
75
(c).cs = (c).nc = 0; \
78
/* Free all cached items, which are pointers to OTYPE, in object cache C. */
79
#define ocache_flush(c, otype) \
82
xfree (((otype **)((c).data))[--(c).nc]); \
86
* Allocate a new item of type pointer to OTYPE, using data from object
87
* cache C if any cached items exist, otherwise calling xmalloc. Return
90
#define ocache_alloc(c, otype, r) \
93
(r) = (otype *)((otype **)((c).data))[--(c).nc]; \
95
(r) = (otype *)xmalloc (sizeof (otype)); \
99
* Free an item R of type pointer to OTYPE, adding to object cache C if
100
* there is room and calling xfree if the cache is full. If R is added
101
* to the object cache, the contents are scrambled.
103
#define ocache_free(c, otype, r) \
105
if ((c).nc < (c).cs) { \
106
OC_MEMSET ((r), 0xdf, sizeof(otype)); \
107
((otype **)((c).data))[(c).nc++] = (r); \
113
* One may declare and use an object cache as (for instance):
115
* sh_obj_cache_t wdcache = {0, 0, 0};
116
* sh_obj_cache_t wlcache = {0, 0, 0};
118
* ocache_create(wdcache, WORD_DESC, 30);
119
* ocache_create(wlcache, WORD_LIST, 30);
122
* ocache_alloc (wdcache, WORD_DESC, wd);
125
* ocache_alloc (wlcache, WORD_LIST, wl);
127
* ocache_free(wdcache, WORD_DESC, wd);
128
* ocache_free(wlcache, WORD_LIST, wl);
130
* The use is almost arbitrary.
133
#endif /* _OCACHE_H */