sds.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /* SDSLib, A C dynamic strings library
  2. *
  3. * Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot com>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * * Redistributions of source code must retain the above copyright notice,
  10. * this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * * Neither the name of Redis nor the names of its contributors may be used
  15. * to endorse or promote products derived from this software without
  16. * specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  19. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  21. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  22. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  23. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  24. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  25. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  26. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  27. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. * POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <ctype.h>
  34. #include <assert.h>
  35. #include "sds.h"
  36. #ifndef va_copy
  37. #define va_copy(dst, src) memcpy(&(dst), &(src), sizeof(va_list))
  38. #endif
  39. size_t sdslen(const sds s) {
  40. struct sdshdr *sh = (struct sdshdr *) (s - (sizeof(struct sdshdr)));
  41. return sh->len;
  42. }
  43. size_t sdsavail(const sds s) {
  44. struct sdshdr *sh = (struct sdshdr *) (s - (sizeof(struct sdshdr)));
  45. return sh->free;
  46. }
  47. /* Create a new sds string with the content specified by the 'init' pointer
  48. * and 'initlen'.
  49. * If NULL is used for 'init' the string is initialized with zero bytes.
  50. *
  51. * The string is always null-termined (all the sds strings are, always) so
  52. * even if you create an sds string with:
  53. *
  54. * mystring = sdsnewlen("abc",3);
  55. *
  56. * You can print the string with printf() as there is an implicit \0 at the
  57. * end of the string. However the string is binary safe and can contain
  58. * \0 characters in the middle, as the length is stored in the sds header. */
  59. sds sdsnewlen(const void *init, size_t initlen) {
  60. struct sdshdr *sh;
  61. if (init) {
  62. sh = malloc(sizeof(struct sdshdr) + initlen + 1);
  63. } else {
  64. sh = calloc(sizeof(struct sdshdr) + initlen + 1, 1);
  65. }
  66. if (sh == NULL) return NULL;
  67. sh->len = initlen;
  68. sh->free = 0;
  69. if (initlen && init)
  70. memcpy(sh->buf, init, initlen);
  71. sh->buf[initlen] = '\0';
  72. return (char *) sh->buf;
  73. }
  74. sds sdsnewEmpty(size_t preAlloclen) {
  75. struct sdshdr *sh;
  76. sh = malloc(sizeof(struct sdshdr) + preAlloclen + 1);
  77. if (sh == NULL) return NULL;
  78. sh->len = 0;
  79. sh->free = preAlloclen;
  80. sh->buf[0] = '\0';
  81. return (char *) sh->buf;
  82. }
  83. /* Create an empty (zero length) sds string. Even in this case the string
  84. * always has an implicit null term. */
  85. sds sdsempty(void) {
  86. return sdsnewlen("", 0);
  87. }
  88. /* Create a new sds string starting from a null terminated C string. */
  89. sds sdsnew(const char *init) {
  90. size_t initlen = (init == NULL) ? 0 : strlen(init);
  91. return sdsnewlen(init, initlen);
  92. }
  93. /* Duplicate an sds string. */
  94. sds sdsdup(const sds s) {
  95. if (s == NULL) return NULL;
  96. return sdsnewlen(s, sdslen(s));
  97. }
  98. /* Free an sds string. No operation is performed if 's' is NULL. */
  99. void sdsfree(sds s) {
  100. if (s == NULL) return;
  101. free(s - sizeof(struct sdshdr));
  102. }
  103. /* Set the sds string length to the length as obtained with strlen(), so
  104. * considering as content only up to the first null term character.
  105. *
  106. * This function is useful when the sds string is hacked manually in some
  107. * way, like in the following example:
  108. *
  109. * s = sdsnew("foobar");
  110. * s[2] = '\0';
  111. * sdsupdatelen(s);
  112. * printf("%d\n", sdslen(s));
  113. *
  114. * The output will be "2", but if we comment out the call to sdsupdatelen()
  115. * the output will be "6" as the string was modified but the logical length
  116. * remains 6 bytes. */
  117. void sdsupdatelen(sds s) {
  118. struct sdshdr *sh = (void *) (s - (sizeof(struct sdshdr)));
  119. int reallen = strlen(s);
  120. sh->free += (sh->len - reallen);
  121. sh->len = reallen;
  122. }
  123. /* Modify an sds string in-place to make it empty (zero length).
  124. * However all the existing buffer is not discarded but set as free space
  125. * so that next append operations will not require allocations up to the
  126. * number of bytes previously available. */
  127. void sdsclear(sds s) {
  128. struct sdshdr *sh = (void *) (s - (sizeof(struct sdshdr)));
  129. sh->free += sh->len;
  130. sh->len = 0;
  131. sh->buf[0] = '\0';
  132. }
  133. /* Enlarge the free space at the end of the sds string so that the caller
  134. * is sure that after calling this function can overwrite up to addlen
  135. * bytes after the end of the string, plus one more byte for nul term.
  136. *
  137. * Note: this does not change the *length* of the sds string as returned
  138. * by sdslen(), but only the free buffer space we have. */
  139. sds sdsMakeRoomFor(sds s, size_t addlen) {
  140. struct sdshdr *sh, *newsh;
  141. size_t free = sdsavail(s);
  142. size_t len, newlen;
  143. if (free >= addlen) return s;
  144. len = sdslen(s);
  145. sh = (void *) (s - (sizeof(struct sdshdr)));
  146. newlen = (len + addlen);
  147. if (newlen < SDS_MAX_PREALLOC)
  148. newlen *= 2;
  149. else
  150. newlen += SDS_MAX_PREALLOC;
  151. newsh = realloc(sh, sizeof(struct sdshdr) + newlen + 1);
  152. if (newsh == NULL) return NULL;
  153. newsh->free = newlen - len;
  154. return newsh->buf;
  155. }
  156. /* Reallocate the sds string so that it has no free space at the end. The
  157. * contained string remains not altered, but next concatenation operations
  158. * will require a reallocation.
  159. *
  160. * After the call, the passed sds string is no longer valid and all the
  161. * references must be substituted with the new pointer returned by the call. */
  162. sds sdsRemoveFreeSpace(sds s) {
  163. struct sdshdr *sh;
  164. sh = (void *) (s - (sizeof(struct sdshdr)));
  165. sh = realloc(sh, sizeof(struct sdshdr) + sh->len + 1);
  166. sh->free = 0;
  167. return sh->buf;
  168. }
  169. /* Return the total size of the allocation of the specifed sds string,
  170. * including:
  171. * 1) The sds header before the pointer.
  172. * 2) The string.
  173. * 3) The free buffer at the end if any.
  174. * 4) The implicit null term.
  175. */
  176. size_t sdsAllocSize(sds s) {
  177. struct sdshdr *sh = (void *) (s - (sizeof(struct sdshdr)));
  178. return sizeof(*sh) + sh->len + sh->free + 1;
  179. }
  180. /* Increment the sds length and decrements the left free space at the
  181. * end of the string according to 'incr'. Also set the null term
  182. * in the new end of the string.
  183. *
  184. * This function is used in order to fix the string length after the
  185. * user calls sdsMakeRoomFor(), writes something after the end of
  186. * the current string, and finally needs to set the new length.
  187. *
  188. * Note: it is possible to use a negative increment in order to
  189. * right-trim the string.
  190. *
  191. * Usage example:
  192. *
  193. * Using sdsIncrLen() and sdsMakeRoomFor() it is possible to mount the
  194. * following schema, to cat bytes coming from the kernel to the end of an
  195. * sds string without copying into an intermediate buffer:
  196. *
  197. * oldlen = sdslen(s);
  198. * s = sdsMakeRoomFor(s, BUFFER_SIZE);
  199. * nread = read(fd, s+oldlen, BUFFER_SIZE);
  200. * ... check for nread <= 0 and handle it ...
  201. * sdsIncrLen(s, nread);
  202. */
  203. void sdsIncrLen(sds s, int incr) {
  204. struct sdshdr *sh = (void *) (s - (sizeof(struct sdshdr)));
  205. if (incr >= 0)
  206. assert(sh->free >= (unsigned int) incr);
  207. else
  208. assert(sh->len >= (unsigned int) (-incr));
  209. sh->len += incr;
  210. sh->free -= incr;
  211. s[sh->len] = '\0';
  212. }
  213. /* Grow the sds to have the specified length. Bytes that were not part of
  214. * the original length of the sds will be set to zero.
  215. *
  216. * if the specified length is smaller than the current length, no operation
  217. * is performed. */
  218. sds sdsgrowzero(sds s, size_t len) {
  219. struct sdshdr *sh = (void *) (s - (sizeof(struct sdshdr)));
  220. size_t totlen, curlen = sh->len;
  221. if (len <= curlen) return s;
  222. s = sdsMakeRoomFor(s, len - curlen);
  223. if (s == NULL) return NULL;
  224. /* Make sure added region doesn't contain garbage */
  225. sh = (void *) (s - (sizeof(struct sdshdr)));
  226. memset(s + curlen, 0, (len - curlen + 1)); /* also set trailing \0 byte */
  227. totlen = sh->len + sh->free;
  228. sh->len = len;
  229. sh->free = totlen - sh->len;
  230. return s;
  231. }
  232. /* Append the specified binary-safe string pointed by 't' of 'len' bytes to the
  233. * end of the specified sds string 's'.
  234. *
  235. * After the call, the passed sds string is no longer valid and all the
  236. * references must be substituted with the new pointer returned by the call. */
  237. sds sdscatlen(sds s, const void *t, size_t len) {
  238. struct sdshdr *sh;
  239. size_t curlen = sdslen(s);
  240. s = sdsMakeRoomFor(s, len);
  241. if (s == NULL) return NULL;
  242. sh = (void *) (s - (sizeof(struct sdshdr)));
  243. memcpy(s + curlen, t, len);
  244. sh->len = curlen + len;
  245. sh->free = sh->free - len;
  246. s[curlen + len] = '\0';
  247. return s;
  248. }
  249. sds sdscatchar(sds s, char c) {
  250. struct sdshdr *sh;
  251. size_t curlen = sdslen(s);
  252. s = sdsMakeRoomFor(s, 1);
  253. if (s == NULL) return NULL;
  254. sh = (void *) (s - (sizeof(struct sdshdr)));
  255. s[curlen] = c;
  256. s[curlen + 1] = '\0';
  257. ++sh->len;
  258. --sh->free;
  259. return s;
  260. }
  261. /* Append the specified null termianted C string to the sds string 's'.
  262. *
  263. * After the call, the passed sds string is no longer valid and all the
  264. * references must be substituted with the new pointer returned by the call. */
  265. sds sdscat(sds s, const char *t) {
  266. if (s == NULL || t == NULL) {
  267. return s;
  268. }
  269. return sdscatlen(s, t, strlen(t));
  270. }
  271. /* Append the specified sds 't' to the existing sds 's'.
  272. *
  273. * After the call, the modified sds string is no longer valid and all the
  274. * references must be substituted with the new pointer returned by the call. */
  275. sds sdscatsds(sds s, const sds t) {
  276. return sdscatlen(s, t, sdslen(t));
  277. }
  278. /* Destructively modify the sds string 's' to hold the specified binary
  279. * safe string pointed by 't' of length 'len' bytes. */
  280. sds sdscpylen(sds s, const char *t, size_t len) {
  281. struct sdshdr *sh = (void *) (s - (sizeof(struct sdshdr)));
  282. size_t totlen = sh->free + sh->len;
  283. if (totlen < len) {
  284. s = sdsMakeRoomFor(s, len - sh->len);
  285. if (s == NULL) return NULL;
  286. sh = (void *) (s - (sizeof(struct sdshdr)));
  287. totlen = sh->free + sh->len;
  288. }
  289. memcpy(s, t, len);
  290. s[len] = '\0';
  291. sh->len = len;
  292. sh->free = totlen - len;
  293. return s;
  294. }
  295. /* Like sdscpylen() but 't' must be a null-termined string so that the length
  296. * of the string is obtained with strlen(). */
  297. sds sdscpy(sds s, const char *t) {
  298. return sdscpylen(s, t, strlen(t));
  299. }
  300. /* Like sdscatprintf() but gets va_list instead of being variadic. */
  301. sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
  302. va_list cpy;
  303. char staticbuf[1024], *buf = staticbuf, *t;
  304. size_t buflen = strlen(fmt) * 2;
  305. /* We try to start using a static buffer for speed.
  306. * If not possible we revert to heap allocation. */
  307. if (buflen > sizeof(staticbuf)) {
  308. buf = malloc(buflen);
  309. if (buf == NULL) return NULL;
  310. } else {
  311. buflen = sizeof(staticbuf);
  312. }
  313. /* Try with buffers two times bigger every time we fail to
  314. * fit the string in the current buffer size. */
  315. while (1) {
  316. buf[buflen - 2] = '\0';
  317. va_copy(cpy, ap);
  318. vsnprintf(buf, buflen, fmt, cpy);
  319. va_end(cpy);
  320. if (buf[buflen - 2] != '\0') {
  321. if (buf != staticbuf) free(buf);
  322. buflen *= 2;
  323. buf = malloc(buflen);
  324. if (buf == NULL) return NULL;
  325. continue;
  326. }
  327. break;
  328. }
  329. /* Finally concat the obtained string to the SDS string and return it. */
  330. t = sdscat(s, buf);
  331. if (buf != staticbuf) free(buf);
  332. return t;
  333. }
  334. /* Append to the sds string 's' a string obtained using printf-alike format
  335. * specifier.
  336. *
  337. * After the call, the modified sds string is no longer valid and all the
  338. * references must be substituted with the new pointer returned by the call.
  339. *
  340. * Example:
  341. *
  342. * s = sdsnew("Sum is: ");
  343. * s = sdscatprintf(s,"%d+%d = %d",a,b,a+b).
  344. *
  345. * Often you need to create a string from scratch with the printf-alike
  346. * format. When this is the need, just use sdsempty() as the target string:
  347. *
  348. * s = sdscatprintf(sdsempty(), "... your format ...", args);
  349. */
  350. sds sdscatprintf(sds s, const char *fmt, ...) {
  351. va_list ap;
  352. char *t;
  353. va_start(ap, fmt);
  354. t = sdscatvprintf(s, fmt, ap);
  355. va_end(ap);
  356. return t;
  357. }