2
0

sds.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. /* SDSLib 2.0 -- A C dynamic strings library
  2. *
  3. * Copyright (c) 2006-2015, Salvatore Sanfilippo <antirez at gmail dot com>
  4. * Copyright (c) 2015, Oran Agra
  5. * Copyright (c) 2015, Redis Labs, Inc
  6. * All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions are met:
  10. *
  11. * * Redistributions of source code must retain the above copyright notice,
  12. * this list of conditions and the following disclaimer.
  13. * * Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. * * Neither the name of Redis nor the names of its contributors may be used
  17. * to endorse or promote products derived from this software without
  18. * specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  21. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  23. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  24. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  25. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  26. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  27. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  30. * POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <string.h>
  35. #include <ctype.h>
  36. #include <assert.h>
  37. #include "sds.h"
  38. #include "sdsalloc.h"
  39. static inline int sdsHdrSize(char type) {
  40. switch(type&SDS_TYPE_MASK) {
  41. case SDS_TYPE_5:
  42. return sizeof(struct sdshdr5);
  43. case SDS_TYPE_8:
  44. return sizeof(struct sdshdr8);
  45. case SDS_TYPE_16:
  46. return sizeof(struct sdshdr16);
  47. case SDS_TYPE_32:
  48. return sizeof(struct sdshdr32);
  49. case SDS_TYPE_64:
  50. return sizeof(struct sdshdr64);
  51. }
  52. return 0;
  53. }
  54. static inline char sdsReqType(size_t string_size) {
  55. if (string_size < 32)
  56. return SDS_TYPE_5;
  57. if (string_size < 0xff)
  58. return SDS_TYPE_8;
  59. if (string_size < 0xffff)
  60. return SDS_TYPE_16;
  61. if (string_size < 0xffffffff)
  62. return SDS_TYPE_32;
  63. return SDS_TYPE_64;
  64. }
  65. /* Create a new sds string with the content specified by the 'init' pointer
  66. * and 'initlen'.
  67. * If NULL is used for 'init' the string is initialized with zero bytes.
  68. *
  69. * The string is always null-termined (all the sds strings are, always) so
  70. * even if you create an sds string with:
  71. *
  72. * mystring = sdsnewlen("abc",3);
  73. *
  74. * You can print the string with printf() as there is an implicit \0 at the
  75. * end of the string. However the string is binary safe and can contain
  76. * \0 characters in the middle, as the length is stored in the sds header. */
  77. sds sdsnewlen(const void *init, size_t initlen) {
  78. void *sh;
  79. sds s;
  80. char type = sdsReqType(initlen);
  81. /* Empty strings are usually created in order to append. Use type 8
  82. * since type 5 is not good at this. */
  83. if (type == SDS_TYPE_5 && initlen == 0) type = SDS_TYPE_8;
  84. int hdrlen = sdsHdrSize(type);
  85. unsigned char *fp; /* flags pointer. */
  86. sh = s_malloc(hdrlen+initlen+1);
  87. if (sh == NULL) return NULL;
  88. if (!init)
  89. memset(sh, 0, hdrlen+initlen+1);
  90. s = (char*)sh+hdrlen;
  91. fp = ((unsigned char*)s)-1;
  92. switch(type) {
  93. case SDS_TYPE_5: {
  94. *fp = type | (initlen << SDS_TYPE_BITS);
  95. break;
  96. }
  97. case SDS_TYPE_8: {
  98. SDS_HDR_VAR(8,s);
  99. sh->len = initlen;
  100. sh->alloc = initlen;
  101. *fp = type;
  102. break;
  103. }
  104. case SDS_TYPE_16: {
  105. SDS_HDR_VAR(16,s);
  106. sh->len = initlen;
  107. sh->alloc = initlen;
  108. *fp = type;
  109. break;
  110. }
  111. case SDS_TYPE_32: {
  112. SDS_HDR_VAR(32,s);
  113. sh->len = initlen;
  114. sh->alloc = initlen;
  115. *fp = type;
  116. break;
  117. }
  118. case SDS_TYPE_64: {
  119. SDS_HDR_VAR(64,s);
  120. sh->len = initlen;
  121. sh->alloc = initlen;
  122. *fp = type;
  123. break;
  124. }
  125. }
  126. if (initlen && init)
  127. memcpy(s, init, initlen);
  128. s[initlen] = '\0';
  129. return s;
  130. }
  131. /* Create an empty (zero length) sds string. Even in this case the string
  132. * always has an implicit null term. */
  133. sds sdsempty(void) {
  134. return sdsnewlen("",0);
  135. }
  136. /* Create a new sds string starting from a null terminated C string. */
  137. sds sdsnew(const char *init) {
  138. size_t initlen = (init == NULL) ? 0 : strlen(init);
  139. return sdsnewlen(init, initlen);
  140. }
  141. /* Duplicate an sds string. */
  142. sds sdsdup(const sds s) {
  143. return sdsnewlen(s, sdslen(s));
  144. }
  145. /* Free an sds string. No operation is performed if 's' is NULL. */
  146. void sdsfree(sds s) {
  147. if (s == NULL) return;
  148. s_free((char*)s-sdsHdrSize(s[-1]));
  149. }
  150. /* Set the sds string length to the length as obtained with strlen(), so
  151. * considering as content only up to the first null term character.
  152. *
  153. * This function is useful when the sds string is hacked manually in some
  154. * way, like in the following example:
  155. *
  156. * s = sdsnew("foobar");
  157. * s[2] = '\0';
  158. * sdsupdatelen(s);
  159. * printf("%d\n", sdslen(s));
  160. *
  161. * The output will be "2", but if we comment out the call to sdsupdatelen()
  162. * the output will be "6" as the string was modified but the logical length
  163. * remains 6 bytes. */
  164. void sdsupdatelen(sds s) {
  165. int reallen = strlen(s);
  166. sdssetlen(s, reallen);
  167. }
  168. /* Modify an sds string in-place to make it empty (zero length).
  169. * However all the existing buffer is not discarded but set as free space
  170. * so that next append operations will not require allocations up to the
  171. * number of bytes previously available. */
  172. void sdsclear(sds s) {
  173. sdssetlen(s, 0);
  174. s[0] = '\0';
  175. }
  176. /* Enlarge the free space at the end of the sds string so that the caller
  177. * is sure that after calling this function can overwrite up to addlen
  178. * bytes after the end of the string, plus one more byte for nul term.
  179. *
  180. * Note: this does not change the *length* of the sds string as returned
  181. * by sdslen(), but only the free buffer space we have. */
  182. sds sdsMakeRoomFor(sds s, size_t addlen) {
  183. void *sh, *newsh;
  184. size_t avail = sdsavail(s);
  185. size_t len, newlen;
  186. char type, oldtype = s[-1] & SDS_TYPE_MASK;
  187. int hdrlen;
  188. /* Return ASAP if there is enough space left. */
  189. if (avail >= addlen) return s;
  190. len = sdslen(s);
  191. sh = (char*)s-sdsHdrSize(oldtype);
  192. newlen = (len+addlen);
  193. if (newlen < SDS_MAX_PREALLOC)
  194. newlen *= 2;
  195. else
  196. newlen += SDS_MAX_PREALLOC;
  197. type = sdsReqType(newlen);
  198. /* Don't use type 5: the user is appending to the string and type 5 is
  199. * not able to remember empty space, so sdsMakeRoomFor() must be called
  200. * at every appending operation. */
  201. if (type == SDS_TYPE_5) type = SDS_TYPE_8;
  202. hdrlen = sdsHdrSize(type);
  203. if (oldtype==type) {
  204. newsh = s_realloc(sh, hdrlen+newlen+1);
  205. if (newsh == NULL) {
  206. s_free(sh);
  207. return NULL;
  208. }
  209. s = (char*)newsh+hdrlen;
  210. } else {
  211. /* Since the header size changes, need to move the string forward,
  212. * and can't use realloc */
  213. newsh = s_malloc(hdrlen+newlen+1);
  214. if (newsh == NULL) return NULL;
  215. memcpy((char*)newsh+hdrlen, s, len+1);
  216. s_free(sh);
  217. s = (char*)newsh+hdrlen;
  218. s[-1] = type;
  219. sdssetlen(s, len);
  220. }
  221. sdssetalloc(s, newlen);
  222. return s;
  223. }
  224. /* Reallocate the sds string so that it has no free space at the end. The
  225. * contained string remains not altered, but next concatenation operations
  226. * will require a reallocation.
  227. *
  228. * After the call, the passed sds string is no longer valid and all the
  229. * references must be substituted with the new pointer returned by the call. */
  230. sds sdsRemoveFreeSpace(sds s) {
  231. void *sh, *newsh;
  232. char type, oldtype = s[-1] & SDS_TYPE_MASK;
  233. int hdrlen;
  234. size_t len = sdslen(s);
  235. sh = (char*)s-sdsHdrSize(oldtype);
  236. type = sdsReqType(len);
  237. hdrlen = sdsHdrSize(type);
  238. if (oldtype==type) {
  239. newsh = s_realloc(sh, hdrlen+len+1);
  240. if (newsh == NULL) return NULL;
  241. s = (char*)newsh+hdrlen;
  242. } else {
  243. newsh = s_malloc(hdrlen+len+1);
  244. if (newsh == NULL) return NULL;
  245. memcpy((char*)newsh+hdrlen, s, len+1);
  246. s_free(sh);
  247. s = (char*)newsh+hdrlen;
  248. s[-1] = type;
  249. sdssetlen(s, len);
  250. }
  251. sdssetalloc(s, len);
  252. return s;
  253. }
  254. /* Return the total size of the allocation of the specifed sds string,
  255. * including:
  256. * 1) The sds header before the pointer.
  257. * 2) The string.
  258. * 3) The free buffer at the end if any.
  259. * 4) The implicit null term.
  260. */
  261. size_t sdsAllocSize(sds s) {
  262. size_t alloc = sdsalloc(s);
  263. return sdsHdrSize(s[-1])+alloc+1;
  264. }
  265. /* Return the pointer of the actual SDS allocation (normally SDS strings
  266. * are referenced by the start of the string buffer). */
  267. void *sdsAllocPtr(sds s) {
  268. return (void*) (s-sdsHdrSize(s[-1]));
  269. }
  270. /* Increment the sds length and decrements the left free space at the
  271. * end of the string according to 'incr'. Also set the null term
  272. * in the new end of the string.
  273. *
  274. * This function is used in order to fix the string length after the
  275. * user calls sdsMakeRoomFor(), writes something after the end of
  276. * the current string, and finally needs to set the new length.
  277. *
  278. * Note: it is possible to use a negative increment in order to
  279. * right-trim the string.
  280. *
  281. * Usage example:
  282. *
  283. * Using sdsIncrLen() and sdsMakeRoomFor() it is possible to mount the
  284. * following schema, to cat bytes coming from the kernel to the end of an
  285. * sds string without copying into an intermediate buffer:
  286. *
  287. * oldlen = sdslen(s);
  288. * s = sdsMakeRoomFor(s, BUFFER_SIZE);
  289. * nread = read(fd, s+oldlen, BUFFER_SIZE);
  290. * ... check for nread <= 0 and handle it ...
  291. * sdsIncrLen(s, nread);
  292. */
  293. void sdsIncrLen(sds s, int incr) {
  294. unsigned char flags = s[-1];
  295. size_t len;
  296. switch(flags&SDS_TYPE_MASK) {
  297. case SDS_TYPE_5: {
  298. unsigned char *fp = ((unsigned char*)s)-1;
  299. unsigned char oldlen = SDS_TYPE_5_LEN(flags);
  300. assert((incr > 0 && oldlen+incr < 32) || (incr < 0 && oldlen >= (unsigned int)(-incr)));
  301. *fp = SDS_TYPE_5 | ((oldlen+incr) << SDS_TYPE_BITS);
  302. len = oldlen+incr;
  303. break;
  304. }
  305. case SDS_TYPE_8: {
  306. SDS_HDR_VAR(8,s);
  307. assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr)));
  308. len = (sh->len += incr);
  309. break;
  310. }
  311. case SDS_TYPE_16: {
  312. SDS_HDR_VAR(16,s);
  313. assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr)));
  314. len = (sh->len += incr);
  315. break;
  316. }
  317. case SDS_TYPE_32: {
  318. SDS_HDR_VAR(32,s);
  319. assert((incr >= 0 && sh->alloc-sh->len >= (unsigned int)incr) || (incr < 0 && sh->len >= (unsigned int)(-incr)));
  320. len = (sh->len += incr);
  321. break;
  322. }
  323. case SDS_TYPE_64: {
  324. SDS_HDR_VAR(64,s);
  325. assert((incr >= 0 && sh->alloc-sh->len >= (uint64_t)incr) || (incr < 0 && sh->len >= (uint64_t)(-incr)));
  326. len = (sh->len += incr);
  327. break;
  328. }
  329. default: len = 0; /* Just to avoid compilation warnings. */
  330. }
  331. s[len] = '\0';
  332. }
  333. /* Grow the sds to have the specified length. Bytes that were not part of
  334. * the original length of the sds will be set to zero.
  335. *
  336. * if the specified length is smaller than the current length, no operation
  337. * is performed. */
  338. sds sdsgrowzero(sds s, size_t len) {
  339. size_t curlen = sdslen(s);
  340. if (len <= curlen) return s;
  341. s = sdsMakeRoomFor(s,len-curlen);
  342. if (s == NULL) return NULL;
  343. /* Make sure added region doesn't contain garbage */
  344. memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */
  345. sdssetlen(s, len);
  346. return s;
  347. }
  348. /* Append the specified binary-safe string pointed by 't' of 'len' bytes to the
  349. * end of the specified sds string 's'.
  350. *
  351. * After the call, the passed sds string is no longer valid and all the
  352. * references must be substituted with the new pointer returned by the call. */
  353. sds sdscatlen(sds s, const void *t, size_t len) {
  354. size_t curlen = sdslen(s);
  355. s = sdsMakeRoomFor(s,len);
  356. if (s == NULL) return NULL;
  357. memcpy(s+curlen, t, len);
  358. sdssetlen(s, curlen+len);
  359. s[curlen+len] = '\0';
  360. return s;
  361. }
  362. /* Append the specified null termianted C string to the sds string 's'.
  363. *
  364. * After the call, the passed sds string is no longer valid and all the
  365. * references must be substituted with the new pointer returned by the call. */
  366. sds sdscat(sds s, const char *t) {
  367. return sdscatlen(s, t, strlen(t));
  368. }
  369. /* Append the specified sds 't' to the existing sds 's'.
  370. *
  371. * After the call, the modified sds string is no longer valid and all the
  372. * references must be substituted with the new pointer returned by the call. */
  373. sds sdscatsds(sds s, const sds t) {
  374. return sdscatlen(s, t, sdslen(t));
  375. }
  376. /* Destructively modify the sds string 's' to hold the specified binary
  377. * safe string pointed by 't' of length 'len' bytes. */
  378. sds sdscpylen(sds s, const char *t, size_t len) {
  379. if (sdsalloc(s) < len) {
  380. s = sdsMakeRoomFor(s,len-sdslen(s));
  381. if (s == NULL) return NULL;
  382. }
  383. memcpy(s, t, len);
  384. s[len] = '\0';
  385. sdssetlen(s, len);
  386. return s;
  387. }
  388. /* Like sdscpylen() but 't' must be a null-termined string so that the length
  389. * of the string is obtained with strlen(). */
  390. sds sdscpy(sds s, const char *t) {
  391. return sdscpylen(s, t, strlen(t));
  392. }
  393. /* Helper for sdscatlonglong() doing the actual number -> string
  394. * conversion. 's' must point to a string with room for at least
  395. * SDS_LLSTR_SIZE bytes.
  396. *
  397. * The function returns the length of the null-terminated string
  398. * representation stored at 's'. */
  399. #define SDS_LLSTR_SIZE 21
  400. int sdsll2str(char *s, long long value) {
  401. char *p, aux;
  402. unsigned long long v;
  403. size_t l;
  404. /* Generate the string representation, this method produces
  405. * an reversed string. */
  406. v = (value < 0) ? -value : value;
  407. p = s;
  408. do {
  409. *p++ = '0'+(v%10);
  410. v /= 10;
  411. } while(v);
  412. if (value < 0) *p++ = '-';
  413. /* Compute length and add null term. */
  414. l = p-s;
  415. *p = '\0';
  416. /* Reverse the string. */
  417. p--;
  418. while(s < p) {
  419. aux = *s;
  420. *s = *p;
  421. *p = aux;
  422. s++;
  423. p--;
  424. }
  425. return l;
  426. }
  427. /* Identical sdsll2str(), but for unsigned long long type. */
  428. int sdsull2str(char *s, unsigned long long v) {
  429. char *p, aux;
  430. size_t l;
  431. /* Generate the string representation, this method produces
  432. * an reversed string. */
  433. p = s;
  434. do {
  435. *p++ = '0'+(v%10);
  436. v /= 10;
  437. } while(v);
  438. /* Compute length and add null term. */
  439. l = p-s;
  440. *p = '\0';
  441. /* Reverse the string. */
  442. p--;
  443. while(s < p) {
  444. aux = *s;
  445. *s = *p;
  446. *p = aux;
  447. s++;
  448. p--;
  449. }
  450. return l;
  451. }
  452. /* Create an sds string from a long long value. It is much faster than:
  453. *
  454. * sdscatprintf(sdsempty(),"%lld\n", value);
  455. */
  456. sds sdsfromlonglong(long long value) {
  457. char buf[SDS_LLSTR_SIZE];
  458. int len = sdsll2str(buf,value);
  459. return sdsnewlen(buf,len);
  460. }
  461. /* Like sdscatprintf() but gets va_list instead of being variadic. */
  462. sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
  463. va_list cpy;
  464. char staticbuf[1024], *buf = staticbuf, *t;
  465. size_t buflen = strlen(fmt)*2;
  466. /* We try to start using a static buffer for speed.
  467. * If not possible we revert to heap allocation. */
  468. if (buflen > sizeof(staticbuf)) {
  469. buf = s_malloc(buflen);
  470. if (buf == NULL) return NULL;
  471. } else {
  472. buflen = sizeof(staticbuf);
  473. }
  474. /* Try with buffers two times bigger every time we fail to
  475. * fit the string in the current buffer size. */
  476. while(1) {
  477. buf[buflen-2] = '\0';
  478. va_copy(cpy,ap);
  479. vsnprintf(buf, buflen, fmt, cpy);
  480. va_end(cpy);
  481. if (buf[buflen-2] != '\0') {
  482. if (buf != staticbuf) s_free(buf);
  483. buflen *= 2;
  484. buf = s_malloc(buflen);
  485. if (buf == NULL) return NULL;
  486. continue;
  487. }
  488. break;
  489. }
  490. /* Finally concat the obtained string to the SDS string and return it. */
  491. t = sdscat(s, buf);
  492. if (buf != staticbuf) s_free(buf);
  493. return t;
  494. }
  495. /* Append to the sds string 's' a string obtained using printf-alike format
  496. * specifier.
  497. *
  498. * After the call, the modified sds string is no longer valid and all the
  499. * references must be substituted with the new pointer returned by the call.
  500. *
  501. * Example:
  502. *
  503. * s = sdsnew("Sum is: ");
  504. * s = sdscatprintf(s,"%d+%d = %d",a,b,a+b).
  505. *
  506. * Often you need to create a string from scratch with the printf-alike
  507. * format. When this is the need, just use sdsempty() as the target string:
  508. *
  509. * s = sdscatprintf(sdsempty(), "... your format ...", args);
  510. */
  511. sds sdscatprintf(sds s, const char *fmt, ...) {
  512. va_list ap;
  513. char *t;
  514. va_start(ap, fmt);
  515. t = sdscatvprintf(s,fmt,ap);
  516. va_end(ap);
  517. return t;
  518. }
  519. /* This function is similar to sdscatprintf, but much faster as it does
  520. * not rely on sprintf() family functions implemented by the libc that
  521. * are often very slow. Moreover directly handling the sds string as
  522. * new data is concatenated provides a performance improvement.
  523. *
  524. * However this function only handles an incompatible subset of printf-alike
  525. * format specifiers:
  526. *
  527. * %s - C String
  528. * %S - SDS string
  529. * %i - signed int
  530. * %I - 64 bit signed integer (long long, int64_t)
  531. * %u - unsigned int
  532. * %U - 64 bit unsigned integer (unsigned long long, uint64_t)
  533. * %% - Verbatim "%" character.
  534. */
  535. sds sdscatfmt(sds s, char const *fmt, ...) {
  536. const char *f = fmt;
  537. int i;
  538. va_list ap;
  539. va_start(ap,fmt);
  540. i = sdslen(s); /* Position of the next byte to write to dest str. */
  541. while(*f) {
  542. char next, *str;
  543. size_t l;
  544. long long num;
  545. unsigned long long unum;
  546. /* Make sure there is always space for at least 1 char. */
  547. if (sdsavail(s)==0) {
  548. s = sdsMakeRoomFor(s,1);
  549. if (s == NULL) goto fmt_error;
  550. }
  551. switch(*f) {
  552. case '%':
  553. next = *(f+1);
  554. f++;
  555. switch(next) {
  556. case 's':
  557. case 'S':
  558. str = va_arg(ap,char*);
  559. l = (next == 's') ? strlen(str) : sdslen(str);
  560. if (sdsavail(s) < l) {
  561. s = sdsMakeRoomFor(s,l);
  562. if (s == NULL) goto fmt_error;
  563. }
  564. memcpy(s+i,str,l);
  565. sdsinclen(s,l);
  566. i += l;
  567. break;
  568. case 'i':
  569. case 'I':
  570. if (next == 'i')
  571. num = va_arg(ap,int);
  572. else
  573. num = va_arg(ap,long long);
  574. {
  575. char buf[SDS_LLSTR_SIZE];
  576. l = sdsll2str(buf,num);
  577. if (sdsavail(s) < l) {
  578. s = sdsMakeRoomFor(s,l);
  579. if (s == NULL) goto fmt_error;
  580. }
  581. memcpy(s+i,buf,l);
  582. sdsinclen(s,l);
  583. i += l;
  584. }
  585. break;
  586. case 'u':
  587. case 'U':
  588. if (next == 'u')
  589. unum = va_arg(ap,unsigned int);
  590. else
  591. unum = va_arg(ap,unsigned long long);
  592. {
  593. char buf[SDS_LLSTR_SIZE];
  594. l = sdsull2str(buf,unum);
  595. if (sdsavail(s) < l) {
  596. s = sdsMakeRoomFor(s,l);
  597. if (s == NULL) goto fmt_error;
  598. }
  599. memcpy(s+i,buf,l);
  600. sdsinclen(s,l);
  601. i += l;
  602. }
  603. break;
  604. default: /* Handle %% and generally %<unknown>. */
  605. s[i++] = next;
  606. sdsinclen(s,1);
  607. break;
  608. }
  609. break;
  610. default:
  611. s[i++] = *f;
  612. sdsinclen(s,1);
  613. break;
  614. }
  615. f++;
  616. }
  617. va_end(ap);
  618. /* Add null-term */
  619. s[i] = '\0';
  620. return s;
  621. fmt_error:
  622. va_end(ap);
  623. return NULL;
  624. }
  625. /* Remove the part of the string from left and from right composed just of
  626. * contiguous characters found in 'cset', that is a null terminted C string.
  627. *
  628. * After the call, the modified sds string is no longer valid and all the
  629. * references must be substituted with the new pointer returned by the call.
  630. *
  631. * Example:
  632. *
  633. * s = sdsnew("AA...AA.a.aa.aHelloWorld :::");
  634. * s = sdstrim(s,"Aa. :");
  635. * printf("%s\n", s);
  636. *
  637. * Output will be just "Hello World".
  638. */
  639. sds sdstrim(sds s, const char *cset) {
  640. char *start, *end, *sp, *ep;
  641. size_t len;
  642. sp = start = s;
  643. ep = end = s+sdslen(s)-1;
  644. while(sp <= end && strchr(cset, *sp)) sp++;
  645. while(ep > sp && strchr(cset, *ep)) ep--;
  646. len = (sp > ep) ? 0 : ((ep-sp)+1);
  647. if (s != sp) memmove(s, sp, len);
  648. s[len] = '\0';
  649. sdssetlen(s,len);
  650. return s;
  651. }
  652. /* Turn the string into a smaller (or equal) string containing only the
  653. * substring specified by the 'start' and 'end' indexes.
  654. *
  655. * start and end can be negative, where -1 means the last character of the
  656. * string, -2 the penultimate character, and so forth.
  657. *
  658. * The interval is inclusive, so the start and end characters will be part
  659. * of the resulting string.
  660. *
  661. * The string is modified in-place.
  662. *
  663. * Example:
  664. *
  665. * s = sdsnew("Hello World");
  666. * sdsrange(s,1,-1); => "ello World"
  667. */
  668. void sdsrange(sds s, int start, int end) {
  669. size_t newlen, len = sdslen(s);
  670. if (len == 0) return;
  671. if (start < 0) {
  672. start = len+start;
  673. if (start < 0) start = 0;
  674. }
  675. if (end < 0) {
  676. end = len+end;
  677. if (end < 0) end = 0;
  678. }
  679. newlen = (start > end) ? 0 : (end-start)+1;
  680. if (newlen != 0) {
  681. if (start >= (signed)len) {
  682. newlen = 0;
  683. } else if (end >= (signed)len) {
  684. end = len-1;
  685. newlen = (start > end) ? 0 : (end-start)+1;
  686. }
  687. } else {
  688. start = 0;
  689. }
  690. if (start && newlen) memmove(s, s+start, newlen);
  691. s[newlen] = 0;
  692. sdssetlen(s,newlen);
  693. }
  694. /* Apply tolower() to every character of the sds string 's'. */
  695. void sdstolower(sds s) {
  696. int len = sdslen(s), j;
  697. for (j = 0; j < len; j++) s[j] = tolower(s[j]);
  698. }
  699. /* Apply toupper() to every character of the sds string 's'. */
  700. void sdstoupper(sds s) {
  701. int len = sdslen(s), j;
  702. for (j = 0; j < len; j++) s[j] = toupper(s[j]);
  703. }
  704. /* Compare two sds strings s1 and s2 with memcmp().
  705. *
  706. * Return value:
  707. *
  708. * positive if s1 > s2.
  709. * negative if s1 < s2.
  710. * 0 if s1 and s2 are exactly the same binary string.
  711. *
  712. * If two strings share exactly the same prefix, but one of the two has
  713. * additional characters, the longer string is considered to be greater than
  714. * the smaller one. */
  715. int sdscmp(const sds s1, const sds s2) {
  716. size_t l1, l2, minlen;
  717. int cmp;
  718. l1 = sdslen(s1);
  719. l2 = sdslen(s2);
  720. minlen = (l1 < l2) ? l1 : l2;
  721. cmp = memcmp(s1,s2,minlen);
  722. if (cmp == 0) return l1-l2;
  723. return cmp;
  724. }
  725. /* Split 's' with separator in 'sep'. An array
  726. * of sds strings is returned. *count will be set
  727. * by reference to the number of tokens returned.
  728. *
  729. * On out of memory, zero length string, zero length
  730. * separator, NULL is returned.
  731. *
  732. * Note that 'sep' is able to split a string using
  733. * a multi-character separator. For example
  734. * sdssplit("foo_-_bar","_-_"); will return two
  735. * elements "foo" and "bar".
  736. *
  737. * This version of the function is binary-safe but
  738. * requires length arguments. sdssplit() is just the
  739. * same function but for zero-terminated strings.
  740. */
  741. sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count) {
  742. int elements = 0, slots = 5, start = 0, j;
  743. sds *tokens;
  744. if (seplen < 1 || len < 0) return NULL;
  745. tokens = s_malloc(sizeof(sds)*slots);
  746. if (tokens == NULL) return NULL;
  747. if (len == 0) {
  748. *count = 0;
  749. return tokens;
  750. }
  751. for (j = 0; j < (len-(seplen-1)); j++) {
  752. /* make sure there is room for the next element and the final one */
  753. if (slots < elements+2) {
  754. sds *newtokens;
  755. slots *= 2;
  756. newtokens = s_realloc(tokens,sizeof(sds)*slots);
  757. if (newtokens == NULL) goto cleanup;
  758. tokens = newtokens;
  759. }
  760. /* search the separator */
  761. if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) {
  762. tokens[elements] = sdsnewlen(s+start,j-start);
  763. if (tokens[elements] == NULL) goto cleanup;
  764. elements++;
  765. start = j+seplen;
  766. j = j+seplen-1; /* skip the separator */
  767. }
  768. }
  769. /* Add the final element. We are sure there is room in the tokens array. */
  770. tokens[elements] = sdsnewlen(s+start,len-start);
  771. if (tokens[elements] == NULL) goto cleanup;
  772. elements++;
  773. *count = elements;
  774. return tokens;
  775. cleanup:
  776. {
  777. int i;
  778. for (i = 0; i < elements; i++) sdsfree(tokens[i]);
  779. s_free(tokens);
  780. *count = 0;
  781. return NULL;
  782. }
  783. }
  784. /* Free the result returned by sdssplitlen(), or do nothing if 'tokens' is NULL. */
  785. void sdsfreesplitres(sds *tokens, int count) {
  786. if (!tokens) return;
  787. while(count--)
  788. sdsfree(tokens[count]);
  789. s_free(tokens);
  790. }
  791. /* Append to the sds string "s" an escaped string representation where
  792. * all the non-printable characters (tested with isprint()) are turned into
  793. * escapes in the form "\n\r\a...." or "\x<hex-number>".
  794. *
  795. * After the call, the modified sds string is no longer valid and all the
  796. * references must be substituted with the new pointer returned by the call. */
  797. sds sdscatrepr(sds s, const char *p, size_t len) {
  798. s = sdscatlen(s,"\"",1);
  799. while(len--) {
  800. switch(*p) {
  801. case '\\':
  802. case '"':
  803. s = sdscatprintf(s,"\\%c",*p);
  804. break;
  805. case '\n': s = sdscatlen(s,"\\n",2); break;
  806. case '\r': s = sdscatlen(s,"\\r",2); break;
  807. case '\t': s = sdscatlen(s,"\\t",2); break;
  808. case '\a': s = sdscatlen(s,"\\a",2); break;
  809. case '\b': s = sdscatlen(s,"\\b",2); break;
  810. default:
  811. if (isprint(*p))
  812. s = sdscatprintf(s,"%c",*p);
  813. else
  814. s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
  815. break;
  816. }
  817. p++;
  818. }
  819. return sdscatlen(s,"\"",1);
  820. }
  821. /* Helper function for sdssplitargs() that returns non zero if 'c'
  822. * is a valid hex digit. */
  823. int is_hex_digit(char c) {
  824. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
  825. (c >= 'A' && c <= 'F');
  826. }
  827. /* Helper function for sdssplitargs() that converts a hex digit into an
  828. * integer from 0 to 15 */
  829. int hex_digit_to_int(char c) {
  830. switch(c) {
  831. case '0': return 0;
  832. case '1': return 1;
  833. case '2': return 2;
  834. case '3': return 3;
  835. case '4': return 4;
  836. case '5': return 5;
  837. case '6': return 6;
  838. case '7': return 7;
  839. case '8': return 8;
  840. case '9': return 9;
  841. case 'a': case 'A': return 10;
  842. case 'b': case 'B': return 11;
  843. case 'c': case 'C': return 12;
  844. case 'd': case 'D': return 13;
  845. case 'e': case 'E': return 14;
  846. case 'f': case 'F': return 15;
  847. default: return 0;
  848. }
  849. }
  850. /* Split a line into arguments, where every argument can be in the
  851. * following programming-language REPL-alike form:
  852. *
  853. * foo bar "newline are supported\n" and "\xff\x00otherstuff"
  854. *
  855. * The number of arguments is stored into *argc, and an array
  856. * of sds is returned.
  857. *
  858. * The caller should free the resulting array of sds strings with
  859. * sdsfreesplitres().
  860. *
  861. * Note that sdscatrepr() is able to convert back a string into
  862. * a quoted string in the same format sdssplitargs() is able to parse.
  863. *
  864. * The function returns the allocated tokens on success, even when the
  865. * input string is empty, or NULL if the input contains unbalanced
  866. * quotes or closed quotes followed by non space characters
  867. * as in: "foo"bar or "foo'
  868. */
  869. sds *sdssplitargs(const char *line, int *argc) {
  870. const char *p = line;
  871. char *current = NULL;
  872. char **vector = NULL;
  873. *argc = 0;
  874. while(1) {
  875. /* skip blanks */
  876. while(*p && isspace(*p)) p++;
  877. if (*p) {
  878. /* get a token */
  879. int inq=0; /* set to 1 if we are in "quotes" */
  880. int insq=0; /* set to 1 if we are in 'single quotes' */
  881. int done=0;
  882. if (current == NULL) current = sdsempty();
  883. while(!done) {
  884. if (inq) {
  885. if (*p == '\\' && *(p+1) == 'x' &&
  886. is_hex_digit(*(p+2)) &&
  887. is_hex_digit(*(p+3)))
  888. {
  889. unsigned char byte;
  890. byte = (hex_digit_to_int(*(p+2))*16)+
  891. hex_digit_to_int(*(p+3));
  892. current = sdscatlen(current,(char*)&byte,1);
  893. p += 3;
  894. } else if (*p == '\\' && *(p+1)) {
  895. char c;
  896. p++;
  897. switch(*p) {
  898. case 'n': c = '\n'; break;
  899. case 'r': c = '\r'; break;
  900. case 't': c = '\t'; break;
  901. case 'b': c = '\b'; break;
  902. case 'a': c = '\a'; break;
  903. default: c = *p; break;
  904. }
  905. current = sdscatlen(current,&c,1);
  906. } else if (*p == '"') {
  907. /* closing quote must be followed by a space or
  908. * nothing at all. */
  909. if (*(p+1) && !isspace(*(p+1))) goto err;
  910. done=1;
  911. } else if (!*p) {
  912. /* unterminated quotes */
  913. goto err;
  914. } else {
  915. current = sdscatlen(current,p,1);
  916. }
  917. } else if (insq) {
  918. if (*p == '\\' && *(p+1) == '\'') {
  919. p++;
  920. current = sdscatlen(current,"'",1);
  921. } else if (*p == '\'') {
  922. /* closing quote must be followed by a space or
  923. * nothing at all. */
  924. if (*(p+1) && !isspace(*(p+1))) goto err;
  925. done=1;
  926. } else if (!*p) {
  927. /* unterminated quotes */
  928. goto err;
  929. } else {
  930. current = sdscatlen(current,p,1);
  931. }
  932. } else {
  933. switch(*p) {
  934. case ' ':
  935. case '\n':
  936. case '\r':
  937. case '\t':
  938. case '\0':
  939. done=1;
  940. break;
  941. case '"':
  942. inq=1;
  943. break;
  944. case '\'':
  945. insq=1;
  946. break;
  947. default:
  948. current = sdscatlen(current,p,1);
  949. break;
  950. }
  951. }
  952. if (*p) p++;
  953. }
  954. /* add the token to the vector */
  955. {
  956. char **new_vector = s_realloc(vector,((*argc)+1)*sizeof(char*));
  957. if (new_vector == NULL) {
  958. s_free(vector);
  959. return NULL;
  960. }
  961. vector = new_vector;
  962. vector[*argc] = current;
  963. (*argc)++;
  964. current = NULL;
  965. }
  966. } else {
  967. /* Even on empty input string return something not NULL. */
  968. if (vector == NULL) vector = s_malloc(sizeof(void*));
  969. return vector;
  970. }
  971. }
  972. err:
  973. while((*argc)--)
  974. sdsfree(vector[*argc]);
  975. s_free(vector);
  976. if (current) sdsfree(current);
  977. *argc = 0;
  978. return NULL;
  979. }
  980. /* Modify the string substituting all the occurrences of the set of
  981. * characters specified in the 'from' string to the corresponding character
  982. * in the 'to' array.
  983. *
  984. * For instance: sdsmapchars(mystring, "ho", "01", 2)
  985. * will have the effect of turning the string "hello" into "0ell1".
  986. *
  987. * The function returns the sds string pointer, that is always the same
  988. * as the input pointer since no resize is needed. */
  989. sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen) {
  990. size_t j, i, l = sdslen(s);
  991. for (j = 0; j < l; j++) {
  992. for (i = 0; i < setlen; i++) {
  993. if (s[j] == from[i]) {
  994. s[j] = to[i];
  995. break;
  996. }
  997. }
  998. }
  999. return s;
  1000. }
  1001. /* Join an array of C strings using the specified separator (also a C string).
  1002. * Returns the result as an sds string. */
  1003. sds sdsjoin(char **argv, int argc, char *sep) {
  1004. sds join = sdsempty();
  1005. int j;
  1006. for (j = 0; j < argc; j++) {
  1007. join = sdscat(join, argv[j]);
  1008. if (j != argc-1) join = sdscat(join,sep);
  1009. }
  1010. return join;
  1011. }
  1012. /* Like sdsjoin, but joins an array of SDS strings. */
  1013. sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen) {
  1014. sds join = sdsempty();
  1015. int j;
  1016. for (j = 0; j < argc; j++) {
  1017. join = sdscatsds(join, argv[j]);
  1018. if (j != argc-1) join = sdscatlen(join,sep,seplen);
  1019. }
  1020. return join;
  1021. }
  1022. /* Wrappers to the allocators used by SDS. Note that SDS will actually
  1023. * just use the macros defined into sdsalloc.h in order to avoid to pay
  1024. * the overhead of function calls. Here we define these wrappers only for
  1025. * the programs SDS is linked to, if they want to touch the SDS internals
  1026. * even if they use a different allocator. */
  1027. void *sds_malloc(size_t size) { return s_malloc(size); }
  1028. void *sds_realloc(void *ptr, size_t size) { return s_realloc(ptr,size); }
  1029. void sds_free(void *ptr) { s_free(ptr); }
  1030. #if defined(SDS_TEST_MAIN)
  1031. #include <stdio.h>
  1032. #include "testhelp.h"
  1033. #include "limits.h"
  1034. #define UNUSED(x) (void)(x)
  1035. int sdsTest(void) {
  1036. {
  1037. sds x = sdsnew("foo"), y;
  1038. test_cond("Create a string and obtain the length",
  1039. sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0)
  1040. sdsfree(x);
  1041. x = sdsnewlen("foo",2);
  1042. test_cond("Create a string with specified length",
  1043. sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0)
  1044. x = sdscat(x,"bar");
  1045. test_cond("Strings concatenation",
  1046. sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0);
  1047. x = sdscpy(x,"a");
  1048. test_cond("sdscpy() against an originally longer string",
  1049. sdslen(x) == 1 && memcmp(x,"a\0",2) == 0)
  1050. x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk");
  1051. test_cond("sdscpy() against an originally shorter string",
  1052. sdslen(x) == 33 &&
  1053. memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0)
  1054. sdsfree(x);
  1055. x = sdscatprintf(sdsempty(),"%d",123);
  1056. test_cond("sdscatprintf() seems working in the base case",
  1057. sdslen(x) == 3 && memcmp(x,"123\0",4) == 0)
  1058. sdsfree(x);
  1059. x = sdsnew("--");
  1060. x = sdscatfmt(x, "Hello %s World %I,%I--", "Hi!", LLONG_MIN,LLONG_MAX);
  1061. test_cond("sdscatfmt() seems working in the base case",
  1062. sdslen(x) == 60 &&
  1063. memcmp(x,"--Hello Hi! World -9223372036854775808,"
  1064. "9223372036854775807--",60) == 0)
  1065. printf("[%s]\n",x);
  1066. sdsfree(x);
  1067. x = sdsnew("--");
  1068. x = sdscatfmt(x, "%u,%U--", UINT_MAX, ULLONG_MAX);
  1069. test_cond("sdscatfmt() seems working with unsigned numbers",
  1070. sdslen(x) == 35 &&
  1071. memcmp(x,"--4294967295,18446744073709551615--",35) == 0)
  1072. sdsfree(x);
  1073. x = sdsnew(" x ");
  1074. sdstrim(x," x");
  1075. test_cond("sdstrim() works when all chars match",
  1076. sdslen(x) == 0)
  1077. sdsfree(x);
  1078. x = sdsnew(" x ");
  1079. sdstrim(x," ");
  1080. test_cond("sdstrim() works when a single char remains",
  1081. sdslen(x) == 1 && x[0] == 'x')
  1082. sdsfree(x);
  1083. x = sdsnew("xxciaoyyy");
  1084. sdstrim(x,"xy");
  1085. test_cond("sdstrim() correctly trims characters",
  1086. sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0)
  1087. y = sdsdup(x);
  1088. sdsrange(y,1,1);
  1089. test_cond("sdsrange(...,1,1)",
  1090. sdslen(y) == 1 && memcmp(y,"i\0",2) == 0)
  1091. sdsfree(y);
  1092. y = sdsdup(x);
  1093. sdsrange(y,1,-1);
  1094. test_cond("sdsrange(...,1,-1)",
  1095. sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
  1096. sdsfree(y);
  1097. y = sdsdup(x);
  1098. sdsrange(y,-2,-1);
  1099. test_cond("sdsrange(...,-2,-1)",
  1100. sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0)
  1101. sdsfree(y);
  1102. y = sdsdup(x);
  1103. sdsrange(y,2,1);
  1104. test_cond("sdsrange(...,2,1)",
  1105. sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
  1106. sdsfree(y);
  1107. y = sdsdup(x);
  1108. sdsrange(y,1,100);
  1109. test_cond("sdsrange(...,1,100)",
  1110. sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
  1111. sdsfree(y);
  1112. y = sdsdup(x);
  1113. sdsrange(y,100,100);
  1114. test_cond("sdsrange(...,100,100)",
  1115. sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
  1116. sdsfree(y);
  1117. sdsfree(x);
  1118. x = sdsnew("foo");
  1119. y = sdsnew("foa");
  1120. test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0)
  1121. sdsfree(y);
  1122. sdsfree(x);
  1123. x = sdsnew("bar");
  1124. y = sdsnew("bar");
  1125. test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0)
  1126. sdsfree(y);
  1127. sdsfree(x);
  1128. x = sdsnew("aar");
  1129. y = sdsnew("bar");
  1130. test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0)
  1131. sdsfree(y);
  1132. sdsfree(x);
  1133. x = sdsnewlen("\a\n\0foo\r",7);
  1134. y = sdscatrepr(sdsempty(),x,sdslen(x));
  1135. test_cond("sdscatrepr(...data...)",
  1136. memcmp(y,"\"\\a\\n\\x00foo\\r\"",15) == 0)
  1137. {
  1138. unsigned int oldfree;
  1139. char *p;
  1140. int step = 10, j, i;
  1141. sdsfree(x);
  1142. sdsfree(y);
  1143. x = sdsnew("0");
  1144. test_cond("sdsnew() free/len buffers", sdslen(x) == 1 && sdsavail(x) == 0);
  1145. /* Run the test a few times in order to hit the first two
  1146. * SDS header types. */
  1147. for (i = 0; i < 10; i++) {
  1148. int oldlen = sdslen(x);
  1149. x = sdsMakeRoomFor(x,step);
  1150. int type = x[-1]&SDS_TYPE_MASK;
  1151. test_cond("sdsMakeRoomFor() len", sdslen(x) == oldlen);
  1152. if (type != SDS_TYPE_5) {
  1153. test_cond("sdsMakeRoomFor() free", sdsavail(x) >= step);
  1154. oldfree = sdsavail(x);
  1155. }
  1156. p = x+oldlen;
  1157. for (j = 0; j < step; j++) {
  1158. p[j] = 'A'+j;
  1159. }
  1160. sdsIncrLen(x,step);
  1161. }
  1162. test_cond("sdsMakeRoomFor() content",
  1163. memcmp("0ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ",x,101) == 0);
  1164. test_cond("sdsMakeRoomFor() final length",sdslen(x)==101);
  1165. sdsfree(x);
  1166. }
  1167. }
  1168. test_report()
  1169. return 0;
  1170. }
  1171. #endif
  1172. #ifdef SDS_TEST_MAIN
  1173. int main(void) {
  1174. return sdsTest();
  1175. }
  1176. #endif