Skip to content

Commit

Permalink
Simplify _to_string encoding of Python strs (#498)
Browse files Browse the repository at this point in the history
Makes a few improvements to the Cython logic of `_to_string`:

* Types the input as `str`: This allows Cython to use CPython API relevant for the specific type (it will check type on entry)
* Do `is not None` check first: This way when Cython generates additional `None` checks inside the branch, the compiler can optimize them out
* Use `str`'s `encode` method: Cython makes a direct CPython call to generate `bytes` and then extracts the pointer and size for C++ to copy

Authors:
  - https://github.com/jakirkham

Approvers:
  - Lawrence Mitchell (https://github.com/wence-)

URL: #498
  • Loading branch information
jakirkham authored Oct 16, 2024
1 parent 22668fa commit a34d6bf
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions python/kvikio/kvikio/_lib/remote_handle.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,13 @@ cdef extern from "<kvikio/remote_handle.hpp>" nogil:
size_t file_offset
) except +

cdef string _to_string(str_or_none):

cdef string _to_string(str s):
"""Convert Python object to a C++ string (if None, return the empty string)"""
if str_or_none is None:
if s is not None:
return s.encode()
else:
return string()
return str.encode(str(str_or_none))


cdef class RemoteFile:
Expand Down

0 comments on commit a34d6bf

Please sign in to comment.