bmem.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (c) 2013 Hugh Bailey <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #pragma once
  17. #include "c99defs.h"
  18. #include "base.h"
  19. #include <wchar.h>
  20. #include <string.h>
  21. #ifdef __cplusplus
  22. extern "C" {
  23. #endif
  24. struct base_allocator {
  25. void *(*malloc)(size_t);
  26. void *(*realloc)(void *, size_t);
  27. void (*free)(void *);
  28. };
  29. EXPORT void base_set_allocator(struct base_allocator *defs);
  30. EXPORT void *bmalloc(size_t size);
  31. EXPORT void *brealloc(void *ptr, size_t size);
  32. EXPORT void bfree(void *ptr);
  33. EXPORT uint64_t bnum_allocs(void);
  34. EXPORT void *bmemdup(const void *ptr, size_t size);
  35. static inline char *bstrdup_n(const char *str, size_t n)
  36. {
  37. char *dup;
  38. if (!str || !*str)
  39. return NULL;
  40. dup = (char*)bmemdup(str, n+1);
  41. dup[n] = 0;
  42. return dup;
  43. }
  44. static inline wchar_t *bwstrdup_n(const wchar_t *str, size_t n)
  45. {
  46. wchar_t *dup;
  47. if (!str || !*str)
  48. return NULL;
  49. dup = (wchar_t*)bmemdup(str, (n+1) * sizeof(wchar_t));
  50. dup[n] = 0;
  51. return dup;
  52. }
  53. static inline char *bstrdup(const char *str)
  54. {
  55. if (!str)
  56. return NULL;
  57. return bstrdup_n(str, strlen(str));
  58. }
  59. static inline wchar_t *bwstrdup(const wchar_t *str)
  60. {
  61. if (!str)
  62. return NULL;
  63. return bwstrdup_n(str, wcslen(str));
  64. }
  65. #ifdef __cplusplus
  66. }
  67. #endif