static_string.hpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  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. // Official repository: https://github.com/boostorg/beast
  8. //
  9. #ifndef BOOST_BEAST_DETAIL_STATIC_STRING_HPP
  10. #define BOOST_BEAST_DETAIL_STATIC_STRING_HPP
  11. #include <boost/assert.hpp>
  12. #include <boost/core/ignore_unused.hpp>
  13. #include <string>
  14. #include <type_traits>
  15. namespace boost {
  16. namespace beast {
  17. namespace detail {
  18. // Maximum number of characters in the decimal
  19. // representation of a binary number. This includes
  20. // the potential minus sign.
  21. //
  22. inline
  23. std::size_t constexpr
  24. max_digits(std::size_t bytes)
  25. {
  26. return static_cast<std::size_t>(
  27. bytes * 2.41) + 1 + 1;
  28. }
  29. template<class CharT, class Integer, class Traits>
  30. CharT*
  31. raw_to_string(
  32. CharT* buf, Integer x, std::true_type)
  33. {
  34. if(x == 0)
  35. {
  36. Traits::assign(*--buf, '0');
  37. return buf;
  38. }
  39. if(x < 0)
  40. {
  41. x = -x;
  42. for(;x > 0; x /= 10)
  43. Traits::assign(*--buf ,
  44. "0123456789"[x % 10]);
  45. Traits::assign(*--buf, '-');
  46. return buf;
  47. }
  48. for(;x > 0; x /= 10)
  49. Traits::assign(*--buf ,
  50. "0123456789"[x % 10]);
  51. return buf;
  52. }
  53. template<class CharT, class Integer, class Traits>
  54. CharT*
  55. raw_to_string(
  56. CharT* buf, Integer x, std::false_type)
  57. {
  58. if(x == 0)
  59. {
  60. *--buf = '0';
  61. return buf;
  62. }
  63. for(;x > 0; x /= 10)
  64. Traits::assign(*--buf ,
  65. "0123456789"[x % 10]);
  66. return buf;
  67. }
  68. template<
  69. class CharT,
  70. class Integer,
  71. class Traits = std::char_traits<CharT>>
  72. CharT*
  73. raw_to_string(CharT* last, std::size_t size, Integer i)
  74. {
  75. boost::ignore_unused(size);
  76. BOOST_ASSERT(size >= max_digits(sizeof(Integer)));
  77. return raw_to_string<CharT, Integer, Traits>(
  78. last, i, std::is_signed<Integer>{});
  79. }
  80. } // detail
  81. } // beast
  82. } // boost
  83. #endif