Skip to content

Lower method for strings - #763

Open
sbundaz wants to merge 2 commits into
spylang:mainfrom
sbundaz:add-str-lower
Open

sbundaz wants to merge 2 commits into
spylang:mainfrom
sbundaz:add-str-lower

Conversation

@sbundaz

@sbundaz sbundaz commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

This PR implements the lower method for strings

@sbundaz sbundaz changed the title implement the lower method for strings Lower method for strings Nov 9, 2026
@paugier

paugier commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

I think it would be cleaner to use a blue function (called with _update_case[True](self))

@blue.generic
def _update_case(to_upper):
    case_offset: u8 = ord(b"a") - ord(b"A")
    first: u8
    last: u8
    if to_upper:
        first = ord(b"a")
        last = ord(b"z")

        @force_inline
        def oper(x: u8, y: u8) -> u8:
            return x - y

    else:
        first = ord(b"A")
        last = ord(b"Z")

        @force_inline
        def oper(x: u8, y: u8) -> u8:
            return x + y

    def impl(input: str) -> str:
        # XXX: this works only for ASCII strings but it's good enough for now
        ll = StrObject.from_str(input)
        llnew = StrObject.alloc(ll.length)
        for i in range(ll.length):
            ch = ll.utf8[i]
            if ch >= first and ch <= last:
                llnew.utf8[i] = oper(ch, case_offset)
            else:
                llnew.utf8[i] = ch
        return StrObject.to_sealed_str(llnew)

    return impl

like that, the redshifted code has no runtime check.

But it is well possible that the C compiler can do the equivalent of this optimization so that this smarter solution won't actually be faster... It might depends on the optimization flag though.

@antocuni

antocuni commented Nov 9, 2026

Copy link
Copy Markdown
Member

NOTE: I haven't reviewed the PR deeply and I'm just answering to this particular comment

But it is well possible that the C compiler can do the equivalent of this optimization so that this smarter solution won't actually be faster... It might depends on the optimization flag though.

I think that this blue code is very clever... but maybe for this case a bit too clever?
For a case like this, I would just write to functions (one for upper, one for lower), even if they contain a small amount of duplicated code. The end result is probably MUCH easier to read

@sbundaz95

sbundaz95 commented Nov 13, 2026 •

Copy link
Copy Markdown

Now there are two methods upper and lower, as we do here @antocuni

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants