You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
2.7KB

  1. /// \file
  2. // Range v3 library
  3. //
  4. // Copyright Eric Niebler 2013-present
  5. //
  6. // Use, modification and distribution is subject to the
  7. // Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at
  9. // http://www.boost.org/LICENSE_1_0.txt)
  10. //
  11. // Project home: https://github.com/ericniebler/range-v3
  12. //
  13. #ifndef RANGES_V3_VIEW_ISTREAM_HPP
  14. #define RANGES_V3_VIEW_ISTREAM_HPP
  15. #include <istream>
  16. #include <range/v3/range_fwd.hpp>
  17. #include <range/v3/iterator/default_sentinel.hpp>
  18. #include <range/v3/utility/semiregular_box.hpp>
  19. #include <range/v3/utility/static_const.hpp>
  20. #include <range/v3/view/facade.hpp>
  21. namespace ranges
  22. {
  23. /// \addtogroup group-views
  24. /// @{
  25. template<typename Val>
  26. struct istream_view : view_facade<istream_view<Val>, unknown>
  27. {
  28. private:
  29. friend range_access;
  30. std::istream * sin_;
  31. semiregular_box_t<Val> obj_;
  32. struct cursor
  33. {
  34. private:
  35. friend range_access;
  36. using single_pass = std::true_type;
  37. istream_view * rng_ = nullptr;
  38. public:
  39. cursor() = default;
  40. explicit cursor(istream_view * rng)
  41. : rng_(rng)
  42. {}
  43. void next()
  44. {
  45. rng_->next();
  46. }
  47. Val & read() const noexcept
  48. {
  49. return rng_->cached();
  50. }
  51. bool equal(default_sentinel_t) const
  52. {
  53. return !rng_->sin_;
  54. }
  55. bool equal(cursor that) const
  56. {
  57. return !rng_->sin_ == !that.rng_->sin_;
  58. }
  59. };
  60. void next()
  61. {
  62. if(!(*sin_ >> cached()))
  63. sin_ = nullptr;
  64. }
  65. cursor begin_cursor()
  66. {
  67. return cursor{this};
  68. }
  69. public:
  70. istream_view() = default;
  71. explicit istream_view(std::istream & sin)
  72. : sin_(&sin)
  73. , obj_{}
  74. {
  75. next(); // prime the pump
  76. }
  77. Val & cached() noexcept
  78. {
  79. return obj_;
  80. }
  81. };
  82. /// \cond
  83. template<typename Val>
  84. using istream_range RANGES_DEPRECATED(
  85. "istream_range<T> has been renamed to istream_view<T>") = istream_view<Val>;
  86. /// \endcond
  87. /// \cond
  88. namespace _istream_
  89. {
  90. /// \endcond
  91. template<typename Val>
  92. inline auto istream(std::istream & sin) -> CPP_ret(istream_view<Val>)( //
  93. requires copy_constructible<Val> && default_constructible<Val>)
  94. {
  95. return istream_view<Val>{sin};
  96. }
  97. /// \cond
  98. } // namespace _istream_
  99. using namespace _istream_;
  100. /// \endcond
  101. /// @}
  102. } // namespace ranges
  103. #endif