How to do IO without encoding in Haskell?

I would like to input and to output octets, via IO (), as is, and without any encoding, respectively. The octets have type [Word8]. The stream shall be stdin, stdout, stderr, and files.

Background: I am going to implement a declarative compiler. This parser should be capable to interpret octet by octet, and render octet by octet.

import qualified Octetable as Oct
import qualified Data.Word as W
import qualified System.IO as SysIo

main :: IO ()
main = 
    do
        putOctets SysIo.stdout octets

putOctets :: SysIo.Handle -> [W.Word8] -> IO ()
putOctets hOut octs = 
    do
        SysIo.hPutBuf hOut ??? octs (length octs)

octets :: [W.Word8]
octets = Oct.toOctets "Hallo!"

How to do implement putOctets to do that?

...and getOctets?

getOctets :: SysIo.Handle -> IO [W.Word8]
getOctets hOut = ...

I will investigate further, and publish. Hopefully, someone will be faster. I already search for days.

Upvotes: 1

Views: 128

Answers (2)

Thanks to Alexis King I could complete the code quite easily.

The complete code is:

import qualified Octetable as Oct
import qualified Data.Word as W
import qualified System.IO as SysIo
import qualified Data.ByteString as BS

main :: IO ()
main = 
    do
        o1 <- getOctets SysIo.stdin
        putOctets SysIo.stdout o1
        putOctets SysIo.stdout o2

putOctets :: SysIo.Handle -> [W.Word8] -> IO ()
putOctets hOut octs = BS.hPut hOut (BS.pack octs)

o2 :: [W.Word8]
o2 = Oct.toOctets "Hallo!"

getOctets :: SysIo.Handle -> IO [W.Word8]
getOctets = (fmap BS.unpack) . BS.hGetContents

Calling like this (Windows 10, cmd):

echo 21435 | stack exec Test3-exe.exe

leads to output:

21435 
Hallo!

Upvotes: 1

Alexis King
Alexis King

Reputation: 43852

Use Data.ByteString from the bytestring package. You can implement getOctets using it quite easily:

import qualified Data.ByteString as BS
import Data.Word
import System.IO (Handle)

getOctets :: Handle -> IO [Word8]
getOctets = fmap BS.unpack . BS.hGetContents

You can implement your putOctets function in a similar way.

Upvotes: 4

Related Questions