1
0

bmem.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Copyright (c) 2023 Lain 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 *bmalloc(size_t size);
  30. EXPORT void *brealloc(void *ptr, size_t size);
  31. EXPORT void bfree(void *ptr);
  32. EXPORT int base_get_alignment(void);
  33. EXPORT long bnum_allocs(void);
  34. EXPORT void *bmemdup(const void *ptr, size_t size);
  35. static inline void *bzalloc(size_t size)
  36. {
  37. void *mem = bmalloc(size);
  38. if (mem)
  39. memset(mem, 0, size);
  40. return mem;
  41. }
  42. static inline char *bstrdup_n(const char *str, size_t n)
  43. {
  44. char *dup;
  45. if (!str)
  46. return NULL;
  47. dup = (char *)bmemdup(str, n + 1);
  48. dup[n] = 0;
  49. return dup;
  50. }
  51. static inline wchar_t *bwstrdup_n(const wchar_t *str, size_t n)
  52. {
  53. wchar_t *dup;
  54. if (!str)
  55. return NULL;
  56. dup = (wchar_t *)bmemdup(str, (n + 1) * sizeof(wchar_t));
  57. dup[n] = 0;
  58. return dup;
  59. }
  60. static inline char *bstrdup(const char *str)
  61. {
  62. if (!str)
  63. return NULL;
  64. return bstrdup_n(str, strlen(str));
  65. }
  66. static inline wchar_t *bwstrdup(const wchar_t *str)
  67. {
  68. if (!str)
  69. return NULL;
  70. return bwstrdup_n(str, wcslen(str));
  71. }
  72. #ifdef __cplusplus
  73. }
  74. #endif