block_pool.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (C) 2009 Joseph Adams <joeyadams3.14159@gmail.com>
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #ifndef CCAN_BLOCK_POOL
  23. #define CCAN_BLOCK_POOL
  24. #include <ccan/talloc/talloc.h>
  25. #include <string.h>
  26. struct block_pool;
  27. /* Construct a new block pool.
  28. ctx is a talloc context (or NULL if you don't know what talloc is ;) ) */
  29. struct block_pool *block_pool_new(void *ctx);
  30. /* Same as block_pool_alloc, but allows you to manually specify alignment.
  31. For instance, strings need not be aligned, so set align=1 for them.
  32. align must be a power of two. */
  33. void *block_pool_alloc_align(struct block_pool *bp, size_t size, size_t align);
  34. /* Allocate a block of a given size. The returned pointer will remain valid
  35. for the life of the block_pool. The block cannot be resized or
  36. freed individually. */
  37. static inline void *block_pool_alloc(struct block_pool *bp, size_t size) {
  38. size_t align = size & -size; //greatest power of two by which size is divisible
  39. if (align > 16)
  40. align = 16;
  41. return block_pool_alloc_align(bp, size, align);
  42. }
  43. static inline void block_pool_free(struct block_pool *bp) {
  44. talloc_free(bp);
  45. }
  46. char *block_pool_strdup(struct block_pool *bp, const char *str);
  47. static inline void *block_pool_memdup(struct block_pool *bp, const void *src, size_t size) {
  48. void *ret = block_pool_alloc(bp, size);
  49. memcpy(ret, src, size);
  50. return ret;
  51. }
  52. #endif