看了一下,zipmapDecodeLength的实现还挺巧妙的,直接使用内存操作:
-
- /* Decode the encoded length pointed by 'p' */
- static unsigned int zipmapDecodeLength(unsigned char *p) {
- unsigned int len = *p;
-
- if (len < ZIPMAP_BIGLEN) return len;
- memcpy(&len,p+1,sizeof(unsigned int));
- memrev32ifbe(&len);
- return len;
- }
-
- static unsigned int zipmapGetEncodedLengthSize(unsigned char *p) {
- return (*p < ZIPMAP_BIGLEN) ? 1: 5;
- }
-
- /* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
- * the amount of bytes required to encode such a length. */
- static unsigned int zipmapEncodeLength(unsigned char *p, unsigned int len) {
- if (p == NULL) {
- return ZIPMAP_LEN_BYTES(len);
- } else {
- if (len < ZIPMAP_BIGLEN) {
- p[0] = len;
- return 1;
- } else {
- p[0] = ZIPMAP_BIGLEN;
- memcpy(p+1,&len,sizeof(len));
- memrev32ifbe(p+1);
- return 1+sizeof(len);
- }
- }
- }