sds.c 40 KB

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