diff options
author | Anna Henningsen <anna@addaleax.net> | 2016-09-10 18:50:02 +0300 |
---|---|---|
committer | Anna Henningsen <anna@addaleax.net> | 2016-09-29 10:46:42 +0300 |
commit | 48ed65440ca33fe6063d92379b3a9b10b65e98e9 (patch) | |
tree | b0fbfa17238c7d00839b92f3712e39c468c77c0a /src/util-inl.h | |
parent | eb927fac38a50252e11ebe0da1764e85294f95f0 (diff) |
src: pass desired return type to allocators
Pass the desired return type directly to the allocation functions,
so that the resulting `static_cast` from `void*` becomes unneccessary
and the return type can be use as a reasonable default value for the
`size` parameter.
PR-URL: https://github.com/nodejs/node/pull/8482
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Michael Dawson <michael_dawson@ca.ibm.com>
Reviewed-By: Ilkka Myller <ilkka.myller@nodefield.com>
Diffstat (limited to 'src/util-inl.h')
-rw-r--r-- | src/util-inl.h | 21 |
1 files changed, 11 insertions, 10 deletions
diff --git a/src/util-inl.h b/src/util-inl.h index 3f3139e1f05..3a5c7622c73 100644 --- a/src/util-inl.h +++ b/src/util-inl.h @@ -244,29 +244,30 @@ inline size_t MultiplyWithOverflowCheck(size_t a, size_t b) { // that the standard allows them to either return a unique pointer or a // nullptr for zero-sized allocation requests. Normalize by always using // a nullptr. -void* Realloc(void* pointer, size_t n, size_t size) { - size_t full_size = MultiplyWithOverflowCheck(size, n); +template <typename T> +T* Realloc(T* pointer, size_t n) { + size_t full_size = MultiplyWithOverflowCheck(sizeof(T), n); if (full_size == 0) { free(pointer); return nullptr; } - return realloc(pointer, full_size); + return static_cast<T*>(realloc(pointer, full_size)); } // As per spec realloc behaves like malloc if passed nullptr. -void* Malloc(size_t n, size_t size) { +template <typename T> +T* Malloc(size_t n) { if (n == 0) n = 1; - if (size == 0) size = 1; - return Realloc(nullptr, n, size); + return Realloc<T>(nullptr, n); } -void* Calloc(size_t n, size_t size) { +template <typename T> +T* Calloc(size_t n) { if (n == 0) n = 1; - if (size == 0) size = 1; - MultiplyWithOverflowCheck(size, n); - return calloc(n, size); + MultiplyWithOverflowCheck(sizeof(T), n); + return static_cast<T*>(calloc(n, sizeof(T))); } } // namespace node |