Coercing a `ByteArray#` into a `MutableByteArray#`

Hello all, I have a use-case where I want to convert `ByteArray#` to `MutableByteArray#` without the copy overhead. Is the underlying memory structure of `ByteArray#` and `MutableByteArray#` the same? If I can guarantee that I won't mutate my `MutableByteArray#`, can I use `unsafeCoerce#` on `ByteArray#` and treat it as `MutableByteArray#`? Best, Adithya

Hi Adithya,
The representations are the same. You can do this. I do this somewhat
often. Just avoid mutating in places where it could result in funky stuffs.
This is usually pretty easy to spot.
Cheers,
chessai
On Mon, Jul 24, 2023, 12:59 Adithya Kumar
Hello all,
I have a use-case where I want to convert `ByteArray#` to `MutableByteArray#` without the copy overhead.
Is the underlying memory structure of `ByteArray#` and `MutableByteArray#` the same?
If I can guarantee that I won't mutate my `MutableByteArray#`, can I use `unsafeCoerce#` on `ByteArray#` and treat it as `MutableByteArray#`?
Best, Adithya _______________________________________________ ghc-devs mailing list ghc-devs@haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/ghc-devs

Indeed, this is what the `primitive` package provides to thaw a
`ByteArray#` without copying:
https://hackage.haskell.org/package/primitive-0.8.0.0/docs/src/Data.Primitiv...
On Mon, 24 Jul 2023, 20:17 chessai,
Hi Adithya,
The representations are the same. You can do this. I do this somewhat often. Just avoid mutating in places where it could result in funky stuffs. This is usually pretty easy to spot.
Cheers, chessai
On Mon, Jul 24, 2023, 12:59 Adithya Kumar
wrote: Hello all,
I have a use-case where I want to convert `ByteArray#` to `MutableByteArray#` without the copy overhead.
Is the underlying memory structure of `ByteArray#` and `MutableByteArray#` the same?
If I can guarantee that I won't mutate my `MutableByteArray#`, can I use `unsafeCoerce#` on `ByteArray#` and treat it as `MutableByteArray#`?
Best, Adithya _______________________________________________ ghc-devs mailing list ghc-devs@haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/ghc-devs
_______________________________________________ ghc-devs mailing list ghc-devs@haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/ghc-devs

Adithya Kumar
Hello all,
I have a use-case where I want to convert `ByteArray#` to `MutableByteArray#` without the copy overhead.
Is the underlying memory structure of `ByteArray#` and `MutableByteArray#` the same?
If I can guarantee that I won't mutate my `MutableByteArray#`, can I use `unsafeCoerce#` on `ByteArray#` and treat it as `MutableByteArray#`?
Note that a future release of GHC (IIRC 9.10) will have a (no-op) operation for precisely this purpose. See [1]. Cheers, - Ben [1] https://gitlab.haskell.org/ghc/ghc/-/issues/22710
participants (4)
-
Adithya Kumar
-
Ben Gamari
-
chessai
-
Sam Derbyshire