% This LaTeX document was generated using the LaTeX backend of PlDoc,
% The SWI-Prolog documentation system



\section{library(prolog_stream): A stream with Prolog callbacks}

\label{sec:prologstream}

This library defines a Prolog stream that realises its low-level I/O
with callbacks to Prolog. The library was developed to bind normal
Prolog I/O to Pengines I/O. This type of I/O redirection is probably the
primary use case.\vspace{0.7cm}

\begin{description}
    \predicate{open_prolog_stream}{4}{+Module, +Mode, -Stream, +Options}
Create a new stream that implements its I/O by calling
predicates in \arg{Module}. The called predicates are:

\begin{description}
    \infixtermitem{\Smodule}{\arg{Module}}{\term{stream_write}{+Stream, +String}}
Called for a \verb$Mode = write$ stream if data is available.
\arg{String} contains the (textual) data that is written
to \arg{Stream}. The callback is called if the buffer of
\arg{Stream} overflows, the user calls \verb$flush_output(Stream)$
or \arg{Stream} is closed and there is buffered data.
    \infixtermitem{\Smodule}{\arg{Module}}{\term{stream_read}{+Stream, -Term}}
Called for a \verb$Mode == read$ stream to get new data. On
success the stream extracts text from the provided \arg{Term}.
\arg{Term} is typically a string, atom, code or character list.
If term is not one of the above, it is handed to \predref{writeq}{1}.
To signal end-of-file, unify stream with an empty text,
e.g., \verb$stream_read(Stream, "")$.
    \infixtermitem{\Smodule}{\arg{Module}}{\term{stream_close}{+Stream}}
Called when the stream is closed. This predicate must
succeed. The callback can be used to cleanup associated
resources.
\end{description}

The current implementation only deals with text streams. The
stream uses the \verb$wchar_t$ encoding. The buffer size must be a
multiple of \verb$wchar_t$, i.e., a multiple of four for portability.
The \textit{newline} mode of the stream is \const{posix} on all platforms,
disabling the translation \verb$"\n" --> "\r\n"$.

\begin{arguments}
\arg{Options} & is currently ignored. \\
\end{arguments}

\begin{tags}
    \tag{bug}
Futher versions might require additional callbacks. As we
demand all callbacks to be defined, existing code needs
to implement the new callbacks.
\end{tags}
\end{description}

