| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- //
- // view.h
- // stream
- //
- // Created by Sam Jaffe on 3/29/23.
- //
- #pragma once
- #include <memory>
- #include <stream/common_view.h>
- #include <stream/detail/traits.h>
- #include <stream/forward.h>
- namespace stream::ranges {
- template <typename T> class view_iterator : public facade<view_iterator<T>> {
- private:
- T (*dereference_)(void *){nullptr};
- bool (*equal_to_)(void *, void *){nullptr};
- void (*increment_)(void *){nullptr};
- std::shared_ptr<void> impl_{nullptr};
- public:
- template <typename It>
- view_iterator(It impl)
- : dereference_([](void * p) -> T { return **((It *)p); }),
- equal_to_([](void * l, void * r) { return *((It *)l) == *((It *)r); }),
- increment_([](void * p) { ++(*(It *)(p)); }),
- impl_(std::make_shared<It>(impl)) {}
- T dereference() const { return dereference_(impl_.get()); }
- void increment() { increment_(impl_.get()); }
- bool equal_to(view_iterator const & other) const {
- return impl_ == other.impl_ ||
- (impl_ && other.impl_ && equal_to_(impl_.get(), other.impl_.get()));
- }
- };
- template <typename T> class any_view {
- private:
- template <typename S>
- using sentinel_iterator =
- common_iterator<detail::begin_t<S>, detail::end_t<S>>;
- template <typename S, typename It>
- using iter_cast_t =
- std::conditional_t<detail::is_sentinal_v<S>, sentinel_iterator<S>, It>;
- using make_iter_t = view_iterator<T> (*)(void *);
- private:
- std::shared_ptr<void> impl_{nullptr};
- make_iter_t begin_{nullptr};
- make_iter_t end_{nullptr};
- public:
- template <typename S>
- any_view(std::shared_ptr<S> impl)
- : impl_(impl), begin_(begin_function<S>()), end_(end_function<S>()) {}
- template <typename S>
- any_view(S & impl) : any_view(std::shared_ptr<S>(&impl, [](void *) {})) {}
- template <typename S>
- any_view(S const & impl)
- : any_view(std::shared_ptr<S const>(&impl, [](void *) {})) {}
- template <typename S>
- any_view(S && impl) : any_view(std::make_shared<S>(std::forward<S>(impl))) {}
- auto begin() const { return begin_(impl_.get()); }
- auto end() const { return end_(impl_.get()); }
- private:
- template <typename S> static make_iter_t begin_function() {
- return [](void * p) -> view_iterator<T> {
- return iter_cast_t<S, detail::begin_t<S>>(static_cast<S *>(p)->begin());
- };
- }
- template <typename S> static make_iter_t end_function() {
- return [](void * p) -> view_iterator<T> {
- return iter_cast_t<S, detail::end_t<S>>(static_cast<S *>(p)->end());
- };
- }
- };
- template <typename S>
- any_view(std::shared_ptr<S>) -> any_view<detail::value_type<S>>;
- template <typename S> any_view(S &) -> any_view<detail::value_type<S>>;
- template <typename S> any_view(S const &) -> any_view<detail::value_type<S>>;
- template <typename S> any_view(S &&) -> any_view<detail::value_type<S>>;
- }
|