Skip to content

Instantly share code, notes, and snippets.

@codeb2cc
Created August 17, 2013 16:58
Show Gist options
  • Save codeb2cc/6257793 to your computer and use it in GitHub Desktop.
Save codeb2cc/6257793 to your computer and use it in GitHub Desktop.
Calculate header size(requested memory) of a item stored in memcached.
#include <stdio.h>
#include <stdint.h>
/** Time relative to server start. Smaller than time_t on 64-bit systems. */
typedef unsigned int rel_time_t;
typedef struct _stritem {
struct _stritem *next;
struct _stritem *prev;
struct _stritem *h_next; /* hash chain next */
rel_time_t time; /* least recent access */
rel_time_t exptime; /* expire time */
int nbytes; /* size of data */
unsigned short refcount;
uint8_t nsuffix; /* length of flags-and-length string */
uint8_t it_flags; /* ITEM_* above */
uint8_t slabs_clsid;/* which slab class we're in */
uint8_t nkey; /* key length, w/terminating null and padding */
/* this odd type prevents type-punning issues when we do
* the little shuffle to save space when not using CAS. */
union {
uint64_t cas;
char end;
} data[];
/* if it_flags & ITEM_CAS we have 8 bytes CAS */
/* then null-terminated key */
/* then " flags length\r\n" (no terminating null) */
/* then data with terminating \r\n (no terminating null; it's binary!) */
} item;
/**
* Generates the variable-sized part of the header for an object.
*
* key - The key
* nkey - The length of the key
* flags - key flags
* nbytes - Number of bytes to hold value and addition CRLF terminator
* suffix - Buffer for the "VALUE" line suffix (flags, size).
* nsuffix - The length of the suffix is stored here.
*
* Returns the total size of the header.
*/
static size_t item_make_header(const uint8_t nkey, const int flags, const int nbytes,
char *suffix, uint8_t *nsuffix) {
/* suffix is defined at 40 chars elsewhere.. */
*nsuffix = (uint8_t) snprintf(suffix, 40, " %d %d\r\n", flags, nbytes - 2);
printf("item\tnkey\tnsuffix\tbytes\n");
printf("%d\t%d\t%d\t%d\n", sizeof(item), nkey, *nsuffix, nbytes);
return sizeof(item) + nkey + *nsuffix + nbytes;
}
void main() {
size_t nkey;
int nbytes;
int flags = 0;
int use_cas = 1;
char suffix[40];
uint8_t nsuffix;
size_t ntotal;
printf("Key length: ");
scanf("%d", &nkey);
printf("Data length: ");
scanf("%d", &nbytes);
printf("\n");
nbytes += 2; // addition CRLF terminator
ntotal = item_make_header(nkey + 1, flags, nbytes, suffix, &nsuffix);
if (use_cas) {
ntotal += sizeof(uint64_t);
}
printf("\n");
printf("Header size: %d\n", ntotal);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment