sd.h (2149B)
1 #ifndef SD_H 2 #define SD_H 3 4 #include <stdint.h> 5 #include <stdlib.h> 6 #include <string.h> 7 8 typedef struct { 9 size_t size; 10 uint8_t *data; 11 } sd; 12 13 /** 14 * Initialise a sized data. 15 * 16 * Allocates memory that needs to be sd_clear'd. 17 * 18 * @param s pointer where to write the sized data obj 19 * @param size number of bytes in the sd 20 */ 21 void sd_init(sd *s, const size_t size); 22 23 /** 24 * Clear a sd. 25 * 26 * @param s pointer to the sd 27 */ 28 void sd_clear(sd *s); 29 30 /** 31 * Computes a hash of a sd. 32 * 33 * This hash is a simple combination of xoring 34 * in all the bytes to a uint64_t in different 35 * positions, then computing the mix64 function 36 * known as murmur64. 37 * 38 * @param s the sd to get hash of 39 * @return hash of s 40 */ 41 uint64_t sd_hash(sd *s); 42 43 /** 44 * Compare two sds. 45 * 46 * Compares the sd's pointed to by x and y. In the 47 * following sense: a < b if either a.size < b.size 48 * or a.data < b.data (in the memcmp order). If 49 * the sd are equal then 0 is returned. 50 * 51 * @param x pointer to first sd 52 * @param y pointer to second sd 53 * @return comparison number (lex order) 54 */ 55 int sd_cmp(sd *x, sd *y); 56 57 /** 58 * Initialises a sd from a uint64_t. 59 * 60 * The size will be 8 bytes, and the order of the 61 * bytes is raw (host order). Allocates memory that 62 * needs to be sd_clear'd. 63 * 64 * @param s ptr to the sd to initialise 65 * @param x the uint64_t to initialize from 66 */ 67 void sd_init_u64(sd *s, const uint64_t x); 68 69 /** 70 * Converts a sd to a uint64_t. 71 * 72 * Gets a uint64_t from a sd that has been created 73 * by sd_init_u64. 74 * 75 * @param s ptr to the sd to convert 76 * @return the uint64_t 77 */ 78 uint64_t sd_conv_u64(sd *s); 79 80 /** 81 * Initializes a sd from a string. 82 * 83 * Copies a string into a sd, including the 84 * terminating null byte. Allocates memory that 85 * needs to be sd_clear'd. 86 * 87 * @param s ptr to the sd to be init'd 88 * @param str the string to copy into new sd 89 */ 90 void sd_init_str(sd *s, const char *str); 91 92 /** 93 * Get string stored in sd. 94 * 95 * This returns a char* to the data stored in the 96 * sd. This assumes that the data is in fact a 97 * null terminated string. 98 * 99 * @param s ptr to the sd to get string from 100 */ 101 char *sd_get_str(sd *s); 102 103 #endif