From 9f8d740ee22b9e70b6589856f6969cae9e8e3149 Mon Sep 17 00:00:00 2001 From: albertexye Date: Mon, 1 Apr 2024 23:54:34 -0400 Subject: [PATCH] a ValueError is raised when argument 'start' is a negative integer --- src/pocketpy.cpp | 2 ++ src/str.cpp | 1 - tests/04_str.py | 12 +++++++++++- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/pocketpy.cpp b/src/pocketpy.cpp index 27455846..37603f5b 100644 --- a/src/pocketpy.cpp +++ b/src/pocketpy.cpp @@ -627,6 +627,7 @@ void init_builtins(VM* _vm) { const Str& self = _CAST(Str&, args[0]); const Str& value = CAST(Str&, args[1]); int start = CAST(int, args[2]); + if (start < 0) vm->ValueError("argument 'start' can't be negative"); int index = self.index(value, start); if(index < 0) vm->ValueError("substring not found"); return VAR(index); @@ -636,6 +637,7 @@ void init_builtins(VM* _vm) { const Str& self = _CAST(Str&, args[0]); const Str& value = CAST(Str&, args[1]); int start = CAST(int, args[2]); + if (start < 0) vm->ValueError("argument 'start' can't be negative"); return VAR(self.index(value, start)); }); diff --git a/src/str.cpp b/src/str.cpp index 9965e6eb..b0308ffb 100644 --- a/src/str.cpp +++ b/src/str.cpp @@ -266,7 +266,6 @@ int utf8len(unsigned char c, bool suppress){ } int Str::index(const Str& sub, int start) const { - if (start < 0) start = 0; auto p = std::search(data + start, data + size, sub.data, sub.data + sub.size); if(p == data + size) return -1; return p - data; diff --git a/tests/04_str.py b/tests/04_str.py index ed2e6d5e..c9c78eac 100644 --- a/tests/04_str.py +++ b/tests/04_str.py @@ -250,7 +250,17 @@ try: except ValueError: pass +try: + a.index('1', -1) + exit(1) +except ValueError: + pass + assert a.find('1') == 0 assert a.find('1', 1) == -1 -assert a.find('1', -1000000) == 0 +try: + a.find('1', -1) + exit(1) +except ValueError: + pass