Skip to content

Commit

Permalink
Add support for links to links
Browse files Browse the repository at this point in the history
  • Loading branch information
HowardHinnant committed Apr 19, 2024
1 parent cd3c579 commit 8f8336f
Showing 1 changed file with 47 additions and 7 deletions.
54 changes: 47 additions & 7 deletions src/tz.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3711,13 +3711,59 @@ get_tzdb()
return get_tzdb_list().front();
}

namespace {

class recursion_limiter
{
unsigned depth_ = 0;
unsigned limit_;

class restore_recursion_depth
{
recursion_limiter* rc_;

public:
~restore_recursion_depth() {--(rc_->depth_);}
restore_recursion_depth(restore_recursion_depth&&) = default;

explicit restore_recursion_depth(recursion_limiter* rc) noexcept
: rc_{rc}
{}
};

public:
recursion_limiter(recursion_limiter const&) = delete;
recursion_limiter& operator=(recursion_limiter const&) = delete;

explicit recursion_limiter(unsigned limit) noexcept
: limit_{limit}
{
}

restore_recursion_depth
count()
{
++depth_;
if (depth_ > limit_)
throw std::runtime_error("recursion limit of " +
std::to_string(limit_) + " exceeded");
return restore_recursion_depth{this};
}
};

} // unnamed namespace

const time_zone*
#if HAS_STRING_VIEW
tzdb::locate_zone(std::string_view tz_name) const
#else
tzdb::locate_zone(const std::string& tz_name) const
#endif
{
// If a link-to-link chain exceeds this limit, give up
thread_local recursion_limiter rc{10};
auto restore_count = rc.count();

auto zi = std::lower_bound(zones.begin(), zones.end(), tz_name,
#if HAS_STRING_VIEW
[](const time_zone& z, const std::string_view& nm)
Expand All @@ -3741,13 +3787,7 @@ tzdb::locate_zone(const std::string& tz_name) const
});
if (li != links.end() && li->name() == tz_name)
{
zi = std::lower_bound(zones.begin(), zones.end(), li->target(),
[](const time_zone& z, const std::string& nm)
{
return z.name() < nm;
});
if (zi != zones.end() && zi->name() == li->target())
return &*zi;
return locate_zone(li->target());
}
#endif // !USE_OS_TZDB
throw std::runtime_error(std::string(tz_name) + " not found in timezone database");
Expand Down

0 comments on commit 8f8336f

Please sign in to comment.