]> mj.ucw.cz Git - libucw.git/blob - ucw/mempool.h
Mempool: Implemented various functions for appending to a growing buffer
[libucw.git] / ucw / mempool.h
1 /*
2  *      UCW Library -- Memory Pools
3  *
4  *      (c) 1997--2014 Martin Mares <mj@ucw.cz>
5  *      (c) 2007 Pavel Charvat <pchar@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #ifndef _UCW_POOLS_H
12 #define _UCW_POOLS_H
13
14 #include <ucw/alloc.h>
15 #include <string.h>
16
17 #ifdef CONFIG_UCW_CLEAN_ABI
18 #define mp_alloc ucw_mp_alloc
19 #define mp_alloc_internal ucw_mp_alloc_internal
20 #define mp_alloc_noalign ucw_mp_alloc_noalign
21 #define mp_alloc_zero ucw_mp_alloc_zero
22 #define mp_append_printf ucw_mp_append_printf
23 #define mp_append_vprintf ucw_mp_append_vprintf
24 #define mp_delete ucw_mp_delete
25 #define mp_flush ucw_mp_flush
26 #define mp_grow_internal ucw_mp_grow_internal
27 #define mp_init ucw_mp_init
28 #define mp_memdup ucw_mp_memdup
29 #define mp_multicat ucw_mp_multicat
30 #define mp_new ucw_mp_new
31 #define mp_open ucw_mp_open
32 #define mp_pop ucw_mp_pop
33 #define mp_printf ucw_mp_printf
34 #define mp_push ucw_mp_push
35 #define mp_realloc ucw_mp_realloc
36 #define mp_realloc_zero ucw_mp_realloc_zero
37 #define mp_restore ucw_mp_restore
38 #define mp_spread_internal ucw_mp_spread_internal
39 #define mp_start ucw_mp_start
40 #define mp_start_internal ucw_mp_start_internal
41 #define mp_start_noalign ucw_mp_start_noalign
42 #define mp_stats ucw_mp_stats
43 #define mp_str_from_mem ucw_mp_str_from_mem
44 #define mp_strdup ucw_mp_strdup
45 #define mp_strjoin ucw_mp_strjoin
46 #define mp_total_size ucw_mp_total_size
47 #define mp_vprintf ucw_mp_vprintf
48 #endif
49
50 /***
51  * [[defs]]
52  * Definitions
53  * -----------
54  ***/
55
56 /**
57  * Memory pool state (see @mp_push(), ...).
58  * You should use this one as an opaque handle only, the insides are internal.
59  **/
60 struct mempool_state {
61   uns free[2];
62   void *last[2];
63   struct mempool_state *next;
64 };
65
66 /**
67  * Memory pool.
68  * You should use this one as an opaque handle only, the insides are internal.
69  **/
70 struct mempool {
71   struct ucw_allocator allocator;
72   struct mempool_state state;
73   void *unused, *last_big;
74   uns chunk_size, threshold, idx;
75   u64 total_size;
76 };
77
78 struct mempool_stats {                  /** Mempool statistics. See @mp_stats(). **/
79   u64 total_size;                       /* Real allocated size in bytes */
80   uns chain_count[3];                   /* Number of allocated chunks in small/big/unused chains */
81   uns chain_size[3];                    /* Size of allocated chunks in small/big/unused chains */
82 };
83
84 /***
85  * [[basic]]
86  * Basic manipulation
87  * ------------------
88  ***/
89
90 /**
91  * Initialize a given mempool structure.
92  * @chunk_size must be in the interval `[1, UINT_MAX / 2]`.
93  * It will allocate memory by this large chunks and take
94  * memory to satisfy requests from them.
95  *
96  * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
97  **/
98 void mp_init(struct mempool *pool, uns chunk_size);
99
100 /**
101  * Allocate and initialize a new memory pool.
102  * See @mp_init() for @chunk_size limitations.
103  *
104  * The new mempool structure is allocated on the new mempool.
105  *
106  * Memory pools can be treated as <<trans:respools,resources>>, see <<trans:res_mempool()>>.
107  **/
108 struct mempool *mp_new(uns chunk_size);
109
110 /**
111  * Cleanup mempool initialized by mp_init or mp_new.
112  * Frees all the memory allocated by this mempool and,
113  * if created by @mp_new(), the @pool itself.
114  **/
115 void mp_delete(struct mempool *pool);
116
117 /**
118  * Frees all data on a memory pool, but leaves it working.
119  * It can keep some of the chunks allocated to serve
120  * further allocation requests. Leaves the @pool alive,
121  * even if it was created with @mp_new().
122  **/
123 void mp_flush(struct mempool *pool);
124
125 /**
126  * Compute some statistics for debug purposes.
127  * See the definition of the <<struct_mempool_stats,mempool_stats structure>>.
128  * This function scans the chunk list, so it can be slow. If you are interested
129  * in total memory consumption only, mp_total_size() is faster.
130  **/
131 void mp_stats(struct mempool *pool, struct mempool_stats *stats);
132
133 /**
134  * Return how many bytes were allocated by the pool, including unused parts
135  * of chunks. This function runs in constant time.
136  **/
137 u64 mp_total_size(struct mempool *pool);
138
139
140 /***
141  * [[alloc]]
142  * Allocation routines
143  * -------------------
144  ***/
145
146 /* For internal use only, do not call directly */
147 void *mp_alloc_internal(struct mempool *pool, uns size) LIKE_MALLOC;
148
149 /**
150  * The function allocates new @size bytes on a given memory pool.
151  * If the @size is zero, the resulting pointer is undefined,
152  * but it may be safely reallocated or used as the parameter
153  * to other functions below.
154  *
155  * The resulting pointer is always aligned to a multiple of
156  * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
157  * after future reallocations.
158  **/
159 void *mp_alloc(struct mempool *pool, uns size);
160
161 /**
162  * The same as @mp_alloc(), but the result may be unaligned.
163  **/
164 void *mp_alloc_noalign(struct mempool *pool, uns size);
165
166 /**
167  * The same as @mp_alloc(), but fills the newly allocated memory with zeroes.
168  **/
169 void *mp_alloc_zero(struct mempool *pool, uns size);
170
171 /**
172  * Inlined version of @mp_alloc().
173  **/
174 static inline void *mp_alloc_fast(struct mempool *pool, uns size)
175 {
176   uns avail = pool->state.free[0] & ~(CPU_STRUCT_ALIGN - 1);
177   if (size <= avail)
178     {
179       pool->state.free[0] = avail - size;
180       return (byte *)pool->state.last[0] - avail;
181     }
182   else
183     return mp_alloc_internal(pool, size);
184 }
185
186 /**
187  * Inlined version of @mp_alloc_noalign().
188  **/
189 static inline void *mp_alloc_fast_noalign(struct mempool *pool, uns size)
190 {
191   if (size <= pool->state.free[0])
192     {
193       void *ptr = (byte *)pool->state.last[0] - pool->state.free[0];
194       pool->state.free[0] -= size;
195       return ptr;
196     }
197   else
198     return mp_alloc_internal(pool, size);
199 }
200
201 /**
202  * Return a generic allocator representing the given mempool.
203  **/
204 static inline struct ucw_allocator *mp_get_allocator(struct mempool *mp)
205 {
206   return &mp->allocator;
207 }
208
209 /***
210  * [[gbuf]]
211  * Growing buffers
212  * ---------------
213  *
214  * You do not need to know, how a buffer will need to be large,
215  * you can grow it incrementally to needed size. You can grow only
216  * one buffer at a time on a given mempool.
217  *
218  * Similar functionality is provided by <<growbuf:,growing buffes>> module.
219  ***/
220
221 /* For internal use only, do not call directly */
222 void *mp_start_internal(struct mempool *pool, uns size) LIKE_MALLOC;
223 void *mp_grow_internal(struct mempool *pool, uns size);
224 void *mp_spread_internal(struct mempool *pool, void *p, uns size);
225
226 static inline uns mp_idx(struct mempool *pool, void *ptr)
227 {
228   return ptr == pool->last_big;
229 }
230
231 /**
232  * Open a new growing buffer (at least @size bytes long).
233  * If the @size is zero, the resulting pointer is undefined,
234  * but it may be safely reallocated or used as the parameter
235  * to other functions below.
236  *
237  * The resulting pointer is always aligned to a multiple of
238  * `CPU_STRUCT_ALIGN` bytes and this condition remains true also
239  * after future reallocations. There is an unaligned version as well.
240  *
241  * Keep in mind that you can't make any other pool allocations
242  * before you "close" the growing buffer with @mp_end().
243  */
244 void *mp_start(struct mempool *pool, uns size);
245 void *mp_start_noalign(struct mempool *pool, uns size);
246
247 /**
248  * Inlined version of @mp_start().
249  **/
250 static inline void *mp_start_fast(struct mempool *pool, uns size)
251 {
252   uns avail = pool->state.free[0] & ~(CPU_STRUCT_ALIGN - 1);
253   if (size <= avail)
254     {
255       pool->idx = 0;
256       pool->state.free[0] = avail;
257       return (byte *)pool->state.last[0] - avail;
258     }
259   else
260     return mp_start_internal(pool, size);
261 }
262
263 /**
264  * Inlined version of @mp_start_noalign().
265  **/
266 static inline void *mp_start_fast_noalign(struct mempool *pool, uns size)
267 {
268   if (size <= pool->state.free[0])
269     {
270       pool->idx = 0;
271       return (byte *)pool->state.last[0] - pool->state.free[0];
272     }
273   else
274     return mp_start_internal(pool, size);
275 }
276
277 /**
278  * Return start pointer of the growing buffer allocated by latest @mp_start() or a similar function.
279  **/
280 static inline void *mp_ptr(struct mempool *pool)
281 {
282   return (byte *)pool->state.last[pool->idx] - pool->state.free[pool->idx];
283 }
284
285 /**
286  * Return the number of bytes available for extending the growing buffer.
287  * (Before a reallocation will be needed).
288  **/
289 static inline uns mp_avail(struct mempool *pool)
290 {
291   return pool->state.free[pool->idx];
292 }
293
294 /**
295  * Grow the buffer allocated by @mp_start() to be at least @size bytes long
296  * (@size may be less than @mp_avail(), even zero). Reallocated buffer may
297  * change its starting position. The content will be unchanged to the minimum
298  * of the old and new sizes; newly allocated memory will be uninitialized.
299  * Multiple calls to mp_grow() have amortized linear cost wrt. the maximum value of @size. */
300 static inline void *mp_grow(struct mempool *pool, uns size)
301 {
302   return (size <= mp_avail(pool)) ? mp_ptr(pool) : mp_grow_internal(pool, size);
303 }
304
305 /**
306  * Grow the buffer by at least one byte -- equivalent to <<mp_grow(),`mp_grow`>>`(@pool, @mp_avail(pool) + 1)`.
307  **/
308 static inline void *mp_expand(struct mempool *pool)
309 {
310   return mp_grow_internal(pool, mp_avail(pool) + 1);
311 }
312
313 /**
314  * Ensure that there is at least @size bytes free after @p,
315  * if not, reallocate and adjust @p.
316  **/
317 static inline void *mp_spread(struct mempool *pool, void *p, uns size)
318 {
319   return (((uns)((byte *)pool->state.last[pool->idx] - (byte *)p) >= size) ? p : mp_spread_internal(pool, p, size));
320 }
321
322 /**
323  * Append a character to the growing buffer. Called with @p pointing after
324  * the last byte in the buffer, returns a pointer after the last byte
325  * of the new (possibly reallocated) buffer.
326  **/
327 static inline char *mp_append_char(struct mempool *pool, char *p, uns c)
328 {
329   p = mp_spread(pool, p, 1);
330   *p++ = c;
331   return p;
332 }
333
334 /**
335  * Append a memory block to the growing buffer. Called with @p pointing after
336  * the last byte in the buffer, returns a pointer after the last byte
337  * of the new (possibly reallocated) buffer.
338  **/
339 static inline void *mp_append_block(struct mempool *pool, void *p, const void *block, uns size)
340 {
341   char *q = mp_spread(pool, p, size);
342   memcpy(q, block, size);
343   return q + size;
344 }
345
346 /**
347  * Append a string to the growing buffer. Called with @p pointing after
348  * the last byte in the buffer, returns a pointer after the last byte
349  * of the new (possibly reallocated) buffer.
350  **/
351 static inline void *mp_append_string(struct mempool *pool, void *p, const char *str)
352 {
353   return mp_append_block(pool, p, str, strlen(str));
354 }
355
356 /**
357  * Close the growing buffer. The @end must point just behind the data, you want to keep
358  * allocated (so it can be in the interval `[@mp_ptr(@pool), @mp_ptr(@pool) + @mp_avail(@pool)]`).
359  * Returns a pointer to the beginning of the just closed block.
360  **/
361 static inline void *mp_end(struct mempool *pool, void *end)
362 {
363   void *p = mp_ptr(pool);
364   pool->state.free[pool->idx] = (byte *)pool->state.last[pool->idx] - (byte *)end;
365   return p;
366 }
367
368 /**
369  * Close the growing buffer as a string. That is, append a zero byte and call mp_end().
370  **/
371 static inline char *mp_end_string(struct mempool *pool, void *end)
372 {
373   end = mp_append_char(pool, end, 0);
374   return mp_end(pool, end);
375 }
376
377 /**
378  * Return size in bytes of the last allocated memory block (with @mp_alloc() or @mp_end()).
379  **/
380 static inline uns mp_size(struct mempool *pool, void *ptr)
381 {
382   uns idx = mp_idx(pool, ptr);
383   return ((byte *)pool->state.last[idx] - (byte *)ptr) - pool->state.free[idx];
384 }
385
386 /**
387  * Open the last memory block (allocated with @mp_alloc() or @mp_end())
388  * for growing and return its size in bytes. The contents and the start pointer
389  * remain unchanged. Do not forget to call @mp_end() to close it.
390  **/
391 uns mp_open(struct mempool *pool, void *ptr);
392
393 /**
394  * Inlined version of @mp_open().
395  **/
396 static inline uns mp_open_fast(struct mempool *pool, void *ptr)
397 {
398   pool->idx = mp_idx(pool, ptr);
399   uns size = ((byte *)pool->state.last[pool->idx] - (byte *)ptr) - pool->state.free[pool->idx];
400   pool->state.free[pool->idx] += size;
401   return size;
402 }
403
404 /**
405  * Reallocate the last memory block (allocated with @mp_alloc() or @mp_end())
406  * to the new @size. Behavior is similar to @mp_grow(), but the resulting
407  * block is closed.
408  **/
409 void *mp_realloc(struct mempool *pool, void *ptr, uns size);
410
411 /**
412  * The same as @mp_realloc(), but fills the additional bytes (if any) with zeroes.
413  **/
414 void *mp_realloc_zero(struct mempool *pool, void *ptr, uns size);
415
416 /**
417  * Inlined version of @mp_realloc().
418  **/
419 static inline void *mp_realloc_fast(struct mempool *pool, void *ptr, uns size)
420 {
421   mp_open_fast(pool, ptr);
422   ptr = mp_grow(pool, size);
423   mp_end(pool, (byte *)ptr + size);
424   return ptr;
425 }
426
427 /***
428  * [[store]]
429  * Storing and restoring state
430  * ---------------------------
431  *
432  * Mempools can remember history of what was allocated and return back
433  * in time.
434  ***/
435
436 /**
437  * Save the current state of a memory pool.
438  * Do not call this function with an opened growing buffer.
439  **/
440 static inline void mp_save(struct mempool *pool, struct mempool_state *state)
441 {
442   *state = pool->state;
443   pool->state.next = state;
444 }
445
446 /**
447  * Save the current state to a newly allocated mempool_state structure.
448  * Do not call this function with an opened growing buffer.
449  **/
450 struct mempool_state *mp_push(struct mempool *pool);
451
452 /**
453  * Restore the state saved by @mp_save() or @mp_push() and free all
454  * data allocated after that point (including the state structure itself).
455  * You can't reallocate the last memory block from the saved state.
456  **/
457 void mp_restore(struct mempool *pool, struct mempool_state *state);
458
459 /**
460  * Inlined version of @mp_restore().
461  **/
462 static inline void mp_restore_fast(struct mempool *pool, struct mempool_state *state)
463 {
464   if (pool->state.last[0] != state->last[0] || pool->state.last[1] != state->last[1])
465     mp_restore(pool, state);
466   else
467     {
468       pool->state = *state;
469       pool->last_big = &pool->last_big;
470     }
471 }
472
473 /**
474  * Restore the state saved by the last call to @mp_push().
475  * @mp_pop() and @mp_push() works as a stack so you can push more states safely.
476  **/
477 void mp_pop(struct mempool *pool);
478
479
480 /***
481  * [[string]]
482  * String operations
483  * -----------------
484  ***/
485
486 char *mp_strdup(struct mempool *, const char *) LIKE_MALLOC;            /** Makes a copy of a string on a mempool. Returns NULL for NULL string. **/
487 void *mp_memdup(struct mempool *, const void *, uns) LIKE_MALLOC;       /** Makes a copy of a memory block on a mempool. **/
488 /**
489  * Concatenates all passed strings. The last parameter must be NULL.
490  * This will concatenate two strings:
491  *
492  *   char *message = mp_multicat(pool, "hello ", "world", NULL);
493  **/
494 char *mp_multicat(struct mempool *, ...) LIKE_MALLOC SENTINEL_CHECK;
495 /**
496  * Concatenates two strings and stores result on @mp.
497  */
498 static inline char *LIKE_MALLOC mp_strcat(struct mempool *mp, const char *x, const char *y)
499 {
500   return mp_multicat(mp, x, y, NULL);
501 }
502 /**
503  * Join strings and place @sep between each two neighboring.
504  * @p is the mempool to provide memory, @a is array of strings and @n
505  * tells how many there is of them.
506  **/
507 char *mp_strjoin(struct mempool *p, char **a, uns n, uns sep) LIKE_MALLOC;
508 /**
509  * Convert memory block to a string. Makes a copy of the given memory block
510  * in the mempool @p, adding an extra terminating zero byte at the end.
511  **/
512 char *mp_str_from_mem(struct mempool *p, const void *mem, uns len) LIKE_MALLOC;
513
514
515 /***
516  * [[format]]
517  * Formatted output
518  * ---------------
519  ***/
520
521 /**
522  * printf() into a in-memory string, allocated on the memory pool.
523  **/
524 char *mp_printf(struct mempool *mp, const char *fmt, ...) FORMAT_CHECK(printf,2,3) LIKE_MALLOC;
525 /**
526  * Like @mp_printf(), but uses `va_list` for parameters.
527  **/
528 char *mp_vprintf(struct mempool *mp, const char *fmt, va_list args) LIKE_MALLOC;
529 /**
530  * Like @mp_printf(), but it appends the data at the end of string
531  * pointed to by @ptr. The string is @mp_open()ed, so you have to
532  * provide something that can be.
533  *
534  * Returns pointer to the beginning of the string (the pointer may have
535  * changed due to reallocation).
536  *
537  * Alternatively, this function may be called mp_printf_append() for compatibility with
538  * previous releases of LibUCW.
539  **/
540 char *mp_append_printf(struct mempool *mp, char *ptr, const char *fmt, ...) FORMAT_CHECK(printf,3,4);
541 #define mp_printf_append mp_append_printf
542 /**
543  * Like @mp_append_printf(), but uses `va_list` for parameters.
544  *
545  * Alternatively, this function may be called mp_vprintf_append() for compatibility with
546  * previous releases of LibUCW.
547  **/
548 char *mp_append_vprintf(struct mempool *mp, char *ptr, const char *fmt, va_list args);
549 #define mp_vprintf_append mp_append_vprintf
550
551 #endif