Hello, all. I decide to write parallel ray tracer on haskell with repa. Now, to save repa array to file I use dirty trick casting repa array ptr to bytestring with fromForeignPtr and then writing it to file with hPut. It looks something like that:

import qualified Data.Array.Repa as R
import qualified Data.Array.Repa.Repr.ForeignPtr as RF

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Internal as BI

type Image = Array F DIM2 Pixel

writeImage :: FilePath -> Image -> IO ()
writeImage path img = bracket (openFile path WriteMode) (hClose) $ \hdl -> B.hPut hdl header >> B.hPut hdl body
  where Z :. h :. w = R.extent img
        header = BC.pack $ "P6\n" ++ show w ++ ' ':show h ++ "\n255\n"
        body = BI.fromForeignPtr(castForeignPtr $ RF.toForeignPtr img) 0 (w*h*3)

My question is: how to write repa array to file safely and fast?