1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2008 Index Data
3 * See the file LICENSE for details.
8 * \brief Implements Nibble Memory
10 * This is a simple and fairly wasteful little module for nibble memory
11 * allocation. Evemtually we'll put in something better.
13 * FIXME - it also has some semaphore stuff, and stuff to handle errno.
14 * These should be moved to some other place!
25 #include <yaz/xmalloc.h>
33 #define NMEM_CHUNK (4*1024)
37 char *buf; /* memory allocated in this block */
38 size_t size; /* size of buf */
39 size_t top; /* top of buffer */
40 struct nmem_block *next;
46 struct nmem_block *blocks;
47 struct nmem_control *next;
65 #define NMEM_ALIGN (offsetof(struct align, u))
67 static int log_level = 0;
68 static int log_level_initialized = 0;
70 static void free_block(struct nmem_block *p)
75 yaz_log (log_level, "nmem free_block p=%p", p);
79 * acquire a block with a minimum of size free bytes.
81 static struct nmem_block *get_block(size_t size)
84 size_t get = NMEM_CHUNK;
87 yaz_log (log_level, "nmem get_block size=%ld", (long) size);
93 yaz_log (log_level, "nmem get_block alloc new block size=%ld",
96 r = (struct nmem_block *) xmalloc(sizeof(*r));
97 r->buf = (char *)xmalloc(r->size = get);
102 void nmem_reset(NMEM n)
104 struct nmem_block *t;
106 yaz_log (log_level, "nmem_reset p=%p", n);
112 n->blocks = n->blocks->next;
118 void *nmem_malloc(NMEM n, int size)
120 struct nmem_block *p;
125 yaz_log (YLOG_FATAL, "calling nmem_malloc with an null pointer");
129 if (!p || p->size < size + p->top)
137 p->top += (size + (NMEM_ALIGN - 1)) & ~(NMEM_ALIGN - 1);
142 int nmem_total(NMEM n)
147 NMEM nmem_create(void)
150 if (!log_level_initialized)
152 log_level = yaz_log_module_level("nmem");
153 log_level_initialized = 1;
156 r = (struct nmem_control *)xmalloc(sizeof(*r));
165 void nmem_destroy(NMEM n)
174 void nmem_transfer (NMEM dst, NMEM src)
176 struct nmem_block *t;
177 while ((t = src->blocks))
179 src->blocks = t->next;
180 t->next = dst->blocks;
183 dst->total += src->total;
192 void yaz_set_errno(int v)
197 void yaz_strerror(char *buf, int max)
203 if (!log_level_initialized)
205 log_level = yaz_log_module_level("nmem");
206 log_level_initialized = 1;
210 err = GetLastError();
214 FORMAT_MESSAGE_FROM_SYSTEM,
217 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default lang */
228 strerror_r(errno, buf, max);
229 /* if buffer is unset - use strerror anyway (GLIBC bug) */
231 strcpy(buf, strerror(yaz_errno()));
233 strcpy(buf, strerror(yaz_errno()));
237 if ((cp = strrchr(buf, '\n')))
239 if ((cp = strrchr(buf, '\r')))
245 * indent-tabs-mode: nil
247 * vim: shiftwidth=4 tabstop=8 expandtab