Merge commit 'remotes/fml/v0.3' into v0.3
[paraslash.git] / portable_io.h
1 /*
2  * Copyright (C) 2007 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file portable_io.h Inline functions for endian-independent 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_u64(const char *buf)
22 {
23         return read_portable(64, buf);
24 }
25
26 static inline uint32_t read_u32(const char *buf)
27 {
28         return read_portable(32, buf);
29 }
30
31 static inline uint16_t read_u16(const char *buf)
32 {
33         return read_portable(16, buf);
34 }
35
36 static inline uint8_t read_u8(const char *buf)
37 {
38         return read_portable(8, buf);
39 }
40
41 static inline void write_portable(unsigned bits, char *buf, uint64_t val)
42 {
43         int i, num_bytes = bits / 8;
44 //      fprintf(stderr, "val: %lu\n", val);
45         for (i = 0; i < num_bytes; i++) {
46                 buf[i] = val & 0xff;
47 //              fprintf(stderr, "buf[%d]=%x\n", i, buf[i]);
48                 val = val >> 8;
49         }
50 }
51
52 static inline void write_u64(char *buf, uint64_t val)
53 {
54         write_portable(64, buf, val);
55 }
56
57 static inline void write_u32(char *buf, uint32_t val)
58 {
59         write_portable(32, buf, (uint64_t) val);
60 }
61
62 static inline void write_u16(char *buf, uint16_t val)
63 {
64         write_portable(16, buf, (uint64_t) val);
65 }
66
67 static inline void write_u8(char *buf, uint8_t val)
68 {
69         write_portable(8, buf, (uint64_t) val);
70 }