Let helpers in portable_io.h receive void * arguments.
[paraslash.git] / portable_io.h
1 /*
2 * Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file portable_io.h Inline functions for binary IO. */
8
9 static inline uint64_t read_portable(unsigned bits, const void *buf)
10 {
11 uint64_t ret = 0;
12 int i, num_bytes = bits / 8;
13 const uint8_t *p = (typeof(p))buf;
14
15 for (i = 0; i < num_bytes; i++) {
16 unsigned char c = p[i];
17 ret += ((uint64_t)c << (8 * i));
18 }
19 return ret;
20 }
21
22 static inline uint64_t read_portable_be(unsigned bits, const void *buf)
23 {
24 uint64_t ret = 0;
25 int i, num_bytes = bits / 8;
26 const uint8_t *p = (typeof(p))buf;
27
28 for (i = 0; i < num_bytes; i++) {
29 unsigned char c = p[i];
30 ret += ((uint64_t)c << (8 * (num_bytes - i - 1)));
31 }
32 return ret;
33 }
34
35 static inline uint64_t read_u64(const void *buf)
36 {
37 return read_portable(64, buf);
38 }
39
40 static inline uint32_t read_u32(const void *buf)
41 {
42 return read_portable(32, buf);
43 }
44
45 static inline uint16_t read_u16(const void *buf)
46 {
47 return read_portable(16, buf);
48 }
49
50 static inline uint8_t read_u8(const void *buf)
51 {
52 return read_portable(8, buf);
53 }
54
55 static inline uint64_t read_u64_be(const void *buf)
56 {
57 return read_portable_be(64, buf);
58 }
59
60 static inline uint32_t read_u32_be(const void *buf)
61 {
62 return read_portable_be(32, buf);
63 }
64
65 static inline uint16_t read_u16_be(const void *buf)
66 {
67 return read_portable_be(16, buf);
68 }
69
70 static inline void write_portable(unsigned bits, char *buf, uint64_t val)
71 {
72 int i, num_bytes = bits / 8;
73 uint8_t *p = (typeof(p))buf;
74
75 for (i = 0; i < num_bytes; i++) {
76 p[i] = val & 0xff;
77 val = val >> 8;
78 }
79 }
80
81 static inline void write_portable_be(unsigned bits, char *buf, uint64_t val)
82 {
83 int i, num_bytes = bits / 8;
84 uint8_t *p = (typeof(p))buf;
85
86 for (i = 0; i < num_bytes; i++) {
87 p[num_bytes - i - 1] = val & 0xff;
88 val = val >> 8;
89 }
90 }
91
92 static inline void write_u64(void *buf, uint64_t val)
93 {
94 write_portable(64, buf, val);
95 }
96
97 static inline void write_u32(void *buf, uint32_t val)
98 {
99 write_portable(32, buf, (uint64_t) val);
100 }
101
102 static inline void write_u16(void *buf, uint16_t val)
103 {
104 write_portable(16, buf, (uint64_t) val);
105 }
106
107 static inline void write_u8(void *buf, uint8_t val)
108 {
109 write_portable(8, buf, (uint64_t) val);
110 }
111
112 static inline void write_u64_be(void *buf, uint64_t val)
113 {
114 write_portable_be(64, buf, val);
115 }
116
117 static inline void write_u32_be(void *buf, uint32_t val)
118 {
119 write_portable_be(32, buf, (uint64_t) val);
120 }
121
122 static inline void write_u16_be(void *buf, uint16_t val)
123 {
124 write_portable_be(16, buf, (uint64_t) val);
125 }