From fa51c8fd98bfb0d90dd335a70730e2c2eb340d63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6nke=20Schau?= Date: Sat, 13 Mar 2021 18:22:00 +0100 Subject: [PATCH] Fix std::out_of_range from string_view::find (#7) The string_view::find operation was unexpectedly throwing an out_of_range exception in cases where the position was nonzero and the string wasn't found. This corrects those cases by accounting for the position, and adds unit tests for validation. Fixes #6 --- include/bpstd/detail/string_view.inl | 2 +- single_include/bpstd/string_view.hpp | 2 +- tests/bpstd/string_view.test.cpp | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/include/bpstd/detail/string_view.inl b/include/bpstd/detail/string_view.inl index 1628a72..5e0a238 100644 --- a/include/bpstd/detail/string_view.inl +++ b/include/bpstd/detail/string_view.inl @@ -293,7 +293,7 @@ namespace bpstd { } const auto offset = pos; - const auto increments = size() - v.size(); + const auto increments = size() - v.size() - offset; for (auto i = 0u; i <= increments; ++i) { const auto j = i + offset; diff --git a/single_include/bpstd/string_view.hpp b/single_include/bpstd/string_view.hpp index ce99295..3988bf4 100644 --- a/single_include/bpstd/string_view.hpp +++ b/single_include/bpstd/string_view.hpp @@ -788,7 +788,7 @@ namespace bpstd { } const auto offset = pos; - const auto increments = size() - v.size(); + const auto increments = size() - v.size() - offset; for (auto i = 0u; i <= increments; ++i) { const auto j = i + offset; diff --git a/tests/bpstd/string_view.test.cpp b/tests/bpstd/string_view.test.cpp index 077dfe8..3ce5a2e 100644 --- a/tests/bpstd/string_view.test.cpp +++ b/tests/bpstd/string_view.test.cpp @@ -545,6 +545,23 @@ TEST_CASE("string_view::find", "[operations]") REQUIRE( result == 0u ); } } + SECTION("Argument is string, offset in string, no match") + { + bpstd::string_view s1 = "01234567890ABCDEFGHIJ"; + bpstd::string_view s2 = "01"; + + auto result = s1.find(s2); + SECTION("prefix find ok") + { + REQUIRE(result != bpstd::string_view::npos); + REQUIRE(s1.size() > 10); + } + auto result1 = s1.find(s2, 10); + SECTION("nonmatching substring") + { + REQUIRE(result1 == bpstd::string_view::npos); + } + } } }