]> git.saurik.com Git - redis.git/blame - src/ziplist.c
BITCOUNT: fix segmentation fault.
[redis.git] / src / ziplist.c
CommitLineData
c4705381
PN
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.
11ac6ff6 8 *
c4705381 9 * ----------------------------------------------------------------------------
11ac6ff6 10 *
c4705381
PN
11 * ZIPLIST OVERALL LAYOUT:
12 * The general layout of the ziplist is as follows:
13 * <zlbytes><zltail><zllen><entry><entry><zlend>
11ac6ff6 14 *
c4705381
PN
15 * <zlbytes> is an unsigned integer to hold the number of bytes that the
16 * ziplist occupies. This value needs to be stored to be able to resize the
17 * entire structure without the need to traverse it first.
18 *
19 * <zltail> is the offset to the last entry in the list. This allows a pop
20 * operation on the far side of the list without the need for full traversal.
21 *
22 * <zllen> is the number of entries.When this value is larger than 2**16-2,
23 * we need to traverse the entire list to know how many items it holds.
24 *
25 * <zlend> is a single byte special value, equal to 255, which indicates the
26 * end of the list.
27 *
28 * ZIPLIST ENTRIES:
29 * Every entry in the ziplist is prefixed by a header that contains two pieces
30 * of information. First, the length of the previous entry is stored to be
31 * able to traverse the list from back to front. Second, the encoding with an
32 * optional string length of the entry itself is stored.
33 *
34 * The length of the previous entry is encoded in the following way:
35 * If this length is smaller than 254 bytes, it will only consume a single
36 * byte that takes the length as value. When the length is greater than or
37 * equal to 254, it will consume 5 bytes. The first byte is set to 254 to
38 * indicate a larger value is following. The remaining 4 bytes take the
39 * length of the previous entry as value.
40 *
41 * The other header field of the entry itself depends on the contents of the
42 * entry. When the entry is a string, the first 2 bits of this header will hold
43 * the type of encoding used to store the length of the string, followed by the
44 * actual length of the string. When the entry is an integer the first 2 bits
45 * are both set to 1. The following 2 bits are used to specify what kind of
46 * integer will be stored after this header. An overview of the different
47 * types and encodings is as follows:
48 *
49 * |00pppppp| - 1 byte
50 * String value with length less than or equal to 63 bytes (6 bits).
51 * |01pppppp|qqqqqqqq| - 2 bytes
52 * String value with length less than or equal to 16383 bytes (14 bits).
53 * |10______|qqqqqqqq|rrrrrrrr|ssssssss|tttttttt| - 5 bytes
54 * String value with length greater than or equal to 16384 bytes.
dcd4efe9 55 * |11000000| - 1 byte
c4705381 56 * Integer encoded as int16_t (2 bytes).
dcd4efe9 57 * |11010000| - 1 byte
c4705381 58 * Integer encoded as int32_t (4 bytes).
dcd4efe9 59 * |11100000| - 1 byte
c4705381 60 * Integer encoded as int64_t (8 bytes).
dcd4efe9 61 * |11110000| - 1 byte
dd51571c 62 * Integer encoded as 24 bit signed (3 bytes).
dcd4efe9 63 * |11111110| - 1 byte
64 * Integer encoded as 8 bit signed (1 byte).
65 * |1111xxxx| - (with xxxx between 0000 and 1101) immediate 4 bit integer.
66 * Unsigned integer from 0 to 12. The encoded value is actually from
67 * 1 to 13 because 0000 and 1111 can not be used, so 1 should be
68 * subtracted from the encoded 4 bit value to obtain the right value.
69 * |11111111| - End of ziplist.
dd51571c 70 *
71 * All the integers are represented in little endian byte order.
11ac6ff6
PN
72 */
73
74#include <stdio.h>
29b14d5f 75#include <stdlib.h>
11ac6ff6 76#include <string.h>
e1f93d4b 77#include <stdint.h>
11ac6ff6 78#include <assert.h>
29b14d5f 79#include <limits.h>
11ac6ff6 80#include "zmalloc.h"
edf23aff 81#include "util.h"
11ac6ff6 82#include "ziplist.h"
7a3e3720 83#include "endianconv.h"
11ac6ff6 84
37fff074 85#define ZIP_END 255
aa549962 86#define ZIP_BIGLEN 254
37fff074 87
c4705381 88/* Different encoding/length possibilities */
dcd4efe9 89#define ZIP_STR_MASK 0xc0
90#define ZIP_INT_MASK 0x30
c4705381
PN
91#define ZIP_STR_06B (0 << 6)
92#define ZIP_STR_14B (1 << 6)
93#define ZIP_STR_32B (2 << 6)
94#define ZIP_INT_16B (0xc0 | 0<<4)
95#define ZIP_INT_32B (0xc0 | 1<<4)
96#define ZIP_INT_64B (0xc0 | 2<<4)
ad91404a 97#define ZIP_INT_24B (0xc0 | 3<<4)
dcd4efe9 98#define ZIP_INT_8B 0xfe
99/* 4 bit integer immediate encoding */
100#define ZIP_INT_IMM_MASK 0x0f
101#define ZIP_INT_IMM_MIN 0xf1 /* 11110001 */
102#define ZIP_INT_IMM_MAX 0xfd /* 11111101 */
103#define ZIP_INT_IMM_VAL(v) (v & ZIP_INT_IMM_MASK)
ad91404a
GT
104
105#define INT24_MAX 0x7fffff
106#define INT24_MIN (-INT24_MAX - 1)
37fff074 107
fe458402
PN
108/* Macro to determine type */
109#define ZIP_IS_STR(enc) (((enc) & ZIP_STR_MASK) < ZIP_STR_MASK)
37fff074
PN
110
111/* Utility macros */
e1f93d4b
PN
112#define ZIPLIST_BYTES(zl) (*((uint32_t*)(zl)))
113#define ZIPLIST_TAIL_OFFSET(zl) (*((uint32_t*)((zl)+sizeof(uint32_t))))
114#define ZIPLIST_LENGTH(zl) (*((uint16_t*)((zl)+sizeof(uint32_t)*2)))
115#define ZIPLIST_HEADER_SIZE (sizeof(uint32_t)*2+sizeof(uint16_t))
116#define ZIPLIST_ENTRY_HEAD(zl) ((zl)+ZIPLIST_HEADER_SIZE)
8e0ef249 117#define ZIPLIST_ENTRY_TAIL(zl) ((zl)+intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl)))
118#define ZIPLIST_ENTRY_END(zl) ((zl)+intrev32ifbe(ZIPLIST_BYTES(zl))-1)
e1f93d4b
PN
119
120/* We know a positive increment can only be 1 because entries can only be
121 * pushed one at a time. */
f6eb1747 122#define ZIPLIST_INCR_LENGTH(zl,incr) { \
56538477 123 if (ZIPLIST_LENGTH(zl) < UINT16_MAX) \
3fa19b7d 124 ZIPLIST_LENGTH(zl) = intrev16ifbe(intrev16ifbe(ZIPLIST_LENGTH(zl))+incr); \
56538477 125}
11ac6ff6 126
a5456b2c
PN
127typedef struct zlentry {
128 unsigned int prevrawlensize, prevrawlen;
129 unsigned int lensize, len;
130 unsigned int headersize;
131 unsigned char encoding;
0c0d0564 132 unsigned char *p;
a5456b2c
PN
133} zlentry;
134
dcd4efe9 135/* Extract the encoding from the byte pointed by 'ptr' and set it into
136 * 'encoding'. */
137#define ZIP_ENTRY_ENCODING(ptr, encoding) do { \
138 (encoding) = (ptr[0]); \
139 if ((encoding) < ZIP_STR_MASK) (encoding) &= ZIP_STR_MASK; \
fe458402 140} while(0)
c4705381 141
37fff074 142/* Return bytes needed to store integer encoded by 'encoding' */
c4705381
PN
143static unsigned int zipIntSize(unsigned char encoding) {
144 switch(encoding) {
dcd4efe9 145 case ZIP_INT_8B: return 1;
146 case ZIP_INT_16B: return 2;
147 case ZIP_INT_24B: return 3;
148 case ZIP_INT_32B: return 4;
149 case ZIP_INT_64B: return 8;
150 default: return 0; /* 4 bit immediate */
37fff074
PN
151 }
152 assert(NULL);
8ce39260 153 return 0;
37fff074
PN
154}
155
37fff074
PN
156/* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
157 * the amount of bytes required to encode such a length. */
c4705381
PN
158static unsigned int zipEncodeLength(unsigned char *p, unsigned char encoding, unsigned int rawlen) {
159 unsigned char len = 1, buf[5];
160
161 if (ZIP_IS_STR(encoding)) {
162 /* Although encoding is given it may not be set for strings,
163 * so we determine it here using the raw length. */
164 if (rawlen <= 0x3f) {
37fff074 165 if (!p) return len;
c4705381
PN
166 buf[0] = ZIP_STR_06B | rawlen;
167 } else if (rawlen <= 0x3fff) {
168 len += 1;
37fff074 169 if (!p) return len;
c4705381
PN
170 buf[0] = ZIP_STR_14B | ((rawlen >> 8) & 0x3f);
171 buf[1] = rawlen & 0xff;
37fff074
PN
172 } else {
173 len += 4;
174 if (!p) return len;
c4705381
PN
175 buf[0] = ZIP_STR_32B;
176 buf[1] = (rawlen >> 24) & 0xff;
177 buf[2] = (rawlen >> 16) & 0xff;
178 buf[3] = (rawlen >> 8) & 0xff;
179 buf[4] = rawlen & 0xff;
37fff074 180 }
c4705381
PN
181 } else {
182 /* Implies integer encoding, so length is always 1. */
183 if (!p) return len;
184 buf[0] = encoding;
37fff074 185 }
37fff074 186
c4705381 187 /* Store this length at p */
37fff074
PN
188 memcpy(p,buf,len);
189 return len;
190}
191
fe458402
PN
192/* Decode the length encoded in 'ptr'. The 'encoding' variable will hold the
193 * entries encoding, the 'lensize' variable will hold the number of bytes
194 * required to encode the entries length, and the 'len' variable will hold the
195 * entries length. */
196#define ZIP_DECODE_LENGTH(ptr, encoding, lensize, len) do { \
197 ZIP_ENTRY_ENCODING((ptr), (encoding)); \
198 if ((encoding) < ZIP_STR_MASK) { \
199 if ((encoding) == ZIP_STR_06B) { \
200 (lensize) = 1; \
201 (len) = (ptr)[0] & 0x3f; \
202 } else if ((encoding) == ZIP_STR_14B) { \
203 (lensize) = 2; \
204 (len) = (((ptr)[0] & 0x3f) << 8) | (ptr)[1]; \
205 } else if (encoding == ZIP_STR_32B) { \
206 (lensize) = 5; \
207 (len) = ((ptr)[1] << 24) | \
208 ((ptr)[2] << 16) | \
209 ((ptr)[3] << 8) | \
210 ((ptr)[4]); \
211 } else { \
212 assert(NULL); \
213 } \
214 } else { \
215 (lensize) = 1; \
216 (len) = zipIntSize(encoding); \
217 } \
218} while(0);
7b1f85c0
PN
219
220/* Encode the length of the previous entry and write it to "p". Return the
221 * number of bytes needed to encode this length if "p" is NULL. */
222static unsigned int zipPrevEncodeLength(unsigned char *p, unsigned int len) {
223 if (p == NULL) {
224 return (len < ZIP_BIGLEN) ? 1 : sizeof(len)+1;
225 } else {
226 if (len < ZIP_BIGLEN) {
227 p[0] = len;
228 return 1;
229 } else {
230 p[0] = ZIP_BIGLEN;
231 memcpy(p+1,&len,sizeof(len));
f2204374 232 memrev32ifbe(p+1);
7b1f85c0
PN
233 return 1+sizeof(len);
234 }
235 }
236}
237
169d2ef1
PN
238/* Encode the length of the previous entry and write it to "p". This only
239 * uses the larger encoding (required in __ziplistCascadeUpdate). */
240static void zipPrevEncodeLengthForceLarge(unsigned char *p, unsigned int len) {
241 if (p == NULL) return;
242 p[0] = ZIP_BIGLEN;
243 memcpy(p+1,&len,sizeof(len));
f2204374 244 memrev32ifbe(p+1);
169d2ef1
PN
245}
246
fe458402
PN
247/* Decode the number of bytes required to store the length of the previous
248 * element, from the perspective of the entry pointed to by 'ptr'. */
249#define ZIP_DECODE_PREVLENSIZE(ptr, prevlensize) do { \
250 if ((ptr)[0] < ZIP_BIGLEN) { \
251 (prevlensize) = 1; \
252 } else { \
253 (prevlensize) = 5; \
254 } \
255} while(0);
256
257/* Decode the length of the previous element, from the perspective of the entry
258 * pointed to by 'ptr'. */
259#define ZIP_DECODE_PREVLEN(ptr, prevlensize, prevlen) do { \
260 ZIP_DECODE_PREVLENSIZE(ptr, prevlensize); \
261 if ((prevlensize) == 1) { \
262 (prevlen) = (ptr)[0]; \
263 } else if ((prevlensize) == 5) { \
264 assert(sizeof((prevlensize)) == 4); \
265 memcpy(&(prevlen), ((char*)(ptr)) + 1, 4); \
b64281cc 266 memrev32ifbe(&prevlen); \
fe458402
PN
267 } \
268} while(0);
269
270/* Return the difference in number of bytes needed to store the length of the
271 * previous element 'len', in the entry pointed to by 'p'. */
dcb9cf4e
PN
272static int zipPrevLenByteDiff(unsigned char *p, unsigned int len) {
273 unsigned int prevlensize;
fe458402
PN
274 ZIP_DECODE_PREVLENSIZE(p, prevlensize);
275 return zipPrevEncodeLength(NULL, len) - prevlensize;
276}
277
278/* Return the total number of bytes used by the entry pointed to by 'p'. */
279static unsigned int zipRawEntryLength(unsigned char *p) {
280 unsigned int prevlensize, encoding, lensize, len;
281 ZIP_DECODE_PREVLENSIZE(p, prevlensize);
282 ZIP_DECODE_LENGTH(p + prevlensize, encoding, lensize, len);
283 return prevlensize + lensize + len;
dcb9cf4e
PN
284}
285
37fff074 286/* Check if string pointed to by 'entry' can be encoded as an integer.
61712508 287 * Stores the integer value in 'v' and its encoding in 'encoding'. */
288static int zipTryEncoding(unsigned char *entry, unsigned int entrylen, long long *v, unsigned char *encoding) {
37fff074 289 long long value;
37fff074 290
61712508 291 if (entrylen >= 32 || entrylen == 0) return 0;
edf23aff 292 if (string2ll((char*)entry,entrylen,&value)) {
61712508 293 /* Great, the string can be encoded. Check what's the smallest
294 * of our encoding types that can hold this value. */
dcd4efe9 295 if (value >= 0 && value <= 12) {
296 *encoding = ZIP_INT_IMM_MIN+value;
297 } else if (value >= INT8_MIN && value <= INT8_MAX) {
298 *encoding = ZIP_INT_8B;
299 } else if (value >= INT16_MIN && value <= INT16_MAX) {
c4705381 300 *encoding = ZIP_INT_16B;
ad91404a
GT
301 } else if (value >= INT24_MIN && value <= INT24_MAX) {
302 *encoding = ZIP_INT_24B;
e1f93d4b 303 } else if (value >= INT32_MIN && value <= INT32_MAX) {
c4705381 304 *encoding = ZIP_INT_32B;
37fff074 305 } else {
c4705381 306 *encoding = ZIP_INT_64B;
37fff074
PN
307 }
308 *v = value;
309 return 1;
310 }
311 return 0;
312}
313
314/* Store integer 'value' at 'p', encoded as 'encoding' */
e1f93d4b
PN
315static void zipSaveInteger(unsigned char *p, int64_t value, unsigned char encoding) {
316 int16_t i16;
317 int32_t i32;
318 int64_t i64;
dcd4efe9 319 if (encoding == ZIP_INT_8B) {
82675c86 320 ((int8_t*)p)[0] = (int8_t)value;
dcd4efe9 321 } else if (encoding == ZIP_INT_16B) {
e1f93d4b
PN
322 i16 = value;
323 memcpy(p,&i16,sizeof(i16));
f2204374 324 memrev16ifbe(p);
ad91404a
GT
325 } else if (encoding == ZIP_INT_24B) {
326 i32 = value<<8;
327 memrev32ifbe(&i32);
82675c86 328 memcpy(p,((uint8_t*)&i32)+1,sizeof(i32)-sizeof(uint8_t));
c4705381 329 } else if (encoding == ZIP_INT_32B) {
e1f93d4b
PN
330 i32 = value;
331 memcpy(p,&i32,sizeof(i32));
f2204374 332 memrev32ifbe(p);
c4705381 333 } else if (encoding == ZIP_INT_64B) {
e1f93d4b
PN
334 i64 = value;
335 memcpy(p,&i64,sizeof(i64));
f2204374 336 memrev64ifbe(p);
dcd4efe9 337 } else if (encoding >= ZIP_INT_IMM_MIN && encoding <= ZIP_INT_IMM_MAX) {
338 /* Nothing to do, the value is stored in the encoding itself. */
37fff074
PN
339 } else {
340 assert(NULL);
341 }
342}
343
344/* Read integer encoded as 'encoding' from 'p' */
e1f93d4b
PN
345static int64_t zipLoadInteger(unsigned char *p, unsigned char encoding) {
346 int16_t i16;
347 int32_t i32;
8ce39260 348 int64_t i64, ret = 0;
dcd4efe9 349 if (encoding == ZIP_INT_8B) {
82675c86 350 ret = ((int8_t*)p)[0];
dcd4efe9 351 } else if (encoding == ZIP_INT_16B) {
e1f93d4b 352 memcpy(&i16,p,sizeof(i16));
f2204374 353 memrev16ifbe(&i16);
e1f93d4b 354 ret = i16;
c4705381 355 } else if (encoding == ZIP_INT_32B) {
e1f93d4b 356 memcpy(&i32,p,sizeof(i32));
66d1b021 357 memrev32ifbe(&i32);
e1f93d4b 358 ret = i32;
ad91404a
GT
359 } else if (encoding == ZIP_INT_24B) {
360 i32 = 0;
82675c86 361 memcpy(((uint8_t*)&i32)+1,p,sizeof(i32)-sizeof(uint8_t));
ad91404a
GT
362 memrev32ifbe(&i32);
363 ret = i32>>8;
c4705381 364 } else if (encoding == ZIP_INT_64B) {
e1f93d4b 365 memcpy(&i64,p,sizeof(i64));
3fa19b7d 366 memrev64ifbe(&i64);
e1f93d4b 367 ret = i64;
dcd4efe9 368 } else if (encoding >= ZIP_INT_IMM_MIN && encoding <= ZIP_INT_IMM_MAX) {
369 ret = (encoding & ZIP_INT_IMM_MASK)-1;
37fff074
PN
370 } else {
371 assert(NULL);
372 }
373 return ret;
374}
375
a5456b2c
PN
376/* Return a struct with all information about an entry. */
377static zlentry zipEntry(unsigned char *p) {
378 zlentry e;
fe458402
PN
379
380 ZIP_DECODE_PREVLEN(p, e.prevrawlensize, e.prevrawlen);
381 ZIP_DECODE_LENGTH(p + e.prevrawlensize, e.encoding, e.lensize, e.len);
382 e.headersize = e.prevrawlensize + e.lensize;
0c0d0564 383 e.p = p;
a5456b2c
PN
384 return e;
385}
386
11ac6ff6
PN
387/* Create a new empty ziplist. */
388unsigned char *ziplistNew(void) {
389 unsigned int bytes = ZIPLIST_HEADER_SIZE+1;
390 unsigned char *zl = zmalloc(bytes);
56538477 391 ZIPLIST_BYTES(zl) = intrev32ifbe(bytes);
392 ZIPLIST_TAIL_OFFSET(zl) = intrev32ifbe(ZIPLIST_HEADER_SIZE);
11ac6ff6
PN
393 ZIPLIST_LENGTH(zl) = 0;
394 zl[bytes-1] = ZIP_END;
395 return zl;
396}
397
37fff074 398/* Resize the ziplist. */
11ac6ff6 399static unsigned char *ziplistResize(unsigned char *zl, unsigned int len) {
37fff074 400 zl = zrealloc(zl,len);
56538477 401 ZIPLIST_BYTES(zl) = intrev32ifbe(len);
11ac6ff6
PN
402 zl[len-1] = ZIP_END;
403 return zl;
404}
405
169d2ef1
PN
406/* When an entry is inserted, we need to set the prevlen field of the next
407 * entry to equal the length of the inserted entry. It can occur that this
408 * length cannot be encoded in 1 byte and the next entry needs to be grow
409 * a bit larger to hold the 5-byte encoded prevlen. This can be done for free,
410 * because this only happens when an entry is already being inserted (which
411 * causes a realloc and memmove). However, encoding the prevlen may require
412 * that this entry is grown as well. This effect may cascade throughout
413 * the ziplist when there are consecutive entries with a size close to
414 * ZIP_BIGLEN, so we need to check that the prevlen can be encoded in every
415 * consecutive entry.
416 *
417 * Note that this effect can also happen in reverse, where the bytes required
418 * to encode the prevlen field can shrink. This effect is deliberately ignored,
419 * because it can cause a "flapping" effect where a chain prevlen fields is
420 * first grown and then shrunk again after consecutive inserts. Rather, the
421 * field is allowed to stay larger than necessary, because a large prevlen
422 * field implies the ziplist is holding large entries anyway.
423 *
424 * The pointer "p" points to the first entry that does NOT need to be
425 * updated, i.e. consecutive fields MAY need an update. */
426static unsigned char *__ziplistCascadeUpdate(unsigned char *zl, unsigned char *p) {
56538477 427 size_t curlen = intrev32ifbe(ZIPLIST_BYTES(zl)), rawlen, rawlensize;
69298a05 428 size_t offset, noffset, extra;
169d2ef1
PN
429 unsigned char *np;
430 zlentry cur, next;
431
432 while (p[0] != ZIP_END) {
433 cur = zipEntry(p);
434 rawlen = cur.headersize + cur.len;
435 rawlensize = zipPrevEncodeLength(NULL,rawlen);
436
437 /* Abort if there is no next entry. */
438 if (p[rawlen] == ZIP_END) break;
439 next = zipEntry(p+rawlen);
440
441 /* Abort when "prevlen" has not changed. */
442 if (next.prevrawlen == rawlen) break;
443
444 if (next.prevrawlensize < rawlensize) {
445 /* The "prevlen" field of "next" needs more bytes to hold
446 * the raw length of "cur". */
447 offset = p-zl;
448 extra = rawlensize-next.prevrawlensize;
449 zl = ziplistResize(zl,curlen+extra);
169d2ef1
PN
450 p = zl+offset;
451
b7d3bf51 452 /* Current pointer and offset for next element. */
169d2ef1
PN
453 np = p+rawlen;
454 noffset = np-zl;
b7d3bf51
PN
455
456 /* Update tail offset when next element is not the tail element. */
3fa19b7d 457 if ((zl+intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))) != np) {
458 ZIPLIST_TAIL_OFFSET(zl) =
459 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+extra);
460 }
b7d3bf51
PN
461
462 /* Move the tail to the back. */
169d2ef1
PN
463 memmove(np+rawlensize,
464 np+next.prevrawlensize,
465 curlen-noffset-next.prevrawlensize-1);
466 zipPrevEncodeLength(np,rawlen);
467
468 /* Advance the cursor */
469 p += rawlen;
306c6a02 470 curlen += extra;
169d2ef1
PN
471 } else {
472 if (next.prevrawlensize > rawlensize) {
473 /* This would result in shrinking, which we want to avoid.
474 * So, set "rawlen" in the available bytes. */
475 zipPrevEncodeLengthForceLarge(p+rawlen,rawlen);
476 } else {
477 zipPrevEncodeLength(p+rawlen,rawlen);
478 }
479
480 /* Stop here, as the raw length of "next" has not changed. */
481 break;
482 }
483 }
484 return zl;
485}
486
0c0d0564 487/* Delete "num" entries, starting at "p". Returns pointer to the ziplist. */
b6eb9703 488static unsigned char *__ziplistDelete(unsigned char *zl, unsigned char *p, unsigned int num) {
0c0d0564 489 unsigned int i, totlen, deleted = 0;
69298a05
PN
490 size_t offset;
491 int nextdiff = 0;
169d2ef1
PN
492 zlentry first, tail;
493
494 first = zipEntry(p);
0c0d0564
PN
495 for (i = 0; p[0] != ZIP_END && i < num; i++) {
496 p += zipRawEntryLength(p);
497 deleted++;
498 }
499
500 totlen = p-first.p;
501 if (totlen > 0) {
502 if (p[0] != ZIP_END) {
2f444526
PN
503 /* Storing `prevrawlen` in this entry may increase or decrease the
504 * number of bytes required compare to the current `prevrawlen`.
505 * There always is room to store this, because it was previously
506 * stored by an entry that is now being deleted. */
0c0d0564 507 nextdiff = zipPrevLenByteDiff(p,first.prevrawlen);
2f444526
PN
508 p -= nextdiff;
509 zipPrevEncodeLength(p,first.prevrawlen);
0c0d0564
PN
510
511 /* Update offset for tail */
3fa19b7d 512 ZIPLIST_TAIL_OFFSET(zl) =
513 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))-totlen);
169d2ef1
PN
514
515 /* When the tail contains more than one entry, we need to take
516 * "nextdiff" in account as well. Otherwise, a change in the
517 * size of prevlen doesn't have an effect on the *tail* offset. */
518 tail = zipEntry(p);
3fa19b7d 519 if (p[tail.headersize+tail.len] != ZIP_END) {
cab1105c 520 ZIPLIST_TAIL_OFFSET(zl) =
3fa19b7d 521 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+nextdiff);
522 }
0c0d0564
PN
523
524 /* Move tail to the front of the ziplist */
2f444526
PN
525 memmove(first.p,p,
526 intrev32ifbe(ZIPLIST_BYTES(zl))-(p-zl)-1);
0c0d0564
PN
527 } else {
528 /* The entire tail was deleted. No need to move memory. */
56538477 529 ZIPLIST_TAIL_OFFSET(zl) =
530 intrev32ifbe((first.p-zl)-first.prevrawlen);
0c0d0564
PN
531 }
532
533 /* Resize and update length */
169d2ef1 534 offset = first.p-zl;
56538477 535 zl = ziplistResize(zl, intrev32ifbe(ZIPLIST_BYTES(zl))-totlen+nextdiff);
0c0d0564 536 ZIPLIST_INCR_LENGTH(zl,-deleted);
169d2ef1
PN
537 p = zl+offset;
538
539 /* When nextdiff != 0, the raw length of the next entry has changed, so
540 * we need to cascade the update throughout the ziplist */
541 if (nextdiff != 0)
542 zl = __ziplistCascadeUpdate(zl,p);
0c0d0564
PN
543 }
544 return zl;
11ac6ff6
PN
545}
546
6435c767 547/* Insert item at "p". */
b6eb9703 548static unsigned char *__ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
56538477 549 size_t curlen = intrev32ifbe(ZIPLIST_BYTES(zl)), reqlen, prevlen = 0;
69298a05
PN
550 size_t offset;
551 int nextdiff = 0;
c4705381 552 unsigned char encoding = 0;
f013f400 553 long long value = 123456789; /* initialized to avoid warning. Using a value
554 that is easy to see if for some reason
555 we use it uninitialized. */
169d2ef1 556 zlentry entry, tail;
11ac6ff6 557
6435c767
PN
558 /* Find out prevlen for the entry that is inserted. */
559 if (p[0] != ZIP_END) {
560 entry = zipEntry(p);
561 prevlen = entry.prevrawlen;
dcb9cf4e 562 } else {
169d2ef1
PN
563 unsigned char *ptail = ZIPLIST_ENTRY_TAIL(zl);
564 if (ptail[0] != ZIP_END) {
565 prevlen = zipRawEntryLength(ptail);
6435c767 566 }
dcb9cf4e
PN
567 }
568
29b14d5f 569 /* See if the entry can be encoded */
61712508 570 if (zipTryEncoding(s,slen,&value,&encoding)) {
c4705381
PN
571 /* 'encoding' is set to the appropriate integer encoding */
572 reqlen = zipIntSize(encoding);
29b14d5f 573 } else {
c4705381
PN
574 /* 'encoding' is untouched, however zipEncodeLength will use the
575 * string length to figure out how to encode it. */
6435c767 576 reqlen = slen;
29b14d5f 577 }
dcb9cf4e
PN
578 /* We need space for both the length of the previous entry and
579 * the length of the payload. */
7b1f85c0 580 reqlen += zipPrevEncodeLength(NULL,prevlen);
6435c767
PN
581 reqlen += zipEncodeLength(NULL,encoding,slen);
582
583 /* When the insert position is not equal to the tail, we need to
584 * make sure that the next entry can hold this entry's length in
585 * its prevlen field. */
177a0a0b 586 nextdiff = (p[0] != ZIP_END) ? zipPrevLenByteDiff(p,reqlen) : 0;
6435c767
PN
587
588 /* Store offset because a realloc may change the address of zl. */
589 offset = p-zl;
590 zl = ziplistResize(zl,curlen+reqlen+nextdiff);
591 p = zl+offset;
592
593 /* Apply memory move when necessary and update tail offset. */
594 if (p[0] != ZIP_END) {
595 /* Subtract one because of the ZIP_END bytes */
596 memmove(p+reqlen,p-nextdiff,curlen-offset-1+nextdiff);
169d2ef1 597
6435c767 598 /* Encode this entry's raw length in the next entry. */
7b1f85c0 599 zipPrevEncodeLength(p+reqlen,reqlen);
169d2ef1 600
6435c767 601 /* Update offset for tail */
3fa19b7d 602 ZIPLIST_TAIL_OFFSET(zl) =
603 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+reqlen);
169d2ef1
PN
604
605 /* When the tail contains more than one entry, we need to take
606 * "nextdiff" in account as well. Otherwise, a change in the
607 * size of prevlen doesn't have an effect on the *tail* offset. */
608 tail = zipEntry(p+reqlen);
3fa19b7d 609 if (p[reqlen+tail.headersize+tail.len] != ZIP_END) {
610 ZIPLIST_TAIL_OFFSET(zl) =
611 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+nextdiff);
612 }
11ac6ff6 613 } else {
6435c767 614 /* This element will be the new tail. */
56538477 615 ZIPLIST_TAIL_OFFSET(zl) = intrev32ifbe(p-zl);
dcb9cf4e
PN
616 }
617
169d2ef1
PN
618 /* When nextdiff != 0, the raw length of the next entry has changed, so
619 * we need to cascade the update throughout the ziplist */
620 if (nextdiff != 0) {
621 offset = p-zl;
622 zl = __ziplistCascadeUpdate(zl,p+reqlen);
623 p = zl+offset;
624 }
625
11ac6ff6 626 /* Write the entry */
7b1f85c0 627 p += zipPrevEncodeLength(p,prevlen);
6435c767 628 p += zipEncodeLength(p,encoding,slen);
c4705381 629 if (ZIP_IS_STR(encoding)) {
6435c767 630 memcpy(p,s,slen);
c4705381
PN
631 } else {
632 zipSaveInteger(p,value,encoding);
29b14d5f 633 }
f6eb1747 634 ZIPLIST_INCR_LENGTH(zl,1);
11ac6ff6
PN
635 return zl;
636}
637
b6eb9703 638unsigned char *ziplistPush(unsigned char *zl, unsigned char *s, unsigned int slen, int where) {
6435c767 639 unsigned char *p;
1ce81fa5 640 p = (where == ZIPLIST_HEAD) ? ZIPLIST_ENTRY_HEAD(zl) : ZIPLIST_ENTRY_END(zl);
6435c767
PN
641 return __ziplistInsert(zl,p,s,slen);
642}
643
c03206fd
PN
644/* Returns an offset to use for iterating with ziplistNext. When the given
645 * index is negative, the list is traversed back to front. When the list
646 * doesn't contain an element at the provided index, NULL is returned. */
647unsigned char *ziplistIndex(unsigned char *zl, int index) {
648 unsigned char *p;
649 zlentry entry;
650 if (index < 0) {
651 index = (-index)-1;
652 p = ZIPLIST_ENTRY_TAIL(zl);
653 if (p[0] != ZIP_END) {
654 entry = zipEntry(p);
655 while (entry.prevrawlen > 0 && index--) {
656 p -= entry.prevrawlen;
657 entry = zipEntry(p);
658 }
659 }
660 } else {
661 p = ZIPLIST_ENTRY_HEAD(zl);
662 while (p[0] != ZIP_END && index--) {
663 p += zipRawEntryLength(p);
664 }
08253bf4 665 }
177a0a0b 666 return (p[0] == ZIP_END || index > 0) ? NULL : p;
08253bf4
PN
667}
668
d51ebef5 669/* Return pointer to next entry in ziplist.
670 *
671 * zl is the pointer to the ziplist
672 * p is the pointer to the current element
673 *
674 * The element after 'p' is returned, otherwise NULL if we are at the end. */
8632fb30
PN
675unsigned char *ziplistNext(unsigned char *zl, unsigned char *p) {
676 ((void) zl);
d71b9865
PN
677
678 /* "p" could be equal to ZIP_END, caused by ziplistDelete,
679 * and we should return NULL. Otherwise, we should return NULL
680 * when the *next* element is ZIP_END (there is no next entry). */
681 if (p[0] == ZIP_END) {
682 return NULL;
d71b9865 683 }
fe458402
PN
684
685 p += zipRawEntryLength(p);
686 if (p[0] == ZIP_END) {
687 return NULL;
688 }
689
690 return p;
75d8978e
PN
691}
692
033fb554 693/* Return pointer to previous entry in ziplist. */
8632fb30
PN
694unsigned char *ziplistPrev(unsigned char *zl, unsigned char *p) {
695 zlentry entry;
696
697 /* Iterating backwards from ZIP_END should return the tail. When "p" is
698 * equal to the first element of the list, we're already at the head,
699 * and should return NULL. */
700 if (p[0] == ZIP_END) {
701 p = ZIPLIST_ENTRY_TAIL(zl);
702 return (p[0] == ZIP_END) ? NULL : p;
703 } else if (p == ZIPLIST_ENTRY_HEAD(zl)) {
704 return NULL;
705 } else {
706 entry = zipEntry(p);
169d2ef1 707 assert(entry.prevrawlen > 0);
8632fb30
PN
708 return p-entry.prevrawlen;
709 }
033fb554
PN
710}
711
75d8978e
PN
712/* Get entry pointer to by 'p' and store in either 'e' or 'v' depending
713 * on the encoding of the entry. 'e' is always set to NULL to be able
714 * to find out whether the string pointer or the integer value was set.
715 * Return 0 if 'p' points to the end of the zipmap, 1 otherwise. */
b6eb9703 716unsigned int ziplistGet(unsigned char *p, unsigned char **sstr, unsigned int *slen, long long *sval) {
a5456b2c 717 zlentry entry;
c03206fd 718 if (p == NULL || p[0] == ZIP_END) return 0;
03e52931 719 if (sstr) *sstr = NULL;
dcb9cf4e 720
a5456b2c 721 entry = zipEntry(p);
c4705381 722 if (ZIP_IS_STR(entry.encoding)) {
03e52931
PN
723 if (sstr) {
724 *slen = entry.len;
b6eb9703 725 *sstr = p+entry.headersize;
75d8978e
PN
726 }
727 } else {
03e52931
PN
728 if (sval) {
729 *sval = zipLoadInteger(p+entry.headersize,entry.encoding);
75d8978e 730 }
08253bf4 731 }
75d8978e 732 return 1;
08253bf4
PN
733}
734
033fb554 735/* Insert an entry at "p". */
b6eb9703 736unsigned char *ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
033fb554 737 return __ziplistInsert(zl,p,s,slen);
779deb60
PN
738}
739
0f10458c
PN
740/* Delete a single entry from the ziplist, pointed to by *p.
741 * Also update *p in place, to be able to iterate over the
742 * ziplist, while deleting entries. */
6a8e35ad 743unsigned char *ziplistDelete(unsigned char *zl, unsigned char **p) {
69298a05 744 size_t offset = *p-zl;
0c0d0564 745 zl = __ziplistDelete(zl,*p,1);
0f10458c 746
0c0d0564 747 /* Store pointer to current element in p, because ziplistDelete will
0f3dfa87
PN
748 * do a realloc which might result in a different "zl"-pointer.
749 * When the delete direction is back to front, we might delete the last
750 * entry and end up with "p" pointing to ZIP_END, so check this. */
6a8e35ad 751 *p = zl+offset;
0f10458c
PN
752 return zl;
753}
754
033fb554
PN
755/* Delete a range of entries from the ziplist. */
756unsigned char *ziplistDeleteRange(unsigned char *zl, unsigned int index, unsigned int num) {
757 unsigned char *p = ziplistIndex(zl,index);
758 return (p == NULL) ? zl : __ziplistDelete(zl,p,num);
759}
760
c09c2c3b 761/* Compare entry pointer to by 'p' with 'entry'. Return 1 if equal. */
b6eb9703 762unsigned int ziplistCompare(unsigned char *p, unsigned char *sstr, unsigned int slen) {
a5456b2c 763 zlentry entry;
b6eb9703
PN
764 unsigned char sencoding;
765 long long zval, sval;
177a0a0b 766 if (p[0] == ZIP_END) return 0;
c09c2c3b 767
a5456b2c 768 entry = zipEntry(p);
c4705381 769 if (ZIP_IS_STR(entry.encoding)) {
c09c2c3b 770 /* Raw compare */
a5456b2c 771 if (entry.len == slen) {
03e52931 772 return memcmp(p+entry.headersize,sstr,slen) == 0;
c09c2c3b
PN
773 } else {
774 return 0;
775 }
c4aace90 776 } else {
0ef88927
PN
777 /* Try to compare encoded values. Don't compare encoding because
778 * different implementations may encoded integers differently. */
61712508 779 if (zipTryEncoding(sstr,slen,&sval,&sencoding)) {
0ef88927
PN
780 zval = zipLoadInteger(p+entry.headersize,entry.encoding);
781 return zval == sval;
c4aace90 782 }
c09c2c3b 783 }
c4aace90 784 return 0;
c09c2c3b
PN
785}
786
fe458402
PN
787/* Find pointer to the entry equal to the specified entry. Skip 'skip' entries
788 * between every comparison. Returns NULL when the field could not be found. */
789unsigned char *ziplistFind(unsigned char *p, unsigned char *vstr, unsigned int vlen, unsigned int skip) {
790 int skipcnt = 0;
791 unsigned char vencoding = 0;
792 long long vll = 0;
793
794 while (p[0] != ZIP_END) {
795 unsigned int prevlensize, encoding, lensize, len;
796 unsigned char *q;
797
798 ZIP_DECODE_PREVLENSIZE(p, prevlensize);
799 ZIP_DECODE_LENGTH(p + prevlensize, encoding, lensize, len);
800 q = p + prevlensize + lensize;
801
802 if (skipcnt == 0) {
803 /* Compare current entry with specified entry */
804 if (ZIP_IS_STR(encoding)) {
805 if (len == vlen && memcmp(q, vstr, vlen) == 0) {
806 return p;
807 }
808 } else {
8361d6c4 809 /* Find out if the searched field can be encoded. Note that
810 * we do it only the first time, once done vencoding is set
811 * to non-zero and vll is set to the integer value. */
fe458402 812 if (vencoding == 0) {
fe458402 813 if (!zipTryEncoding(vstr, vlen, &vll, &vencoding)) {
8361d6c4 814 /* If the entry can't be encoded we set it to
815 * UCHAR_MAX so that we don't retry again the next
816 * time. */
fe458402
PN
817 vencoding = UCHAR_MAX;
818 }
fe458402
PN
819 /* Must be non-zero by now */
820 assert(vencoding);
821 }
822
8361d6c4 823 /* Compare current entry with specified entry, do it only
824 * if vencoding != UCHAR_MAX because if there is no encoding
825 * possible for the field it can't be a valid integer. */
826 if (vencoding != UCHAR_MAX) {
fe458402
PN
827 long long ll = zipLoadInteger(q, encoding);
828 if (ll == vll) {
829 return p;
830 }
831 }
832 }
833
834 /* Reset skip count */
835 skipcnt = skip;
836 } else {
837 /* Skip entry */
838 skipcnt--;
839 }
840
841 /* Move to next entry */
842 p = q + len;
843 }
844
845 return NULL;
846}
847
6205b463
PN
848/* Return length of ziplist. */
849unsigned int ziplistLen(unsigned char *zl) {
850 unsigned int len = 0;
56538477 851 if (intrev16ifbe(ZIPLIST_LENGTH(zl)) < UINT16_MAX) {
852 len = intrev16ifbe(ZIPLIST_LENGTH(zl));
6205b463
PN
853 } else {
854 unsigned char *p = zl+ZIPLIST_HEADER_SIZE;
855 while (*p != ZIP_END) {
856 p += zipRawEntryLength(p);
857 len++;
858 }
859
860 /* Re-store length if small enough */
56538477 861 if (len < UINT16_MAX) ZIPLIST_LENGTH(zl) = intrev16ifbe(len);
6205b463
PN
862 }
863 return len;
864}
865
d4fb9f41 866/* Return ziplist blob size in bytes. */
867size_t ziplistBlobLen(unsigned char *zl) {
56538477 868 return intrev32ifbe(ZIPLIST_BYTES(zl));
4812cf28
PN
869}
870
11ac6ff6 871void ziplistRepr(unsigned char *zl) {
c8d9e7f4 872 unsigned char *p;
169d2ef1 873 int index = 0;
c8d9e7f4 874 zlentry entry;
11ac6ff6 875
169d2ef1
PN
876 printf(
877 "{total bytes %d} "
878 "{length %u}\n"
879 "{tail offset %u}\n",
56538477 880 intrev32ifbe(ZIPLIST_BYTES(zl)),
881 intrev16ifbe(ZIPLIST_LENGTH(zl)),
882 intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl)));
1ce81fa5 883 p = ZIPLIST_ENTRY_HEAD(zl);
11ac6ff6 884 while(*p != ZIP_END) {
c8d9e7f4 885 entry = zipEntry(p);
169d2ef1
PN
886 printf(
887 "{"
888 "addr 0x%08lx, "
889 "index %2d, "
890 "offset %5ld, "
891 "rl: %5u, "
892 "hs %2u, "
893 "pl: %5u, "
894 "pls: %2u, "
895 "payload %5u"
896 "} ",
10c12171 897 (long unsigned)p,
169d2ef1 898 index,
10c12171 899 (unsigned long) (p-zl),
169d2ef1
PN
900 entry.headersize+entry.len,
901 entry.headersize,
902 entry.prevrawlen,
903 entry.prevrawlensize,
904 entry.len);
c8d9e7f4 905 p += entry.headersize;
c4705381 906 if (ZIP_IS_STR(entry.encoding)) {
169d2ef1 907 if (entry.len > 40) {
10c12171 908 if (fwrite(p,40,1,stdout) == 0) perror("fwrite");
169d2ef1
PN
909 printf("...");
910 } else {
10c12171 911 if (entry.len &&
912 fwrite(p,entry.len,1,stdout) == 0) perror("fwrite");
169d2ef1 913 }
29b14d5f 914 } else {
3688d7f3 915 printf("%lld", (long long) zipLoadInteger(p,entry.encoding));
29b14d5f 916 }
11ac6ff6 917 printf("\n");
c8d9e7f4 918 p += entry.len;
169d2ef1 919 index++;
11ac6ff6
PN
920 }
921 printf("{end}\n\n");
922}
923
924#ifdef ZIPLIST_TEST_MAIN
ffc15852 925#include <sys/time.h>
306c6a02
PN
926#include "adlist.h"
927#include "sds.h"
928
929#define debug(f, ...) { if (DEBUG) printf(f, __VA_ARGS__); }
11ac6ff6 930
08253bf4
PN
931unsigned char *createList() {
932 unsigned char *zl = ziplistNew();
b84186ff
PN
933 zl = ziplistPush(zl, (unsigned char*)"foo", 3, ZIPLIST_TAIL);
934 zl = ziplistPush(zl, (unsigned char*)"quux", 4, ZIPLIST_TAIL);
935 zl = ziplistPush(zl, (unsigned char*)"hello", 5, ZIPLIST_HEAD);
936 zl = ziplistPush(zl, (unsigned char*)"1024", 4, ZIPLIST_TAIL);
08253bf4
PN
937 return zl;
938}
939
29b14d5f
PN
940unsigned char *createIntList() {
941 unsigned char *zl = ziplistNew();
942 char buf[32];
943
944 sprintf(buf, "100");
b84186ff 945 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
29b14d5f 946 sprintf(buf, "128000");
b84186ff 947 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
29b14d5f 948 sprintf(buf, "-100");
b84186ff 949 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_HEAD);
29b14d5f 950 sprintf(buf, "4294967296");
b84186ff 951 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_HEAD);
29b14d5f 952 sprintf(buf, "non integer");
b84186ff 953 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
29b14d5f 954 sprintf(buf, "much much longer non integer");
b84186ff 955 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
29b14d5f
PN
956 return zl;
957}
958
ffc15852
PN
959long long usec(void) {
960 struct timeval tv;
961 gettimeofday(&tv,NULL);
962 return (((long long)tv.tv_sec)*1000000)+tv.tv_usec;
963}
964
965void stress(int pos, int num, int maxsize, int dnum) {
966 int i,j,k;
967 unsigned char *zl;
968 char posstr[2][5] = { "HEAD", "TAIL" };
969 long long start;
970 for (i = 0; i < maxsize; i+=dnum) {
971 zl = ziplistNew();
972 for (j = 0; j < i; j++) {
973 zl = ziplistPush(zl,(unsigned char*)"quux",4,ZIPLIST_TAIL);
974 }
975
976 /* Do num times a push+pop from pos */
977 start = usec();
978 for (k = 0; k < num; k++) {
979 zl = ziplistPush(zl,(unsigned char*)"quux",4,pos);
980 zl = ziplistDeleteRange(zl,0,1);
981 }
982 printf("List size: %8d, bytes: %8d, %dx push+pop (%s): %6lld usec\n",
56538477 983 i,intrev32ifbe(ZIPLIST_BYTES(zl)),num,posstr[pos],usec()-start);
ffc15852
PN
984 zfree(zl);
985 }
986}
987
306974f5
PN
988void pop(unsigned char *zl, int where) {
989 unsigned char *p, *vstr;
990 unsigned int vlen;
991 long long vlong;
992
993 p = ziplistIndex(zl,where == ZIPLIST_HEAD ? 0 : -1);
994 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
995 if (where == ZIPLIST_HEAD)
996 printf("Pop head: ");
997 else
998 printf("Pop tail: ");
999
1000 if (vstr)
10c12171 1001 if (vlen && fwrite(vstr,vlen,1,stdout) == 0) perror("fwrite");
306974f5
PN
1002 else
1003 printf("%lld", vlong);
1004
1005 printf("\n");
1006 ziplistDeleteRange(zl,-1,1);
1007 } else {
1008 printf("ERROR: Could not pop\n");
1009 exit(1);
1010 }
1011}
1012
b7d3bf51 1013int randstring(char *target, unsigned int min, unsigned int max) {
306c6a02
PN
1014 int p, len = min+rand()%(max-min+1);
1015 int minval, maxval;
1016 switch(rand() % 3) {
1017 case 0:
1018 minval = 0;
1019 maxval = 255;
1020 break;
1021 case 1:
1022 minval = 48;
1023 maxval = 122;
1024 break;
1025 case 2:
1026 minval = 48;
1027 maxval = 52;
1028 break;
1029 default:
1030 assert(NULL);
1031 }
1032
1033 while(p < len)
1034 target[p++] = minval+rand()%(maxval-minval+1);
b7d3bf51 1035 return len;
306c6a02
PN
1036}
1037
89bf6f58
PN
1038void verify(unsigned char *zl, zlentry *e) {
1039 int i;
1040 int len = ziplistLen(zl);
1041 zlentry _e;
1042
1043 for (i = 0; i < len; i++) {
1044 memset(&e[i], 0, sizeof(zlentry));
1045 e[i] = zipEntry(ziplistIndex(zl, i));
1046
1047 memset(&_e, 0, sizeof(zlentry));
1048 _e = zipEntry(ziplistIndex(zl, -len+i));
1049
1050 assert(memcmp(&e[i], &_e, sizeof(zlentry)) == 0);
1051 }
1052}
1053
08253bf4 1054int main(int argc, char **argv) {
a24ba809 1055 unsigned char *zl, *p;
b84186ff 1056 unsigned char *entry;
335d16bc 1057 unsigned int elen;
75d8978e 1058 long long value;
08253bf4 1059
84403fe7
PN
1060 /* If an argument is given, use it as the random seed. */
1061 if (argc == 2)
1062 srand(atoi(argv[1]));
1063
29b14d5f
PN
1064 zl = createIntList();
1065 ziplistRepr(zl);
1066
08253bf4 1067 zl = createList();
11ac6ff6
PN
1068 ziplistRepr(zl);
1069
306974f5 1070 pop(zl,ZIPLIST_TAIL);
11ac6ff6
PN
1071 ziplistRepr(zl);
1072
306974f5 1073 pop(zl,ZIPLIST_HEAD);
11ac6ff6
PN
1074 ziplistRepr(zl);
1075
306974f5 1076 pop(zl,ZIPLIST_TAIL);
dcb9cf4e
PN
1077 ziplistRepr(zl);
1078
306974f5 1079 pop(zl,ZIPLIST_TAIL);
dcb9cf4e
PN
1080 ziplistRepr(zl);
1081
c03206fd
PN
1082 printf("Get element at index 3:\n");
1083 {
1084 zl = createList();
1085 p = ziplistIndex(zl, 3);
1086 if (!ziplistGet(p, &entry, &elen, &value)) {
1087 printf("ERROR: Could not access index 3\n");
1088 return 1;
1089 }
1090 if (entry) {
10c12171 1091 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
c03206fd
PN
1092 printf("\n");
1093 } else {
1094 printf("%lld\n", value);
1095 }
1096 printf("\n");
1097 }
1098
1099 printf("Get element at index 4 (out of range):\n");
1100 {
1101 zl = createList();
1102 p = ziplistIndex(zl, 4);
1103 if (p == NULL) {
1104 printf("No entry\n");
1105 } else {
1106 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
1107 return 1;
1108 }
1109 printf("\n");
1110 }
1111
1112 printf("Get element at index -1 (last element):\n");
1113 {
1114 zl = createList();
1115 p = ziplistIndex(zl, -1);
1116 if (!ziplistGet(p, &entry, &elen, &value)) {
1117 printf("ERROR: Could not access index -1\n");
1118 return 1;
1119 }
1120 if (entry) {
10c12171 1121 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
c03206fd
PN
1122 printf("\n");
1123 } else {
1124 printf("%lld\n", value);
1125 }
1126 printf("\n");
1127 }
1128
1129 printf("Get element at index -4 (first element):\n");
1130 {
1131 zl = createList();
1132 p = ziplistIndex(zl, -4);
1133 if (!ziplistGet(p, &entry, &elen, &value)) {
1134 printf("ERROR: Could not access index -4\n");
1135 return 1;
1136 }
1137 if (entry) {
10c12171 1138 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
c03206fd
PN
1139 printf("\n");
1140 } else {
1141 printf("%lld\n", value);
1142 }
1143 printf("\n");
1144 }
1145
1146 printf("Get element at index -5 (reverse out of range):\n");
1147 {
1148 zl = createList();
1149 p = ziplistIndex(zl, -5);
1150 if (p == NULL) {
1151 printf("No entry\n");
1152 } else {
1153 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
1154 return 1;
1155 }
1156 printf("\n");
1157 }
1158
08253bf4
PN
1159 printf("Iterate list from 0 to end:\n");
1160 {
1161 zl = createList();
1162 p = ziplistIndex(zl, 0);
75d8978e 1163 while (ziplistGet(p, &entry, &elen, &value)) {
335d16bc 1164 printf("Entry: ");
75d8978e 1165 if (entry) {
10c12171 1166 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
75d8978e
PN
1167 } else {
1168 printf("%lld", value);
1169 }
8632fb30 1170 p = ziplistNext(zl,p);
75d8978e 1171 printf("\n");
08253bf4
PN
1172 }
1173 printf("\n");
1174 }
1175
1176 printf("Iterate list from 1 to end:\n");
1177 {
1178 zl = createList();
1179 p = ziplistIndex(zl, 1);
75d8978e 1180 while (ziplistGet(p, &entry, &elen, &value)) {
335d16bc 1181 printf("Entry: ");
75d8978e 1182 if (entry) {
10c12171 1183 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
75d8978e
PN
1184 } else {
1185 printf("%lld", value);
1186 }
8632fb30 1187 p = ziplistNext(zl,p);
75d8978e 1188 printf("\n");
08253bf4
PN
1189 }
1190 printf("\n");
1191 }
1192
1193 printf("Iterate list from 2 to end:\n");
1194 {
1195 zl = createList();
1196 p = ziplistIndex(zl, 2);
75d8978e 1197 while (ziplistGet(p, &entry, &elen, &value)) {
335d16bc 1198 printf("Entry: ");
75d8978e 1199 if (entry) {
10c12171 1200 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
75d8978e
PN
1201 } else {
1202 printf("%lld", value);
1203 }
8632fb30 1204 p = ziplistNext(zl,p);
75d8978e 1205 printf("\n");
08253bf4
PN
1206 }
1207 printf("\n");
1208 }
1209
1210 printf("Iterate starting out of range:\n");
1211 {
1212 zl = createList();
75d8978e
PN
1213 p = ziplistIndex(zl, 4);
1214 if (!ziplistGet(p, &entry, &elen, &value)) {
08253bf4
PN
1215 printf("No entry\n");
1216 } else {
1217 printf("ERROR\n");
1218 }
779deb60
PN
1219 printf("\n");
1220 }
1221
0f3dfa87
PN
1222 printf("Iterate from back to front:\n");
1223 {
1224 zl = createList();
1225 p = ziplistIndex(zl, -1);
1226 while (ziplistGet(p, &entry, &elen, &value)) {
1227 printf("Entry: ");
1228 if (entry) {
10c12171 1229 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
0f3dfa87
PN
1230 } else {
1231 printf("%lld", value);
1232 }
8632fb30 1233 p = ziplistPrev(zl,p);
0f3dfa87
PN
1234 printf("\n");
1235 }
1236 printf("\n");
1237 }
1238
1239 printf("Iterate from back to front, deleting all items:\n");
1240 {
1241 zl = createList();
1242 p = ziplistIndex(zl, -1);
1243 while (ziplistGet(p, &entry, &elen, &value)) {
1244 printf("Entry: ");
1245 if (entry) {
10c12171 1246 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
0f3dfa87
PN
1247 } else {
1248 printf("%lld", value);
1249 }
8632fb30
PN
1250 zl = ziplistDelete(zl,&p);
1251 p = ziplistPrev(zl,p);
0f3dfa87
PN
1252 printf("\n");
1253 }
1254 printf("\n");
1255 }
1256
779deb60
PN
1257 printf("Delete inclusive range 0,0:\n");
1258 {
1259 zl = createList();
ba5b4bde 1260 zl = ziplistDeleteRange(zl, 0, 1);
779deb60
PN
1261 ziplistRepr(zl);
1262 }
1263
1264 printf("Delete inclusive range 0,1:\n");
1265 {
1266 zl = createList();
ba5b4bde 1267 zl = ziplistDeleteRange(zl, 0, 2);
779deb60
PN
1268 ziplistRepr(zl);
1269 }
1270
1271 printf("Delete inclusive range 1,2:\n");
1272 {
1273 zl = createList();
ba5b4bde 1274 zl = ziplistDeleteRange(zl, 1, 2);
779deb60
PN
1275 ziplistRepr(zl);
1276 }
1277
1278 printf("Delete with start index out of range:\n");
1279 {
1280 zl = createList();
ba5b4bde 1281 zl = ziplistDeleteRange(zl, 5, 1);
779deb60
PN
1282 ziplistRepr(zl);
1283 }
1284
1285 printf("Delete with num overflow:\n");
1286 {
1287 zl = createList();
ba5b4bde 1288 zl = ziplistDeleteRange(zl, 1, 5);
779deb60 1289 ziplistRepr(zl);
08253bf4
PN
1290 }
1291
0f10458c
PN
1292 printf("Delete foo while iterating:\n");
1293 {
1294 zl = createList();
b84186ff
PN
1295 p = ziplistIndex(zl,0);
1296 while (ziplistGet(p,&entry,&elen,&value)) {
1297 if (entry && strncmp("foo",(char*)entry,elen) == 0) {
0f10458c 1298 printf("Delete foo\n");
b84186ff 1299 zl = ziplistDelete(zl,&p);
0f10458c
PN
1300 } else {
1301 printf("Entry: ");
75d8978e 1302 if (entry) {
10c12171 1303 if (elen && fwrite(entry,elen,1,stdout) == 0)
1304 perror("fwrite");
75d8978e 1305 } else {
b84186ff 1306 printf("%lld",value);
75d8978e 1307 }
b84186ff 1308 p = ziplistNext(zl,p);
75d8978e 1309 printf("\n");
0f10458c
PN
1310 }
1311 }
1312 printf("\n");
1313 ziplistRepr(zl);
c09c2c3b
PN
1314 }
1315
b0d605c1
PN
1316 printf("Regression test for >255 byte strings:\n");
1317 {
1318 char v1[257],v2[257];
1319 memset(v1,'x',256);
1320 memset(v2,'y',256);
1321 zl = ziplistNew();
1322 zl = ziplistPush(zl,(unsigned char*)v1,strlen(v1),ZIPLIST_TAIL);
1323 zl = ziplistPush(zl,(unsigned char*)v2,strlen(v2),ZIPLIST_TAIL);
1324
1325 /* Pop values again and compare their value. */
1326 p = ziplistIndex(zl,0);
1327 assert(ziplistGet(p,&entry,&elen,&value));
306c6a02 1328 assert(strncmp(v1,(char*)entry,elen) == 0);
b0d605c1
PN
1329 p = ziplistIndex(zl,1);
1330 assert(ziplistGet(p,&entry,&elen,&value));
306c6a02 1331 assert(strncmp(v2,(char*)entry,elen) == 0);
b0d605c1
PN
1332 printf("SUCCESS\n\n");
1333 }
1334
89bf6f58
PN
1335 printf("Regression test deleting next to last entries:\n");
1336 {
1337 char v[3][257];
1338 zlentry e[3];
1339 int i;
1340
1341 for (i = 0; i < (sizeof(v)/sizeof(v[0])); i++) {
1342 memset(v[i], 'a' + i, sizeof(v[0]));
1343 }
1344
1345 v[0][256] = '\0';
1346 v[1][ 1] = '\0';
1347 v[2][256] = '\0';
1348
1349 zl = ziplistNew();
1350 for (i = 0; i < (sizeof(v)/sizeof(v[0])); i++) {
1351 zl = ziplistPush(zl, (unsigned char *) v[i], strlen(v[i]), ZIPLIST_TAIL);
1352 }
1353
1354 verify(zl, e);
1355
1356 assert(e[0].prevrawlensize == 1);
1357 assert(e[1].prevrawlensize == 5);
1358 assert(e[2].prevrawlensize == 1);
1359
1360 /* Deleting entry 1 will increase `prevrawlensize` for entry 2 */
1361 unsigned char *p = e[1].p;
1362 zl = ziplistDelete(zl, &p);
1363
1364 verify(zl, e);
1365
1366 assert(e[0].prevrawlensize == 1);
1367 assert(e[1].prevrawlensize == 5);
1368
1369 printf("SUCCESS\n\n");
1370 }
1371
dbaa41c6
PN
1372 printf("Create long list and check indices:\n");
1373 {
1374 zl = ziplistNew();
1375 char buf[32];
1376 int i,len;
1377 for (i = 0; i < 1000; i++) {
1378 len = sprintf(buf,"%d",i);
b84186ff 1379 zl = ziplistPush(zl,(unsigned char*)buf,len,ZIPLIST_TAIL);
dbaa41c6
PN
1380 }
1381 for (i = 0; i < 1000; i++) {
1382 p = ziplistIndex(zl,i);
1383 assert(ziplistGet(p,NULL,NULL,&value));
1384 assert(i == value);
1385
1386 p = ziplistIndex(zl,-i-1);
1387 assert(ziplistGet(p,NULL,NULL,&value));
1388 assert(999-i == value);
1389 }
1390 printf("SUCCESS\n\n");
1391 }
1392
c09c2c3b
PN
1393 printf("Compare strings with ziplist entries:\n");
1394 {
1395 zl = createList();
b84186ff
PN
1396 p = ziplistIndex(zl,0);
1397 if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
dcb9cf4e 1398 printf("ERROR: not \"hello\"\n");
a24ba809 1399 return 1;
c09c2c3b 1400 }
b84186ff 1401 if (ziplistCompare(p,(unsigned char*)"hella",5)) {
dcb9cf4e 1402 printf("ERROR: \"hella\"\n");
a24ba809 1403 return 1;
c09c2c3b
PN
1404 }
1405
b84186ff
PN
1406 p = ziplistIndex(zl,3);
1407 if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
dcb9cf4e 1408 printf("ERROR: not \"1024\"\n");
a24ba809 1409 return 1;
c09c2c3b 1410 }
b84186ff 1411 if (ziplistCompare(p,(unsigned char*)"1025",4)) {
dcb9cf4e 1412 printf("ERROR: \"1025\"\n");
a24ba809 1413 return 1;
c09c2c3b 1414 }
169d2ef1
PN
1415 printf("SUCCESS\n\n");
1416 }
1417
1418 printf("Stress with random payloads of different encoding:\n");
1419 {
306c6a02 1420 int i,j,len,where;
169d2ef1 1421 unsigned char *p;
306c6a02 1422 char buf[1024];
b7d3bf51 1423 int buflen;
306c6a02
PN
1424 list *ref;
1425 listNode *refnode;
1426
1427 /* Hold temp vars from ziplist */
1428 unsigned char *sstr;
1429 unsigned int slen;
1430 long long sval;
1431
306c6a02
PN
1432 for (i = 0; i < 20000; i++) {
1433 zl = ziplistNew();
1434 ref = listCreate();
1435 listSetFreeMethod(ref,sdsfree);
1436 len = rand() % 256;
1437
1438 /* Create lists */
1439 for (j = 0; j < len; j++) {
1440 where = (rand() & 1) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
b7d3bf51
PN
1441 if (rand() % 2) {
1442 buflen = randstring(buf,1,sizeof(buf)-1);
1443 } else {
1444 switch(rand() % 3) {
1445 case 0:
1446 buflen = sprintf(buf,"%lld",(0LL + rand()) >> 20);
1447 break;
1448 case 1:
1449 buflen = sprintf(buf,"%lld",(0LL + rand()));
1450 break;
1451 case 2:
1452 buflen = sprintf(buf,"%lld",(0LL + rand()) << 20);
1453 break;
1454 default:
1455 assert(NULL);
1456 }
306c6a02
PN
1457 }
1458
1459 /* Add to ziplist */
b7d3bf51 1460 zl = ziplistPush(zl, (unsigned char*)buf, buflen, where);
169d2ef1 1461
306c6a02
PN
1462 /* Add to reference list */
1463 if (where == ZIPLIST_HEAD) {
b7d3bf51 1464 listAddNodeHead(ref,sdsnewlen(buf, buflen));
306c6a02 1465 } else if (where == ZIPLIST_TAIL) {
b7d3bf51 1466 listAddNodeTail(ref,sdsnewlen(buf, buflen));
306c6a02
PN
1467 } else {
1468 assert(NULL);
1469 }
169d2ef1
PN
1470 }
1471
306c6a02
PN
1472 assert(listLength(ref) == ziplistLen(zl));
1473 for (j = 0; j < len; j++) {
1474 /* Naive way to get elements, but similar to the stresser
1475 * executed from the Tcl test suite. */
1476 p = ziplistIndex(zl,j);
1477 refnode = listIndex(ref,j);
1478
1479 assert(ziplistGet(p,&sstr,&slen,&sval));
1480 if (sstr == NULL) {
b7d3bf51 1481 buflen = sprintf(buf,"%lld",sval);
306c6a02 1482 } else {
b7d3bf51
PN
1483 buflen = slen;
1484 memcpy(buf,sstr,buflen);
1485 buf[buflen] = '\0';
306c6a02 1486 }
b7d3bf51 1487 assert(memcmp(buf,listNodeValue(refnode),buflen) == 0);
306c6a02
PN
1488 }
1489 zfree(zl);
1490 listRelease(ref);
169d2ef1
PN
1491 }
1492 printf("SUCCESS\n\n");
0f10458c
PN
1493 }
1494
ffc15852
PN
1495 printf("Stress with variable ziplist size:\n");
1496 {
1497 stress(ZIPLIST_HEAD,100000,16384,256);
1498 stress(ZIPLIST_TAIL,100000,16384,256);
1499 }
1500
11ac6ff6
PN
1501 return 0;
1502}
ffc15852 1503
11ac6ff6 1504#endif