|
| 1 | +/* |
| 2 | + * Copyright (C) the Rugged contributors. All rights reserved. |
| 3 | + * |
| 4 | + * This file is part of Rugged, distributed under the MIT license. |
| 5 | + * For full terms see the included LICENSE file. |
| 6 | + */ |
| 7 | + |
| 8 | +#include "rugged.h" |
| 9 | +#include <git2/sys/alloc.h> |
| 10 | + |
| 11 | +static void *rugged_gmalloc(size_t n, const char *file, int line) |
| 12 | +{ |
| 13 | + return xmalloc(n); |
| 14 | +} |
| 15 | + |
| 16 | +static void *rugged_gcalloc(size_t nelem, size_t elsize, const char *file, int line) |
| 17 | +{ |
| 18 | + return xcalloc(nelem, elsize); |
| 19 | +} |
| 20 | + |
| 21 | +static char *rugged_gstrdup(const char *str, const char *file, int line) |
| 22 | +{ |
| 23 | + return ruby_strdup(str); |
| 24 | +} |
| 25 | + |
| 26 | +static char *rugged_gstrndup(const char *str, size_t n, const char *file, int line) |
| 27 | +{ |
| 28 | + size_t len; |
| 29 | + char *newstr; |
| 30 | + |
| 31 | + len = strlen(str); |
| 32 | + if (len < n) |
| 33 | + n = len; |
| 34 | + |
| 35 | + newstr = xmalloc(n+1); |
| 36 | + memcpy(newstr, str, n); |
| 37 | + newstr[n] = '\0'; |
| 38 | + |
| 39 | + return newstr; |
| 40 | +} |
| 41 | + |
| 42 | +static char *rugged_gsubstrdup(const char *str, size_t n, const char *file, int line) |
| 43 | +{ |
| 44 | + char *newstr; |
| 45 | + |
| 46 | + newstr = xmalloc(n+1); |
| 47 | + memcpy(newstr, str, n); |
| 48 | + newstr[n] = '\0'; |
| 49 | + |
| 50 | + return newstr; |
| 51 | +} |
| 52 | + |
| 53 | +static void *rugged_grealloc(void *ptr, size_t size, const char *file, int line) |
| 54 | +{ |
| 55 | + return xrealloc(ptr, size); |
| 56 | +} |
| 57 | + |
| 58 | +static void *rugged_greallocarray(void *ptr, size_t nelem, size_t elsize, const char *file, int line) |
| 59 | +{ |
| 60 | + return xrealloc2(ptr, nelem, elsize); |
| 61 | +} |
| 62 | + |
| 63 | +static void *rugged_gmallocarray(size_t nelem, size_t elsize, const char *file, int line) |
| 64 | +{ |
| 65 | + return xmalloc2(nelem, elsize); |
| 66 | +} |
| 67 | + |
| 68 | +static void rugged_gfree(void *ptr) |
| 69 | +{ |
| 70 | + xfree(ptr); |
| 71 | +} |
| 72 | + |
| 73 | +void rugged_set_allocator(void) |
| 74 | +{ |
| 75 | + git_allocator allocator; |
| 76 | + |
| 77 | + allocator.gmalloc = rugged_gmalloc; |
| 78 | + allocator.gcalloc = rugged_gcalloc; |
| 79 | + allocator.gstrdup = rugged_gstrdup; |
| 80 | + allocator.gstrndup = rugged_gstrndup; |
| 81 | + allocator.gstrndup = rugged_gstrndup; |
| 82 | + allocator.gsubstrdup = rugged_gsubstrdup; |
| 83 | + allocator.grealloc = rugged_grealloc; |
| 84 | + allocator.greallocarray = rugged_greallocarray; |
| 85 | + allocator.gmallocarray = rugged_gmallocarray; |
| 86 | + allocator.gfree = rugged_gfree; |
| 87 | + |
| 88 | + git_libgit2_opts(GIT_OPT_SET_ALLOCATOR, &allocator); |
| 89 | +} |
0 commit comments