bmem.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /******************************************************************************
  2. Copyright (c) 2013 by Hugh Bailey <[email protected]>
  3. This software is provided 'as-is', without any express or implied
  4. warranty. In no event will the authors be held liable for any damages
  5. arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it
  8. freely, subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not
  10. claim that you wrote the original software. If you use this software
  11. in a product, an acknowledgment in the product documentation would be
  12. appreciated but is not required.
  13. 2. Altered source versions must be plainly marked as such, and must not be
  14. misrepresented as being the original software.
  15. 3. This notice may not be removed or altered from any source
  16. distribution.
  17. ******************************************************************************/
  18. #pragma once
  19. #include "c99defs.h"
  20. #include "base.h"
  21. #include <wchar.h>
  22. #include <string.h>
  23. #ifdef __cplusplus
  24. extern "C" {
  25. #endif
  26. struct base_allocator {
  27. void *(*malloc)(size_t);
  28. void *(*realloc)(void *, size_t);
  29. void (*free)(void *);
  30. };
  31. EXPORT void base_set_allocator(struct base_allocator *defs);
  32. EXPORT void *bmalloc(size_t size);
  33. EXPORT void *brealloc(void *ptr, size_t size);
  34. EXPORT void bfree(void *ptr);
  35. EXPORT size_t bnum_allocs(void);
  36. EXPORT void *bmemdup(const void *ptr, size_t size);
  37. static inline char *bstrdup_n(const char *str, size_t n)
  38. {
  39. char *dup;
  40. if (!str || !*str)
  41. return NULL;
  42. dup = (char*)bmemdup(str, n+1);
  43. dup[n] = 0;
  44. return dup;
  45. }
  46. static inline wchar_t *bwstrdup_n(const wchar_t *str, size_t n)
  47. {
  48. wchar_t *dup;
  49. if (!str || !*str)
  50. return NULL;
  51. dup = (wchar_t*)bmemdup(str, (n+1) * sizeof(wchar_t));
  52. dup[n] = 0;
  53. return dup;
  54. }
  55. static inline char *bstrdup(const char *str)
  56. {
  57. if (!str)
  58. return NULL;
  59. return bstrdup_n(str, strlen(str));
  60. }
  61. static inline wchar_t *bwstrdup(const wchar_t *str)
  62. {
  63. if (!str)
  64. return NULL;
  65. return bwstrdup_n(str, wcslen(str));
  66. }
  67. #ifdef __cplusplus
  68. }
  69. #endif