Posix.IO.Stream

This module provides an API for working with strams and pipes.

type alias Stream input output =
Stream input output

Stream pipes

stdIn : Stream Never Bytes
stdOut : Stream Bytes Never
utf8Decode : Stream Bytes String

Convert bytes to utf8 string

stdInAsString : Stream Never String
stdInAsString =
    stdIn
        |> pipeTo utf8Decode
utf8Encode : Stream String Bytes

Convert an utf8 string to bytes.

stdOutAsString : Stream String Never
stdOutAsString =
    utf8Encode
        |> pipeTo stdOut
line : Stream String String

Read stream line by line, splitting on the NL char.

gunzip : Stream Bytes Bytes

Uncompress stream using gzip

gzip : Stream Bytes Bytes

Compress stream using gzip

Stream pipelines

Compose Streams into pipelines.

pipeTo : Stream a output -> Stream input a -> Stream input output

Connect the output of one stream to the input of another.

readLineByLine : Stream Never String
readLineByLine =
    stdIn
        |> pipeTo gunzip
        |> pipeTo utf8Decode
        |> pipeTo line

Read

read : Stream x output -> IO String (Maybe output)

Read one value from a stream. Will block until one value can be returned.

Each consecutive call to read will return the next value (Just value) until the stream is exhausted (EOF) in which case it will result in Nothing.

Read until stream is exhausted

These functions are convenient when you want to read all data in a stream and process it somehow. Conceptually you can think of it as variations of List.foldl but for streams.

(value -> acc -> IO String acc)
-> acc
-> Stream Never value
-> IO String acc

Read a stream until it is exhausted (EOF) and reduce it.

collect : (value -> acc -> acc) -> acc -> Stream Never value -> IO String acc

Read a stream until it is exhausted (EOF) and collect all values using an accumulator function.

toList : Stream Never value -> IO String (List value)
toList stream =
    collect (::) [] stream
forEach : (value -> IO String ()) -> Stream Never value -> IO String ()

Read a stream until it is exhausted (EOF) and perform output on each value.

printStream : Stream Never String -> IO String ()
printStream stream =
    forEach IO.printLn stream

Write

write : input -> Stream input x -> IO String ()

Write data to a stream.

Read / write streams with typed errors

read_ : Stream x output -> IO ReadError output

Same as read but with a typed error.

= EOF String
| CouldNotRead
{ code : String
, message : String
}

Stream read errors

write_ : input -> Stream input x -> IO WriteError ()

Same as write but with a typed error.

= BrokenPipe String
| CouldNotWrite
{ code : String
, message : String
}

Stream write errors

Run pipeline

run : Stream Never Never -> IO String ()

Run a pipeline where the input and output are connected.

passthrough : IO String ()
passthrough =
    stdIn
        |> pipeTo stdOut
        |> run