-
Notifications
You must be signed in to change notification settings - Fork 2
/
mem.h
112 lines (92 loc) · 2.4 KB
/
mem.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
Copyright (c) 2019 Vicente Romero Calero. All rights reserved.
Licensed under the MIT License.
See LICENSE file in the project root for full license information.
*/
#ifndef VTENC_MEM_H_
#define VTENC_MEM_H_
#include <stdint.h>
#include <string.h>
#include "bits.h"
static inline unsigned mem_is_little_endian(void)
{
const union { uint32_t u; uint8_t c[4]; } one = { 1 };
return one.c[0];
}
/* Generic read functions */
static inline uint16_t mem_read_u16(const void* mem_ptr)
{
uint16_t value;
memcpy(&value, mem_ptr, sizeof(value));
return value;
}
static inline uint32_t mem_read_u32(const void* mem_ptr)
{
uint32_t value;
memcpy(&value, mem_ptr, sizeof(value));
return value;
}
static inline uint64_t mem_read_u64(const void* mem_ptr)
{
uint64_t value;
memcpy(&value, mem_ptr, sizeof(value));
return value;
}
/* Generic write functions */
static inline void mem_write_u16(void* mem_ptr, uint16_t value)
{
memcpy(mem_ptr, &value, sizeof(value));
}
static inline void mem_write_u32(void* mem_ptr, uint32_t value)
{
memcpy(mem_ptr, &value, sizeof(value));
}
static inline void mem_write_u64(void* mem_ptr, uint64_t value)
{
memcpy(mem_ptr, &value, sizeof(value));
}
/* Little endian read functions */
static inline uint16_t mem_read_le_u16(const void* mem_ptr)
{
if (mem_is_little_endian())
return mem_read_u16(mem_ptr);
else
return bits_swap_u16(mem_read_u16(mem_ptr));
}
static inline uint32_t mem_read_le_u32(const void* mem_ptr)
{
if (mem_is_little_endian())
return mem_read_u32(mem_ptr);
else
return bits_swap_u32(mem_read_u32(mem_ptr));
}
static inline uint64_t mem_read_le_u64(const void* mem_ptr)
{
if (mem_is_little_endian())
return mem_read_u64(mem_ptr);
else
return bits_swap_u64(mem_read_u64(mem_ptr));
}
/* Little endian write functions */
static inline void mem_write_le_u16(void* mem_ptr, uint16_t value)
{
if (mem_is_little_endian())
mem_write_u16(mem_ptr, value);
else
mem_write_u16(mem_ptr, bits_swap_u16(value));
}
static inline void mem_write_le_u32(void* mem_ptr, uint32_t value)
{
if (mem_is_little_endian())
mem_write_u32(mem_ptr, value);
else
mem_write_u32(mem_ptr, bits_swap_u32(value));
}
static inline void mem_write_le_u64(void* mem_ptr, uint64_t value)
{
if (mem_is_little_endian())
mem_write_u64(mem_ptr, value);
else
mem_write_u64(mem_ptr, bits_swap_u64(value));
}
#endif /* VTENC_MEM_H_ */