ziplist.c 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  1. /* The ziplist is a specially encoded dually linked list that is designed
  2. * to be very memory efficient. It stores both strings and integer values,
  3. * where integers are encoded as actual integers instead of a series of
  4. * characters. It allows push and pop operations on either side of the list
  5. * in O(1) time. However, because every operation requires a reallocation of
  6. * the memory used by the ziplist, the actual complexity is related to the
  7. * amount of memory used by the ziplist.
  8. *
  9. * ----------------------------------------------------------------------------
  10. *
  11. * ZIPLIST OVERALL LAYOUT
  12. * ======================
  13. *
  14. * The general layout of the ziplist is as follows:
  15. *
  16. * <zlbytes> <zltail> <zllen> <entry> <entry> ... <entry> <zlend>
  17. *
  18. * NOTE: all fields are stored in little endian, if not specified otherwise.
  19. *
  20. * <uint32_t zlbytes> is an unsigned integer to hold the number of bytes that
  21. * the ziplist occupies, including the four bytes of the zlbytes field itself.
  22. * This value needs to be stored to be able to resize the entire structure
  23. * without the need to traverse it first.
  24. *
  25. * <uint32_t zltail> is the offset to the last entry in the list. This allows
  26. * a pop operation on the far side of the list without the need for full
  27. * traversal.
  28. *
  29. * <uint16_t zllen> is the number of entries. When there are more than
  30. * 2^16-2 entries, this value is set to 2^16-1 and we need to traverse the
  31. * entire list to know how many items it holds.
  32. *
  33. * <uint8_t zlend> is a special entry representing the end of the ziplist.
  34. * Is encoded as a single byte equal to 255. No other normal entry starts
  35. * with a byte set to the value of 255.
  36. *
  37. * ZIPLIST ENTRIES
  38. * ===============
  39. *
  40. * Every entry in the ziplist is prefixed by metadata that contains two pieces
  41. * of information. First, the length of the previous entry is stored to be
  42. * able to traverse the list from back to front. Second, the entry encoding is
  43. * provided. It represents the entry type, integer or string, and in the case
  44. * of strings it also represents the length of the string payload.
  45. * So a complete entry is stored like this:
  46. *
  47. * <prevlen> <encoding> <entry-data>
  48. *
  49. * Sometimes the encoding represents the entry itself, like for small integers
  50. * as we'll see later. In such a case the <entry-data> part is missing, and we
  51. * could have just:
  52. *
  53. * <prevlen> <encoding>
  54. *
  55. * The length of the previous entry, <prevlen>, is encoded in the following way:
  56. * If this length is smaller than 254 bytes, it will only consume a single
  57. * byte representing the length as an unsinged 8 bit integer. When the length
  58. * is greater than or equal to 254, it will consume 5 bytes. The first byte is
  59. * set to 254 (FE) to indicate a larger value is following. The remaining 4
  60. * bytes take the length of the previous entry as value.
  61. *
  62. * So practically an entry is encoded in the following way:
  63. *
  64. * <prevlen from 0 to 253> <encoding> <entry>
  65. *
  66. * Or alternatively if the previous entry length is greater than 253 bytes
  67. * the following encoding is used:
  68. *
  69. * 0xFE <4 bytes unsigned little endian prevlen> <encoding> <entry>
  70. *
  71. * The encoding field of the entry depends on the content of the
  72. * entry. When the entry is a string, the first 2 bits of the encoding first
  73. * byte will hold the type of encoding used to store the length of the string,
  74. * followed by the actual length of the string. When the entry is an integer
  75. * the first 2 bits are both set to 1. The following 2 bits are used to specify
  76. * what kind of integer will be stored after this header. An overview of the
  77. * different types and encodings is as follows. The first byte is always enough
  78. * to determine the kind of entry.
  79. *
  80. * |00pppppp| - 1 byte
  81. * String value with length less than or equal to 63 bytes (6 bits).
  82. * "pppppp" represents the unsigned 6 bit length.
  83. * |01pppppp|qqqqqqqq| - 2 bytes
  84. * String value with length less than or equal to 16383 bytes (14 bits).
  85. * IMPORTANT: The 14 bit number is stored in big endian.
  86. * |10000000|qqqqqqqq|rrrrrrrr|ssssssss|tttttttt| - 5 bytes
  87. * String value with length greater than or equal to 16384 bytes.
  88. * Only the 4 bytes following the first byte represents the length
  89. * up to 32^2-1. The 6 lower bits of the first byte are not used and
  90. * are set to zero.
  91. * IMPORTANT: The 32 bit number is stored in big endian.
  92. * |11000000| - 3 bytes
  93. * Integer encoded as int16_t (2 bytes).
  94. * |11010000| - 5 bytes
  95. * Integer encoded as int32_t (4 bytes).
  96. * |11100000| - 9 bytes
  97. * Integer encoded as int64_t (8 bytes).
  98. * |11110000| - 4 bytes
  99. * Integer encoded as 24 bit signed (3 bytes).
  100. * |11111110| - 2 bytes
  101. * Integer encoded as 8 bit signed (1 byte).
  102. * |1111xxxx| - (with xxxx between 0000 and 1101) immediate 4 bit integer.
  103. * Unsigned integer from 0 to 12. The encoded value is actually from
  104. * 1 to 13 because 0000 and 1111 can not be used, so 1 should be
  105. * subtracted from the encoded 4 bit value to obtain the right value.
  106. * |11111111| - End of ziplist special entry.
  107. *
  108. * Like for the ziplist header, all the integers are represented in little
  109. * endian byte order, even when this code is compiled in big endian systems.
  110. *
  111. * EXAMPLES OF ACTUAL ZIPLISTS
  112. * ===========================
  113. *
  114. * The following is a ziplist containing the two elements representing
  115. * the strings "2" and "5". It is composed of 15 bytes, that we visually
  116. * split into sections:
  117. *
  118. * [0f 00 00 00] [0c 00 00 00] [02 00] [00 f3] [02 f6] [ff]
  119. * | | | | | |
  120. * zlbytes zltail entries "2" "5" end
  121. *
  122. * The first 4 bytes represent the number 15, that is the number of bytes
  123. * the whole ziplist is composed of. The second 4 bytes are the offset
  124. * at which the last ziplist entry is found, that is 12, in fact the
  125. * last entry, that is "5", is at offset 12 inside the ziplist.
  126. * The next 16 bit integer represents the number of elements inside the
  127. * ziplist, its value is 2 since there are just two elements inside.
  128. * Finally "00 f3" is the first entry representing the number 2. It is
  129. * composed of the previous entry length, which is zero because this is
  130. * our first entry, and the byte F3 which corresponds to the encoding
  131. * |1111xxxx| with xxxx between 0001 and 1101. We need to remove the "F"
  132. * higher order bits 1111, and subtract 1 from the "3", so the entry value
  133. * is "2". The next entry has a prevlen of 02, since the first entry is
  134. * composed of exactly two bytes. The entry itself, F6, is encoded exactly
  135. * like the first entry, and 6-1 = 5, so the value of the entry is 5.
  136. * Finally the special entry FF signals the end of the ziplist.
  137. *
  138. * Adding another element to the above string with the value "Hello World"
  139. * allows us to show how the ziplist encodes small strings. We'll just show
  140. * the hex dump of the entry itself. Imagine the bytes as following the
  141. * entry that stores "5" in the ziplist above:
  142. *
  143. * [02] [0b] [48 65 6c 6c 6f 20 57 6f 72 6c 64]
  144. *
  145. * The first byte, 02, is the length of the previous entry. The next
  146. * byte represents the encoding in the pattern |00pppppp| that means
  147. * that the entry is a string of length <pppppp>, so 0B means that
  148. * an 11 bytes string follows. From the third byte (48) to the last (64)
  149. * there are just the ASCII characters for "Hello World".
  150. *
  151. * ----------------------------------------------------------------------------
  152. *
  153. * Copyright (c) 2009-2012, Pieter Noordhuis <pcnoordhuis at gmail dot com>
  154. * Copyright (c) 2009-2017, Salvatore Sanfilippo <antirez at gmail dot com>
  155. * All rights reserved.
  156. *
  157. * Redistribution and use in source and binary forms, with or without
  158. * modification, are permitted provided that the following conditions are met:
  159. *
  160. * * Redistributions of source code must retain the above copyright notice,
  161. * this list of conditions and the following disclaimer.
  162. * * Redistributions in binary form must reproduce the above copyright
  163. * notice, this list of conditions and the following disclaimer in the
  164. * documentation and/or other materials provided with the distribution.
  165. * * Neither the name of Redis nor the names of its contributors may be used
  166. * to endorse or promote products derived from this software without
  167. * specific prior written permission.
  168. *
  169. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  170. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  171. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  172. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  173. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  174. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  175. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  176. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  177. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  178. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  179. * POSSIBILITY OF SUCH DAMAGE.
  180. */
  181. #include <stdio.h>
  182. #include <stdlib.h>
  183. #include <string.h>
  184. #include <stdint.h>
  185. #include <limits.h>
  186. #include "zmalloc.h"
  187. #include "util.h"
  188. #include "ziplist.h"
  189. #include "endianconv.h"
  190. #include "redisassert.h"
  191. #define ZIP_END 255 /* Special "end of ziplist" entry. */
  192. #define ZIP_BIG_PREVLEN 254 /* Max number of bytes of the previous entry, for
  193. the "prevlen" field prefixing each entry, to be
  194. represented with just a single byte. Otherwise
  195. it is represented as FF AA BB CC DD, where
  196. AA BB CC DD are a 4 bytes unsigned integer
  197. representing the previous entry len. */
  198. /* Different encoding/length possibilities */
  199. #define ZIP_STR_MASK 0xc0
  200. #define ZIP_INT_MASK 0x30
  201. #define ZIP_STR_06B (0 << 6)
  202. #define ZIP_STR_14B (1 << 6)
  203. #define ZIP_STR_32B (2 << 6)
  204. #define ZIP_INT_16B (0xc0 | 0<<4)
  205. #define ZIP_INT_32B (0xc0 | 1<<4)
  206. #define ZIP_INT_64B (0xc0 | 2<<4)
  207. #define ZIP_INT_24B (0xc0 | 3<<4)
  208. #define ZIP_INT_8B 0xfe
  209. /* 4 bit integer immediate encoding |1111xxxx| with xxxx between
  210. * 0001 and 1101. */
  211. #define ZIP_INT_IMM_MASK 0x0f /* Mask to extract the 4 bits value. To add
  212. one is needed to reconstruct the value. */
  213. #define ZIP_INT_IMM_MIN 0xf1 /* 11110001 */
  214. #define ZIP_INT_IMM_MAX 0xfd /* 11111101 */
  215. #define INT24_MAX 0x7fffff
  216. #define INT24_MIN (-INT24_MAX - 1)
  217. /* Macro to determine if the entry is a string. String entries never start
  218. * with "11" as most significant bits of the first byte. */
  219. #define ZIP_IS_STR(enc) (((enc) & ZIP_STR_MASK) < ZIP_STR_MASK)
  220. /* Utility macros.*/
  221. /* Return total bytes a ziplist is composed of. */
  222. #define ZIPLIST_BYTES(zl) (*((uint32_t*)(zl)))
  223. /* Return the offset of the last item inside the ziplist. */
  224. #define ZIPLIST_TAIL_OFFSET(zl) (*((uint32_t*)((zl)+sizeof(uint32_t))))
  225. /* Return the length of a ziplist, or UINT16_MAX if the length cannot be
  226. * determined without scanning the whole ziplist. */
  227. #define ZIPLIST_LENGTH(zl) (*((uint16_t*)((zl)+sizeof(uint32_t)*2)))
  228. /* The size of a ziplist header: two 32 bit integers for the total
  229. * bytes count and last item offset. One 16 bit integer for the number
  230. * of items field. */
  231. #define ZIPLIST_HEADER_SIZE (sizeof(uint32_t)*2+sizeof(uint16_t))
  232. /* Size of the "end of ziplist" entry. Just one byte. */
  233. #define ZIPLIST_END_SIZE (sizeof(uint8_t))
  234. /* Return the pointer to the first entry of a ziplist. */
  235. #define ZIPLIST_ENTRY_HEAD(zl) ((zl)+ZIPLIST_HEADER_SIZE)
  236. /* Return the pointer to the last entry of a ziplist, using the
  237. * last entry offset inside the ziplist header. */
  238. #define ZIPLIST_ENTRY_TAIL(zl) ((zl)+intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl)))
  239. /* Return the pointer to the last byte of a ziplist, which is, the
  240. * end of ziplist FF entry. */
  241. #define ZIPLIST_ENTRY_END(zl) ((zl)+intrev32ifbe(ZIPLIST_BYTES(zl))-1)
  242. /* Increment the number of items field in the ziplist header. Note that this
  243. * macro should never overflow the unsigned 16 bit integer, since entries are
  244. * always pushed one at a time. When UINT16_MAX is reached we want the count
  245. * to stay there to signal that a full scan is needed to get the number of
  246. * items inside the ziplist. */
  247. #define ZIPLIST_INCR_LENGTH(zl,incr) { \
  248. if (ZIPLIST_LENGTH(zl) < UINT16_MAX) \
  249. ZIPLIST_LENGTH(zl) = intrev16ifbe(intrev16ifbe(ZIPLIST_LENGTH(zl))+incr); \
  250. }
  251. /* We use this function to receive information about a ziplist entry.
  252. * Note that this is not how the data is actually encoded, is just what we
  253. * get filled by a function in order to operate more easily. */
  254. typedef struct zlentry {
  255. unsigned int prevrawlensize; /* Bytes used to encode the previous entry len*/
  256. unsigned int prevrawlen; /* Previous entry len. */
  257. unsigned int lensize; /* Bytes used to encode this entry type/len.
  258. For example strings have a 1, 2 or 5 bytes
  259. header. Integers always use a single byte.*/
  260. unsigned int len; /* Bytes used to represent the actual entry.
  261. For strings this is just the string length
  262. while for integers it is 1, 2, 3, 4, 8 or
  263. 0 (for 4 bit immediate) depending on the
  264. number range. */
  265. unsigned int headersize; /* prevrawlensize + lensize. */
  266. unsigned char encoding; /* Set to ZIP_STR_* or ZIP_INT_* depending on
  267. the entry encoding. However for 4 bits
  268. immediate integers this can assume a range
  269. of values and must be range-checked. */
  270. unsigned char *p; /* Pointer to the very start of the entry, that
  271. is, this points to prev-entry-len field. */
  272. } zlentry;
  273. #define ZIPLIST_ENTRY_ZERO(zle) { \
  274. (zle)->prevrawlensize = (zle)->prevrawlen = 0; \
  275. (zle)->lensize = (zle)->len = (zle)->headersize = 0; \
  276. (zle)->encoding = 0; \
  277. (zle)->p = NULL; \
  278. }
  279. /* Extract the encoding from the byte pointed by 'ptr' and set it into
  280. * 'encoding' field of the zlentry structure. */
  281. #define ZIP_ENTRY_ENCODING(ptr, encoding) do { \
  282. (encoding) = (ptr[0]); \
  283. if ((encoding) < ZIP_STR_MASK) (encoding) &= ZIP_STR_MASK; \
  284. } while(0)
  285. /* Return bytes needed to store integer encoded by 'encoding'. */
  286. unsigned int zipIntSize(unsigned char encoding) {
  287. switch(encoding) {
  288. case ZIP_INT_8B: return 1;
  289. case ZIP_INT_16B: return 2;
  290. case ZIP_INT_24B: return 3;
  291. case ZIP_INT_32B: return 4;
  292. case ZIP_INT_64B: return 8;
  293. }
  294. if (encoding >= ZIP_INT_IMM_MIN && encoding <= ZIP_INT_IMM_MAX)
  295. return 0; /* 4 bit immediate */
  296. panic("Invalid integer encoding 0x%02X", encoding);
  297. return 0;
  298. }
  299. /* Write the encoidng header of the entry in 'p'. If p is NULL it just returns
  300. * the amount of bytes required to encode such a length. Arguments:
  301. *
  302. * 'encoding' is the encoding we are using for the entry. It could be
  303. * ZIP_INT_* or ZIP_STR_* or between ZIP_INT_IMM_MIN and ZIP_INT_IMM_MAX
  304. * for single-byte small immediate integers.
  305. *
  306. * 'rawlen' is only used for ZIP_STR_* encodings and is the length of the
  307. * srting that this entry represents.
  308. *
  309. * The function returns the number of bytes used by the encoding/length
  310. * header stored in 'p'. */
  311. unsigned int zipStoreEntryEncoding(unsigned char *p, unsigned char encoding, unsigned int rawlen) {
  312. unsigned char len = 1, buf[5];
  313. if (ZIP_IS_STR(encoding)) {
  314. /* Although encoding is given it may not be set for strings,
  315. * so we determine it here using the raw length. */
  316. if (rawlen <= 0x3f) {
  317. if (!p) return len;
  318. buf[0] = ZIP_STR_06B | rawlen;
  319. } else if (rawlen <= 0x3fff) {
  320. len += 1;
  321. if (!p) return len;
  322. buf[0] = ZIP_STR_14B | ((rawlen >> 8) & 0x3f);
  323. buf[1] = rawlen & 0xff;
  324. } else {
  325. len += 4;
  326. if (!p) return len;
  327. buf[0] = ZIP_STR_32B;
  328. buf[1] = (rawlen >> 24) & 0xff;
  329. buf[2] = (rawlen >> 16) & 0xff;
  330. buf[3] = (rawlen >> 8) & 0xff;
  331. buf[4] = rawlen & 0xff;
  332. }
  333. } else {
  334. /* Implies integer encoding, so length is always 1. */
  335. if (!p) return len;
  336. buf[0] = encoding;
  337. }
  338. /* Store this length at p. */
  339. memcpy(p,buf,len);
  340. return len;
  341. }
  342. /* Decode the entry encoding type and data length (string length for strings,
  343. * number of bytes used for the integer for integer entries) encoded in 'ptr'.
  344. * The 'encoding' variable will hold the entry encoding, the 'lensize'
  345. * variable will hold the number of bytes required to encode the entry
  346. * length, and the 'len' variable will hold the entry length. */
  347. #define ZIP_DECODE_LENGTH(ptr, encoding, lensize, len) do { \
  348. ZIP_ENTRY_ENCODING((ptr), (encoding)); \
  349. if ((encoding) < ZIP_STR_MASK) { \
  350. if ((encoding) == ZIP_STR_06B) { \
  351. (lensize) = 1; \
  352. (len) = (ptr)[0] & 0x3f; \
  353. } else if ((encoding) == ZIP_STR_14B) { \
  354. (lensize) = 2; \
  355. (len) = (((ptr)[0] & 0x3f) << 8) | (ptr)[1]; \
  356. } else if ((encoding) == ZIP_STR_32B) { \
  357. (lensize) = 5; \
  358. (len) = ((ptr)[1] << 24) | \
  359. ((ptr)[2] << 16) | \
  360. ((ptr)[3] << 8) | \
  361. ((ptr)[4]); \
  362. } else { \
  363. panic("Invalid string encoding 0x%02X", (encoding)); \
  364. } \
  365. } else { \
  366. (lensize) = 1; \
  367. (len) = zipIntSize(encoding); \
  368. } \
  369. } while(0);
  370. /* Encode the length of the previous entry and write it to "p". This only
  371. * uses the larger encoding (required in __ziplistCascadeUpdate). */
  372. int zipStorePrevEntryLengthLarge(unsigned char *p, unsigned int len) {
  373. if (p != NULL) {
  374. p[0] = ZIP_BIG_PREVLEN;
  375. memcpy(p+1,&len,sizeof(len));
  376. memrev32ifbe(p+1);
  377. }
  378. return 1+sizeof(len);
  379. }
  380. /* Encode the length of the previous entry and write it to "p". Return the
  381. * number of bytes needed to encode this length if "p" is NULL. */
  382. unsigned int zipStorePrevEntryLength(unsigned char *p, unsigned int len) {
  383. if (p == NULL) {
  384. return (len < ZIP_BIG_PREVLEN) ? 1 : sizeof(len)+1;
  385. } else {
  386. if (len < ZIP_BIG_PREVLEN) {
  387. p[0] = len;
  388. return 1;
  389. } else {
  390. return zipStorePrevEntryLengthLarge(p,len);
  391. }
  392. }
  393. }
  394. /* Return the number of bytes used to encode the length of the previous
  395. * entry. The length is returned by setting the var 'prevlensize'. */
  396. #define ZIP_DECODE_PREVLENSIZE(ptr, prevlensize) do { \
  397. if ((ptr)[0] < ZIP_BIG_PREVLEN) { \
  398. (prevlensize) = 1; \
  399. } else { \
  400. (prevlensize) = 5; \
  401. } \
  402. } while(0);
  403. /* Return the length of the previous element, and the number of bytes that
  404. * are used in order to encode the previous element length.
  405. * 'ptr' must point to the prevlen prefix of an entry (that encodes the
  406. * length of the previous entry in order to navigate the elements backward).
  407. * The length of the previous entry is stored in 'prevlen', the number of
  408. * bytes needed to encode the previous entry length are stored in
  409. * 'prevlensize'. */
  410. #define ZIP_DECODE_PREVLEN(ptr, prevlensize, prevlen) do { \
  411. ZIP_DECODE_PREVLENSIZE(ptr, prevlensize); \
  412. if ((prevlensize) == 1) { \
  413. (prevlen) = (ptr)[0]; \
  414. } else if ((prevlensize) == 5) { \
  415. assert(sizeof((prevlen)) == 4); \
  416. memcpy(&(prevlen), ((char*)(ptr)) + 1, 4); \
  417. memrev32ifbe(&prevlen); \
  418. } \
  419. } while(0);
  420. /* Given a pointer 'p' to the prevlen info that prefixes an entry, this
  421. * function returns the difference in number of bytes needed to encode
  422. * the prevlen if the previous entry changes of size.
  423. *
  424. * So if A is the number of bytes used right now to encode the 'prevlen'
  425. * field.
  426. *
  427. * And B is the number of bytes that are needed in order to encode the
  428. * 'prevlen' if the previous element will be updated to one of size 'len'.
  429. *
  430. * Then the function returns B - A
  431. *
  432. * So the function returns a positive number if more space is needed,
  433. * a negative number if less space is needed, or zero if the same space
  434. * is needed. */
  435. int zipPrevLenByteDiff(unsigned char *p, unsigned int len) {
  436. unsigned int prevlensize;
  437. ZIP_DECODE_PREVLENSIZE(p, prevlensize);
  438. return zipStorePrevEntryLength(NULL, len) - prevlensize;
  439. }
  440. /* Return the total number of bytes used by the entry pointed to by 'p'. */
  441. unsigned int zipRawEntryLength(unsigned char *p) {
  442. unsigned int prevlensize, encoding, lensize, len;
  443. ZIP_DECODE_PREVLENSIZE(p, prevlensize);
  444. ZIP_DECODE_LENGTH(p + prevlensize, encoding, lensize, len);
  445. return prevlensize + lensize + len;
  446. }
  447. /* Check if string pointed to by 'entry' can be encoded as an integer.
  448. * Stores the integer value in 'v' and its encoding in 'encoding'. */
  449. int zipTryEncoding(unsigned char *entry, unsigned int entrylen, long long *v, unsigned char *encoding) {
  450. long long value;
  451. if (entrylen >= 32 || entrylen == 0) return 0;
  452. if (string2ll((char*)entry,entrylen,&value)) {
  453. /* Great, the string can be encoded. Check what's the smallest
  454. * of our encoding types that can hold this value. */
  455. if (value >= 0 && value <= 12) {
  456. *encoding = ZIP_INT_IMM_MIN+value;
  457. } else if (value >= INT8_MIN && value <= INT8_MAX) {
  458. *encoding = ZIP_INT_8B;
  459. } else if (value >= INT16_MIN && value <= INT16_MAX) {
  460. *encoding = ZIP_INT_16B;
  461. } else if (value >= INT24_MIN && value <= INT24_MAX) {
  462. *encoding = ZIP_INT_24B;
  463. } else if (value >= INT32_MIN && value <= INT32_MAX) {
  464. *encoding = ZIP_INT_32B;
  465. } else {
  466. *encoding = ZIP_INT_64B;
  467. }
  468. *v = value;
  469. return 1;
  470. }
  471. return 0;
  472. }
  473. /* Store integer 'value' at 'p', encoded as 'encoding' */
  474. void zipSaveInteger(unsigned char *p, int64_t value, unsigned char encoding) {
  475. int16_t i16;
  476. int32_t i32;
  477. int64_t i64;
  478. if (encoding == ZIP_INT_8B) {
  479. ((int8_t*)p)[0] = (int8_t)value;
  480. } else if (encoding == ZIP_INT_16B) {
  481. i16 = value;
  482. memcpy(p,&i16,sizeof(i16));
  483. memrev16ifbe(p);
  484. } else if (encoding == ZIP_INT_24B) {
  485. i32 = value<<8;
  486. memrev32ifbe(&i32);
  487. memcpy(p,((uint8_t*)&i32)+1,sizeof(i32)-sizeof(uint8_t));
  488. } else if (encoding == ZIP_INT_32B) {
  489. i32 = value;
  490. memcpy(p,&i32,sizeof(i32));
  491. memrev32ifbe(p);
  492. } else if (encoding == ZIP_INT_64B) {
  493. i64 = value;
  494. memcpy(p,&i64,sizeof(i64));
  495. memrev64ifbe(p);
  496. } else if (encoding >= ZIP_INT_IMM_MIN && encoding <= ZIP_INT_IMM_MAX) {
  497. /* Nothing to do, the value is stored in the encoding itself. */
  498. } else {
  499. assert(NULL);
  500. }
  501. }
  502. /* Read integer encoded as 'encoding' from 'p' */
  503. int64_t zipLoadInteger(unsigned char *p, unsigned char encoding) {
  504. int16_t i16;
  505. int32_t i32;
  506. int64_t i64, ret = 0;
  507. if (encoding == ZIP_INT_8B) {
  508. ret = ((int8_t*)p)[0];
  509. } else if (encoding == ZIP_INT_16B) {
  510. memcpy(&i16,p,sizeof(i16));
  511. memrev16ifbe(&i16);
  512. ret = i16;
  513. } else if (encoding == ZIP_INT_32B) {
  514. memcpy(&i32,p,sizeof(i32));
  515. memrev32ifbe(&i32);
  516. ret = i32;
  517. } else if (encoding == ZIP_INT_24B) {
  518. i32 = 0;
  519. memcpy(((uint8_t*)&i32)+1,p,sizeof(i32)-sizeof(uint8_t));
  520. memrev32ifbe(&i32);
  521. ret = i32>>8;
  522. } else if (encoding == ZIP_INT_64B) {
  523. memcpy(&i64,p,sizeof(i64));
  524. memrev64ifbe(&i64);
  525. ret = i64;
  526. } else if (encoding >= ZIP_INT_IMM_MIN && encoding <= ZIP_INT_IMM_MAX) {
  527. ret = (encoding & ZIP_INT_IMM_MASK)-1;
  528. } else {
  529. assert(NULL);
  530. }
  531. return ret;
  532. }
  533. /* Return a struct with all information about an entry. */
  534. void zipEntry(unsigned char *p, zlentry *e) {
  535. ZIP_DECODE_PREVLEN(p, e->prevrawlensize, e->prevrawlen);
  536. ZIP_DECODE_LENGTH(p + e->prevrawlensize, e->encoding, e->lensize, e->len);
  537. e->headersize = e->prevrawlensize + e->lensize;
  538. e->p = p;
  539. }
  540. /* Create a new empty ziplist. */
  541. unsigned char *ziplistNew(void) {
  542. unsigned int bytes = ZIPLIST_HEADER_SIZE+ZIPLIST_END_SIZE;
  543. unsigned char *zl = zmalloc(bytes);
  544. ZIPLIST_BYTES(zl) = intrev32ifbe(bytes);
  545. ZIPLIST_TAIL_OFFSET(zl) = intrev32ifbe(ZIPLIST_HEADER_SIZE);
  546. ZIPLIST_LENGTH(zl) = 0;
  547. zl[bytes-1] = ZIP_END;
  548. return zl;
  549. }
  550. /* Resize the ziplist. */
  551. unsigned char *ziplistResize(unsigned char *zl, unsigned int len) {
  552. zl = zrealloc(zl,len);
  553. ZIPLIST_BYTES(zl) = intrev32ifbe(len);
  554. zl[len-1] = ZIP_END;
  555. return zl;
  556. }
  557. /* When an entry is inserted, we need to set the prevlen field of the next
  558. * entry to equal the length of the inserted entry. It can occur that this
  559. * length cannot be encoded in 1 byte and the next entry needs to be grow
  560. * a bit larger to hold the 5-byte encoded prevlen. This can be done for free,
  561. * because this only happens when an entry is already being inserted (which
  562. * causes a realloc and memmove). However, encoding the prevlen may require
  563. * that this entry is grown as well. This effect may cascade throughout
  564. * the ziplist when there are consecutive entries with a size close to
  565. * ZIP_BIG_PREVLEN, so we need to check that the prevlen can be encoded in
  566. * every consecutive entry.
  567. *
  568. * Note that this effect can also happen in reverse, where the bytes required
  569. * to encode the prevlen field can shrink. This effect is deliberately ignored,
  570. * because it can cause a "flapping" effect where a chain prevlen fields is
  571. * first grown and then shrunk again after consecutive inserts. Rather, the
  572. * field is allowed to stay larger than necessary, because a large prevlen
  573. * field implies the ziplist is holding large entries anyway.
  574. *
  575. * The pointer "p" points to the first entry that does NOT need to be
  576. * updated, i.e. consecutive fields MAY need an update. */
  577. unsigned char *__ziplistCascadeUpdate(unsigned char *zl, unsigned char *p) {
  578. size_t curlen = intrev32ifbe(ZIPLIST_BYTES(zl)), rawlen, rawlensize;
  579. size_t offset, noffset, extra;
  580. unsigned char *np;
  581. zlentry cur, next;
  582. while (p[0] != ZIP_END) {
  583. zipEntry(p, &cur);
  584. rawlen = cur.headersize + cur.len;
  585. rawlensize = zipStorePrevEntryLength(NULL,rawlen);
  586. /* Abort if there is no next entry. */
  587. if (p[rawlen] == ZIP_END) break;
  588. zipEntry(p+rawlen, &next);
  589. /* Abort when "prevlen" has not changed. */
  590. if (next.prevrawlen == rawlen) break;
  591. if (next.prevrawlensize < rawlensize) {
  592. /* The "prevlen" field of "next" needs more bytes to hold
  593. * the raw length of "cur". */
  594. offset = p-zl;
  595. extra = rawlensize-next.prevrawlensize;
  596. zl = ziplistResize(zl,curlen+extra);
  597. p = zl+offset;
  598. /* Current pointer and offset for next element. */
  599. np = p+rawlen;
  600. noffset = np-zl;
  601. /* Update tail offset when next element is not the tail element. */
  602. if ((zl+intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))) != np) {
  603. ZIPLIST_TAIL_OFFSET(zl) =
  604. intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+extra);
  605. }
  606. /* Move the tail to the back. */
  607. memmove(np+rawlensize,
  608. np+next.prevrawlensize,
  609. curlen-noffset-next.prevrawlensize-1);
  610. zipStorePrevEntryLength(np,rawlen);
  611. /* Advance the cursor */
  612. p += rawlen;
  613. curlen += extra;
  614. } else {
  615. if (next.prevrawlensize > rawlensize) {
  616. /* This would result in shrinking, which we want to avoid.
  617. * So, set "rawlen" in the available bytes. */
  618. zipStorePrevEntryLengthLarge(p+rawlen,rawlen);
  619. } else {
  620. zipStorePrevEntryLength(p+rawlen,rawlen);
  621. }
  622. /* Stop here, as the raw length of "next" has not changed. */
  623. break;
  624. }
  625. }
  626. return zl;
  627. }
  628. /* Delete "num" entries, starting at "p". Returns pointer to the ziplist. */
  629. unsigned char *__ziplistDelete(unsigned char *zl, unsigned char *p, unsigned int num) {
  630. unsigned int i, totlen, deleted = 0;
  631. size_t offset;
  632. int nextdiff = 0;
  633. zlentry first, tail;
  634. zipEntry(p, &first);
  635. for (i = 0; p[0] != ZIP_END && i < num; i++) {
  636. p += zipRawEntryLength(p);
  637. deleted++;
  638. }
  639. totlen = p-first.p; /* Bytes taken by the element(s) to delete. */
  640. if (totlen > 0) {
  641. if (p[0] != ZIP_END) {
  642. /* Storing `prevrawlen` in this entry may increase or decrease the
  643. * number of bytes required compare to the current `prevrawlen`.
  644. * There always is room to store this, because it was previously
  645. * stored by an entry that is now being deleted. */
  646. nextdiff = zipPrevLenByteDiff(p,first.prevrawlen);
  647. /* Note that there is always space when p jumps backward: if
  648. * the new previous entry is large, one of the deleted elements
  649. * had a 5 bytes prevlen header, so there is for sure at least
  650. * 5 bytes free and we need just 4. */
  651. p -= nextdiff;
  652. zipStorePrevEntryLength(p,first.prevrawlen);
  653. /* Update offset for tail */
  654. ZIPLIST_TAIL_OFFSET(zl) =
  655. intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))-totlen);
  656. /* When the tail contains more than one entry, we need to take
  657. * "nextdiff" in account as well. Otherwise, a change in the
  658. * size of prevlen doesn't have an effect on the *tail* offset. */
  659. zipEntry(p, &tail);
  660. if (p[tail.headersize+tail.len] != ZIP_END) {
  661. ZIPLIST_TAIL_OFFSET(zl) =
  662. intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+nextdiff);
  663. }
  664. /* Move tail to the front of the ziplist */
  665. memmove(first.p,p,
  666. intrev32ifbe(ZIPLIST_BYTES(zl))-(p-zl)-1);
  667. } else {
  668. /* The entire tail was deleted. No need to move memory. */
  669. ZIPLIST_TAIL_OFFSET(zl) =
  670. intrev32ifbe((first.p-zl)-first.prevrawlen);
  671. }
  672. /* Resize and update length */
  673. offset = first.p-zl;
  674. zl = ziplistResize(zl, intrev32ifbe(ZIPLIST_BYTES(zl))-totlen+nextdiff);
  675. ZIPLIST_INCR_LENGTH(zl,-deleted);
  676. p = zl+offset;
  677. /* When nextdiff != 0, the raw length of the next entry has changed, so
  678. * we need to cascade the update throughout the ziplist */
  679. if (nextdiff != 0)
  680. zl = __ziplistCascadeUpdate(zl,p);
  681. }
  682. return zl;
  683. }
  684. /* Insert item at "p". */
  685. unsigned char *__ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
  686. size_t curlen = intrev32ifbe(ZIPLIST_BYTES(zl)), reqlen;
  687. unsigned int prevlensize, prevlen = 0;
  688. size_t offset;
  689. int nextdiff = 0;
  690. unsigned char encoding = 0;
  691. long long value = 123456789; /* initialized to avoid warning. Using a value
  692. that is easy to see if for some reason
  693. we use it uninitialized. */
  694. zlentry tail;
  695. /* Find out prevlen for the entry that is inserted. */
  696. if (p[0] != ZIP_END) {
  697. ZIP_DECODE_PREVLEN(p, prevlensize, prevlen);
  698. } else {
  699. unsigned char *ptail = ZIPLIST_ENTRY_TAIL(zl);
  700. if (ptail[0] != ZIP_END) {
  701. prevlen = zipRawEntryLength(ptail);
  702. }
  703. }
  704. /* See if the entry can be encoded */
  705. if (zipTryEncoding(s,slen,&value,&encoding)) {
  706. /* 'encoding' is set to the appropriate integer encoding */
  707. reqlen = zipIntSize(encoding);
  708. } else {
  709. /* 'encoding' is untouched, however zipStoreEntryEncoding will use the
  710. * string length to figure out how to encode it. */
  711. reqlen = slen;
  712. }
  713. /* We need space for both the length of the previous entry and
  714. * the length of the payload. */
  715. reqlen += zipStorePrevEntryLength(NULL,prevlen);
  716. reqlen += zipStoreEntryEncoding(NULL,encoding,slen);
  717. /* When the insert position is not equal to the tail, we need to
  718. * make sure that the next entry can hold this entry's length in
  719. * its prevlen field. */
  720. int forcelarge = 0;
  721. nextdiff = (p[0] != ZIP_END) ? zipPrevLenByteDiff(p,reqlen) : 0;
  722. if (nextdiff == -4 && reqlen < 4) {
  723. nextdiff = 0;
  724. forcelarge = 1;
  725. }
  726. /* Store offset because a realloc may change the address of zl. */
  727. offset = p-zl;
  728. zl = ziplistResize(zl,curlen+reqlen+nextdiff);
  729. p = zl+offset;
  730. /* Apply memory move when necessary and update tail offset. */
  731. if (p[0] != ZIP_END) {
  732. /* Subtract one because of the ZIP_END bytes */
  733. memmove(p+reqlen,p-nextdiff,curlen-offset-1+nextdiff);
  734. /* Encode this entry's raw length in the next entry. */
  735. if (forcelarge)
  736. zipStorePrevEntryLengthLarge(p+reqlen,reqlen);
  737. else
  738. zipStorePrevEntryLength(p+reqlen,reqlen);
  739. /* Update offset for tail */
  740. ZIPLIST_TAIL_OFFSET(zl) =
  741. intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+reqlen);
  742. /* When the tail contains more than one entry, we need to take
  743. * "nextdiff" in account as well. Otherwise, a change in the
  744. * size of prevlen doesn't have an effect on the *tail* offset. */
  745. zipEntry(p+reqlen, &tail);
  746. if (p[reqlen+tail.headersize+tail.len] != ZIP_END) {
  747. ZIPLIST_TAIL_OFFSET(zl) =
  748. intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+nextdiff);
  749. }
  750. } else {
  751. /* This element will be the new tail. */
  752. ZIPLIST_TAIL_OFFSET(zl) = intrev32ifbe(p-zl);
  753. }
  754. /* When nextdiff != 0, the raw length of the next entry has changed, so
  755. * we need to cascade the update throughout the ziplist */
  756. if (nextdiff != 0) {
  757. offset = p-zl;
  758. zl = __ziplistCascadeUpdate(zl,p+reqlen);
  759. p = zl+offset;
  760. }
  761. /* Write the entry */
  762. p += zipStorePrevEntryLength(p,prevlen);
  763. p += zipStoreEntryEncoding(p,encoding,slen);
  764. if (ZIP_IS_STR(encoding)) {
  765. memcpy(p,s,slen);
  766. } else {
  767. zipSaveInteger(p,value,encoding);
  768. }
  769. ZIPLIST_INCR_LENGTH(zl,1);
  770. return zl;
  771. }
  772. /* Merge ziplists 'first' and 'second' by appending 'second' to 'first'.
  773. *
  774. * NOTE: The larger ziplist is reallocated to contain the new merged ziplist.
  775. * Either 'first' or 'second' can be used for the result. The parameter not
  776. * used will be free'd and set to NULL.
  777. *
  778. * After calling this function, the input parameters are no longer valid since
  779. * they are changed and free'd in-place.
  780. *
  781. * The result ziplist is the contents of 'first' followed by 'second'.
  782. *
  783. * On failure: returns NULL if the merge is impossible.
  784. * On success: returns the merged ziplist (which is expanded version of either
  785. * 'first' or 'second', also frees the other unused input ziplist, and sets the
  786. * input ziplist argument equal to newly reallocated ziplist return value. */
  787. unsigned char *ziplistMerge(unsigned char **first, unsigned char **second) {
  788. /* If any params are null, we can't merge, so NULL. */
  789. if (first == NULL || *first == NULL || second == NULL || *second == NULL)
  790. return NULL;
  791. /* Can't merge same list into itself. */
  792. if (*first == *second)
  793. return NULL;
  794. size_t first_bytes = intrev32ifbe(ZIPLIST_BYTES(*first));
  795. size_t first_len = intrev16ifbe(ZIPLIST_LENGTH(*first));
  796. size_t second_bytes = intrev32ifbe(ZIPLIST_BYTES(*second));
  797. size_t second_len = intrev16ifbe(ZIPLIST_LENGTH(*second));
  798. int append;
  799. unsigned char *source, *target;
  800. size_t target_bytes, source_bytes;
  801. /* Pick the largest ziplist so we can resize easily in-place.
  802. * We must also track if we are now appending or prepending to
  803. * the target ziplist. */
  804. if (first_len >= second_len) {
  805. /* retain first, append second to first. */
  806. target = *first;
  807. target_bytes = first_bytes;
  808. source = *second;
  809. source_bytes = second_bytes;
  810. append = 1;
  811. } else {
  812. /* else, retain second, prepend first to second. */
  813. target = *second;
  814. target_bytes = second_bytes;
  815. source = *first;
  816. source_bytes = first_bytes;
  817. append = 0;
  818. }
  819. /* Calculate final bytes (subtract one pair of metadata) */
  820. size_t zlbytes = first_bytes + second_bytes -
  821. ZIPLIST_HEADER_SIZE - ZIPLIST_END_SIZE;
  822. size_t zllength = first_len + second_len;
  823. /* Combined zl length should be limited within UINT16_MAX */
  824. zllength = zllength < UINT16_MAX ? zllength : UINT16_MAX;
  825. /* Save offset positions before we start ripping memory apart. */
  826. size_t first_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*first));
  827. size_t second_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*second));
  828. /* Extend target to new zlbytes then append or prepend source. */
  829. target = zrealloc(target, zlbytes);
  830. if (append) {
  831. /* append == appending to target */
  832. /* Copy source after target (copying over original [END]):
  833. * [TARGET - END, SOURCE - HEADER] */
  834. memcpy(target + target_bytes - ZIPLIST_END_SIZE,
  835. source + ZIPLIST_HEADER_SIZE,
  836. source_bytes - ZIPLIST_HEADER_SIZE);
  837. } else {
  838. /* !append == prepending to target */
  839. /* Move target *contents* exactly size of (source - [END]),
  840. * then copy source into vacataed space (source - [END]):
  841. * [SOURCE - END, TARGET - HEADER] */
  842. memmove(target + source_bytes - ZIPLIST_END_SIZE,
  843. target + ZIPLIST_HEADER_SIZE,
  844. target_bytes - ZIPLIST_HEADER_SIZE);
  845. memcpy(target, source, source_bytes - ZIPLIST_END_SIZE);
  846. }
  847. /* Update header metadata. */
  848. ZIPLIST_BYTES(target) = intrev32ifbe(zlbytes);
  849. ZIPLIST_LENGTH(target) = intrev16ifbe(zllength);
  850. /* New tail offset is:
  851. * + N bytes of first ziplist
  852. * - 1 byte for [END] of first ziplist
  853. * + M bytes for the offset of the original tail of the second ziplist
  854. * - J bytes for HEADER because second_offset keeps no header. */
  855. ZIPLIST_TAIL_OFFSET(target) = intrev32ifbe(
  856. (first_bytes - ZIPLIST_END_SIZE) +
  857. (second_offset - ZIPLIST_HEADER_SIZE));
  858. /* __ziplistCascadeUpdate just fixes the prev length values until it finds a
  859. * correct prev length value (then it assumes the rest of the list is okay).
  860. * We tell CascadeUpdate to start at the first ziplist's tail element to fix
  861. * the merge seam. */
  862. target = __ziplistCascadeUpdate(target, target+first_offset);
  863. /* Now free and NULL out what we didn't realloc */
  864. if (append) {
  865. zfree(*second);
  866. *second = NULL;
  867. *first = target;
  868. } else {
  869. zfree(*first);
  870. *first = NULL;
  871. *second = target;
  872. }
  873. return target;
  874. }
  875. unsigned char *ziplistPush(unsigned char *zl, unsigned char *s, unsigned int slen, int where) {
  876. unsigned char *p;
  877. p = (where == ZIPLIST_HEAD) ? ZIPLIST_ENTRY_HEAD(zl) : ZIPLIST_ENTRY_END(zl);
  878. return __ziplistInsert(zl,p,s,slen);
  879. }
  880. /* Returns an offset to use for iterating with ziplistNext. When the given
  881. * index is negative, the list is traversed back to front. When the list
  882. * doesn't contain an element at the provided index, NULL is returned. */
  883. unsigned char *ziplistIndex(unsigned char *zl, int index) {
  884. unsigned char *p;
  885. unsigned int prevlensize, prevlen = 0;
  886. if (index < 0) {
  887. index = (-index)-1;
  888. p = ZIPLIST_ENTRY_TAIL(zl);
  889. if (p[0] != ZIP_END) {
  890. ZIP_DECODE_PREVLEN(p, prevlensize, prevlen);
  891. while (prevlen > 0 && index--) {
  892. p -= prevlen;
  893. ZIP_DECODE_PREVLEN(p, prevlensize, prevlen);
  894. }
  895. }
  896. } else {
  897. p = ZIPLIST_ENTRY_HEAD(zl);
  898. while (p[0] != ZIP_END && index--) {
  899. p += zipRawEntryLength(p);
  900. }
  901. }
  902. return (p[0] == ZIP_END || index > 0) ? NULL : p;
  903. }
  904. /* Return pointer to next entry in ziplist.
  905. *
  906. * zl is the pointer to the ziplist
  907. * p is the pointer to the current element
  908. *
  909. * The element after 'p' is returned, otherwise NULL if we are at the end. */
  910. unsigned char *ziplistNext(unsigned char *zl, unsigned char *p) {
  911. ((void) zl);
  912. /* "p" could be equal to ZIP_END, caused by ziplistDelete,
  913. * and we should return NULL. Otherwise, we should return NULL
  914. * when the *next* element is ZIP_END (there is no next entry). */
  915. if (p[0] == ZIP_END) {
  916. return NULL;
  917. }
  918. p += zipRawEntryLength(p);
  919. if (p[0] == ZIP_END) {
  920. return NULL;
  921. }
  922. return p;
  923. }
  924. /* Return pointer to previous entry in ziplist. */
  925. unsigned char *ziplistPrev(unsigned char *zl, unsigned char *p) {
  926. unsigned int prevlensize, prevlen = 0;
  927. /* Iterating backwards from ZIP_END should return the tail. When "p" is
  928. * equal to the first element of the list, we're already at the head,
  929. * and should return NULL. */
  930. if (p[0] == ZIP_END) {
  931. p = ZIPLIST_ENTRY_TAIL(zl);
  932. return (p[0] == ZIP_END) ? NULL : p;
  933. } else if (p == ZIPLIST_ENTRY_HEAD(zl)) {
  934. return NULL;
  935. } else {
  936. ZIP_DECODE_PREVLEN(p, prevlensize, prevlen);
  937. assert(prevlen > 0);
  938. return p-prevlen;
  939. }
  940. }
  941. /* Get entry pointed to by 'p' and store in either '*sstr' or 'sval' depending
  942. * on the encoding of the entry. '*sstr' is always set to NULL to be able
  943. * to find out whether the string pointer or the integer value was set.
  944. * Return 0 if 'p' points to the end of the ziplist, 1 otherwise. */
  945. unsigned int ziplistGet(unsigned char *p, unsigned char **sstr, unsigned int *slen, long long *sval) {
  946. zlentry entry;
  947. if (p == NULL || p[0] == ZIP_END) return 0;
  948. if (sstr) *sstr = NULL;
  949. zipEntry(p, &entry);
  950. if (ZIP_IS_STR(entry.encoding)) {
  951. if (sstr) {
  952. *slen = entry.len;
  953. *sstr = p+entry.headersize;
  954. }
  955. } else {
  956. if (sval) {
  957. *sval = zipLoadInteger(p+entry.headersize,entry.encoding);
  958. }
  959. }
  960. return 1;
  961. }
  962. /* Insert an entry at "p". */
  963. unsigned char *ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
  964. return __ziplistInsert(zl,p,s,slen);
  965. }
  966. /* Delete a single entry from the ziplist, pointed to by *p.
  967. * Also update *p in place, to be able to iterate over the
  968. * ziplist, while deleting entries. */
  969. unsigned char *ziplistDelete(unsigned char *zl, unsigned char **p) {
  970. size_t offset = *p-zl;
  971. zl = __ziplistDelete(zl,*p,1);
  972. /* Store pointer to current element in p, because ziplistDelete will
  973. * do a realloc which might result in a different "zl"-pointer.
  974. * When the delete direction is back to front, we might delete the last
  975. * entry and end up with "p" pointing to ZIP_END, so check this. */
  976. *p = zl+offset;
  977. return zl;
  978. }
  979. /* Delete a range of entries from the ziplist. */
  980. unsigned char *ziplistDeleteRange(unsigned char *zl, int index, unsigned int num) {
  981. unsigned char *p = ziplistIndex(zl,index);
  982. return (p == NULL) ? zl : __ziplistDelete(zl,p,num);
  983. }
  984. /* Compare entry pointer to by 'p' with 'sstr' of length 'slen'. */
  985. /* Return 1 if equal. */
  986. unsigned int ziplistCompare(unsigned char *p, unsigned char *sstr, unsigned int slen) {
  987. zlentry entry;
  988. unsigned char sencoding;
  989. long long zval, sval;
  990. if (p[0] == ZIP_END) return 0;
  991. zipEntry(p, &entry);
  992. if (ZIP_IS_STR(entry.encoding)) {
  993. /* Raw compare */
  994. if (entry.len == slen) {
  995. return memcmp(p+entry.headersize,sstr,slen) == 0;
  996. } else {
  997. return 0;
  998. }
  999. } else {
  1000. /* Try to compare encoded values. Don't compare encoding because
  1001. * different implementations may encoded integers differently. */
  1002. if (zipTryEncoding(sstr,slen,&sval,&sencoding)) {
  1003. zval = zipLoadInteger(p+entry.headersize,entry.encoding);
  1004. return zval == sval;
  1005. }
  1006. }
  1007. return 0;
  1008. }
  1009. /* Find pointer to the entry equal to the specified entry. Skip 'skip' entries
  1010. * between every comparison. Returns NULL when the field could not be found. */
  1011. unsigned char *ziplistFind(unsigned char *p, unsigned char *vstr, unsigned int vlen, unsigned int skip) {
  1012. int skipcnt = 0;
  1013. unsigned char vencoding = 0;
  1014. long long vll = 0;
  1015. while (p[0] != ZIP_END) {
  1016. unsigned int prevlensize, encoding, lensize, len;
  1017. unsigned char *q;
  1018. ZIP_DECODE_PREVLENSIZE(p, prevlensize);
  1019. ZIP_DECODE_LENGTH(p + prevlensize, encoding, lensize, len);
  1020. q = p + prevlensize + lensize;
  1021. if (skipcnt == 0) {
  1022. /* Compare current entry with specified entry */
  1023. if (ZIP_IS_STR(encoding)) {
  1024. if (len == vlen && memcmp(q, vstr, vlen) == 0) {
  1025. return p;
  1026. }
  1027. } else {
  1028. /* Find out if the searched field can be encoded. Note that
  1029. * we do it only the first time, once done vencoding is set
  1030. * to non-zero and vll is set to the integer value. */
  1031. if (vencoding == 0) {
  1032. if (!zipTryEncoding(vstr, vlen, &vll, &vencoding)) {
  1033. /* If the entry can't be encoded we set it to
  1034. * UCHAR_MAX so that we don't retry again the next
  1035. * time. */
  1036. vencoding = UCHAR_MAX;
  1037. }
  1038. /* Must be non-zero by now */
  1039. assert(vencoding);
  1040. }
  1041. /* Compare current entry with specified entry, do it only
  1042. * if vencoding != UCHAR_MAX because if there is no encoding
  1043. * possible for the field it can't be a valid integer. */
  1044. if (vencoding != UCHAR_MAX) {
  1045. long long ll = zipLoadInteger(q, encoding);
  1046. if (ll == vll) {
  1047. return p;
  1048. }
  1049. }
  1050. }
  1051. /* Reset skip count */
  1052. skipcnt = skip;
  1053. } else {
  1054. /* Skip entry */
  1055. skipcnt--;
  1056. }
  1057. /* Move to next entry */
  1058. p = q + len;
  1059. }
  1060. return NULL;
  1061. }
  1062. /* Return length of ziplist. */
  1063. unsigned int ziplistLen(unsigned char *zl) {
  1064. unsigned int len = 0;
  1065. if (intrev16ifbe(ZIPLIST_LENGTH(zl)) < UINT16_MAX) {
  1066. len = intrev16ifbe(ZIPLIST_LENGTH(zl));
  1067. } else {
  1068. unsigned char *p = zl+ZIPLIST_HEADER_SIZE;
  1069. while (*p != ZIP_END) {
  1070. p += zipRawEntryLength(p);
  1071. len++;
  1072. }
  1073. /* Re-store length if small enough */
  1074. if (len < UINT16_MAX) ZIPLIST_LENGTH(zl) = intrev16ifbe(len);
  1075. }
  1076. return len;
  1077. }
  1078. /* Return ziplist blob size in bytes. */
  1079. size_t ziplistBlobLen(unsigned char *zl) {
  1080. return intrev32ifbe(ZIPLIST_BYTES(zl));
  1081. }
  1082. void ziplistRepr(unsigned char *zl) {
  1083. unsigned char *p;
  1084. int index = 0;
  1085. zlentry entry;
  1086. printf(
  1087. "{total bytes %d} "
  1088. "{num entries %u}\n"
  1089. "{tail offset %u}\n",
  1090. intrev32ifbe(ZIPLIST_BYTES(zl)),
  1091. intrev16ifbe(ZIPLIST_LENGTH(zl)),
  1092. intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl)));
  1093. p = ZIPLIST_ENTRY_HEAD(zl);
  1094. while(*p != ZIP_END) {
  1095. zipEntry(p, &entry);
  1096. printf(
  1097. "{\n"
  1098. "\taddr 0x%08lx,\n"
  1099. "\tindex %2d,\n"
  1100. "\toffset %5ld,\n"
  1101. "\thdr+entry len: %5u,\n"
  1102. "\thdr len%2u,\n"
  1103. "\tprevrawlen: %5u,\n"
  1104. "\tprevrawlensize: %2u,\n"
  1105. "\tpayload %5u\n",
  1106. (long unsigned)p,
  1107. index,
  1108. (unsigned long) (p-zl),
  1109. entry.headersize+entry.len,
  1110. entry.headersize,
  1111. entry.prevrawlen,
  1112. entry.prevrawlensize,
  1113. entry.len);
  1114. printf("\tbytes: ");
  1115. for (unsigned int i = 0; i < entry.headersize+entry.len; i++) {
  1116. printf("%02x|",p[i]);
  1117. }
  1118. printf("\n");
  1119. p += entry.headersize;
  1120. if (ZIP_IS_STR(entry.encoding)) {
  1121. printf("\t[str]");
  1122. if (entry.len > 40) {
  1123. if (fwrite(p,40,1,stdout) == 0) perror("fwrite");
  1124. printf("...");
  1125. } else {
  1126. if (entry.len &&
  1127. fwrite(p,entry.len,1,stdout) == 0) perror("fwrite");
  1128. }
  1129. } else {
  1130. printf("\t[int]%lld", (long long) zipLoadInteger(p,entry.encoding));
  1131. }
  1132. printf("\n}\n");
  1133. p += entry.len;
  1134. index++;
  1135. }
  1136. printf("{end}\n\n");
  1137. }
  1138. #ifdef REDIS_TEST
  1139. #include <sys/time.h>
  1140. #include "adlist.h"
  1141. #include "sds.h"
  1142. #define debug(f, ...) { if (DEBUG) printf(f, __VA_ARGS__); }
  1143. static unsigned char *createList() {
  1144. unsigned char *zl = ziplistNew();
  1145. zl = ziplistPush(zl, (unsigned char*)"foo", 3, ZIPLIST_TAIL);
  1146. zl = ziplistPush(zl, (unsigned char*)"quux", 4, ZIPLIST_TAIL);
  1147. zl = ziplistPush(zl, (unsigned char*)"hello", 5, ZIPLIST_HEAD);
  1148. zl = ziplistPush(zl, (unsigned char*)"1024", 4, ZIPLIST_TAIL);
  1149. return zl;
  1150. }
  1151. static unsigned char *createIntList() {
  1152. unsigned char *zl = ziplistNew();
  1153. char buf[32];
  1154. sprintf(buf, "100");
  1155. zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
  1156. sprintf(buf, "128000");
  1157. zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
  1158. sprintf(buf, "-100");
  1159. zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_HEAD);
  1160. sprintf(buf, "4294967296");
  1161. zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_HEAD);
  1162. sprintf(buf, "non integer");
  1163. zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
  1164. sprintf(buf, "much much longer non integer");
  1165. zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
  1166. return zl;
  1167. }
  1168. static long long usec(void) {
  1169. struct timeval tv;
  1170. gettimeofday(&tv,NULL);
  1171. return (((long long)tv.tv_sec)*1000000)+tv.tv_usec;
  1172. }
  1173. static void stress(int pos, int num, int maxsize, int dnum) {
  1174. int i,j,k;
  1175. unsigned char *zl;
  1176. char posstr[2][5] = { "HEAD", "TAIL" };
  1177. long long start;
  1178. for (i = 0; i < maxsize; i+=dnum) {
  1179. zl = ziplistNew();
  1180. for (j = 0; j < i; j++) {
  1181. zl = ziplistPush(zl,(unsigned char*)"quux",4,ZIPLIST_TAIL);
  1182. }
  1183. /* Do num times a push+pop from pos */
  1184. start = usec();
  1185. for (k = 0; k < num; k++) {
  1186. zl = ziplistPush(zl,(unsigned char*)"quux",4,pos);
  1187. zl = ziplistDeleteRange(zl,0,1);
  1188. }
  1189. printf("List size: %8d, bytes: %8d, %dx push+pop (%s): %6lld usec\n",
  1190. i,intrev32ifbe(ZIPLIST_BYTES(zl)),num,posstr[pos],usec()-start);
  1191. zfree(zl);
  1192. }
  1193. }
  1194. static unsigned char *pop(unsigned char *zl, int where) {
  1195. unsigned char *p, *vstr;
  1196. unsigned int vlen;
  1197. long long vlong;
  1198. p = ziplistIndex(zl,where == ZIPLIST_HEAD ? 0 : -1);
  1199. if (ziplistGet(p,&vstr,&vlen,&vlong)) {
  1200. if (where == ZIPLIST_HEAD)
  1201. printf("Pop head: ");
  1202. else
  1203. printf("Pop tail: ");
  1204. if (vstr) {
  1205. if (vlen && fwrite(vstr,vlen,1,stdout) == 0) perror("fwrite");
  1206. }
  1207. else {
  1208. printf("%lld", vlong);
  1209. }
  1210. printf("\n");
  1211. return ziplistDelete(zl,&p);
  1212. } else {
  1213. printf("ERROR: Could not pop\n");
  1214. exit(1);
  1215. }
  1216. }
  1217. static int randstring(char *target, unsigned int min, unsigned int max) {
  1218. int p = 0;
  1219. int len = min+rand()%(max-min+1);
  1220. int minval, maxval;
  1221. switch(rand() % 3) {
  1222. case 0:
  1223. minval = 0;
  1224. maxval = 255;
  1225. break;
  1226. case 1:
  1227. minval = 48;
  1228. maxval = 122;
  1229. break;
  1230. case 2:
  1231. minval = 48;
  1232. maxval = 52;
  1233. break;
  1234. default:
  1235. assert(NULL);
  1236. }
  1237. while(p < len)
  1238. target[p++] = minval+rand()%(maxval-minval+1);
  1239. return len;
  1240. }
  1241. static void verify(unsigned char *zl, zlentry *e) {
  1242. int len = ziplistLen(zl);
  1243. zlentry _e;
  1244. ZIPLIST_ENTRY_ZERO(&_e);
  1245. for (int i = 0; i < len; i++) {
  1246. memset(&e[i], 0, sizeof(zlentry));
  1247. zipEntry(ziplistIndex(zl, i), &e[i]);
  1248. memset(&_e, 0, sizeof(zlentry));
  1249. zipEntry(ziplistIndex(zl, -len+i), &_e);
  1250. assert(memcmp(&e[i], &_e, sizeof(zlentry)) == 0);
  1251. }
  1252. }
  1253. int ziplistTest(int argc, char **argv) {
  1254. unsigned char *zl, *p;
  1255. unsigned char *entry;
  1256. unsigned int elen;
  1257. long long value;
  1258. /* If an argument is given, use it as the random seed. */
  1259. if (argc == 2)
  1260. srand(atoi(argv[1]));
  1261. zl = createIntList();
  1262. ziplistRepr(zl);
  1263. zfree(zl);
  1264. zl = createList();
  1265. ziplistRepr(zl);
  1266. zl = pop(zl,ZIPLIST_TAIL);
  1267. ziplistRepr(zl);
  1268. zl = pop(zl,ZIPLIST_HEAD);
  1269. ziplistRepr(zl);
  1270. zl = pop(zl,ZIPLIST_TAIL);
  1271. ziplistRepr(zl);
  1272. zl = pop(zl,ZIPLIST_TAIL);
  1273. ziplistRepr(zl);
  1274. zfree(zl);
  1275. printf("Get element at index 3:\n");
  1276. {
  1277. zl = createList();
  1278. p = ziplistIndex(zl, 3);
  1279. if (!ziplistGet(p, &entry, &elen, &value)) {
  1280. printf("ERROR: Could not access index 3\n");
  1281. return 1;
  1282. }
  1283. if (entry) {
  1284. if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
  1285. printf("\n");
  1286. } else {
  1287. printf("%lld\n", value);
  1288. }
  1289. printf("\n");
  1290. zfree(zl);
  1291. }
  1292. printf("Get element at index 4 (out of range):\n");
  1293. {
  1294. zl = createList();
  1295. p = ziplistIndex(zl, 4);
  1296. if (p == NULL) {
  1297. printf("No entry\n");
  1298. } else {
  1299. printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
  1300. return 1;
  1301. }
  1302. printf("\n");
  1303. zfree(zl);
  1304. }
  1305. printf("Get element at index -1 (last element):\n");
  1306. {
  1307. zl = createList();
  1308. p = ziplistIndex(zl, -1);
  1309. if (!ziplistGet(p, &entry, &elen, &value)) {
  1310. printf("ERROR: Could not access index -1\n");
  1311. return 1;
  1312. }
  1313. if (entry) {
  1314. if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
  1315. printf("\n");
  1316. } else {
  1317. printf("%lld\n", value);
  1318. }
  1319. printf("\n");
  1320. zfree(zl);
  1321. }
  1322. printf("Get element at index -4 (first element):\n");
  1323. {
  1324. zl = createList();
  1325. p = ziplistIndex(zl, -4);
  1326. if (!ziplistGet(p, &entry, &elen, &value)) {
  1327. printf("ERROR: Could not access index -4\n");
  1328. return 1;
  1329. }
  1330. if (entry) {
  1331. if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
  1332. printf("\n");
  1333. } else {
  1334. printf("%lld\n", value);
  1335. }
  1336. printf("\n");
  1337. zfree(zl);
  1338. }
  1339. printf("Get element at index -5 (reverse out of range):\n");
  1340. {
  1341. zl = createList();
  1342. p = ziplistIndex(zl, -5);
  1343. if (p == NULL) {
  1344. printf("No entry\n");
  1345. } else {
  1346. printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
  1347. return 1;
  1348. }
  1349. printf("\n");
  1350. zfree(zl);
  1351. }
  1352. printf("Iterate list from 0 to end:\n");
  1353. {
  1354. zl = createList();
  1355. p = ziplistIndex(zl, 0);
  1356. while (ziplistGet(p, &entry, &elen, &value)) {
  1357. printf("Entry: ");
  1358. if (entry) {
  1359. if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
  1360. } else {
  1361. printf("%lld", value);
  1362. }
  1363. p = ziplistNext(zl,p);
  1364. printf("\n");
  1365. }
  1366. printf("\n");
  1367. zfree(zl);
  1368. }
  1369. printf("Iterate list from 1 to end:\n");
  1370. {
  1371. zl = createList();
  1372. p = ziplistIndex(zl, 1);
  1373. while (ziplistGet(p, &entry, &elen, &value)) {
  1374. printf("Entry: ");
  1375. if (entry) {
  1376. if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
  1377. } else {
  1378. printf("%lld", value);
  1379. }
  1380. p = ziplistNext(zl,p);
  1381. printf("\n");
  1382. }
  1383. printf("\n");
  1384. zfree(zl);
  1385. }
  1386. printf("Iterate list from 2 to end:\n");
  1387. {
  1388. zl = createList();
  1389. p = ziplistIndex(zl, 2);
  1390. while (ziplistGet(p, &entry, &elen, &value)) {
  1391. printf("Entry: ");
  1392. if (entry) {
  1393. if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
  1394. } else {
  1395. printf("%lld", value);
  1396. }
  1397. p = ziplistNext(zl,p);
  1398. printf("\n");
  1399. }
  1400. printf("\n");
  1401. zfree(zl);
  1402. }
  1403. printf("Iterate starting out of range:\n");
  1404. {
  1405. zl = createList();
  1406. p = ziplistIndex(zl, 4);
  1407. if (!ziplistGet(p, &entry, &elen, &value)) {
  1408. printf("No entry\n");
  1409. } else {
  1410. printf("ERROR\n");
  1411. }
  1412. printf("\n");
  1413. zfree(zl);
  1414. }
  1415. printf("Iterate from back to front:\n");
  1416. {
  1417. zl = createList();
  1418. p = ziplistIndex(zl, -1);
  1419. while (ziplistGet(p, &entry, &elen, &value)) {
  1420. printf("Entry: ");
  1421. if (entry) {
  1422. if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
  1423. } else {
  1424. printf("%lld", value);
  1425. }
  1426. p = ziplistPrev(zl,p);
  1427. printf("\n");
  1428. }
  1429. printf("\n");
  1430. zfree(zl);
  1431. }
  1432. printf("Iterate from back to front, deleting all items:\n");
  1433. {
  1434. zl = createList();
  1435. p = ziplistIndex(zl, -1);
  1436. while (ziplistGet(p, &entry, &elen, &value)) {
  1437. printf("Entry: ");
  1438. if (entry) {
  1439. if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
  1440. } else {
  1441. printf("%lld", value);
  1442. }
  1443. zl = ziplistDelete(zl,&p);
  1444. p = ziplistPrev(zl,p);
  1445. printf("\n");
  1446. }
  1447. printf("\n");
  1448. zfree(zl);
  1449. }
  1450. printf("Delete inclusive range 0,0:\n");
  1451. {
  1452. zl = createList();
  1453. zl = ziplistDeleteRange(zl, 0, 1);
  1454. ziplistRepr(zl);
  1455. zfree(zl);
  1456. }
  1457. printf("Delete inclusive range 0,1:\n");
  1458. {
  1459. zl = createList();
  1460. zl = ziplistDeleteRange(zl, 0, 2);
  1461. ziplistRepr(zl);
  1462. zfree(zl);
  1463. }
  1464. printf("Delete inclusive range 1,2:\n");
  1465. {
  1466. zl = createList();
  1467. zl = ziplistDeleteRange(zl, 1, 2);
  1468. ziplistRepr(zl);
  1469. zfree(zl);
  1470. }
  1471. printf("Delete with start index out of range:\n");
  1472. {
  1473. zl = createList();
  1474. zl = ziplistDeleteRange(zl, 5, 1);
  1475. ziplistRepr(zl);
  1476. zfree(zl);
  1477. }
  1478. printf("Delete with num overflow:\n");
  1479. {
  1480. zl = createList();
  1481. zl = ziplistDeleteRange(zl, 1, 5);
  1482. ziplistRepr(zl);
  1483. zfree(zl);
  1484. }
  1485. printf("Delete foo while iterating:\n");
  1486. {
  1487. zl = createList();
  1488. p = ziplistIndex(zl,0);
  1489. while (ziplistGet(p,&entry,&elen,&value)) {
  1490. if (entry && strncmp("foo",(char*)entry,elen) == 0) {
  1491. printf("Delete foo\n");
  1492. zl = ziplistDelete(zl,&p);
  1493. } else {
  1494. printf("Entry: ");
  1495. if (entry) {
  1496. if (elen && fwrite(entry,elen,1,stdout) == 0)
  1497. perror("fwrite");
  1498. } else {
  1499. printf("%lld",value);
  1500. }
  1501. p = ziplistNext(zl,p);
  1502. printf("\n");
  1503. }
  1504. }
  1505. printf("\n");
  1506. ziplistRepr(zl);
  1507. zfree(zl);
  1508. }
  1509. printf("Regression test for >255 byte strings:\n");
  1510. {
  1511. char v1[257] = {0}, v2[257] = {0};
  1512. memset(v1,'x',256);
  1513. memset(v2,'y',256);
  1514. zl = ziplistNew();
  1515. zl = ziplistPush(zl,(unsigned char*)v1,strlen(v1),ZIPLIST_TAIL);
  1516. zl = ziplistPush(zl,(unsigned char*)v2,strlen(v2),ZIPLIST_TAIL);
  1517. /* Pop values again and compare their value. */
  1518. p = ziplistIndex(zl,0);
  1519. assert(ziplistGet(p,&entry,&elen,&value));
  1520. assert(strncmp(v1,(char*)entry,elen) == 0);
  1521. p = ziplistIndex(zl,1);
  1522. assert(ziplistGet(p,&entry,&elen,&value));
  1523. assert(strncmp(v2,(char*)entry,elen) == 0);
  1524. printf("SUCCESS\n\n");
  1525. zfree(zl);
  1526. }
  1527. printf("Regression test deleting next to last entries:\n");
  1528. {
  1529. char v[3][257] = {{0}};
  1530. zlentry e[3] = {{.prevrawlensize = 0, .prevrawlen = 0, .lensize = 0,
  1531. .len = 0, .headersize = 0, .encoding = 0, .p = NULL}};
  1532. size_t i;
  1533. for (i = 0; i < (sizeof(v)/sizeof(v[0])); i++) {
  1534. memset(v[i], 'a' + i, sizeof(v[0]));
  1535. }
  1536. v[0][256] = '\0';
  1537. v[1][ 1] = '\0';
  1538. v[2][256] = '\0';
  1539. zl = ziplistNew();
  1540. for (i = 0; i < (sizeof(v)/sizeof(v[0])); i++) {
  1541. zl = ziplistPush(zl, (unsigned char *) v[i], strlen(v[i]), ZIPLIST_TAIL);
  1542. }
  1543. verify(zl, e);
  1544. assert(e[0].prevrawlensize == 1);
  1545. assert(e[1].prevrawlensize == 5);
  1546. assert(e[2].prevrawlensize == 1);
  1547. /* Deleting entry 1 will increase `prevrawlensize` for entry 2 */
  1548. unsigned char *p = e[1].p;
  1549. zl = ziplistDelete(zl, &p);
  1550. verify(zl, e);
  1551. assert(e[0].prevrawlensize == 1);
  1552. assert(e[1].prevrawlensize == 5);
  1553. printf("SUCCESS\n\n");
  1554. zfree(zl);
  1555. }
  1556. printf("Create long list and check indices:\n");
  1557. {
  1558. zl = ziplistNew();
  1559. char buf[32];
  1560. int i,len;
  1561. for (i = 0; i < 1000; i++) {
  1562. len = sprintf(buf,"%d",i);
  1563. zl = ziplistPush(zl,(unsigned char*)buf,len,ZIPLIST_TAIL);
  1564. }
  1565. for (i = 0; i < 1000; i++) {
  1566. p = ziplistIndex(zl,i);
  1567. assert(ziplistGet(p,NULL,NULL,&value));
  1568. assert(i == value);
  1569. p = ziplistIndex(zl,-i-1);
  1570. assert(ziplistGet(p,NULL,NULL,&value));
  1571. assert(999-i == value);
  1572. }
  1573. printf("SUCCESS\n\n");
  1574. zfree(zl);
  1575. }
  1576. printf("Compare strings with ziplist entries:\n");
  1577. {
  1578. zl = createList();
  1579. p = ziplistIndex(zl,0);
  1580. if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
  1581. printf("ERROR: not \"hello\"\n");
  1582. return 1;
  1583. }
  1584. if (ziplistCompare(p,(unsigned char*)"hella",5)) {
  1585. printf("ERROR: \"hella\"\n");
  1586. return 1;
  1587. }
  1588. p = ziplistIndex(zl,3);
  1589. if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
  1590. printf("ERROR: not \"1024\"\n");
  1591. return 1;
  1592. }
  1593. if (ziplistCompare(p,(unsigned char*)"1025",4)) {
  1594. printf("ERROR: \"1025\"\n");
  1595. return 1;
  1596. }
  1597. printf("SUCCESS\n\n");
  1598. zfree(zl);
  1599. }
  1600. printf("Merge test:\n");
  1601. {
  1602. /* create list gives us: [hello, foo, quux, 1024] */
  1603. zl = createList();
  1604. unsigned char *zl2 = createList();
  1605. unsigned char *zl3 = ziplistNew();
  1606. unsigned char *zl4 = ziplistNew();
  1607. if (ziplistMerge(&zl4, &zl4)) {
  1608. printf("ERROR: Allowed merging of one ziplist into itself.\n");
  1609. return 1;
  1610. }
  1611. /* Merge two empty ziplists, get empty result back. */
  1612. zl4 = ziplistMerge(&zl3, &zl4);
  1613. ziplistRepr(zl4);
  1614. if (ziplistLen(zl4)) {
  1615. printf("ERROR: Merging two empty ziplists created entries.\n");
  1616. return 1;
  1617. }
  1618. zfree(zl4);
  1619. zl2 = ziplistMerge(&zl, &zl2);
  1620. /* merge gives us: [hello, foo, quux, 1024, hello, foo, quux, 1024] */
  1621. ziplistRepr(zl2);
  1622. if (ziplistLen(zl2) != 8) {
  1623. printf("ERROR: Merged length not 8, but: %u\n", ziplistLen(zl2));
  1624. return 1;
  1625. }
  1626. p = ziplistIndex(zl2,0);
  1627. if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
  1628. printf("ERROR: not \"hello\"\n");
  1629. return 1;
  1630. }
  1631. if (ziplistCompare(p,(unsigned char*)"hella",5)) {
  1632. printf("ERROR: \"hella\"\n");
  1633. return 1;
  1634. }
  1635. p = ziplistIndex(zl2,3);
  1636. if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
  1637. printf("ERROR: not \"1024\"\n");
  1638. return 1;
  1639. }
  1640. if (ziplistCompare(p,(unsigned char*)"1025",4)) {
  1641. printf("ERROR: \"1025\"\n");
  1642. return 1;
  1643. }
  1644. p = ziplistIndex(zl2,4);
  1645. if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
  1646. printf("ERROR: not \"hello\"\n");
  1647. return 1;
  1648. }
  1649. if (ziplistCompare(p,(unsigned char*)"hella",5)) {
  1650. printf("ERROR: \"hella\"\n");
  1651. return 1;
  1652. }
  1653. p = ziplistIndex(zl2,7);
  1654. if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
  1655. printf("ERROR: not \"1024\"\n");
  1656. return 1;
  1657. }
  1658. if (ziplistCompare(p,(unsigned char*)"1025",4)) {
  1659. printf("ERROR: \"1025\"\n");
  1660. return 1;
  1661. }
  1662. printf("SUCCESS\n\n");
  1663. zfree(zl);
  1664. }
  1665. printf("Stress with random payloads of different encoding:\n");
  1666. {
  1667. int i,j,len,where;
  1668. unsigned char *p;
  1669. char buf[1024];
  1670. int buflen;
  1671. list *ref;
  1672. listNode *refnode;
  1673. /* Hold temp vars from ziplist */
  1674. unsigned char *sstr;
  1675. unsigned int slen;
  1676. long long sval;
  1677. for (i = 0; i < 20000; i++) {
  1678. zl = ziplistNew();
  1679. ref = listCreate();
  1680. listSetFreeMethod(ref,(void (*)(void*))sdsfree);
  1681. len = rand() % 256;
  1682. /* Create lists */
  1683. for (j = 0; j < len; j++) {
  1684. where = (rand() & 1) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
  1685. if (rand() % 2) {
  1686. buflen = randstring(buf,1,sizeof(buf)-1);
  1687. } else {
  1688. switch(rand() % 3) {
  1689. case 0:
  1690. buflen = sprintf(buf,"%lld",(0LL + rand()) >> 20);
  1691. break;
  1692. case 1:
  1693. buflen = sprintf(buf,"%lld",(0LL + rand()));
  1694. break;
  1695. case 2:
  1696. buflen = sprintf(buf,"%lld",(0LL + rand()) << 20);
  1697. break;
  1698. default:
  1699. assert(NULL);
  1700. }
  1701. }
  1702. /* Add to ziplist */
  1703. zl = ziplistPush(zl, (unsigned char*)buf, buflen, where);
  1704. /* Add to reference list */
  1705. if (where == ZIPLIST_HEAD) {
  1706. listAddNodeHead(ref,sdsnewlen(buf, buflen));
  1707. } else if (where == ZIPLIST_TAIL) {
  1708. listAddNodeTail(ref,sdsnewlen(buf, buflen));
  1709. } else {
  1710. assert(NULL);
  1711. }
  1712. }
  1713. assert(listLength(ref) == ziplistLen(zl));
  1714. for (j = 0; j < len; j++) {
  1715. /* Naive way to get elements, but similar to the stresser
  1716. * executed from the Tcl test suite. */
  1717. p = ziplistIndex(zl,j);
  1718. refnode = listIndex(ref,j);
  1719. assert(ziplistGet(p,&sstr,&slen,&sval));
  1720. if (sstr == NULL) {
  1721. buflen = sprintf(buf,"%lld",sval);
  1722. } else {
  1723. buflen = slen;
  1724. memcpy(buf,sstr,buflen);
  1725. buf[buflen] = '\0';
  1726. }
  1727. assert(memcmp(buf,listNodeValue(refnode),buflen) == 0);
  1728. }
  1729. zfree(zl);
  1730. listRelease(ref);
  1731. }
  1732. printf("SUCCESS\n\n");
  1733. }
  1734. printf("Stress with variable ziplist size:\n");
  1735. {
  1736. stress(ZIPLIST_HEAD,100000,16384,256);
  1737. stress(ZIPLIST_TAIL,100000,16384,256);
  1738. }
  1739. return 0;
  1740. }
  1741. #endif