2 * Copyright (C) 1995-2007, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: nmem.c,v 1.30 2007-04-17 20:26:18 adam Exp $
10 * \brief Implements Nibble Memory
12 * This is a simple and fairly wasteful little module for nibble memory
13 * allocation. Evemtually we'll put in something better.
15 * FIXME - it also has some semaphore stuff, and stuff to handle errno.
16 * These should be moved to some other place!
27 #include <yaz/xmalloc.h>
35 #define NMEM_CHUNK (4*1024)
39 char *buf; /* memory allocated in this block */
40 size_t size; /* size of buf */
41 size_t top; /* top of buffer */
42 struct nmem_block *next;
48 struct nmem_block *blocks;
49 struct nmem_control *next;
67 #define NMEM_ALIGN (offsetof(struct align, u))
69 static int log_level = 0;
70 static int log_level_initialized = 0;
72 static void free_block(struct nmem_block *p)
77 yaz_log (log_level, "nmem free_block p=%p", p);
81 * acquire a block with a minimum of size free bytes.
83 static struct nmem_block *get_block(size_t size)
86 size_t get = NMEM_CHUNK;
89 yaz_log (log_level, "nmem get_block size=%ld", (long) size);
95 yaz_log (log_level, "nmem get_block alloc new block size=%ld",
98 r = (struct nmem_block *) xmalloc(sizeof(*r));
99 r->buf = (char *)xmalloc(r->size = get);
104 void nmem_reset(NMEM n)
106 struct nmem_block *t;
108 yaz_log (log_level, "nmem_reset p=%p", n);
114 n->blocks = n->blocks->next;
120 void *nmem_malloc(NMEM n, int size)
122 struct nmem_block *p;
127 yaz_log (YLOG_FATAL, "calling nmem_malloc with an null pointer");
131 if (!p || p->size < size + p->top)
139 p->top += (size + (NMEM_ALIGN - 1)) & ~(NMEM_ALIGN - 1);
144 int nmem_total(NMEM n)
149 NMEM nmem_create(void)
152 if (!log_level_initialized)
154 log_level = yaz_log_module_level("nmem");
155 log_level_initialized = 1;
158 r = (struct nmem_control *)xmalloc(sizeof(*r));
167 void nmem_destroy(NMEM n)
176 void nmem_transfer (NMEM dst, NMEM src)
178 struct nmem_block *t;
179 while ((t = src->blocks))
181 src->blocks = t->next;
182 t->next = dst->blocks;
185 dst->total += src->total;
194 void yaz_set_errno(int v)
199 void yaz_strerror(char *buf, int max)
205 if (!log_level_initialized)
207 log_level = yaz_log_module_level("nmem");
208 log_level_initialized = 1;
212 err = GetLastError();
216 FORMAT_MESSAGE_FROM_SYSTEM,
219 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default lang */
230 strerror_r(errno, buf, max);
231 /* if buffer is unset - use strerror anyway (GLIBC bug) */
233 strcpy(buf, strerror(yaz_errno()));
235 strcpy(buf, strerror(yaz_errno()));
239 if ((cp = strrchr(buf, '\n')))
241 if ((cp = strrchr(buf, '\r')))
247 * indent-tabs-mode: nil
249 * vim: shiftwidth=4 tabstop=8 expandtab