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