From 19ad368f68164b99a2cfedb11747d7ca2d040ee0 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Wed, 10 May 2017 21:29:46 +0200 Subject: Cleaner code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Mattias Andrée --- src/util/emalloc.h | 29 ++++++++++++++++++++++++++--- src/util/io.h | 16 ++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) (limited to 'src/util') diff --git a/src/util/emalloc.h b/src/util/emalloc.h index 81816be..f4a7f12 100644 --- a/src/util/emalloc.h +++ b/src/util/emalloc.h @@ -1,9 +1,15 @@ /* See LICENSE file for copyright and license details. */ #include +#include -#define emalloc(...) enmalloc(1, __VA_ARGS__) -#define ecalloc(...) encalloc(1, __VA_ARGS__) -#define erealloc(...) enrealloc(1, __VA_ARGS__) +#define emalloc(...) enmalloc(1, __VA_ARGS__) +#define emalloc2(...) enmalloc2(1, __VA_ARGS__) +#define ecalloc(...) encalloc(1, __VA_ARGS__) +#define erealloc(...) enrealloc(1, __VA_ARGS__) +#define erealloc2(...) enrealloc2(1, __VA_ARGS__) + +#define malloc2(n, m) malloc(n * m); +#define realloc3(p, n, m) realloc(p, n * m); static inline void * enmalloc(int status, size_t n) @@ -14,6 +20,15 @@ enmalloc(int status, size_t n) return ptr; } +static inline void * +enmalloc2(int status, size_t n, size_t m) +{ + void *ptr; + if (n > SIZE_MAX / m || !(ptr = malloc(n * m))) + enprintf(status, "malloc: out of memory\n"); + return ptr; +} + static inline void * encalloc(int status, size_t n, size_t m) { @@ -31,3 +46,11 @@ enrealloc(int status, void *ptr, size_t n) enprintf(status, "realloc: out of memory\n"); return ptr; } + +static inline void * +enrealloc2(int status, void *ptr, size_t n, size_t m) +{ + if (n > SIZE_MAX / m || !(ptr = realloc(ptr, n * m))) + enprintf(status, "realloc: out of memory\n"); + return ptr; +} diff --git a/src/util/io.h b/src/util/io.h index 8c646cb..44c0a92 100644 --- a/src/util/io.h +++ b/src/util/io.h @@ -1,5 +1,6 @@ /* See LICENSE file for copyright and license details. */ #include +#include #if defined(POSIX_FADV_SEQUENTIAL) # define fadvise_sequential(...) posix_fadvise(__VA_ARGS__, POSIX_FADV_SEQUENTIAL) @@ -17,6 +18,7 @@ #define ereadall(...) enreadall(1, __VA_ARGS__) #define epwriteall(...) enpwriteall(1, __VA_ARGS__) #define ewritezeroes(...) enwritezeroes(1, __VA_ARGS__) +#define egetfile(...) engetfile(1, __VA_ARGS__) int writeall(int fd, void *buf, size_t n); @@ -55,3 +57,17 @@ enwritezeroes(int status, int fd, void *buf, size_t bufsize, size_t n, const cha if (writezeroes(fd, buf, bufsize, n)) enprintf(status, "write %s:", fname); } + +int getfile(int fd, void *bufp, size_t *restrict ptrp, size_t *restrict sizep); + +static inline void +engetfile(int status, int fd, void *bufp, size_t *restrict ptrp, + size_t *restrict sizep, const char *fname) +{ + if (getfile(fd, bufp, ptrp, sizep)) { + if (errno == ENOMEM) + enprintf(status, "realloc:"); + else + enprintf(status, "read %s:", fname); + } +} -- cgit v1.2.3-70-g09d2