How do I get a TextIO.instream from a POSIX file descriptor?

Viewed 80
1 Answers

This'll do the trick. It requires a "name" for the instream, which the basis library claims is used for error messages shown to the user. So I would recommend using the name or path of the underlying file, if there is one.

fun fdToInstream (name: string, fd: Posix.FileSys.file_desc) : TextIO.instream =
  let
    val (flags, _) = Posix.IO.getfl fd
    val isNonBlockMode = Posix.IO.O.anySet (Posix.IO.O.nonblock, flags)

    val reader: TextIO.StreamIO.reader =
      Posix.IO.mkTextReader
        { fd = fd
        , name = name
        , initBlkMode = not isNonBlockMode
        }

    val stream_ins: TextIO.StreamIO.instream =
      TextIO.StreamIO.mkInstream (reader, "")
  in
    TextIO.mkInstream stream_ins
  end
Related