#include <stdlib.h>
#include <assert.h>
#include "request.h"
#include "memcache.h"
#include "../common.h"
struct memcache_req *memcache_req_alloc (struct memcache *mc, enum memcache_command cmd_type, const struct memcache_key *key, void *cb_arg) {
struct memcache_req *req = NULL;
// allocate it
if ((req = calloc(1, sizeof(*req))) == NULL)
ERROR("calloc");
// state
req->state = MEMCACHE_STATE_INVALID;
// copy the key
if ((req->key.buf = malloc(key->len)) == NULL)
ERROR("malloc key buf");
// copy over the key
memcpy(req->key.buf, key->buf, key->len);
req->key.len = key->len;
// store the other data
req->mc = mc;
req->cmd_type = cmd_type;
req->cb_arg = cb_arg;
// success
return req;
error:
if (req) {
free(req->key.buf);
free(req);
}
return NULL;
}
static void _memcache_req_notify (struct memcache_req *req) {
req->mc->cb_fn(req, req->cb_arg);
}
void memcache_req_error (struct memcache_req *req) {
// forget our connection
req->conn = NULL;
req->state = MEMCACHE_STATE_ERROR;
_memcache_req_notify(req);
}
void memcache_req_queued (struct memcache_req *req) {
req->state = MEMCACHE_STATE_QUEUED;
// _memcache_req_notify(req);
}
void memcache_req_send (struct memcache_req *req) {
req->state = MEMCACHE_STATE_SEND;
// _memcache_req_notify(req);
}
void memcache_req_reply (struct memcache_req *req, enum memcache_reply reply_type) {
req->state = MEMCACHE_STATE_REPLY;
req->reply_type = reply_type;
_memcache_req_notify(req);
}
void memcache_req_done (struct memcache_req *req) {
// make sure we are in the STATE_SEND state
assert(req->state == MEMCACHE_STATE_SEND);
// forget the connection
req->conn = NULL;
// our state is currently indeterminate until req_reply is called
req->state = MEMCACHE_STATE_INVALID;
}
void memcache_req_free (struct memcache_req *req) {
// must be unused
assert(req->conn == NULL);
assert(req->state == MEMCACHE_STATE_INVALID || req->state == MEMCACHE_STATE_ERROR);
free(req->key.buf);
free(req);
}