2 * Eddie Kohler, Yandong Mao, Robert Morris
3 * Copyright (c) 2012-2014 President and Fellows of Harvard College
4 * Copyright (c) 2012-2014 Massachusetts Institute of Technology
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, subject to the conditions
9 * listed in the Masstree LICENSE file. These conditions include: you must
10 * preserve this copyright notice, and you cannot mention the copyright
11 * holders in advertising related to the Software without their permission.
12 * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
13 * notice is a summary of the Masstree LICENSE file; the license in that file
16 // buffered read and write for kvc/kvd.
17 // stdio is good but not quite what I want.
18 // need to be able to check if any input
19 // available, and do non-blocking check.
20 // also, fwrite just isn't very fast, at
26 #include <sys/select.h>
34 // API to allocate a new kvout.
35 kvout* new_kvout(int fd, int buflen) {
36 kvout* kv = (kvout*) malloc(sizeof(kvout));
38 memset(kv, 0, sizeof(*kv));
39 kv->capacity = buflen;
40 kv->buf = (char*) malloc(kv->capacity);
46 // API to allocate a new kvout for a buffer, no fd.
47 kvout* new_bufkvout() {
48 kvout *kv = (kvout*) malloc(sizeof(kvout));
50 memset(kv, 0, sizeof(*kv));
52 kv->buf = (char*) malloc(kv->capacity);
59 // API to clear out a buf kvout.
60 void kvout_reset(kvout* kv) {
65 // API to free a kvout.
66 // does not close() the fd.
67 void free_kvout(kvout* kv) {
74 void kvflush(kvout* kv) {
77 while (kv->n > sent) {
78 ssize_t cc = write(kv->fd, kv->buf + sent, kv->n - sent);
80 if (errno == EWOULDBLOCK) {
84 perror("kvflush write");
93 void kvout::grow(unsigned want) {
98 while (want > capacity)
100 buf = (char*) realloc(buf, capacity);
104 int kvwrite(kvout* kv, const void* buf, unsigned n) {
105 if (kv->n + n > kv->capacity && kv->fd >= 0)
107 if (kv->n + n > kv->capacity)
109 memcpy(kv->buf + kv->n, buf, n);