module Data.Repa.Array.Auto.IO
(
hGetArray, hGetArrayPre
, hPutArray
, getArrayFromXSV, hGetArrayFromXSV
, putArrayAsXSV, hPutArrayAsXSV)
where
import Data.Repa.Array.Auto.Base
import Data.Repa.Array.Generic.Convert
import System.IO
import Data.Word
import Data.Char
import qualified Data.Repa.Array.Material.Auto as A
import qualified Data.Repa.Array.Material.Foreign as A
import qualified Data.Repa.Array.Material.Nested as A
import qualified Data.Repa.Array.Meta as A
import qualified Data.Repa.Array.Generic as A
import qualified Foreign.Ptr as F
import qualified Foreign.ForeignPtr as F
import qualified Foreign.Marshal.Alloc as F
import qualified Foreign.Marshal.Utils as F
hGetArray :: Handle -> Int -> IO (Array Word8)
hGetArray h len
= do buf :: F.Ptr Word8 <- F.mallocBytes len
bytesRead <- hGetBuf h buf len
fptr <- F.newForeignPtr F.finalizerFree buf
return $! convert $! A.fromForeignPtr bytesRead fptr
hGetArrayPre :: Handle -> Int -> Array Word8 -> IO (Array Word8)
hGetArrayPre h len arr
| (offset, lenPre, fptrPre :: F.ForeignPtr Word8)
<- A.toForeignPtr $ convert arr
= F.withForeignPtr fptrPre
$ \ptrPre' -> do
let ptrPre = F.plusPtr ptrPre' offset
ptrBuf :: F.Ptr Word8 <- F.mallocBytes (lenPre + len)
F.copyBytes ptrBuf ptrPre lenPre
lenRead <- hGetBuf h (F.plusPtr ptrBuf lenPre) len
let bytesTotal = lenPre + lenRead
fptrBuf <- F.newForeignPtr F.finalizerFree ptrBuf
return $ convert $! A.fromForeignPtr bytesTotal fptrBuf
hPutArray :: Handle -> Array Word8 -> IO ()
hPutArray h arr
| (offset, lenPre, fptrPre :: F.ForeignPtr Word8)
<- A.toForeignPtr $ convert arr
= F.withForeignPtr fptrPre
$ \ptr' -> do
let ptr = F.plusPtr ptr' offset
hPutBuf h ptr lenPre
getArrayFromXSV
:: Char
-> FilePath
-> IO (Array (Array (Array Char)))
getArrayFromXSV !cSep !filePath
= do h <- openFile filePath ReadMode
arr <- hGetArrayFromXSV cSep h
hClose h
return arr
hGetArrayFromXSV
:: Char
-> Handle
-> IO (Array (Array (Array Char)))
hGetArrayFromXSV !cSep !hIn
= do
start <- hTell hIn
hSeek hIn SeekFromEnd 0
end <- hTell hIn
let !len = end start
hSeek hIn AbsoluteSeek start
!arr8 <- hGetArray hIn (fromIntegral len)
let !nl = fromIntegral $ ord '\n'
let !nc = fromIntegral $ ord cSep
let !arrChar
= A.mapElems
(A.mapElems (A.computeS A.F . A.map (chr . fromIntegral)))
(A.diceSep nc nl arr8)
return $ convert arrChar
putArrayAsXSV
:: Char
-> FilePath
-> Array (Array (Array Char))
-> IO ()
putArrayAsXSV !cSep !filePath !arrChar
= do h <- openFile filePath WriteMode
hPutArrayAsXSV cSep h arrChar
hClose h
hPutArrayAsXSV
:: Char
-> Handle
-> Array (Array (Array Char))
-> IO ()
hPutArrayAsXSV !cSep !hOut !arrChar
= do
let !arrC = A.fromList A.U [cSep]
let !arrNL = A.fromList A.U ['\n']
let !arrOut
= A.mapS A.A (fromIntegral . ord)
$ A.concat A.U
$ A.mapS A.B (\arrFields
-> A.concat A.U $ A.fromList A.B
[ A.intercalate A.U arrC arrFields, arrNL])
$ arrChar
hPutArray hOut arrOut