Unsafe aspects of ByteString
Donald Bruce Stewart
dons at cse.unsw.edu.au
Sun Jan 28 18:42:59 EST 2007
iavor.diatchki:
> Hello,
> The "packCString" function (and other similar functions) in the
> ByteString library break referential transperancy, which is one of the
> big selling points of Haskell (and its libraries). Here is an
> example:
>
> main = do x <- newCString "Hello"
> let s = packCString x
> h1 = B.head s
> print s
> -- print h1
> poke x (toEnum 97)
> print s
> let h2 = B.head s
> print h1
> print h2
> Output:
> "Hello"
> "aello"
> 97
> 97
>
> This is already confusing because the "pure" value 's' has magically
Right, in order to support zero-copy string between C and Haskell, for
efficiency, the default packCString just wraps up the Ptr CChar to look
like a ByteString. It doesn't copy it. If you the mutate the C String,
well, as you see above.
Here you should be using:
copyCString :: CString -> IO ByteString
The functions should document this behaviour better. Of course, you're
paying with poke and C strings so you should be careful anyway. I'll
correct the documentation to explain all this.
Thanks for noticing!
-- Don
More information about the Libraries
mailing list