Skip to content

Commit 0425bec

Browse files
committed
Support start, end in str.startswith, str.endswith
1 parent fb6faaf commit 0425bec

File tree

1 file changed

+38
-8
lines changed

1 file changed

+38
-8
lines changed

src/obj_str.c

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -825,17 +825,47 @@ KRK_Method(str,index) {
825825
}
826826

827827
KRK_Method(str,startswith) {
828-
METHOD_TAKES_EXACTLY(1); /* I know the Python versions of these take optional start, end... */
829-
CHECK_ARG(1,str,KrkString*,prefix);
830-
return BOOLEAN_VAL(substringMatch(self->chars,self->length,prefix->chars,prefix->length));
828+
KrkString * substr;
829+
int start = 0;
830+
int end = self->codesLength;
831+
if (!krk_parseArgs(".O!|ii",(const char*[]){"prefix","start","end"}, KRK_BASE_CLASS(str), &substr, &start, &end)) {
832+
return NONE_VAL();
833+
}
834+
835+
WRAP_INDEX(start);
836+
WRAP_INDEX(end);
837+
838+
krk_unicodeString(self);
839+
krk_unicodeString(substr);
840+
841+
if (end < start || (size_t)(end - start) < substr->codesLength) return BOOLEAN_VAL(0);
842+
843+
for (size_t i = 0; i < substr->codesLength; ++i) {
844+
if (KRK_STRING_FAST(self, start + i) != KRK_STRING_FAST(substr,i)) return BOOLEAN_VAL(0);
845+
}
846+
return BOOLEAN_VAL(1);
831847
}
832848

833849
KRK_Method(str,endswith) {
834-
METHOD_TAKES_EXACTLY(1); /* I know the Python versions of these take optional start, end... */
835-
CHECK_ARG(1,str,KrkString*,suffix);
836-
if (suffix->length > self->length) return BOOLEAN_VAL(0);
837-
return BOOLEAN_VAL(substringMatch(self->chars + (self->length - suffix->length),
838-
suffix->length, suffix->chars, suffix->length));
850+
KrkString * substr;
851+
int start = 0;
852+
int end = self->codesLength;
853+
if (!krk_parseArgs(".O!|ii",(const char*[]){"suffix","start","end"}, KRK_BASE_CLASS(str), &substr, &start, &end)) {
854+
return NONE_VAL();
855+
}
856+
857+
WRAP_INDEX(start);
858+
WRAP_INDEX(end);
859+
860+
krk_unicodeString(self);
861+
krk_unicodeString(substr);
862+
863+
if (end < start || (size_t)(end - start) < substr->codesLength) return BOOLEAN_VAL(0);
864+
865+
for (size_t i = 0; i < substr->codesLength; ++i) {
866+
if (KRK_STRING_FAST(self, (end - i - 1)) != KRK_STRING_FAST(substr,(substr->codesLength - i - 1))) return BOOLEAN_VAL(0);
867+
}
868+
return BOOLEAN_VAL(1);
839869
}
840870

841871
/**

0 commit comments

Comments
 (0)