From cc65b2d9b46142ebda764502e62be714d9da5809 Mon Sep 17 00:00:00 2001 From: Tsung-Wei Huang Date: Sun, 7 Jun 2026 15:27:53 -0500 Subject: [PATCH] updated iterator distance to return 0 on invalid size --- taskflow/utility/iterator.hpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/taskflow/utility/iterator.hpp b/taskflow/utility/iterator.hpp index aecd25739..751f0d8db 100644 --- a/taskflow/utility/iterator.hpp +++ b/taskflow/utility/iterator.hpp @@ -64,20 +64,20 @@ size_t dist = distance(5, 20, 5); // Returns 3, the sequence is [5, 10, 15] @endcode @attention -It is user's responsibility to ensure the given index range is valid. -For instance, a range from 0 to 10 with a step size of -2 is invalid. +An invalid index range will return 0. */ template constexpr size_t distance(T beg, T end, T step) { if constexpr (std::is_unsigned_v) { - // step is always positive for unsigned types — standard ceiling division - return static_cast((end - beg + step - T{1}) / step); + return end > beg + ? static_cast((end - beg + step - T{1}) / step) + : size_t{0}; } else { - // signed: step may be positive or negative - return static_cast((end - beg + step + (step > T{0} ? T{-1} : T{1})) / step); + return static_cast( + std::max(T{0}, (end - beg + step + (step > T{0} ? T{-1} : T{1})) / step) + ); } } - // ---------------------------------------------------------------------------- // IndexRange (primary template, N > 1)