RSS Feed

Lisp Project of the Day

with-output-to-stream

You can support this project by donating at:

Donate using PatreonDonate using Liberapay

Or see the list of project sponsors.

with-output-to-streammacroiotrivial

Documentation🥺
Docstrings🥺
Tests 🥺
Examples🥺
RepositoryActivity🥺
CI 🥺

This is a "trivial" library by @HexstreamSoft. It simplifies the writing of the functions which would like to accept a stream argument as format function does.

CL's format function accepts as the first parameter a nil, t or a stream object. In first case it returns a string and in second - outputs to *standard-output*.

When you are writing a custom function with similar semantics, you have to handle all these cases by hand. Here is where with-output-to-stream helps you:

POFTHEDAY> (defun log-info (obj &key (stream t))
             (with-output-to-stream:with-output-to-stream (s stream)
               (write-string "INFO " s)
               (write obj :stream s)
               (terpri s)))

;; Here is we return result as a string:
POFTHEDAY> (log-info 100500 :stream nil)
"INFO 100500
"

;; This will output to *standard-output*:
POFTHEDAY> (log-info 100500 :stream t)
INFO 100500
NIL

;; But you can pass any stream as the argument:
POFTHEDAY> (log-info 100500 :stream *error-output*)
INFO 100500
NIL

POFTHEDAY> (with-output-to-string (s)
             (log-info 100500 :stream s)
             (log-info 42 :stream s))
"INFO 100500
INFO 42
"

That is it for today.


Brought to you by 40Ants under Creative Commons License