Commit d40fd2e9 authored by Krzysztof Klinikowski's avatar Krzysztof Klinikowski

Lower, upper and swapcase impl for strings

parent 03103602
......@@ -377,14 +377,6 @@ Box* _strSlice(BoxedString* self, i64 start, i64 stop, i64 step) {
return boxString(std::string(chars.begin(), chars.end()));
}
Box* strLower(BoxedString* self) {
assert(self->cls == str_cls);
std::string lowered(self->s);
std::transform(lowered.begin(), lowered.end(), lowered.begin(), tolower);
return boxString(std::move(lowered));
}
Box* strJoin(BoxedString* self, Box* rhs) {
assert(self->cls == str_cls);
......@@ -477,6 +469,27 @@ Box* strRStrip(BoxedString* self, Box* chars) {
}
}
Box* strLower(BoxedString* self) {
assert(self->cls == str_cls);
return boxString(llvm::StringRef(self->s).lower());
}
Box* strUpper(BoxedString* self) {
assert(self->cls == str_cls);
return boxString(llvm::StringRef(self->s).upper());
}
Box* strSwapcase(BoxedString* self) {
std::string s(self->s);
for (auto& i : s) {
if ( std::islower(i) ) i = std::toupper(i);
else if ( std::isupper(i) ) i = std::tolower(i);
}
return boxString(s);
}
Box* strContains(BoxedString* self, Box* elt) {
assert(self->cls == str_cls);
if (elt->cls != str_cls)
......@@ -610,6 +623,8 @@ void setupStr() {
str_cls->giveAttr("__nonzero__", new BoxedFunction(boxRTFunction((void*)strNonzero, BOXED_BOOL, 1)));
str_cls->giveAttr("lower", new BoxedFunction(boxRTFunction((void*)strLower, STR, 1)));
str_cls->giveAttr("swapcase", new BoxedFunction(boxRTFunction((void*)strSwapcase, STR, 1)));
str_cls->giveAttr("upper", new BoxedFunction(boxRTFunction((void*)strUpper, STR, 1)));
str_cls->giveAttr("strip", new BoxedFunction(boxRTFunction((void*)strStrip, STR, 2, 1, false, false), { None }));
......
# Tests for lower, upper and swapcase
def test_lower_upper_swapcase(s):
print repr(s), repr(s.lower()), repr(s.upper()), repr(s.swapcase())
test_lower_upper_swapcase('HeLLo')
test_lower_upper_swapcase('hello')
test_lower_upper_swapcase('PoZdRaWiAm AgATE')
test_lower_upper_swapcase('KrZySIU jem zUPe')
test_lower_upper_swapcase('PchnAc W te LOdZ JeZa lUb OsM SkRzyN Fig\n')
test_lower_upper_swapcase('HeLLo cOmpUteRs')
test_lower_upper_swapcase('hEllO CoMPuTErS')
try:
var = 'hello'
var.lower(42)
print 'TypeError not raised'
except TypeError:
print 'TypeError raised'
try:
var = 'hello'
var.upper(42)
print 'TypeError not raised'
except TypeError:
print 'TypeError raised'
try:
var = 'hello'
var.swapcase(42)
print 'TypeError not raised'
except TypeError:
print 'TypeError raised'
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment