Skip to content

Instantly share code, notes, and snippets.

@niamtokik
Created November 17, 2017 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niamtokik/22366f145a268dbf5efac13195f4fb1d to your computer and use it in GitHub Desktop.
Save niamtokik/22366f145a268dbf5efac13195f4fb1d to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/param.h>
#include <stdlib.h>
#include <string.h>
struct tuple {
struct iovec key;
struct iovec value;
};
struct tuples {
struct tuple *tuples;
size_t len;
};
void
iovec_init(struct iovec *io) {
io->iov_base = NULL;
io->iov_len = 0;
}
void
iovec_set(struct iovec *io, void *base, size_t len) {
io->iov_base = base;
io->iov_len = len;
}
void
tuple_init(struct tuple *t) {
struct iovec *key = &t->key;
struct iovec *value = &t->value;
iovec_init(key);
iovec_init(value);
}
void
tuple_key(struct tuple *t, void *key, size_t len) {
struct iovec *io = &t->key;
iovec_set(io, key, len);
}
void
tuple_value(struct tuple *t, void *value, size_t len) {
struct iovec *io = &t->value;
iovec_set(io, value, len);
}
void
tuple_print(struct tuple *t) {
printf("key: %s\n", t->key.iov_base);
printf("value: %s\n", t->value.iov_base);
}
void test() {
int i;
struct tuple *t = malloc(sizeof(struct tuple)*10);
for(i=0 ; i<10; i++)
tuple_init(&t[i]);
for(i=0 ; i<10; i++) {
tuple_key(&t[i], "test", 5);
tuple_value(&t[i], "data", 5);
tuple_print(&t[i]);
}
free(t);
}
struct tuples *
new_tuples(void) {
struct tuples *t = malloc(sizeof(struct tuples));
t->tuples = NULL;
t->len = 0;
return t;
}
void
tuples_add(struct tuples *t, struct tuple *a) {
t->len = (t->len)+1;
if (t->len > 0) {
struct tuple *n = realloc(t->tuples, sizeof(struct tuple)*(t->len+1));
memcpy(n+(t->len-1), a, sizeof(struct tuple));
t->tuples = n;
}
else {
t->tuples = malloc(sizeof(struct tuple));
memcpy(t->tuples, a, sizeof(struct tuple));
}
}
void
free_tuples(struct tuples *t) {
if (t->tuples)
free(t->tuples);
if (t)
free(t);
}
void test2() {
struct tuples *t = new_tuples();
struct tuple ta;
tuple_init(&ta);
tuple_key(&ta, "test", 5);
tuple_value(&ta, "tata", 5);
tuples_add(t, &ta);
tuples_add(t, &ta);
tuples_add(t, &ta);
tuples_add(t, &ta);
tuples_add(t, &ta);
int i;
for (i=0; i<t->len; i++) {
printf("%s - %d\n", t->tuples[i].key.iov_base, t->tuples[i].key.iov_len);
printf("%s - %d\n", t->tuples[i].value.iov_base, t->tuples[i].value.iov_len);
}
free_tuples(t);
}
int
main(void) {
test2();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment