| 1 |
#define _BSD_SOURCE |
| 2 |
#include <nl_types.h> |
| 3 |
#include <endian.h> |
| 4 |
#include <stdlib.h> |
| 5 |
#include <stdint.h> |
| 6 |
#include <errno.h> |
| 7 |
|
| 8 |
#define V(p) be32toh(*(uint32_t *)(p)) |
| 9 |
|
| 10 |
#ifdef __wasilibc_unmodified_upstream // wasi-libc doesn't support catgets yet |
| 11 |
static int cmp(const void *a, const void *b) |
| 12 |
{ |
| 13 |
uint32_t x = V(a), y = V(b); |
| 14 |
return x<y ? -1 : x>y ? 1 : 0; |
| 15 |
} |
| 16 |
#endif |
| 17 |
|
| 18 |
char *catgets (nl_catd catd, int set_id, int msg_id, const char *s) |
| 19 |
{ |
| 20 |
#ifdef __wasilibc_unmodified_upstream // wasi-libc doesn't support catgets yet |
| 21 |
const char *map = (const char *)catd; |
| 22 |
uint32_t nsets = V(map+4); |
| 23 |
const char *sets = map+20; |
| 24 |
const char *msgs = map+20+V(map+12); |
| 25 |
const char *strings = map+20+V(map+16); |
| 26 |
uint32_t set_id_be = htobe32(set_id); |
| 27 |
uint32_t msg_id_be = htobe32(msg_id); |
| 28 |
const char *set = bsearch(&set_id_be, sets, nsets, 12, cmp); |
| 29 |
if (!set) { |
| 30 |
errno = ENOMSG; |
| 31 |
return (char *)s; |
| 32 |
} |
| 33 |
uint32_t nmsgs = V(set+4); |
| 34 |
msgs += 12*V(set+8); |
| 35 |
const char *msg = bsearch(&msg_id_be, msgs, nmsgs, 12, cmp); |
| 36 |
if (!msg) { |
| 37 |
errno = ENOMSG; |
| 38 |
return (char *)s; |
| 39 |
} |
| 40 |
return (char *)(strings + V(msg+8)); |
| 41 |
#else |
| 42 |
return (char *)s; |
| 43 |
#endif |
| 44 |
} |