common_view.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // common_view.h
  3. // stream
  4. //
  5. // Created by Sam Jaffe on 3/30/23.
  6. //
  7. #pragma once
  8. #include <iterator/sentinel_iterator.h>
  9. #include <stream/detail/traits.h>
  10. #include <stream/forward.h>
  11. #include <iterator/detail/macro.h>
  12. #define FWD(x) std::forward<decltype(x)>(x)
  13. namespace stream::ranges {
  14. template <typename S> class common_view {
  15. private:
  16. using iterator =
  17. iterator::sentinel_iterator<detail::begin_t<S>, detail::end_t<S>>;
  18. private:
  19. S stream_;
  20. public:
  21. common_view(S && stream) : stream_(FWD(stream)) {}
  22. auto begin() const { return iterator(stream_.begin()); }
  23. auto end() const { return iterator(stream_.end()); }
  24. SFINAE(detail::has_empty_v<S>, bool) empty() const { return stream_.empty(); }
  25. SFINAE(detail::has_size_v<S>, bool) size() const { return stream_.size(); }
  26. };
  27. template <typename S> common_view(S &&) -> common_view<S>;
  28. }
  29. namespace stream::ranges::views {
  30. struct common {
  31. template <typename Stream> friend auto operator|(Stream && stream, common) {
  32. if constexpr (detail::is_sentinal_v<Stream>) {
  33. return common_view(FWD(stream));
  34. } else {
  35. return FWD(stream);
  36. }
  37. }
  38. };
  39. }
  40. #undef FWD
  41. #include <iterator/detail/undef.h>