Skip to content

Commit e161977

Browse files
committed
Add sdsnative()
Use the existing memory space for an SDS to convert it to a regular character buffer so we don't need to allocate duplicate space just to extract a usable buffer for native operations.
1 parent c6bf20c commit e161977

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

src/sds.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,17 @@ void sdsfree(sds s) {
8888
zfree(s-sizeof(struct sdshdr));
8989
}
9090

91+
/* Remove sds header so we can use buffer as malloc'd byte array.
92+
* Returns the contents of 's' usable as a full malloc'd C string. */
93+
char *sdsnative(sds s) {
94+
if (!s) return NULL;
95+
96+
size_t len = sdslen(s);
97+
char *base = s-sizeof(struct sdshdr);
98+
memmove(base, s, len);
99+
return zrealloc(base, len);
100+
}
101+
91102
/* Set the sds string length to the length as obtained with strlen(), so
92103
* considering as content only up to the first null term character.
93104
*

src/sds.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ sds sdsempty(void);
6060
size_t sdslen(const sds s);
6161
sds sdsdup(const sds s);
6262
void sdsfree(sds s);
63+
char *sdsnative(sds s);
6364
size_t sdsavail(const sds s);
6465
sds sdsgrowzero(sds s, size_t len);
6566
sds sdscatlen(sds s, const void *t, size_t len);

0 commit comments

Comments
 (0)