iostream_state_saver.h 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef ABSL_RANDOM_INTERNAL_IOSTREAM_STATE_SAVER_H_
  15. #define ABSL_RANDOM_INTERNAL_IOSTREAM_STATE_SAVER_H_
  16. #include <cmath>
  17. #include <iostream>
  18. #include <limits>
  19. #include <type_traits>
  20. #include "absl/meta/type_traits.h"
  21. #include "absl/numeric/int128.h"
  22. namespace absl {
  23. ABSL_NAMESPACE_BEGIN
  24. namespace random_internal {
  25. // The null_state_saver does nothing.
  26. template <typename T>
  27. class null_state_saver {
  28. public:
  29. using stream_type = T;
  30. using flags_type = std::ios_base::fmtflags;
  31. null_state_saver(T&, flags_type) {}
  32. ~null_state_saver() {}
  33. };
  34. // ostream_state_saver is a RAII object to save and restore the common
  35. // basic_ostream flags used when implementing `operator <<()` on any of
  36. // the absl random distributions.
  37. template <typename OStream>
  38. class ostream_state_saver {
  39. public:
  40. using ostream_type = OStream;
  41. using flags_type = std::ios_base::fmtflags;
  42. using fill_type = typename ostream_type::char_type;
  43. using precision_type = std::streamsize;
  44. ostream_state_saver(ostream_type& os, // NOLINT(runtime/references)
  45. flags_type flags, fill_type fill)
  46. : os_(os),
  47. flags_(os.flags(flags)),
  48. fill_(os.fill(fill)),
  49. precision_(os.precision()) {
  50. // Save state in initialized variables.
  51. }
  52. ~ostream_state_saver() {
  53. // Restore saved state.
  54. os_.precision(precision_);
  55. os_.fill(fill_);
  56. os_.flags(flags_);
  57. }
  58. private:
  59. ostream_type& os_;
  60. const flags_type flags_;
  61. const fill_type fill_;
  62. const precision_type precision_;
  63. };
  64. #if defined(__NDK_MAJOR__) && __NDK_MAJOR__ < 16
  65. #define ABSL_RANDOM_INTERNAL_IOSTREAM_HEXFLOAT 1
  66. #else
  67. #define ABSL_RANDOM_INTERNAL_IOSTREAM_HEXFLOAT 0
  68. #endif
  69. template <typename CharT, typename Traits>
  70. ostream_state_saver<std::basic_ostream<CharT, Traits>> make_ostream_state_saver(
  71. std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
  72. std::ios_base::fmtflags flags = std::ios_base::dec | std::ios_base::left |
  73. #if ABSL_RANDOM_INTERNAL_IOSTREAM_HEXFLOAT
  74. std::ios_base::fixed |
  75. #endif
  76. std::ios_base::scientific) {
  77. using result_type = ostream_state_saver<std::basic_ostream<CharT, Traits>>;
  78. return result_type(os, flags, os.widen(' '));
  79. }
  80. template <typename T>
  81. typename absl::enable_if_t<!std::is_base_of<std::ios_base, T>::value,
  82. null_state_saver<T>>
  83. make_ostream_state_saver(T& is, // NOLINT(runtime/references)
  84. std::ios_base::fmtflags flags = std::ios_base::dec) {
  85. std::cerr << "null_state_saver";
  86. using result_type = null_state_saver<T>;
  87. return result_type(is, flags);
  88. }
  89. // stream_precision_helper<type>::kPrecision returns the base 10 precision
  90. // required to stream and reconstruct a real type exact binary value through
  91. // a binary->decimal->binary transition.
  92. template <typename T>
  93. struct stream_precision_helper {
  94. // max_digits10 may be 0 on MSVC; if so, use digits10 + 3.
  95. static constexpr int kPrecision =
  96. (std::numeric_limits<T>::max_digits10 > std::numeric_limits<T>::digits10)
  97. ? std::numeric_limits<T>::max_digits10
  98. : (std::numeric_limits<T>::digits10 + 3);
  99. };
  100. template <>
  101. struct stream_precision_helper<float> {
  102. static constexpr int kPrecision = 9;
  103. };
  104. template <>
  105. struct stream_precision_helper<double> {
  106. static constexpr int kPrecision = 17;
  107. };
  108. template <>
  109. struct stream_precision_helper<long double> {
  110. static constexpr int kPrecision = 36; // assuming fp128
  111. };
  112. // istream_state_saver is a RAII object to save and restore the common
  113. // std::basic_istream<> flags used when implementing `operator >>()` on any of
  114. // the absl random distributions.
  115. template <typename IStream>
  116. class istream_state_saver {
  117. public:
  118. using istream_type = IStream;
  119. using flags_type = std::ios_base::fmtflags;
  120. istream_state_saver(istream_type& is, // NOLINT(runtime/references)
  121. flags_type flags)
  122. : is_(is), flags_(is.flags(flags)) {}
  123. ~istream_state_saver() { is_.flags(flags_); }
  124. private:
  125. istream_type& is_;
  126. flags_type flags_;
  127. };
  128. template <typename CharT, typename Traits>
  129. istream_state_saver<std::basic_istream<CharT, Traits>> make_istream_state_saver(
  130. std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
  131. std::ios_base::fmtflags flags = std::ios_base::dec |
  132. std::ios_base::scientific |
  133. std::ios_base::skipws) {
  134. using result_type = istream_state_saver<std::basic_istream<CharT, Traits>>;
  135. return result_type(is, flags);
  136. }
  137. template <typename T>
  138. typename absl::enable_if_t<!std::is_base_of<std::ios_base, T>::value,
  139. null_state_saver<T>>
  140. make_istream_state_saver(T& is, // NOLINT(runtime/references)
  141. std::ios_base::fmtflags flags = std::ios_base::dec) {
  142. using result_type = null_state_saver<T>;
  143. return result_type(is, flags);
  144. }
  145. // stream_format_type<T> is a helper struct to convert types which
  146. // basic_iostream cannot output as decimal numbers into types which
  147. // basic_iostream can output as decimal numbers. Specifically:
  148. // * signed/unsigned char-width types are converted to int.
  149. // * TODO(lar): __int128 => uint128, except there is no operator << yet.
  150. //
  151. template <typename T>
  152. struct stream_format_type
  153. : public std::conditional<(sizeof(T) == sizeof(char)), int, T> {};
  154. // stream_u128_helper allows us to write out either absl::uint128 or
  155. // __uint128_t types in the same way, which enables their use as internal
  156. // state of PRNG engines.
  157. template <typename T>
  158. struct stream_u128_helper;
  159. template <>
  160. struct stream_u128_helper<absl::uint128> {
  161. template <typename IStream>
  162. inline absl::uint128 read(IStream& in) {
  163. uint64_t h = 0;
  164. uint64_t l = 0;
  165. in >> h >> l;
  166. return absl::MakeUint128(h, l);
  167. }
  168. template <typename OStream>
  169. inline void write(absl::uint128 val, OStream& out) {
  170. uint64_t h = absl::Uint128High64(val);
  171. uint64_t l = absl::Uint128Low64(val);
  172. out << h << out.fill() << l;
  173. }
  174. };
  175. #ifdef ABSL_HAVE_INTRINSIC_INT128
  176. template <>
  177. struct stream_u128_helper<__uint128_t> {
  178. template <typename IStream>
  179. inline __uint128_t read(IStream& in) {
  180. uint64_t h = 0;
  181. uint64_t l = 0;
  182. in >> h >> l;
  183. return (static_cast<__uint128_t>(h) << 64) | l;
  184. }
  185. template <typename OStream>
  186. inline void write(__uint128_t val, OStream& out) {
  187. uint64_t h = static_cast<uint64_t>(val >> 64u);
  188. uint64_t l = static_cast<uint64_t>(val);
  189. out << h << out.fill() << l;
  190. }
  191. };
  192. #endif
  193. template <typename FloatType, typename IStream>
  194. inline FloatType read_floating_point(IStream& is) {
  195. static_assert(std::is_floating_point<FloatType>::value, "");
  196. FloatType dest;
  197. is >> dest;
  198. // Parsing a double value may report a subnormal value as an error
  199. // despite being able to represent it.
  200. // See https://stackoverflow.com/q/52410931/3286653
  201. // It may also report an underflow when parsing DOUBLE_MIN as an
  202. // ERANGE error, as the parsed value may be smaller than DOUBLE_MIN
  203. // and rounded up.
  204. // See: https://stackoverflow.com/q/42005462
  205. if (is.fail() &&
  206. (std::fabs(dest) == (std::numeric_limits<FloatType>::min)() ||
  207. std::fpclassify(dest) == FP_SUBNORMAL)) {
  208. is.clear(is.rdstate() & (~std::ios_base::failbit));
  209. }
  210. return dest;
  211. }
  212. } // namespace random_internal
  213. ABSL_NAMESPACE_END
  214. } // namespace absl
  215. #endif // ABSL_RANDOM_INTERNAL_IOSTREAM_STATE_SAVER_H_