Skip to content

Commit

Permalink
counted pointer
Browse files Browse the repository at this point in the history
  • Loading branch information
keithalewis committed Jun 13, 2024
1 parent c2e5ef1 commit abc04f2
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 19 deletions.
23 changes: 18 additions & 5 deletions fms_iterable.h
Original file line number Diff line number Diff line change
Expand Up @@ -584,26 +584,36 @@ namespace fms::iterable {
}
};

// Unsafe pointer interface.
// Unsafe counted pointer interface with std::span semantics.
template <class T>
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<size_t>::max()) noexcept
: p(p), n(n)
{ }

bool operator==(const pointer& _p) const = default;

auto begin() const
{
return *this;
}
auto end() const
{
return pointer<T>(p + n, 0);
}

explicit operator bool() const noexcept
{
return p != nullptr; // unsafe
return n != 0; // possibly unsafe
}
value_type operator*() const noexcept
{
Expand All @@ -616,6 +626,9 @@ namespace fms::iterable {
pointer& operator++() noexcept
{
++p;
if (n > 0) {
--n;
}

return *this;
}
Expand Down
47 changes: 33 additions & 14 deletions fms_iterable.t.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down

0 comments on commit abc04f2

Please sign in to comment.