|
| 1 | +#ifndef MMDB_TEST_WRITER_H |
| 2 | +#define MMDB_TEST_WRITER_H |
| 3 | + |
| 4 | +/* |
| 5 | + * Shared helpers for tests that construct MMDB files in memory. |
| 6 | + * Each function writes one MMDB data-format element into buf and returns |
| 7 | + * the number of bytes written. |
| 8 | + */ |
| 9 | + |
| 10 | +#include <stdint.h> |
| 11 | +#include <string.h> |
| 12 | + |
| 13 | +/* MMDB binary format constants */ |
| 14 | +#define METADATA_MARKER "\xab\xcd\xefMaxMind.com" |
| 15 | +#define METADATA_MARKER_LEN 14 |
| 16 | +#define DATA_SEPARATOR_SIZE 16 |
| 17 | + |
| 18 | +static inline int write_map(uint8_t *buf, uint32_t size) { |
| 19 | + buf[0] = (7 << 5) | (size & 0x1f); |
| 20 | + return 1; |
| 21 | +} |
| 22 | + |
| 23 | +static inline int write_string(uint8_t *buf, const char *str, uint32_t len) { |
| 24 | + buf[0] = (2 << 5) | (len & 0x1f); |
| 25 | + memcpy(buf + 1, str, len); |
| 26 | + return 1 + len; |
| 27 | +} |
| 28 | + |
| 29 | +static inline int write_uint16(uint8_t *buf, uint16_t value) { |
| 30 | + buf[0] = (5 << 5) | 2; |
| 31 | + buf[1] = (value >> 8) & 0xff; |
| 32 | + buf[2] = value & 0xff; |
| 33 | + return 3; |
| 34 | +} |
| 35 | + |
| 36 | +static inline int write_uint32(uint8_t *buf, uint32_t value) { |
| 37 | + buf[0] = (6 << 5) | 4; |
| 38 | + buf[1] = (value >> 24) & 0xff; |
| 39 | + buf[2] = (value >> 16) & 0xff; |
| 40 | + buf[3] = (value >> 8) & 0xff; |
| 41 | + buf[4] = value & 0xff; |
| 42 | + return 5; |
| 43 | +} |
| 44 | + |
| 45 | +static inline int write_uint64(uint8_t *buf, uint64_t value) { |
| 46 | + buf[0] = (0 << 5) | 8; |
| 47 | + buf[1] = 2; /* extended type: 7 + 2 = 9 (uint64) */ |
| 48 | + buf[2] = (value >> 56) & 0xff; |
| 49 | + buf[3] = (value >> 48) & 0xff; |
| 50 | + buf[4] = (value >> 40) & 0xff; |
| 51 | + buf[5] = (value >> 32) & 0xff; |
| 52 | + buf[6] = (value >> 24) & 0xff; |
| 53 | + buf[7] = (value >> 16) & 0xff; |
| 54 | + buf[8] = (value >> 8) & 0xff; |
| 55 | + buf[9] = value & 0xff; |
| 56 | + return 10; |
| 57 | +} |
| 58 | + |
| 59 | +static inline int write_meta_key(uint8_t *buf, const char *key) { |
| 60 | + return write_string(buf, key, strlen(key)); |
| 61 | +} |
| 62 | + |
| 63 | +#endif /* MMDB_TEST_WRITER_H */ |
0 commit comments