cast_char.hpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*=============================================================================
  2. Copyright (c) 2001-2014 Joel de Guzman
  3. Copyright (c) 2001-2011 Hartmut Kaiser
  4. Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. =============================================================================*/
  7. #if !defined(BOOST_SPIRIT_X3_CAST_CHAR_NOVEMBER_10_2006_0907AM)
  8. #define BOOST_SPIRIT_X3_CAST_CHAR_NOVEMBER_10_2006_0907AM
  9. #include <boost/type_traits/is_signed.hpp>
  10. #include <boost/type_traits/make_unsigned.hpp>
  11. #include <boost/type_traits/make_signed.hpp>
  12. namespace boost { namespace spirit { namespace x3 { namespace detail
  13. {
  14. // Here's the thing... typical encodings (except ASCII) deal with unsigned
  15. // integers > 127 (ASCII uses only 127). Yet, most char and wchar_t are signed.
  16. // Thus, a char with value > 127 is negative (e.g. char 233 is -23). When you
  17. // cast this to an unsigned int with 32 bits, you get 4294967273!
  18. //
  19. // The trick is to cast to an unsigned version of the source char first
  20. // before casting to the target. {P.S. Don't worry about the code, the
  21. // optimizer will optimize the if-else branches}
  22. template <typename TargetChar, typename SourceChar>
  23. TargetChar cast_char(SourceChar ch)
  24. {
  25. #if defined(_MSC_VER)
  26. # pragma warning(push)
  27. # pragma warning(disable: 4127) // conditional expression is constant
  28. #endif
  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. #if defined(_MSC_VER)
  50. # pragma warning(pop)
  51. #endif
  52. }
  53. }}}}
  54. #endif