Statistics
| Branch: | Revision:

iof-bird / bird-2.0.1 / lib / unaligned.h @ 6b3f1a54

History | View | Annotate | Download (1.72 KB)

1
/*
2
 *        Unaligned Data Accesses -- Generic Version, Network Order
3
 *
4
 *        (c) 2000 Martin Mares <mj@ucw.cz>
5
 *
6
 *        Can be freely distributed and used under the terms of the GNU GPL.
7
 */
8

    
9
#ifndef _BIRD_UNALIGNED_H_
10
#define _BIRD_UNALIGNED_H_
11

    
12
/*
13
 *  We don't do any clever tricks with unaligned accesses since it's
14
 *  virtually impossible to figure out what alignment does the CPU want
15
 *  (unaligned accesses can be emulated by the OS which makes them work,
16
 *  but unusably slow). We use memcpy and hope GCC will optimize it out
17
 *  if possible.
18
 */
19

    
20
#include "sysdep/unix/endian.h"
21
#include "lib/string.h"
22

    
23
static inline u16
24
get_u16(const void *p)
25
{
26
  u16 x;
27
  memcpy(&x, p, 2);
28
  return ntohs(x);
29
}
30

    
31
static inline u32
32
get_u24(const void *P)
33
{
34
  const byte *p = P;
35
  return (p[0] << 16) + (p[1] << 8) + p[2];
36
}
37

    
38
static inline u32
39
get_u32(const void *p)
40
{
41
  u32 x;
42
  memcpy(&x, p, 4);
43
  return ntohl(x);
44
}
45

    
46
static inline u64
47
get_u64(const void *p)
48
{
49
  u32 xh, xl;
50
  memcpy(&xh, p, 4);
51
  memcpy(&xl, p+4, 4);
52
  return (((u64) ntohl(xh)) << 32) | ntohl(xl);
53
}
54

    
55
static inline void
56
put_u16(void *p, u16 x)
57
{
58
  x = htons(x);
59
  memcpy(p, &x, 2);
60
}
61

    
62
static inline void
63
put_u24(void *p, u32 x)
64
{
65
  x = htonl(x);
66
  memcpy(p, ((char *) &x) + 1, 3);
67
}
68

    
69
static inline void
70
put_u32(void *p, u32 x)
71
{
72
  x = htonl(x);
73
  memcpy(p, &x, 4);
74
}
75

    
76
static inline void
77
put_u64(void *p, u64 x)
78
{
79
  u32 xh, xl;
80
  xh = htonl(x >> 32);
81
  xl = htonl((u32) x);
82
  memcpy(p, &xh, 4);
83
  memcpy(p+4, &xl, 4);
84
}
85

    
86
static inline void
87
get_u32s(const void *p, u32 *x, int n)
88
{
89
  int i;
90
  memcpy(x, p, 4*n);
91
  for (i = 0; i < n; i++)
92
    x[i] = ntohl(x[i]);
93
}
94

    
95
static inline void
96
put_u32s(void *p, const u32 *x, int n)
97
{
98
  int i;
99
  for (i = 0; i < n; i++)
100
    put_u32((byte *) p + 4*i, x[i]);
101
}
102

    
103

    
104
#endif