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