Add peekCString, withCString for converting NUL terminated C strings#254
Add peekCString, withCString for converting NUL terminated C strings#254andersk wants to merge 1 commit intohaskell:masterfrom
Conversation
Since NUL-terminated CString is much more common in foreign APIs than CStringLen, one should not have to manually build these functions out of `peekCStringLen`, `withCStringLen` (and perhaps get it wrong, like I did in jgm/cmark-hs#13). While here, document that `withCStringLen` is O(n) as well. Fixes haskell#32. Signed-off-by: Anders Kaseorg <andersk@mit.edu>
| -- | ||
| -- @since 1.2.5.0 | ||
| withCString :: Text -> (CString -> IO a) -> IO a | ||
| withCString t act = useAsCString (encodeUtf8 t) act |
There was a problem hiding this comment.
Since text-2 this does redundant copying.
| -- | ||
| -- @since 1.2.5.0 | ||
| withCString :: Text -> (CString -> IO a) -> IO a | ||
| withCString t act = useAsCString (encodeUtf8 t) act |
There was a problem hiding this comment.
Since text-2 this does redundant copying.
There was a problem hiding this comment.
It's redundant in both. encodeUtf8 creates a bytestring, which can be used unsafely, as nothing else refers to it.
In text-2.0 one could have unsafe withCString (or just withCStringLen, as there is no NUL at the end) variants though, which would just pass the Ptr to ByteArray contents.
There was a problem hiding this comment.
Scrap that. text ByteArray's are not (always) pinned, so sometimes copying is unavoidable.
There was a problem hiding this comment.
At least one round of memcpy is unavoidable unless the byte array in Text has that final null.
Since NUL-terminated
CStringis much more common in foreign APIs thanCStringLen, one should not have to manually build these functions out ofpeekCStringLen,withCStringLen(and perhaps get it wrong, like I did in jgm/cmark-hs#13).While here, document that
peekCStringLen,withCStringLenare O(n) as well.Fixes #32.