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.

getlines.hpp 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. namespace ranges
  22. {
  23. /// \addtogroup group-views
  24. /// @{
  25. struct getlines_view : view_facade<getlines_view, unknown>
  26. {
  27. private:
  28. friend range_access;
  29. std::istream * sin_;
  30. std::string str_;
  31. char delim_;
  32. struct cursor
  33. {
  34. private:
  35. friend range_access;
  36. using single_pass = std::true_type;
  37. getlines_view * rng_ = nullptr;
  38. public:
  39. cursor() = default;
  40. explicit cursor(getlines_view * rng)
  41. : rng_(rng)
  42. {}
  43. void next()
  44. {
  45. rng_->next();
  46. }
  47. std::string & read() const noexcept
  48. {
  49. return rng_->str_;
  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(!std::getline(*sin_, str_, delim_))
  63. sin_ = nullptr;
  64. }
  65. cursor begin_cursor()
  66. {
  67. return cursor{this};
  68. }
  69. public:
  70. getlines_view() = default;
  71. getlines_view(std::istream & sin, char delim = '\n')
  72. : sin_(&sin)
  73. , str_{}
  74. , delim_(delim)
  75. {
  76. this->next(); // prime the pump
  77. }
  78. std::string & cached() noexcept
  79. {
  80. return str_;
  81. }
  82. };
  83. /// \cond
  84. using getlines_range RANGES_DEPRECATED(
  85. "getlines_range has been renamed getlines_view") = getlines_view;
  86. /// \endcond
  87. struct getlines_fn
  88. {
  89. getlines_view operator()(std::istream & sin, char delim = '\n') const
  90. {
  91. return getlines_view{sin, delim};
  92. }
  93. };
  94. RANGES_INLINE_VARIABLE(getlines_fn, getlines)
  95. /// @}
  96. } // namespace ranges
  97. #endif