Skip to content

Commit d8c2136

Browse files
committed
tightening compatbility with python's behavior in edge cases
1 parent f64d7e3 commit d8c2136

File tree

2 files changed

+626
-8
lines changed

2 files changed

+626
-8
lines changed

pystring_impl.h

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -504,11 +504,18 @@ const std::string colon = ":";
504504
if ( len == 0 ) return false;
505505
if( len == 1 ) return ::islower( str[0] );
506506

507-
for ( i = 0; i < len; ++i )
508-
{
509-
if ( !::islower( str[i] ) ) return false;
507+
// python's islower is a lot more leniant than c++
508+
// this will match the python behavior so that something like
509+
// islower("hello123") is true
510+
511+
bool has_cased = false;
512+
for (i = 0; i < len; ++i) {
513+
if (::islower(str[i]))
514+
has_cased = true;
515+
else if (::isupper(str[i]))
516+
return false;
510517
}
511-
return true;
518+
return has_cased;
512519
}
513520

514521
//////////////////////////////////////////////////////////////////////////////////////////////
@@ -580,13 +587,22 @@ const std::string colon = ":";
580587
if ( len == 0 ) return false;
581588
if( len == 1 ) return ::isupper( str[0] );
582589

583-
for ( i = 0; i < len; ++i )
584-
{
585-
if ( !::isupper( str[i] ) ) return false;
590+
// python's isupper is a lot more leniant than c++
591+
// this will match the python behavior so that something like
592+
// isupper("HELLO123") is true
593+
594+
bool has_cased = false;
595+
for (std::string::size_type i = 0; i < str.size(); ++i) {
596+
if (::isupper(str[i]))
597+
has_cased = true;
598+
else if (::islower(str[i]))
599+
return false;
586600
}
587-
return true;
601+
return has_cased;
588602
}
589603

604+
605+
590606
//////////////////////////////////////////////////////////////////////////////////////////////
591607
///
592608
///
@@ -927,6 +943,16 @@ const std::string colon = ":";
927943
int nummatches = 0;
928944
int cursor = start;
929945

946+
// special handling for an empty substring
947+
// this will match python's behavior of
948+
// "bob".count("") == 4
949+
// "".count("") == 1
950+
if ( substr.empty() )
951+
{
952+
PYSTRING_ADJUST_INDICES(start, end, (int)str.size());
953+
return end - start + 1;
954+
}
955+
930956
while ( 1 )
931957
{
932958
cursor = find( str, substr, cursor, end );

0 commit comments

Comments
 (0)