From abc04f2ee57bd901e199a75f906b5b94682bdc49 Mon Sep 17 00:00:00 2001 From: "Keith A. Lewis" Date: Thu, 13 Jun 2024 13:58:59 -0400 Subject: [PATCH] counted pointer --- fms_iterable.h | 23 ++++++++++++++++++----- fms_iterable.t.cpp | 47 ++++++++++++++++++++++++++++++++-------------- 2 files changed, 51 insertions(+), 19 deletions(-) diff --git a/fms_iterable.h b/fms_iterable.h index abc3698..9733997 100644 --- a/fms_iterable.h +++ b/fms_iterable.h @@ -584,26 +584,36 @@ namespace fms::iterable { } }; - // Unsafe pointer interface. + // Unsafe counted pointer interface with std::span semantics. template class pointer { T* p; + size_t n; public: using iterator_category = std::input_iterator_tag; using value_type = T; using reference = T&; using difference_type = std::ptrdiff_t; - // pointer() is empty iterator - pointer(T* p = nullptr) noexcept - : p(p) + // possible unsafe + pointer(T* p, size_t n = std::numeric_limits::max()) noexcept + : p(p), n(n) { } bool operator==(const pointer& _p) const = default; + auto begin() const + { + return *this; + } + auto end() const + { + return pointer(p + n, 0); + } + explicit operator bool() const noexcept { - return p != nullptr; // unsafe + return n != 0; // possibly unsafe } value_type operator*() const noexcept { @@ -616,6 +626,9 @@ namespace fms::iterable { pointer& operator++() noexcept { ++p; + if (n > 0) { + --n; + } return *this; } diff --git a/fms_iterable.t.cpp b/fms_iterable.t.cpp index d6d0b2f..3220ada 100644 --- a/fms_iterable.t.cpp +++ b/fms_iterable.t.cpp @@ -320,20 +320,39 @@ int test_fold() { } int test_pointer() { - int i[] = { 1, 2, 3 }; - pointer p(i); - pointer p2(p); - assert(p == p2); - p = p2; - assert(!(p2 != p)); - - assert(p); - assert(*p == 1); - ++p; - assert(*p == 2); - ++p; - assert(*p == 3); - ++p; // *p is undefined + { + int i[] = { 1, 2, 3 }; + pointer p(i); + pointer p2(p); + assert(p == p2); + p = p2; + assert(!(p2 != p)); + + assert(p); + assert(*p == 1); + ++p; + assert(*p == 2); + ++p; + assert(*p == 3); + ++p; // *p is undefined + } + { + int i[] = { 1, 2, 3 }; + pointer p(i, 3); + pointer p2(p); + assert(p == p2); + p = p2; + assert(!(p2 != p)); + + assert(p); + assert(*p == 1); + ++p; + assert(*p == 2); + ++p; + assert(*p == 3); + ++p; + assert(!p); + } return 0; }