]>
git.saurik.com Git - redis.git/blob - zipmap.c
1 /* String -> String Map data structure optimized for size.
2 * This file implements a data structure mapping strings to other strings
3 * implementing an O(n) lookup data structure designed to be very memory
6 * The Redis Hash type uses this data structure for hashes composed of a small
7 * number of elements, to switch to an hash table once a given number of
10 * Given that many times Redis Hashes are used to represent objects composed
11 * of few fields, this is a very big win in terms of used memory.
13 * --------------------------------------------------------------------------
15 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
16 * All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are met:
21 * * Redistributions of source code must retain the above copyright notice,
22 * this list of conditions and the following disclaimer.
23 * * Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
26 * * Neither the name of Redis nor the names of its contributors may be used
27 * to endorse or promote products derived from this software without
28 * specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
31 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
34 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
35 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
36 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40 * POSSIBILITY OF SUCH DAMAGE.
43 /* Memory layout of a zipmap, for the map "foo" => "bar", "hello" => "world":
45 * <status><len>"foo"<len><free>"bar"<len>"hello"<len><free>"world"
47 * <status> is 1 byte status. Currently only 1 bit is used: if the least
48 * significant bit is set, it means the zipmap needs to be defragmented.
50 * <len> is the length of the following string (key or value).
51 * <len> lengths are encoded in a single value or in a 5 bytes value.
52 * If the first byte value (as an unsigned 8 bit value) is between 0 and
53 * 252, it's a single-byte length. If it is 253 then a four bytes unsigned
54 * integer follows (in the host byte ordering). A value fo 255 is used to
55 * signal the end of the hash. The special value 254 is used to mark
56 * empty space that can be used to add new key/value pairs.
58 * <free> is the number of free unused bytes
59 * after the string, resulting from modification of values associated to a
60 * key (for instance if "foo" is set to "bar', and later "foo" will be se to
61 * "hi", I'll have a free byte to use if the value will enlarge again later,
62 * or even in order to add a key/value pair if it fits.
64 * <free> is always an unsigned 8 bit number, because if after an
65 * update operation there are more than a few free bytes, they'll be converted
66 * into empty space prefixed by the special value 254.
68 * The most compact representation of the above two elements hash is actually:
70 * "\x00\x03\x00foo\x03\x00bar\x05\x00hello\x05\x00world\xff"
72 * Empty space is marked using a 254 bytes + a <len> (coded as already
73 * specified). The length includes the 254 bytes in the count and the
74 * space taken by the <len> field. So for instance removing the "foo" key
75 * from the zipmap above will lead to the following representation:
77 * "\xfd\x10........\x05\x00hello\x05\x00world\xff"
79 * Note that because empty space, keys, values, are all prefixed length
80 * "objects", the lookup will take O(N) where N is the numeber of elements
81 * in the zipmap and *not* the number of bytes needed to represent the zipmap.
82 * This lowers the constant times considerably.
90 #define ZIPMAP_BIGLEN 253
91 #define ZIPMAP_EMPTY 254
92 #define ZIPMAP_END 255
94 #define ZIPMAP_STATUS_FRAGMENTED 1
96 /* The following defines the max value for the <free> field described in the
97 * comments above, that is, the max number of trailing bytes in a value. */
98 #define ZIPMAP_VALUE_MAX_FREE 5
100 /* Create a new empty zipmap. */
101 unsigned char *zipmapNew(void) {
102 unsigned char *zm
= zmalloc(2);
104 zm
[0] = 0; /* Status */
109 /* Decode the encoded length pointed by 'p' */
110 static unsigned int zipmapDecodeLength(unsigned char *p
) {
111 unsigned int len
= *p
;
113 if (len
< ZIPMAP_BIGLEN
) return len
;
114 memcpy(&len
,p
,sizeof(unsigned int));
118 /* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
119 * the amount of bytes required to encode such a length. */
120 static unsigned int zipmapEncodeLength(unsigned char *p
, unsigned int len
) {
122 return (len
< ZIPMAP_BIGLEN
) ? 1 : 1+sizeof(unsigned int);
124 if (len
< ZIPMAP_BIGLEN
) {
128 p
[0] = ZIPMAP_BIGLEN
;
129 memcpy(p
+1,&len
,sizeof(len
));
130 return 1+sizeof(len
);
135 /* Search for a matching key, returning a pointer to the entry inside the
136 * zipmap. Returns NULL if the key is not found.
138 * If NULL is returned, and totlen is not NULL, it is set to the entire
139 * size of the zimap, so that the calling function will be able to
140 * reallocate the original zipmap to make room for more entries.
142 * If NULL is returned, and freeoff and freelen are not NULL, they are set
143 * to the offset of the first empty space that can hold '*freelen' bytes
144 * (freelen is an integer pointer used both to signal the required length
145 * and to get the reply from the function). If there is not a suitable
146 * free space block to hold the requested bytes, *freelen is set to 0. */
147 static unsigned char *zipmapLookupRaw(unsigned char *zm
, unsigned char *key
, unsigned int klen
, unsigned int *totlen
, unsigned int *freeoff
, unsigned int *freelen
) {
148 unsigned char *p
= zm
+1;
150 unsigned int reqfreelen
;
153 reqfreelen
= *freelen
;
155 assert(reqfreelen
!= 0);
157 while(*p
!= ZIPMAP_END
) {
158 if (*p
== ZIPMAP_EMPTY
) {
159 l
= zipmapDecodeLength(p
+1);
160 /* if the user want a free space report, and this space is
161 * enough, and we did't already found a suitable space... */
162 if (freelen
&& l
>= reqfreelen
&& *freelen
== 0) {
167 zm
[0] |= ZIPMAP_STATUS_FRAGMENTED
;
171 /* Match or skip the key */
172 l
= zipmapDecodeLength(p
);
173 if (l
== klen
&& !memcmp(p
+1,key
,l
)) return p
;
174 p
+= zipmapEncodeLength(NULL
,l
) + l
;
175 /* Skip the value as well */
176 l
= zipmapDecodeLength(p
);
177 p
+= zipmapEncodeLength(NULL
,l
);
179 p
+= l
+1+free
; /* +1 to skip the free byte */
182 if (totlen
!= NULL
) *totlen
= (unsigned int)(p
-zm
)+1;
186 static unsigned long zipmapRequiredLength(unsigned int klen
, unsigned int vlen
) {
190 if (klen
>= ZIPMAP_BIGLEN
) l
+= 4;
191 if (vlen
>= ZIPMAP_BIGLEN
) l
+= 4;
195 /* Return the total amount used by a key (encoded length + payload) */
196 static unsigned int zipmapRawKeyLength(unsigned char *p
) {
197 unsigned int l
= zipmapDecodeLength(p
);
199 return zipmapEncodeLength(NULL
,l
) + l
;
202 /* Return the total amount used by a value
203 * (encoded length + single byte free count + payload) */
204 static unsigned int zipmapRawValueLength(unsigned char *p
) {
205 unsigned int l
= zipmapDecodeLength(p
);
208 used
= zipmapEncodeLength(NULL
,l
);
209 used
+= p
[used
] + 1 + l
;
213 /* Set key to value, creating the key if it does not already exist. */
214 unsigned char *zipmapSet(unsigned char *zm
, unsigned char *key
, unsigned int klen
, unsigned char *val
, unsigned int vlen
) {
215 unsigned int oldlen
= 0, freeoff
= 0, freelen
;
216 unsigned int reqlen
= zipmapRequiredLength(klen
,vlen
);
217 unsigned int empty
, vempty
;
221 p
= zipmapLookupRaw(zm
,key
,klen
,&oldlen
,&freeoff
,&freelen
);
222 if (p
== NULL
&& freelen
== 0) {
223 printf("HERE oldlen:%u required:%u\n",oldlen
,reqlen
);
224 /* Key not found, and not space for the new key. Enlarge */
225 zm
= zrealloc(zm
,oldlen
+reqlen
);
227 zm
[oldlen
+reqlen
-1] = ZIPMAP_END
;
229 printf("New total length is: %u\n", oldlen
+reqlen
);
230 } else if (p
== NULL
) {
231 /* Key not found, but there is enough free space. */
233 /* note: freelen is already set in this case */
235 unsigned char *b
= p
;
237 /* Key found. Is there enough space for the new value? */
238 /* Compute the total length: */
239 freelen
= zipmapRawKeyLength(b
);
241 freelen
+= zipmapRawValueLength(b
);
242 if (freelen
< reqlen
) {
243 /* Mark this blog as free and recurse */
245 zipmapEncodeLength(p
+1,freelen
);
246 return zipmapSet(zm
,key
,klen
,val
,vlen
);
250 /* Ok we have a suitable block where to write the new key/value
252 empty
= freelen
-reqlen
;
253 /* If there is too much free space mark it as a free block instead
254 * of adding it as trailing empty space for the value, as we want
255 * zipmaps to be very space efficient. */
256 if (empty
> ZIPMAP_VALUE_MAX_FREE
) {
261 zipmapEncodeLength(e
+1,empty
);
263 zm
[0] |= ZIPMAP_STATUS_FRAGMENTED
;
268 /* Just write the key + value and we are done. */
270 p
+= zipmapEncodeLength(p
,klen
);
274 p
+= zipmapEncodeLength(p
,vlen
);
280 void zipmapRepr(unsigned char *p
) {
283 printf("{status %u}",*p
++);
285 if (p
[0] == ZIPMAP_END
) {
288 } else if (p
[0] == ZIPMAP_EMPTY
) {
289 l
= zipmapDecodeLength(p
+1);
290 printf("{%u empty block}", l
);
295 l
= zipmapDecodeLength(p
);
296 printf("{key %u}",l
);
297 p
+= zipmapEncodeLength(NULL
,l
);
298 fwrite(p
,l
,1,stdout
);
301 l
= zipmapDecodeLength(p
);
302 printf("{value %u}",l
);
303 p
+= zipmapEncodeLength(NULL
,l
);
305 fwrite(p
,l
,1,stdout
);
309 while(e
--) printf(".");
321 zm
= zipmapSet(zm
,(unsigned char*) "hello",5, (unsigned char*) "world!",6);
322 zm
= zipmapSet(zm
,(unsigned char*) "foo",3, (unsigned char*) "bar",3);
323 zm
= zipmapSet(zm
,(unsigned char*) "foo",3, (unsigned char*) "!",1);