resp.h (2516B)
1 #ifndef UDPHOLE_RESP_H 2 #define UDPHOLE_RESP_H 3 4 #include <stddef.h> 5 6 #define RESPT_SIMPLE 0 7 #define RESPT_ERROR 1 8 #define RESPT_BULK 2 9 #define RESPT_INT 3 10 #define RESPT_ARRAY 4 11 12 typedef struct resp_object resp_object; 13 struct resp_object { 14 int type; 15 union { 16 char *s; 17 long long i; 18 struct { 19 resp_object *elem; 20 size_t n; 21 } arr; 22 } u; 23 }; 24 25 void resp_free(resp_object *o); 26 /* Takes ownership: frees the object and all nested data */ 27 28 resp_object *resp_deep_copy(const resp_object *o); 29 /* Returns new object: caller owns the result, must call resp_free() */ 30 31 resp_object *resp_map_get(const resp_object *o, const char *key); 32 /* Returns pointer into o: caller must NOT call resp_free() on result */ 33 34 const char *resp_map_get_string(const resp_object *o, const char *key); 35 /* Returns pointer into o: caller must NOT free the result */ 36 37 void resp_map_set(resp_object *map, const char *key, resp_object *value); 38 /* Takes ownership of value */ 39 40 resp_object *resp_read(int fd); 41 /* Returns new object: caller owns the result, must call resp_free() */ 42 43 int resp_read_buf(const char *buf, size_t len, resp_object **out_obj); 44 /* Returns 0=no data yet, <0=incomplete (need more data), >0=bytes consumed from buffer */ 45 /* If out_obj is NULL, returns -1 */ 46 /* If *out_obj is NULL, creates new object */ 47 /* If *out_obj exists, appends to it (for arrays) */ 48 49 int resp_encode_array(int argc, const resp_object *const *argv, char **out_buf, size_t *out_len); 50 /* Returns allocated string in out_buf: caller must free() the string */ 51 52 int resp_serialize(const resp_object *o, char **out_buf, size_t *out_len); 53 /* Returns allocated string in out_buf: caller must free() the string */ 54 55 resp_object *resp_array_init(void); 56 /* Returns new array object: caller owns the result, must call resp_free() */ 57 58 resp_object *resp_simple_init(const char *value); 59 /* Returns new simple string object: caller owns the result, must call 60 * resp_free() */ 61 62 resp_object *resp_error_init(const char *value); 63 /* Returns new error object: caller owns the result, must call resp_free() */ 64 65 int resp_array_append_obj(resp_object *destination, resp_object *value); 66 /* Takes ownership of value */ 67 68 int resp_array_append_simple(resp_object *destination, const char *str); 69 /* Copies str: caller may free str after return */ 70 71 int resp_array_append_bulk(resp_object *destination, const char *str); 72 /* Copies str: caller may free str after return */ 73 74 int resp_array_append_int(resp_object *destination, long long i); 75 76 #endif