]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/boost/spirit/home/x3/char/detail/cast_char.hpp
update sources to v12.2.3
[ceph.git] / ceph / src / boost / boost / spirit / home / x3 / char / detail / cast_char.hpp
1 /*=============================================================================
2 Copyright (c) 2001-2014 Joel de Guzman
3 Copyright (c) 2001-2011 Hartmut Kaiser
4
5 Distributed under the Boost Software License, Version 1.0. (See accompanying
6 file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 =============================================================================*/
8 #if !defined(BOOST_SPIRIT_X3_CAST_CHAR_NOVEMBER_10_2006_0907AM)
9 #define BOOST_SPIRIT_X3_CAST_CHAR_NOVEMBER_10_2006_0907AM
10
11 #include <boost/type_traits/is_signed.hpp>
12 #include <boost/type_traits/make_unsigned.hpp>
13 #include <boost/type_traits/make_signed.hpp>
14
15 namespace boost { namespace spirit { namespace x3 { namespace detail
16 {
17 // Here's the thing... typical encodings (except ASCII) deal with unsigned
18 // integers > 127 (ASCII uses only 127). Yet, most char and wchar_t are signed.
19 // Thus, a char with value > 127 is negative (e.g. char 233 is -23). When you
20 // cast this to an unsigned int with 32 bits, you get 4294967273!
21 //
22 // The trick is to cast to an unsigned version of the source char first
23 // before casting to the target. {P.S. Don't worry about the code, the
24 // optimizer will optimize the if-else branches}
25
26 template <typename TargetChar, typename SourceChar>
27 TargetChar cast_char(SourceChar ch)
28 {
29 if (is_signed<TargetChar>::value != is_signed<SourceChar>::value)
30 {
31 if (is_signed<SourceChar>::value)
32 {
33 // source is signed, target is unsigned
34 typedef typename make_unsigned<SourceChar>::type USourceChar;
35 return TargetChar(USourceChar(ch));
36 }
37 else
38 {
39 // source is unsigned, target is signed
40 typedef typename make_signed<SourceChar>::type SSourceChar;
41 return TargetChar(SSourceChar(ch));
42 }
43 }
44 else
45 {
46 // source and target has same signedness
47 return TargetChar(ch); // just cast
48 }
49 }
50 }}}}
51
52 #endif
53
54