]> git.saurik.com Git - redis.git/blame - src/ziplist.c
free memory if the maxmemory parameter is reduced via CONFIG SET
[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;
412 } else {
413 if (next.prevrawlensize > rawlensize) {
414 /* This would result in shrinking, which we want to avoid.
415 * So, set "rawlen" in the available bytes. */
416 zipPrevEncodeLengthForceLarge(p+rawlen,rawlen);
417 } else {
418 zipPrevEncodeLength(p+rawlen,rawlen);
419 }
420
421 /* Stop here, as the raw length of "next" has not changed. */
422 break;
423 }
424 }
425 return zl;
426}
427
0c0d0564 428/* Delete "num" entries, starting at "p". Returns pointer to the ziplist. */
b6eb9703 429static unsigned char *__ziplistDelete(unsigned char *zl, unsigned char *p, unsigned int num) {
0c0d0564 430 unsigned int i, totlen, deleted = 0;
169d2ef1
PN
431 int offset, nextdiff = 0;
432 zlentry first, tail;
433
434 first = zipEntry(p);
0c0d0564
PN
435 for (i = 0; p[0] != ZIP_END && i < num; i++) {
436 p += zipRawEntryLength(p);
437 deleted++;
438 }
439
440 totlen = p-first.p;
441 if (totlen > 0) {
442 if (p[0] != ZIP_END) {
443 /* Tricky: storing the prevlen in this entry might reduce or
444 * increase the number of bytes needed, compared to the current
445 * prevlen. Note that we can always store this length because
446 * it was previously stored by an entry that is being deleted. */
447 nextdiff = zipPrevLenByteDiff(p,first.prevrawlen);
7b1f85c0 448 zipPrevEncodeLength(p-nextdiff,first.prevrawlen);
0c0d0564
PN
449
450 /* Update offset for tail */
169d2ef1
PN
451 ZIPLIST_TAIL_OFFSET(zl) -= totlen;
452
453 /* When the tail contains more than one entry, we need to take
454 * "nextdiff" in account as well. Otherwise, a change in the
455 * size of prevlen doesn't have an effect on the *tail* offset. */
456 tail = zipEntry(p);
457 if (p[tail.headersize+tail.len] != ZIP_END)
458 ZIPLIST_TAIL_OFFSET(zl) += nextdiff;
0c0d0564
PN
459
460 /* Move tail to the front of the ziplist */
461 memmove(first.p,p-nextdiff,ZIPLIST_BYTES(zl)-(p-zl)-1+nextdiff);
462 } else {
463 /* The entire tail was deleted. No need to move memory. */
464 ZIPLIST_TAIL_OFFSET(zl) = (first.p-zl)-first.prevrawlen;
465 }
466
467 /* Resize and update length */
169d2ef1 468 offset = first.p-zl;
0c0d0564
PN
469 zl = ziplistResize(zl, ZIPLIST_BYTES(zl)-totlen+nextdiff);
470 ZIPLIST_INCR_LENGTH(zl,-deleted);
169d2ef1
PN
471 p = zl+offset;
472
473 /* When nextdiff != 0, the raw length of the next entry has changed, so
474 * we need to cascade the update throughout the ziplist */
475 if (nextdiff != 0)
476 zl = __ziplistCascadeUpdate(zl,p);
0c0d0564
PN
477 }
478 return zl;
11ac6ff6
PN
479}
480
6435c767 481/* Insert item at "p". */
b6eb9703 482static unsigned char *__ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
6435c767
PN
483 unsigned int curlen = ZIPLIST_BYTES(zl), reqlen, prevlen = 0;
484 unsigned int offset, nextdiff = 0;
c4705381 485 unsigned char encoding = 0;
29b14d5f 486 long long value;
169d2ef1 487 zlentry entry, tail;
11ac6ff6 488
6435c767
PN
489 /* Find out prevlen for the entry that is inserted. */
490 if (p[0] != ZIP_END) {
491 entry = zipEntry(p);
492 prevlen = entry.prevrawlen;
dcb9cf4e 493 } else {
169d2ef1
PN
494 unsigned char *ptail = ZIPLIST_ENTRY_TAIL(zl);
495 if (ptail[0] != ZIP_END) {
496 prevlen = zipRawEntryLength(ptail);
6435c767 497 }
dcb9cf4e
PN
498 }
499
29b14d5f 500 /* See if the entry can be encoded */
61712508 501 if (zipTryEncoding(s,slen,&value,&encoding)) {
c4705381
PN
502 /* 'encoding' is set to the appropriate integer encoding */
503 reqlen = zipIntSize(encoding);
29b14d5f 504 } else {
c4705381
PN
505 /* 'encoding' is untouched, however zipEncodeLength will use the
506 * string length to figure out how to encode it. */
6435c767 507 reqlen = slen;
29b14d5f 508 }
dcb9cf4e
PN
509 /* We need space for both the length of the previous entry and
510 * the length of the payload. */
7b1f85c0 511 reqlen += zipPrevEncodeLength(NULL,prevlen);
6435c767
PN
512 reqlen += zipEncodeLength(NULL,encoding,slen);
513
514 /* When the insert position is not equal to the tail, we need to
515 * make sure that the next entry can hold this entry's length in
516 * its prevlen field. */
177a0a0b 517 nextdiff = (p[0] != ZIP_END) ? zipPrevLenByteDiff(p,reqlen) : 0;
6435c767
PN
518
519 /* Store offset because a realloc may change the address of zl. */
520 offset = p-zl;
521 zl = ziplistResize(zl,curlen+reqlen+nextdiff);
522 p = zl+offset;
523
524 /* Apply memory move when necessary and update tail offset. */
525 if (p[0] != ZIP_END) {
526 /* Subtract one because of the ZIP_END bytes */
527 memmove(p+reqlen,p-nextdiff,curlen-offset-1+nextdiff);
169d2ef1 528
6435c767 529 /* Encode this entry's raw length in the next entry. */
7b1f85c0 530 zipPrevEncodeLength(p+reqlen,reqlen);
169d2ef1 531
6435c767 532 /* Update offset for tail */
169d2ef1
PN
533 ZIPLIST_TAIL_OFFSET(zl) += reqlen;
534
535 /* When the tail contains more than one entry, we need to take
536 * "nextdiff" in account as well. Otherwise, a change in the
537 * size of prevlen doesn't have an effect on the *tail* offset. */
538 tail = zipEntry(p+reqlen);
539 if (p[reqlen+tail.headersize+tail.len] != ZIP_END)
540 ZIPLIST_TAIL_OFFSET(zl) += nextdiff;
11ac6ff6 541 } else {
6435c767
PN
542 /* This element will be the new tail. */
543 ZIPLIST_TAIL_OFFSET(zl) = p-zl;
dcb9cf4e
PN
544 }
545
169d2ef1
PN
546 /* When nextdiff != 0, the raw length of the next entry has changed, so
547 * we need to cascade the update throughout the ziplist */
548 if (nextdiff != 0) {
549 offset = p-zl;
550 zl = __ziplistCascadeUpdate(zl,p+reqlen);
551 p = zl+offset;
552 }
553
11ac6ff6 554 /* Write the entry */
7b1f85c0 555 p += zipPrevEncodeLength(p,prevlen);
6435c767 556 p += zipEncodeLength(p,encoding,slen);
c4705381 557 if (ZIP_IS_STR(encoding)) {
6435c767 558 memcpy(p,s,slen);
c4705381
PN
559 } else {
560 zipSaveInteger(p,value,encoding);
29b14d5f 561 }
f6eb1747 562 ZIPLIST_INCR_LENGTH(zl,1);
11ac6ff6
PN
563 return zl;
564}
565
b6eb9703 566unsigned char *ziplistPush(unsigned char *zl, unsigned char *s, unsigned int slen, int where) {
6435c767 567 unsigned char *p;
1ce81fa5 568 p = (where == ZIPLIST_HEAD) ? ZIPLIST_ENTRY_HEAD(zl) : ZIPLIST_ENTRY_END(zl);
6435c767
PN
569 return __ziplistInsert(zl,p,s,slen);
570}
571
c03206fd
PN
572/* Returns an offset to use for iterating with ziplistNext. When the given
573 * index is negative, the list is traversed back to front. When the list
574 * doesn't contain an element at the provided index, NULL is returned. */
575unsigned char *ziplistIndex(unsigned char *zl, int index) {
576 unsigned char *p;
577 zlentry entry;
578 if (index < 0) {
579 index = (-index)-1;
580 p = ZIPLIST_ENTRY_TAIL(zl);
581 if (p[0] != ZIP_END) {
582 entry = zipEntry(p);
583 while (entry.prevrawlen > 0 && index--) {
584 p -= entry.prevrawlen;
585 entry = zipEntry(p);
586 }
587 }
588 } else {
589 p = ZIPLIST_ENTRY_HEAD(zl);
590 while (p[0] != ZIP_END && index--) {
591 p += zipRawEntryLength(p);
592 }
08253bf4 593 }
177a0a0b 594 return (p[0] == ZIP_END || index > 0) ? NULL : p;
08253bf4
PN
595}
596
75d8978e 597/* Return pointer to next entry in ziplist. */
8632fb30
PN
598unsigned char *ziplistNext(unsigned char *zl, unsigned char *p) {
599 ((void) zl);
d71b9865
PN
600
601 /* "p" could be equal to ZIP_END, caused by ziplistDelete,
602 * and we should return NULL. Otherwise, we should return NULL
603 * when the *next* element is ZIP_END (there is no next entry). */
604 if (p[0] == ZIP_END) {
605 return NULL;
606 } else {
607 p = p+zipRawEntryLength(p);
608 return (p[0] == ZIP_END) ? NULL : p;
609 }
75d8978e
PN
610}
611
033fb554 612/* Return pointer to previous entry in ziplist. */
8632fb30
PN
613unsigned char *ziplistPrev(unsigned char *zl, unsigned char *p) {
614 zlentry entry;
615
616 /* Iterating backwards from ZIP_END should return the tail. When "p" is
617 * equal to the first element of the list, we're already at the head,
618 * and should return NULL. */
619 if (p[0] == ZIP_END) {
620 p = ZIPLIST_ENTRY_TAIL(zl);
621 return (p[0] == ZIP_END) ? NULL : p;
622 } else if (p == ZIPLIST_ENTRY_HEAD(zl)) {
623 return NULL;
624 } else {
625 entry = zipEntry(p);
169d2ef1 626 assert(entry.prevrawlen > 0);
8632fb30
PN
627 return p-entry.prevrawlen;
628 }
033fb554
PN
629}
630
75d8978e
PN
631/* Get entry pointer to by 'p' and store in either 'e' or 'v' depending
632 * on the encoding of the entry. 'e' is always set to NULL to be able
633 * to find out whether the string pointer or the integer value was set.
634 * Return 0 if 'p' points to the end of the zipmap, 1 otherwise. */
b6eb9703 635unsigned int ziplistGet(unsigned char *p, unsigned char **sstr, unsigned int *slen, long long *sval) {
a5456b2c 636 zlentry entry;
c03206fd 637 if (p == NULL || p[0] == ZIP_END) return 0;
03e52931 638 if (sstr) *sstr = NULL;
dcb9cf4e 639
a5456b2c 640 entry = zipEntry(p);
c4705381 641 if (ZIP_IS_STR(entry.encoding)) {
03e52931
PN
642 if (sstr) {
643 *slen = entry.len;
b6eb9703 644 *sstr = p+entry.headersize;
75d8978e
PN
645 }
646 } else {
03e52931
PN
647 if (sval) {
648 *sval = zipLoadInteger(p+entry.headersize,entry.encoding);
75d8978e 649 }
08253bf4 650 }
75d8978e 651 return 1;
08253bf4
PN
652}
653
033fb554 654/* Insert an entry at "p". */
b6eb9703 655unsigned char *ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
033fb554 656 return __ziplistInsert(zl,p,s,slen);
779deb60
PN
657}
658
0f10458c
PN
659/* Delete a single entry from the ziplist, pointed to by *p.
660 * Also update *p in place, to be able to iterate over the
661 * ziplist, while deleting entries. */
6a8e35ad 662unsigned char *ziplistDelete(unsigned char *zl, unsigned char **p) {
0c0d0564
PN
663 unsigned int offset = *p-zl;
664 zl = __ziplistDelete(zl,*p,1);
0f10458c 665
0c0d0564 666 /* Store pointer to current element in p, because ziplistDelete will
0f3dfa87
PN
667 * do a realloc which might result in a different "zl"-pointer.
668 * When the delete direction is back to front, we might delete the last
669 * entry and end up with "p" pointing to ZIP_END, so check this. */
6a8e35ad 670 *p = zl+offset;
0f10458c
PN
671 return zl;
672}
673
033fb554
PN
674/* Delete a range of entries from the ziplist. */
675unsigned char *ziplistDeleteRange(unsigned char *zl, unsigned int index, unsigned int num) {
676 unsigned char *p = ziplistIndex(zl,index);
677 return (p == NULL) ? zl : __ziplistDelete(zl,p,num);
678}
679
c09c2c3b 680/* Compare entry pointer to by 'p' with 'entry'. Return 1 if equal. */
b6eb9703 681unsigned int ziplistCompare(unsigned char *p, unsigned char *sstr, unsigned int slen) {
a5456b2c 682 zlentry entry;
b6eb9703
PN
683 unsigned char sencoding;
684 long long zval, sval;
177a0a0b 685 if (p[0] == ZIP_END) return 0;
c09c2c3b 686
a5456b2c 687 entry = zipEntry(p);
c4705381 688 if (ZIP_IS_STR(entry.encoding)) {
c09c2c3b 689 /* Raw compare */
a5456b2c 690 if (entry.len == slen) {
03e52931 691 return memcmp(p+entry.headersize,sstr,slen) == 0;
c09c2c3b
PN
692 } else {
693 return 0;
694 }
c4aace90 695 } else {
d593c488 696 /* Try to compare encoded values */
61712508 697 if (zipTryEncoding(sstr,slen,&sval,&sencoding)) {
d593c488 698 if (entry.encoding == sencoding) {
b6eb9703
PN
699 zval = zipLoadInteger(p+entry.headersize,entry.encoding);
700 return zval == sval;
d593c488 701 }
c4aace90 702 }
c09c2c3b 703 }
c4aace90 704 return 0;
c09c2c3b
PN
705}
706
6205b463
PN
707/* Return length of ziplist. */
708unsigned int ziplistLen(unsigned char *zl) {
709 unsigned int len = 0;
e1f93d4b 710 if (ZIPLIST_LENGTH(zl) < UINT16_MAX) {
6205b463
PN
711 len = ZIPLIST_LENGTH(zl);
712 } else {
713 unsigned char *p = zl+ZIPLIST_HEADER_SIZE;
714 while (*p != ZIP_END) {
715 p += zipRawEntryLength(p);
716 len++;
717 }
718
719 /* Re-store length if small enough */
e1f93d4b 720 if (len < UINT16_MAX) ZIPLIST_LENGTH(zl) = len;
6205b463
PN
721 }
722 return len;
723}
724
4812cf28
PN
725/* Return size in bytes of ziplist. */
726unsigned int ziplistSize(unsigned char *zl) {
727 return ZIPLIST_BYTES(zl);
728}
729
11ac6ff6 730void ziplistRepr(unsigned char *zl) {
c8d9e7f4 731 unsigned char *p;
169d2ef1 732 int index = 0;
c8d9e7f4 733 zlentry entry;
11ac6ff6 734
169d2ef1
PN
735 printf(
736 "{total bytes %d} "
737 "{length %u}\n"
738 "{tail offset %u}\n",
739 ZIPLIST_BYTES(zl),
740 ZIPLIST_LENGTH(zl),
741 ZIPLIST_TAIL_OFFSET(zl));
1ce81fa5 742 p = ZIPLIST_ENTRY_HEAD(zl);
11ac6ff6 743 while(*p != ZIP_END) {
c8d9e7f4 744 entry = zipEntry(p);
169d2ef1
PN
745 printf(
746 "{"
747 "addr 0x%08lx, "
748 "index %2d, "
749 "offset %5ld, "
750 "rl: %5u, "
751 "hs %2u, "
752 "pl: %5u, "
753 "pls: %2u, "
754 "payload %5u"
755 "} ",
756 (long unsigned int)p,
757 index,
758 p-zl,
759 entry.headersize+entry.len,
760 entry.headersize,
761 entry.prevrawlen,
762 entry.prevrawlensize,
763 entry.len);
c8d9e7f4 764 p += entry.headersize;
c4705381 765 if (ZIP_IS_STR(entry.encoding)) {
169d2ef1
PN
766 if (entry.len > 40) {
767 fwrite(p,40,1,stdout);
768 printf("...");
769 } else {
770 fwrite(p,entry.len,1,stdout);
771 }
29b14d5f 772 } else {
3688d7f3 773 printf("%lld", (long long) zipLoadInteger(p,entry.encoding));
29b14d5f 774 }
11ac6ff6 775 printf("\n");
c8d9e7f4 776 p += entry.len;
169d2ef1 777 index++;
11ac6ff6
PN
778 }
779 printf("{end}\n\n");
780}
781
782#ifdef ZIPLIST_TEST_MAIN
ffc15852 783#include <sys/time.h>
11ac6ff6 784
08253bf4
PN
785unsigned char *createList() {
786 unsigned char *zl = ziplistNew();
b84186ff
PN
787 zl = ziplistPush(zl, (unsigned char*)"foo", 3, ZIPLIST_TAIL);
788 zl = ziplistPush(zl, (unsigned char*)"quux", 4, ZIPLIST_TAIL);
789 zl = ziplistPush(zl, (unsigned char*)"hello", 5, ZIPLIST_HEAD);
790 zl = ziplistPush(zl, (unsigned char*)"1024", 4, ZIPLIST_TAIL);
08253bf4
PN
791 return zl;
792}
793
29b14d5f
PN
794unsigned char *createIntList() {
795 unsigned char *zl = ziplistNew();
796 char buf[32];
797
798 sprintf(buf, "100");
b84186ff 799 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
29b14d5f 800 sprintf(buf, "128000");
b84186ff 801 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
29b14d5f 802 sprintf(buf, "-100");
b84186ff 803 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_HEAD);
29b14d5f 804 sprintf(buf, "4294967296");
b84186ff 805 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_HEAD);
29b14d5f 806 sprintf(buf, "non integer");
b84186ff 807 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
29b14d5f 808 sprintf(buf, "much much longer non integer");
b84186ff 809 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
29b14d5f
PN
810 return zl;
811}
812
ffc15852
PN
813long long usec(void) {
814 struct timeval tv;
815 gettimeofday(&tv,NULL);
816 return (((long long)tv.tv_sec)*1000000)+tv.tv_usec;
817}
818
819void stress(int pos, int num, int maxsize, int dnum) {
820 int i,j,k;
821 unsigned char *zl;
822 char posstr[2][5] = { "HEAD", "TAIL" };
823 long long start;
824 for (i = 0; i < maxsize; i+=dnum) {
825 zl = ziplistNew();
826 for (j = 0; j < i; j++) {
827 zl = ziplistPush(zl,(unsigned char*)"quux",4,ZIPLIST_TAIL);
828 }
829
830 /* Do num times a push+pop from pos */
831 start = usec();
832 for (k = 0; k < num; k++) {
833 zl = ziplistPush(zl,(unsigned char*)"quux",4,pos);
834 zl = ziplistDeleteRange(zl,0,1);
835 }
836 printf("List size: %8d, bytes: %8d, %dx push+pop (%s): %6lld usec\n",
837 i,ZIPLIST_BYTES(zl),num,posstr[pos],usec()-start);
838 zfree(zl);
839 }
840}
841
306974f5
PN
842void pop(unsigned char *zl, int where) {
843 unsigned char *p, *vstr;
844 unsigned int vlen;
845 long long vlong;
846
847 p = ziplistIndex(zl,where == ZIPLIST_HEAD ? 0 : -1);
848 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
849 if (where == ZIPLIST_HEAD)
850 printf("Pop head: ");
851 else
852 printf("Pop tail: ");
853
854 if (vstr)
855 fwrite(vstr,vlen,1,stdout);
856 else
857 printf("%lld", vlong);
858
859 printf("\n");
860 ziplistDeleteRange(zl,-1,1);
861 } else {
862 printf("ERROR: Could not pop\n");
863 exit(1);
864 }
865}
866
08253bf4 867int main(int argc, char **argv) {
a24ba809 868 unsigned char *zl, *p;
b84186ff 869 unsigned char *entry;
335d16bc 870 unsigned int elen;
75d8978e 871 long long value;
08253bf4 872
84403fe7
PN
873 /* If an argument is given, use it as the random seed. */
874 if (argc == 2)
875 srand(atoi(argv[1]));
876
29b14d5f
PN
877 zl = createIntList();
878 ziplistRepr(zl);
879
08253bf4 880 zl = createList();
11ac6ff6
PN
881 ziplistRepr(zl);
882
306974f5 883 pop(zl,ZIPLIST_TAIL);
11ac6ff6
PN
884 ziplistRepr(zl);
885
306974f5 886 pop(zl,ZIPLIST_HEAD);
11ac6ff6
PN
887 ziplistRepr(zl);
888
306974f5 889 pop(zl,ZIPLIST_TAIL);
dcb9cf4e
PN
890 ziplistRepr(zl);
891
306974f5 892 pop(zl,ZIPLIST_TAIL);
dcb9cf4e
PN
893 ziplistRepr(zl);
894
c03206fd
PN
895 printf("Get element at index 3:\n");
896 {
897 zl = createList();
898 p = ziplistIndex(zl, 3);
899 if (!ziplistGet(p, &entry, &elen, &value)) {
900 printf("ERROR: Could not access index 3\n");
901 return 1;
902 }
903 if (entry) {
904 fwrite(entry,elen,1,stdout);
905 printf("\n");
906 } else {
907 printf("%lld\n", value);
908 }
909 printf("\n");
910 }
911
912 printf("Get element at index 4 (out of range):\n");
913 {
914 zl = createList();
915 p = ziplistIndex(zl, 4);
916 if (p == NULL) {
917 printf("No entry\n");
918 } else {
919 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
920 return 1;
921 }
922 printf("\n");
923 }
924
925 printf("Get element at index -1 (last element):\n");
926 {
927 zl = createList();
928 p = ziplistIndex(zl, -1);
929 if (!ziplistGet(p, &entry, &elen, &value)) {
930 printf("ERROR: Could not access index -1\n");
931 return 1;
932 }
933 if (entry) {
934 fwrite(entry,elen,1,stdout);
935 printf("\n");
936 } else {
937 printf("%lld\n", value);
938 }
939 printf("\n");
940 }
941
942 printf("Get element at index -4 (first element):\n");
943 {
944 zl = createList();
945 p = ziplistIndex(zl, -4);
946 if (!ziplistGet(p, &entry, &elen, &value)) {
947 printf("ERROR: Could not access index -4\n");
948 return 1;
949 }
950 if (entry) {
951 fwrite(entry,elen,1,stdout);
952 printf("\n");
953 } else {
954 printf("%lld\n", value);
955 }
956 printf("\n");
957 }
958
959 printf("Get element at index -5 (reverse out of range):\n");
960 {
961 zl = createList();
962 p = ziplistIndex(zl, -5);
963 if (p == NULL) {
964 printf("No entry\n");
965 } else {
966 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
967 return 1;
968 }
969 printf("\n");
970 }
971
08253bf4
PN
972 printf("Iterate list from 0 to end:\n");
973 {
974 zl = createList();
975 p = ziplistIndex(zl, 0);
75d8978e 976 while (ziplistGet(p, &entry, &elen, &value)) {
335d16bc 977 printf("Entry: ");
75d8978e
PN
978 if (entry) {
979 fwrite(entry,elen,1,stdout);
980 } else {
981 printf("%lld", value);
982 }
8632fb30 983 p = ziplistNext(zl,p);
75d8978e 984 printf("\n");
08253bf4
PN
985 }
986 printf("\n");
987 }
988
989 printf("Iterate list from 1 to end:\n");
990 {
991 zl = createList();
992 p = ziplistIndex(zl, 1);
75d8978e 993 while (ziplistGet(p, &entry, &elen, &value)) {
335d16bc 994 printf("Entry: ");
75d8978e
PN
995 if (entry) {
996 fwrite(entry,elen,1,stdout);
997 } else {
998 printf("%lld", value);
999 }
8632fb30 1000 p = ziplistNext(zl,p);
75d8978e 1001 printf("\n");
08253bf4
PN
1002 }
1003 printf("\n");
1004 }
1005
1006 printf("Iterate list from 2 to end:\n");
1007 {
1008 zl = createList();
1009 p = ziplistIndex(zl, 2);
75d8978e 1010 while (ziplistGet(p, &entry, &elen, &value)) {
335d16bc 1011 printf("Entry: ");
75d8978e
PN
1012 if (entry) {
1013 fwrite(entry,elen,1,stdout);
1014 } else {
1015 printf("%lld", value);
1016 }
8632fb30 1017 p = ziplistNext(zl,p);
75d8978e 1018 printf("\n");
08253bf4
PN
1019 }
1020 printf("\n");
1021 }
1022
1023 printf("Iterate starting out of range:\n");
1024 {
1025 zl = createList();
75d8978e
PN
1026 p = ziplistIndex(zl, 4);
1027 if (!ziplistGet(p, &entry, &elen, &value)) {
08253bf4
PN
1028 printf("No entry\n");
1029 } else {
1030 printf("ERROR\n");
1031 }
779deb60
PN
1032 printf("\n");
1033 }
1034
0f3dfa87
PN
1035 printf("Iterate from back to front:\n");
1036 {
1037 zl = createList();
1038 p = ziplistIndex(zl, -1);
1039 while (ziplistGet(p, &entry, &elen, &value)) {
1040 printf("Entry: ");
1041 if (entry) {
1042 fwrite(entry,elen,1,stdout);
1043 } else {
1044 printf("%lld", value);
1045 }
8632fb30 1046 p = ziplistPrev(zl,p);
0f3dfa87
PN
1047 printf("\n");
1048 }
1049 printf("\n");
1050 }
1051
1052 printf("Iterate from back to front, deleting all items:\n");
1053 {
1054 zl = createList();
1055 p = ziplistIndex(zl, -1);
1056 while (ziplistGet(p, &entry, &elen, &value)) {
1057 printf("Entry: ");
1058 if (entry) {
1059 fwrite(entry,elen,1,stdout);
1060 } else {
1061 printf("%lld", value);
1062 }
8632fb30
PN
1063 zl = ziplistDelete(zl,&p);
1064 p = ziplistPrev(zl,p);
0f3dfa87
PN
1065 printf("\n");
1066 }
1067 printf("\n");
1068 }
1069
779deb60
PN
1070 printf("Delete inclusive range 0,0:\n");
1071 {
1072 zl = createList();
ba5b4bde 1073 zl = ziplistDeleteRange(zl, 0, 1);
779deb60
PN
1074 ziplistRepr(zl);
1075 }
1076
1077 printf("Delete inclusive range 0,1:\n");
1078 {
1079 zl = createList();
ba5b4bde 1080 zl = ziplistDeleteRange(zl, 0, 2);
779deb60
PN
1081 ziplistRepr(zl);
1082 }
1083
1084 printf("Delete inclusive range 1,2:\n");
1085 {
1086 zl = createList();
ba5b4bde 1087 zl = ziplistDeleteRange(zl, 1, 2);
779deb60
PN
1088 ziplistRepr(zl);
1089 }
1090
1091 printf("Delete with start index out of range:\n");
1092 {
1093 zl = createList();
ba5b4bde 1094 zl = ziplistDeleteRange(zl, 5, 1);
779deb60
PN
1095 ziplistRepr(zl);
1096 }
1097
1098 printf("Delete with num overflow:\n");
1099 {
1100 zl = createList();
ba5b4bde 1101 zl = ziplistDeleteRange(zl, 1, 5);
779deb60 1102 ziplistRepr(zl);
08253bf4
PN
1103 }
1104
0f10458c
PN
1105 printf("Delete foo while iterating:\n");
1106 {
1107 zl = createList();
b84186ff
PN
1108 p = ziplistIndex(zl,0);
1109 while (ziplistGet(p,&entry,&elen,&value)) {
1110 if (entry && strncmp("foo",(char*)entry,elen) == 0) {
0f10458c 1111 printf("Delete foo\n");
b84186ff 1112 zl = ziplistDelete(zl,&p);
0f10458c
PN
1113 } else {
1114 printf("Entry: ");
75d8978e
PN
1115 if (entry) {
1116 fwrite(entry,elen,1,stdout);
1117 } else {
b84186ff 1118 printf("%lld",value);
75d8978e 1119 }
b84186ff 1120 p = ziplistNext(zl,p);
75d8978e 1121 printf("\n");
0f10458c
PN
1122 }
1123 }
1124 printf("\n");
1125 ziplistRepr(zl);
c09c2c3b
PN
1126 }
1127
b0d605c1
PN
1128 printf("Regression test for >255 byte strings:\n");
1129 {
1130 char v1[257],v2[257];
1131 memset(v1,'x',256);
1132 memset(v2,'y',256);
1133 zl = ziplistNew();
1134 zl = ziplistPush(zl,(unsigned char*)v1,strlen(v1),ZIPLIST_TAIL);
1135 zl = ziplistPush(zl,(unsigned char*)v2,strlen(v2),ZIPLIST_TAIL);
1136
1137 /* Pop values again and compare their value. */
1138 p = ziplistIndex(zl,0);
1139 assert(ziplistGet(p,&entry,&elen,&value));
1140 assert(strncmp(v1,entry,elen) == 0);
1141 p = ziplistIndex(zl,1);
1142 assert(ziplistGet(p,&entry,&elen,&value));
1143 assert(strncmp(v2,entry,elen) == 0);
1144 printf("SUCCESS\n\n");
1145 }
1146
dbaa41c6
PN
1147 printf("Create long list and check indices:\n");
1148 {
1149 zl = ziplistNew();
1150 char buf[32];
1151 int i,len;
1152 for (i = 0; i < 1000; i++) {
1153 len = sprintf(buf,"%d",i);
b84186ff 1154 zl = ziplistPush(zl,(unsigned char*)buf,len,ZIPLIST_TAIL);
dbaa41c6
PN
1155 }
1156 for (i = 0; i < 1000; i++) {
1157 p = ziplistIndex(zl,i);
1158 assert(ziplistGet(p,NULL,NULL,&value));
1159 assert(i == value);
1160
1161 p = ziplistIndex(zl,-i-1);
1162 assert(ziplistGet(p,NULL,NULL,&value));
1163 assert(999-i == value);
1164 }
1165 printf("SUCCESS\n\n");
1166 }
1167
c09c2c3b
PN
1168 printf("Compare strings with ziplist entries:\n");
1169 {
1170 zl = createList();
b84186ff
PN
1171 p = ziplistIndex(zl,0);
1172 if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
dcb9cf4e 1173 printf("ERROR: not \"hello\"\n");
a24ba809 1174 return 1;
c09c2c3b 1175 }
b84186ff 1176 if (ziplistCompare(p,(unsigned char*)"hella",5)) {
dcb9cf4e 1177 printf("ERROR: \"hella\"\n");
a24ba809 1178 return 1;
c09c2c3b
PN
1179 }
1180
b84186ff
PN
1181 p = ziplistIndex(zl,3);
1182 if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
dcb9cf4e 1183 printf("ERROR: not \"1024\"\n");
a24ba809 1184 return 1;
c09c2c3b 1185 }
b84186ff 1186 if (ziplistCompare(p,(unsigned char*)"1025",4)) {
dcb9cf4e 1187 printf("ERROR: \"1025\"\n");
a24ba809 1188 return 1;
c09c2c3b 1189 }
169d2ef1
PN
1190 printf("SUCCESS\n\n");
1191 }
1192
1193 printf("Stress with random payloads of different encoding:\n");
1194 {
1195 int i, idx, where, len;
1196 long long v;
1197 unsigned char *p;
1198 char buf[0x4041]; /* max length of generated string */
1199 zl = ziplistNew();
1200 for (i = 0; i < 100000; i++) {
1201 where = (rand() & 1) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
1202 if (rand() & 1) {
1203 /* equally likely create a 16, 32 or 64 bit int */
1204 v = (rand() & INT16_MAX) + ((1ll << 32) >> ((rand() % 3)*16));
1205 v *= 2*(rand() & 1)-1; /* randomly flip sign */
1206 sprintf(buf, "%lld", v);
1207 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), where);
1208 } else {
1209 /* equally likely generate 6, 14 or >14 bit length */
1210 v = rand() & 0x3f;
1211 v += 0x4000 >> ((rand() % 3)*8);
1212 memset(buf, 'x', v);
1213 zl = ziplistPush(zl, (unsigned char*)buf, v, where);
1214 }
1215
1216 /* delete a random element */
1217 if ((len = ziplistLen(zl)) >= 10) {
1218 idx = rand() % len;
1219 // printf("Delete index %d\n", idx);
1220 // ziplistRepr(zl);
1221 ziplistDeleteRange(zl, idx, 1);
1222 // ziplistRepr(zl);
1223 len--;
1224 }
1225
1226 /* iterate from front to back */
1227 idx = 0;
1228 p = ziplistIndex(zl, 0);
1229 while((p = ziplistNext(zl,p)))
1230 idx++;
1231 assert(len == idx+1);
1232
1233 /* iterate from back to front */
1234 idx = 0;
1235 p = ziplistIndex(zl, -1);
1236 while((p = ziplistPrev(zl,p)))
1237 idx++;
1238 assert(len == idx+1);
1239 }
1240 printf("SUCCESS\n\n");
0f10458c
PN
1241 }
1242
ffc15852
PN
1243 printf("Stress with variable ziplist size:\n");
1244 {
1245 stress(ZIPLIST_HEAD,100000,16384,256);
1246 stress(ZIPLIST_TAIL,100000,16384,256);
1247 }
1248
11ac6ff6
PN
1249 return 0;
1250}
ffc15852 1251
11ac6ff6 1252#endif