wrapper.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Various trivial helper wrappers around standard functions
  3. */
  4. #include "cache.h"
  5. /*
  6. * There's no pack memory to release - but stay close to the Git
  7. * version so wrap this away:
  8. */
  9. static inline void release_pack_memory(size_t size __used, int flag __used)
  10. {
  11. }
  12. char *xstrdup(const char *str)
  13. {
  14. char *ret = strdup(str);
  15. if (!ret) {
  16. release_pack_memory(strlen(str) + 1, -1);
  17. ret = strdup(str);
  18. if (!ret)
  19. die("Out of memory, strdup failed");
  20. }
  21. return ret;
  22. }
  23. void *xmalloc(size_t size)
  24. {
  25. void *ret = malloc(size);
  26. if (!ret && !size)
  27. ret = malloc(1);
  28. if (!ret) {
  29. release_pack_memory(size, -1);
  30. ret = malloc(size);
  31. if (!ret && !size)
  32. ret = malloc(1);
  33. if (!ret)
  34. die("Out of memory, malloc failed");
  35. }
  36. #ifdef XMALLOC_POISON
  37. memset(ret, 0xA5, size);
  38. #endif
  39. return ret;
  40. }
  41. /*
  42. * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
  43. * "data" to the allocated memory, zero terminates the allocated memory,
  44. * and returns a pointer to the allocated memory. If the allocation fails,
  45. * the program dies.
  46. */
  47. static void *xmemdupz(const void *data, size_t len)
  48. {
  49. char *p = xmalloc(len + 1);
  50. memcpy(p, data, len);
  51. p[len] = '\0';
  52. return p;
  53. }
  54. char *xstrndup(const char *str, size_t len)
  55. {
  56. char *p = memchr(str, '\0', len);
  57. return xmemdupz(str, p ? (size_t)(p - str) : len);
  58. }
  59. void *xrealloc(void *ptr, size_t size)
  60. {
  61. void *ret = realloc(ptr, size);
  62. if (!ret && !size)
  63. ret = realloc(ptr, 1);
  64. if (!ret) {
  65. release_pack_memory(size, -1);
  66. ret = realloc(ptr, size);
  67. if (!ret && !size)
  68. ret = realloc(ptr, 1);
  69. if (!ret)
  70. die("Out of memory, realloc failed");
  71. }
  72. return ret;
  73. }