2
0

sds.c 41 KB

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