]> git.proxmox.com Git - libgit2.git/blob - src/bswap.h
Cleanup legal data
[libgit2.git] / src / bswap.h
1 /*
2 * Copyright (C) 2009-2011 the libgit2 contributors
3 *
4 * This file is part of libgit2, distributed under the GNU GPL v2 with
5 * a Linking Exception. For full terms see the included COPYING file.
6 */
7
8 #include "common.h"
9
10 /*
11 * Default version that the compiler ought to optimize properly with
12 * constant values.
13 */
14 GIT_INLINE(uint32_t) default_swab32(uint32_t val)
15 {
16 return (((val & 0xff000000) >> 24) |
17 ((val & 0x00ff0000) >> 8) |
18 ((val & 0x0000ff00) << 8) |
19 ((val & 0x000000ff) << 24));
20 }
21
22 #undef bswap32
23
24 GIT_INLINE(uint16_t) default_swab16(uint16_t val)
25 {
26 return (((val & 0xff00) >> 8) |
27 ((val & 0x00ff) << 8));
28 }
29
30 #undef bswap16
31
32 #if defined(__GNUC__) && defined(__i386__)
33
34 #define bswap32(x) ({ \
35 uint32_t __res; \
36 if (__builtin_constant_p(x)) { \
37 __res = default_swab32(x); \
38 } else { \
39 __asm__("bswap %0" : "=r" (__res) : "0" ((uint32_t)(x))); \
40 } \
41 __res; })
42
43 #define bswap16(x) ({ \
44 uint16_t __res; \
45 if (__builtin_constant_p(x)) { \
46 __res = default_swab16(x); \
47 } else { \
48 __asm__("xchgb %b0,%h0" : "=q" (__res) : "0" ((uint16_t)(x))); \
49 } \
50 __res; })
51
52 #elif defined(__GNUC__) && defined(__x86_64__)
53
54 #define bswap32(x) ({ \
55 uint32_t __res; \
56 if (__builtin_constant_p(x)) { \
57 __res = default_swab32(x); \
58 } else { \
59 __asm__("bswapl %0" : "=r" (__res) : "0" ((uint32_t)(x))); \
60 } \
61 __res; })
62
63 #define bswap16(x) ({ \
64 uint16_t __res; \
65 if (__builtin_constant_p(x)) { \
66 __res = default_swab16(x); \
67 } else { \
68 __asm__("xchgb %b0,%h0" : "=Q" (__res) : "0" ((uint16_t)(x))); \
69 } \
70 __res; })
71
72 #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
73
74 #include <stdlib.h>
75
76 #define bswap32(x) _byteswap_ulong(x)
77 #define bswap16(x) _byteswap_ushort(x)
78
79 #endif
80
81 #ifdef bswap32
82
83 #undef ntohl
84 #undef htonl
85 #define ntohl(x) bswap32(x)
86 #define htonl(x) bswap32(x)
87
88 #endif
89
90 #ifdef bswap16
91
92 #undef ntohs
93 #undef htons
94 #define ntohs(x) bswap16(x)
95 #define htons(x) bswap16(x)
96
97 #endif