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