2 * Various trivial helper wrappers around standard functions
7 * There's no pack memory to release - but stay close to the Git
8 * version so wrap this away:
10 static inline void release_pack_memory(size_t size __used, int flag __used)
14 char *xstrdup(const char *str)
16 char *ret = strdup(str);
18 release_pack_memory(strlen(str) + 1, -1);
21 die("Out of memory, strdup failed");
26 void *xmalloc(size_t size)
28 void *ret = malloc(size);
32 release_pack_memory(size, -1);
37 die("Out of memory, malloc failed");
40 memset(ret, 0xA5, size);
46 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
47 * "data" to the allocated memory, zero terminates the allocated memory,
48 * and returns a pointer to the allocated memory. If the allocation fails,
51 void *xmemdupz(const void *data, size_t len)
53 char *p = xmalloc(len + 1);
59 char *xstrndup(const char *str, size_t len)
61 char *p = memchr(str, '\0', len);
63 return xmemdupz(str, p ? (size_t)(p - str) : len);
66 void *xrealloc(void *ptr, size_t size)
68 void *ret = realloc(ptr, size);
70 ret = realloc(ptr, 1);
72 release_pack_memory(size, -1);
73 ret = realloc(ptr, size);
75 ret = realloc(ptr, 1);
77 die("Out of memory, realloc failed");
83 * xread() is the same a read(), but it automatically restarts read()
84 * operations with a recoverable error (EAGAIN and EINTR). xread()
85 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
87 static ssize_t xread(int fd, void *buf, size_t len)
91 nr = read(fd, buf, len);
92 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
99 * xwrite() is the same a write(), but it automatically restarts write()
100 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
101 * GUARANTEE that "len" bytes is written even if the operation is successful.
103 static ssize_t xwrite(int fd, const void *buf, size_t len)
107 nr = write(fd, buf, len);
108 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
114 ssize_t read_in_full(int fd, void *buf, size_t count)
120 ssize_t loaded = xread(fd, p, count);
122 return total ? total : loaded;
131 ssize_t write_in_full(int fd, const void *buf, size_t count)
137 ssize_t written = xwrite(fd, p, count);