Lessons from mod_mcpage

I made a bunch of progress over the weekend on mod_mcpage, and now the plugin is placing pages into memcached as well as retrieving them, and setting the content type correctly. It's pretty cool, although there's still some rough edges to wear down, and I'll need to run it through valgrind some to make sure there's not horrid memleaks somewhere.

While I was working on getting mod_mcpage to put pages into memcached, I also figured out some stuff that seems painfully obvious now. For instance, I earlier discussed various ways to encode the content type and page before putting in it memcached, and they were all pretty complicated. Turns out there's an even easier way.

First, for ease of passing it around I made a struct to hold the content type and page in a buffer together, the length of that buffer, and the URI:

typedef struct {
       size_t mclen;
       char *uri;
       char *page;
       } mcstore;
, which we initialize as *mccontent.

Storing the length is easy-peasy: mccontent->mclen = strlen(pagestore->content_type->ptr) + strlen(pagestore->outpg->ptr) + 2;

Alloc storage, of course, and set the URI:

mccontent->page = malloc(mccontent->mclen * sizeof(char));
mccontent->uri = malloc((strlen(con->request.uri->ptr) + 1) * sizeof(char));
strcpy(mccontent->uri, con->request.uri->ptr);

None of that's rocket science. Of course, this isn't rocket science either, but it's a lot fewer steps than what I was thinking about earlier:

memcpy(mccontent->page, pagestore->content_type->ptr, strlen(pagestore->content_type->ptr) + 1);
memcpy(mccontent->page + strlen(pagestore->content_type->ptr) + 1, pagestore->outpg->ptr, strlen(pagestore->outpg->ptr) + 1);

I'm a little embarrassed by how much simpler that is than what I had come up with before. Extracting the content type and page once it's returned from memcached is even easier. Here, retpage is a char pointer containing the content type and page content, separated by a null byte.

char *retpage;
char *content_type;
char *send_page;

... get retpage out of memcached and whatnot, and see if it's NULL. If it isn't: ...
content_type = retpage;
send_page = retpage + strlen(content_type) + 1;

... do whatever we wanted to do ...

Again, ridiculously less complicated than what I was thinking about doing before. I've noticed that sometimes writing down what you're working on can help you look at things a little more differently (and hopefully a little less absolutely idiotically).

comments powered by Disqus