module Data.Repa.Array.Auto.XSV
( getArrayFromXSV, hGetArrayFromXSV
, putArrayAsXSV, hPutArrayAsXSV)
where
import Data.Repa.Array.Auto.IO
import Data.Repa.Array.Auto.Base
import Data.Repa.Array.Generic.Convert
import Data.Char
import qualified Data.Repa.Array.Material.Auto 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 System.IO as S
import qualified System.FileLock as S
getArrayFromXSV
:: Char
-> FilePath
-> IO (Array (Array (Array Char)))
getArrayFromXSV !cSep !path
= S.withFileLock path S.Shared
$ \_lock -> do
h <- S.openFile path S.ReadMode
arr <- hGetArrayFromXSV cSep h
S.hClose h
return arr
hGetArrayFromXSV
:: Char
-> S.Handle
-> IO (Array (Array (Array Char)))
hGetArrayFromXSV !cSep !hIn
= do
start <- S.hTell hIn
S.hSeek hIn S.SeekFromEnd 0
end <- S.hTell hIn
let !len = end start
S.hSeek hIn S.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 !path !arrChar
= S.withFileLock path S.Exclusive
$ \_lock -> do
h <- S.openFile path S.WriteMode
hPutArrayAsXSV cSep h arrChar
S.hClose h
hPutArrayAsXSV
:: Char
-> S.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