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