Merge branch 'refs/heads/t/wma'
[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 char *buf)
10 {
11 uint64_t ret = 0;
12 int i, num_bytes = bits / 8;
13
14 for (i = 0; i < num_bytes; i++) {
15 unsigned char c = buf[i];
16 ret += ((uint64_t)c << (8 * i));
17 }
18 return ret;
19 }
20
21 static inline uint64_t read_portable_be(unsigned bits, const char *buf)
22 {
23 uint64_t ret = 0;
24 int i, num_bytes = bits / 8;
25
26 for (i = 0; i < num_bytes; i++) {
27 unsigned char c = buf[i];
28 ret += ((uint64_t)c << (8 * (num_bytes - i - 1)));
29 }
30 return ret;
31 }
32
33 static inline uint64_t read_u64(const char *buf)
34 {
35 return read_portable(64, buf);
36 }
37
38 static inline uint32_t read_u32(const char *buf)
39 {
40 return read_portable(32, buf);
41 }
42
43 static inline uint16_t read_u16(const char *buf)
44 {
45 return read_portable(16, buf);
46 }
47
48 static inline uint8_t read_u8(const char *buf)
49 {
50 return read_portable(8, buf);
51 }
52
53 static inline uint64_t read_u64_be(const char *buf)
54 {
55 return read_portable_be(64, buf);
56 }
57
58 static inline uint32_t read_u32_be(const char *buf)
59 {
60 return read_portable_be(32, buf);
61 }
62
63 static inline uint16_t read_u16_be(const char *buf)
64 {
65 return read_portable_be(16, buf);
66 }
67
68 static inline void write_portable(unsigned bits, char *buf, uint64_t val)
69 {
70 int i, num_bytes = bits / 8;
71 for (i = 0; i < num_bytes; i++) {
72 buf[i] = val & 0xff;
73 val = val >> 8;
74 }
75 }
76
77 static inline void write_portable_be(unsigned bits, char *buf, uint64_t val)
78 {
79 int i, num_bytes = bits / 8;
80 for (i = 0; i < num_bytes; i++) {
81 buf[num_bytes - i - 1] = val & 0xff;
82 val = val >> 8;
83 }
84 }
85
86 static inline void write_u64(char *buf, uint64_t val)
87 {
88 write_portable(64, buf, val);
89 }
90
91 static inline void write_u32(char *buf, uint32_t val)
92 {
93 write_portable(32, buf, (uint64_t) val);
94 }
95
96 static inline void write_u16(char *buf, uint16_t val)
97 {
98 write_portable(16, buf, (uint64_t) val);
99 }
100
101 static inline void write_u8(char *buf, uint8_t val)
102 {
103 write_portable(8, buf, (uint64_t) val);
104 }
105
106 static inline void write_u64_be(char *buf, uint64_t val)
107 {
108 write_portable_be(64, buf, val);
109 }
110
111 static inline void write_u32_be(char *buf, uint32_t val)
112 {
113 write_portable_be(32, buf, (uint64_t) val);
114 }
115
116 static inline void write_u16_be(char *buf, uint16_t val)
117 {
118 write_portable_be(16, buf, (uint64_t) val);
119 }