From a34d6bf039b945cfe4e65993373b28e153abbaa7 Mon Sep 17 00:00:00 2001 From: jakirkham Date: Wed, 16 Oct 2024 01:21:26 -0700 Subject: [PATCH] Simplify `_to_string` encoding of Python `str`s (#498) 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: https://github.com/rapidsai/kvikio/pull/498 --- python/kvikio/kvikio/_lib/remote_handle.pyx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/python/kvikio/kvikio/_lib/remote_handle.pyx b/python/kvikio/kvikio/_lib/remote_handle.pyx index 5e58da32f0..93c6ac398a 100644 --- a/python/kvikio/kvikio/_lib/remote_handle.pyx +++ b/python/kvikio/kvikio/_lib/remote_handle.pyx @@ -40,11 +40,13 @@ cdef extern from "" 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: