a ValueError is raised when argument 'start' is a negative integer

This commit is contained in:
albertexye 2024-04-01 23:54:34 -04:00
parent 8059ab8c96
commit 9f8d740ee2
3 changed files with 13 additions and 2 deletions

View File

@ -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));
});

View File

@ -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;

View File

@ -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