getlines.hpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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_GETLINES_HPP
  14. #define RANGES_V3_VIEW_GETLINES_HPP
  15. #include <istream>
  16. #include <string>
  17. #include <range/v3/range_fwd.hpp>
  18. #include <range/v3/iterator/default_sentinel.hpp>
  19. #include <range/v3/utility/static_const.hpp>
  20. #include <range/v3/view/facade.hpp>
  21. #include <range/v3/detail/prologue.hpp>
  22. namespace ranges
  23. {
  24. /// \addtogroup group-views
  25. /// @{
  26. struct getlines_view : view_facade<getlines_view, unknown>
  27. {
  28. private:
  29. friend range_access;
  30. std::istream * sin_;
  31. std::string str_;
  32. char delim_;
  33. struct cursor
  34. {
  35. private:
  36. friend range_access;
  37. using single_pass = std::true_type;
  38. getlines_view * rng_ = nullptr;
  39. public:
  40. cursor() = default;
  41. explicit cursor(getlines_view * rng)
  42. : rng_(rng)
  43. {}
  44. void next()
  45. {
  46. rng_->next();
  47. }
  48. std::string & read() const noexcept
  49. {
  50. return rng_->str_;
  51. }
  52. bool equal(default_sentinel_t) const
  53. {
  54. return !rng_->sin_;
  55. }
  56. bool equal(cursor that) const
  57. {
  58. return !rng_->sin_ == !that.rng_->sin_;
  59. }
  60. };
  61. void next()
  62. {
  63. if(!std::getline(*sin_, str_, delim_))
  64. sin_ = nullptr;
  65. }
  66. cursor begin_cursor()
  67. {
  68. return cursor{this};
  69. }
  70. public:
  71. getlines_view() = default;
  72. getlines_view(std::istream & sin, char delim = '\n')
  73. : sin_(&sin)
  74. , str_{}
  75. , delim_(delim)
  76. {
  77. this->next(); // prime the pump
  78. }
  79. std::string & cached() noexcept
  80. {
  81. return str_;
  82. }
  83. };
  84. /// \cond
  85. using getlines_range RANGES_DEPRECATED(
  86. "getlines_range has been renamed getlines_view") = getlines_view;
  87. /// \endcond
  88. struct getlines_fn
  89. {
  90. getlines_view operator()(std::istream & sin, char delim = '\n') const
  91. {
  92. return getlines_view{sin, delim};
  93. }
  94. };
  95. RANGES_INLINE_VARIABLE(getlines_fn, getlines)
  96. /// @}
  97. } // namespace ranges
  98. #include <range/v3/detail/epilogue.hpp>
  99. #endif