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