paludis  Version 2.6.0
byte_swap.hh
1 /* vim: set sw=4 sts=4 et foldmethod=syntax : */
2 
3 /*
4  * Copyright (c) 2007, 2008 David Leverton
5  *
6  * This file is part of the Paludis package manager. Paludis is free software;
7  * you can redistribute it and/or modify it under the terms of the GNU General
8  * Public License version 2, as published by the Free Software Foundation.
9  *
10  * Paludis is distributed in the hope that it will be useful, but WITHOUT ANY
11  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13  * details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
17  * Place, Suite 330, Boston, MA 02111-1307 USA
18  */
19 
20 #ifndef PALUDIS_GUARD_PALUDIS_UTIL_BYTE_SWAP_HH
21 #define PALUDIS_GUARD_PALUDIS_UTIL_BYTE_SWAP_HH
22 
23 #include <cstddef>
24 
25 namespace paludis
26 {
27  namespace byte_swap_internals
28  {
29  template <std::size_t, typename> struct ByteSwap;
30 
31  template <typename T_>
32  struct ByteSwap<1, T_>
33  {
34  static T_ swap(T_ x)
35  {
36  return x;
37  }
38  };
39 
40  template <typename T_>
41  struct ByteSwap<2, T_>
42  {
43  static T_ swap(T_ x)
44  {
45  return ((x << 8) & (T_(0xFF) << 8)) | ((x >> 8) & T_(0xFF));
46  }
47  };
48 
49  template <typename T_>
50  struct ByteSwap<4, T_>
51  {
52  static T_ swap(T_ x)
53  {
54  return ((x << 24) & (T_(0xFF) << 24)) | ((x << 8) & (T_(0xFF) << 16))
55  | ((x >> 8) & (T_(0xFF) << 8)) | ((x >> 24) & T_(0xFF) );
56  }
57  };
58 
59  template <typename T_>
60  struct ByteSwap<8, T_>
61  {
62  static T_ swap(T_ x)
63  {
64  return ((x << 56) & (T_(0xFF) << 56)) | ((x << 40) & (T_(0xFF) << 48))
65  | ((x << 24) & (T_(0xFF) << 40)) | ((x << 8) & (T_(0xFF) << 32))
66  | ((x >> 8) & (T_(0xFF) << 24)) | ((x >> 24) & (T_(0xFF) << 16))
67  | ((x >> 40) & (T_(0xFF) << 8)) | ((x >> 56) & T_(0xFF) );
68  }
69  };
70  }
71 
72  template <typename T_>
73  inline T_
74  byte_swap(T_ x)
75  {
77  }
78 
79 #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
80  template <typename T_>
81  inline T_
82  from_bigendian(T_ x)
83  {
84  return x;
85  }
86 
87  template <typename T_>
88  inline T_
89  to_bigendian(T_ x)
90  {
91  return x;
92  }
93 #else
94  template <typename T_>
95  inline T_
96  from_bigendian(T_ x)
97  {
98  return byte_swap(x);
99  }
100 
101  template <typename T_>
102  inline T_
103  to_bigendian(T_ x)
104  {
105  return byte_swap(x);
106  }
107 #endif
108 }
109 
110 #endif
Definition: about_metadata-fwd.hh:23
Definition: byte_swap.hh:29