chiark / gitweb /
poll: Introduce and use BEFOREPOLL_WANT_FDS
[secnet.git] / unaligned.h
1 #ifndef unaligned_h
2 #define unaligned_h
3
4 #include <stdint.h>
5 #include "util.h"
6
7 /* Parts of the secnet key-exchange protocol require access to
8    unaligned big-endian quantities in buffers. These macros provide
9    convenient access, even on architectures that don't support unaligned
10    accesses. */
11
12 #define put_uint32(a,v) do { (a)[0]=(v)>>24; (a)[1]=((v)&0xff0000)>>16; \
13 (a)[2]=((v)&0xff00)>>8; (a)[3]=(v)&0xff; } while(0)
14
15 #define put_uint16(a,v) do {(a)[0]=((v)&0xff00)>>8; (a)[1]=(v)&0xff;} while(0)
16
17 #define put_uint8(a,v) do {(a)[0]=((v)&0xff);} while(0)
18
19 #define get_uint32(a)                                   \
20   (((uint32_t)(a)[0]<<24) | ((uint32_t)(a)[1]<<16) |    \
21    ((uint32_t)(a)[2]<<8)  |  (uint32_t)(a)[3])
22
23 #define get_uint16(a) (((uint16_t)(a)[0]<<8)|(uint16_t)(a)[1])
24
25 #define get_uint8(a) (((uint8_t)(a)[0]))
26
27 #define UNALIGNED_DEF_FORTYPE(type,appre)                               \
28 static inline void buf_##appre##_##type(struct buffer_if *buf, type##_t v) \
29 {                                                                       \
30     uint8_t *c=buf_##appre(buf,sizeof(type##_t));                       \
31     put_##type(c,v);                                                    \
32 }                                                                       \
33 static inline type##_t buf_un##appre##_##type(struct buffer_if *buf)    \
34 {                                                                       \
35     const uint8_t *c=buf_un##appre(buf,sizeof(type##_t));               \
36     return get_##type(c);                                               \
37 }
38
39 UNALIGNED_DEF_FORTYPE(uint32,append)
40 UNALIGNED_DEF_FORTYPE(uint16,append)
41 UNALIGNED_DEF_FORTYPE(uint8,append)
42 UNALIGNED_DEF_FORTYPE(uint32,prepend)
43 UNALIGNED_DEF_FORTYPE(uint16,prepend)
44 UNALIGNED_DEF_FORTYPE(uint8,prepend)
45
46 #endif /* unaligned_h */