From 86f41497b7847c082338801227f13fe227abee00 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 23 May 2026 07:25:13 +0000 Subject: [PATCH] libap: add idx_t (ptrdiff_t) xmalloc variants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add ximalloc, xirealloc, xicalloc, xizalloc, ximemdup, ximemdup0 — the signed-size (idx_t) counterparts to the size_t xmalloc family. Implemented as simple casts to size_t delegating to the existing unsigned variants. gnulib's idx_t is typedef'd as ptrdiff_t. https://claude.ai/code/session_01WGAwvvTwDg2yknFkmZ3qzs --- sys/include/ape/xalloc.h | 8 ++++++ sys/src/ape/lib/ap/malloc/xmalloc.c | 40 +++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/sys/include/ape/xalloc.h b/sys/include/ape/xalloc.h index 31b7a0ffd..61940f9eb 100644 --- a/sys/include/ape/xalloc.h +++ b/sys/include/ape/xalloc.h @@ -28,6 +28,14 @@ extern void *x2nrealloc(void *, size_t *, size_t); /* growing: ~1.5x */ extern void *x2realloc(void *, size_t *); extern void *xpalloc(void *, ptrdiff_t *, ptrdiff_t, ptrdiff_t, ptrdiff_t); +/* idx_t (ptrdiff_t) signed-size variants */ +extern void *ximalloc(ptrdiff_t); +extern void *xirealloc(void *, ptrdiff_t); +extern void *xicalloc(ptrdiff_t, ptrdiff_t); +extern void *xizalloc(ptrdiff_t); +extern void *ximemdup(void const *, ptrdiff_t); +extern char *ximemdup0(void const *, ptrdiff_t); + /* Convenience: typed versions */ #define XMALLOC(t, n) ((t *)xmalloc((n) * sizeof(t))) #define XCALLOC(t, n) ((t *)xcalloc((n), sizeof(t))) diff --git a/sys/src/ape/lib/ap/malloc/xmalloc.c b/sys/src/ape/lib/ap/malloc/xmalloc.c index a24484ada..889cd48f5 100644 --- a/sys/src/ape/lib/ap/malloc/xmalloc.c +++ b/sys/src/ape/lib/ap/malloc/xmalloc.c @@ -169,3 +169,43 @@ xpalloc(void *pa, ptrdiff_t *pn, ptrdiff_t n_incr_min, ptrdiff_t n_max, ptrdiff_ *pn = n; return pa; } + +/* idx_t (ptrdiff_t) variants — same semantics, signed-size argument. */ + +void * +ximalloc(ptrdiff_t s) +{ + return xmalloc((size_t)s); +} + +void * +xirealloc(void *p, ptrdiff_t s) +{ + return xrealloc(p, (size_t)s); +} + +void * +xicalloc(ptrdiff_t n, ptrdiff_t s) +{ + return xcalloc((size_t)n, (size_t)s); +} + +void * +xizalloc(ptrdiff_t s) +{ + return xicalloc(s, 1); +} + +void * +ximemdup(void const *p, ptrdiff_t s) +{ + return xmemdup(p, (size_t)s); +} + +char * +ximemdup0(void const *p, ptrdiff_t s) +{ + char *result = ximalloc(s + 1); + result[s] = '\0'; + return memcpy(result, p, s); +}