Skip to content

Commit

Permalink
Added a view to just the names of TermNames
Browse files Browse the repository at this point in the history
  • Loading branch information
Tomaqa committed Oct 17, 2024
1 parent e8ee0c4 commit ca3fef7
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions src/common/TermNames.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

#include <optional>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <vector>

Expand Down Expand Up @@ -76,6 +77,8 @@ class TermNames {
bool empty() const noexcept { return scopedNamesAndTerms.empty(); }
std::size_t size() const noexcept { return scopedNamesAndTerms.size(); }

// A const view to just the names
inline auto names() const;
// A const view to just the terms
inline auto terms() const;

Expand All @@ -86,7 +89,10 @@ class TermNames {
using NameToTermMap = std::unordered_map<TermName, PTRef>;
using TermToNamesMap = std::unordered_map<PTRef, std::vector<TermName>, PTRefHash>;

class TermsView;
template<bool namesView>
class NamesOrTermsView;
using NamesView = NamesOrTermsView<true>;
using TermsView = NamesOrTermsView<false>;

// avoid undesired overload resolution with the public `namesForTerm`
std::vector<TermName> & _namesForTerm(PTRef term) const {
Expand Down Expand Up @@ -118,17 +124,26 @@ class TermNames {
TermToNamesMap termToNames;
};

class TermNames::TermsView {
template<bool namesView>
class TermNames::NamesOrTermsView {
public:
explicit TermsView(TermNames const & termNames_) : termNames{termNames_} {}
explicit NamesOrTermsView(TermNames const & termNames_) : termNames{termNames_} {}

class Iterator {
public:
using PairIterator = ScopedNamesAndTerms::const_iterator;

using Value = std::conditional_t<namesView, TermName const &, PTRef>;

explicit Iterator(PairIterator pit) : pairIterator{pit} {}

PTRef operator*() const { return pairIterator->second; }
Value operator*() const {
if constexpr (namesView) {
return pairIterator->first;
} else {
return pairIterator->second;
}
}

Iterator & operator++() {
++pairIterator;
Expand All @@ -151,10 +166,15 @@ class TermNames::TermsView {

bool empty() const noexcept { return termNames.scopedNamesAndTerms.empty(); }
std::size_t size() const noexcept { return termNames.scopedNamesAndTerms.size(); }

protected:
TermNames const & termNames;
};

auto TermNames::names() const {
return NamesView(*this);
}

auto TermNames::terms() const {
return TermsView(*this);
}
Expand Down

0 comments on commit ca3fef7

Please sign in to comment.