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