13.1.10 More Port Constructors, Procedures, and Events (original) (raw)

13.1.10 More Port Constructors, Procedures, and Events🔗

The bindings documented in this section are provided by the racket/port and racket libraries, but not racket/base.

13.1.10.1 Port String and List Conversions🔗

Returns a list whose elements are produced by calling ron in until it produces eof.

Examples:

Reads all characters from in and returns them as a string. The input port is closed unless close? is #f.

Example:

Changed in version 6.8.0.2 of package base: Added the #:close? argument.

Reads all bytes from in and returns them as a byte string. The input port is closed unless close? is #f.

Example:

Changed in version 6.8.0.2 of package base: Added the #:close? argument.

Read all characters from in, breaking them into lines. Theline-mode argument is the same as the second argument toread-line, but the default is 'any instead of'linefeed. The input port is closed unless close? is #f.

Example:

'("line 1" "line 2" " line 3" "line 4")

Changed in version 6.8.0.2 of package base: Added the #:close? argument.

Like port->lines, but reading bytes and collecting them into lines like read-bytes-line. The input port is closed unless close? is #f.

Example:

'(#"line 1" #"line 2" #" line 3" #"line 4")

Changed in version 6.8.0.2 of package base: Added the #:close? argument.

Uses display on each element of lst to out, addingseparator after each element.

Calls proc with an output port that accumulates all output into a string, and returns the string.

The port passed to proc is like the one created byopen-output-string, except that it is wrapped viadup-output-port, so that proc cannot access the port’s content using get-output-string. If control jumps back into proc, the port continues to accumulate new data, andcall-with-output-string returns both the old data and newly accumulated data.

Like call-with-output-string, but returns the accumulated result in a byte string instead of a string. Furthermore, the port’s content is emptied when call-with-output-bytes returns, so that if control jumps back into proc and returns a second time, only the newly accumulated bytes are returned.

Equivalent to

Equivalent to

Equivalent to

Equivalent to

13.1.10.2 Creating Ports🔗

Takes any number of input ports and returns an input port. Reading from the input port draws bytes (and special non-byte values) from the given input ports in order. If close-at-eof? is true, then each port is closed when an end-of-file is encountered from the port, or when the result input port is closed. Otherwise, data not read from the returned input port remains available for reading in its original input port.

The name argument determines the name as reported byobject-name for the returned input port.

See also merge-input, which interleaves data from multiple input ports as it becomes available.

Changed in version 6.90.0.19 of package base: Added the name argument.

Similar to make-input-port, but if the given read-inreturns an event, the event’s value must be 0. The resulting port’s peek operation is implemented automatically (in terms ofread-in) in a way that can handle special non-byte values. The progress-event and commit operations are also implemented automatically. The resulting port is thread-safe, but not kill-safe (i.e., if a thread is terminated or suspended while using the port, the port may become damaged).

The read-in, close, get-location,count-lines!, init-position, andbuffer-mode procedures are the same as formake-input-port.

The fast-peek argument can be either #f or a procedure of three arguments: a byte string to receive a peek, a skip count, and a procedure of two arguments. The fast-peekprocedure can either implement the requested peek, or it can dispatch to its third argument to implement the peek. The fast-peek is not used when a peek request has an associated progress event.

The buffering? argument determines whether read-incan be called to read more characters than are immediately demanded by the user of the new port. If buffer-mode is not #f, then buffering? determines the initial buffer mode, andbuffering? is enabled after a buffering change only if the new mode is 'block.

If on-consumed is not #f, it is called when data is read (or committed) from the port, as opposed to merely peeked. The argument toon-consumed is the result value of the port’s reading procedure, so it can be an integer or any result fromread-in.

Returns a port whose content is drawn from in, but where an end-of-file is reported after limit bytes (and non-byte special values) have been read. If close-orig? is true, then the original port is closed if the returned port is closed.

Bytes are consumed from in only when they are consumed from the returned port. In particular, peeking into the returned port peeks into the original port.

If in is used directly while the resulting port is also used, then the limit bytes provided by the port need not be contiguous parts of the original port’s stream.

Returns two ports: an input port and an output port. The ports behave like those returned by make-pipe, except that the ports support non-byte values written with procedures such aswrite-special and read with procedures such asget-byte-or-special.

The limit argument determines the maximum capacity of the pipe in bytes, but this limit is disabled if special values are written to the pipe before limit is reached. The limit is re-enabled after the special value is read from the pipe.

The optional in-name and out-name arguments determine the names of the result ports.

Accepts two output ports and returns a new output port combining the original ports. When written to, the combined port first writes as many bytes as possible to a-out, and then tries to write the same number of bytes to b-out. If that doesn’t succeed, what is left over is buffered and no further writes can go through until the ports are evened out. The port is ready (for the purposes of synchronization) when each port reports being ready. However, the first port may stop being ready while waiting on the second port to sync, so it cannot be guaranteed that both ports are ready at once. Closing the combined port is done after writing all remaining bytes to b-out.

Added in version 7.7.0.10 of package base.

Accepts two input ports and returns a new input port. The new port merges the data from two original ports, so data can be read from the new port whenever it is available from either of the two original ports. The data from the original ports are interleaved. When an end-of-file has been read from an original port, it no longer contributes characters to the new port. After an end-of-file has been read from both original ports, the new port returns end-of-file. Closing the merged port does not close the original ports.

The optional buffer-limit argument limits the number of bytes to be buffered from a-in and b-in, so that the merge process does not advance arbitrarily beyond the rate of consumption of the merged data. A #f value disables the limit. As formake-pipe-with-specials, buffer-limit does not apply when a special value is produced by one of the input ports before the limit is reached.

See also input-port-append, which concatenates input streams instead of interleaving them.

Creates and returns an output port that discards all output sent to it (without blocking). The name argument is used as the port’s name. If the special-ok? argument is true, then the resulting port supports write-special, otherwise it does not.

Returns an input port whose content is determined by peeking intoin. In other words, the resulting port contains an internal skip count, and each read of the port peeks into in with the internal skip count, and then increments the skip count according to the amount of data successfully peeked.

The optional name argument is the name of the resulting port. The skip argument is the port initial skip count, and it defaults to 0.

The resulting port’s initial position (as reported by file-position) is (- init-position 1), no matter the position of in.

The resulting port supports buffering, and a 'block buffer mode allows the port to peek further into in than requested. The resulting port’s initial buffer mode is'block, unless in supports buffer mode and its mode is initially 'none (i.e., the initial buffer mode is taken from in when it supports buffering). If in supports buffering, adjusting the resulting port’s buffer mode viafile-stream-buffer-mode adjusts in’s buffer mode.

For example, when you read from a peeking port, you see the same answers as when you read from the original port:

Examples:

Beware that the read from the original port is invisible to the peeking port, which keeps its own separate internal counter, and thus interleaving reads on the two ports can produce confusing results. Continuing the example before, if we read three more characters from the peeking port, we end up skipping over the 456 in the port (but only because we disabled buffering above):

Example:

If we had left the buffer mode of a-peeking-port alone, that last read-string would have likely produced "456" as a result of buffering bytes from an-original-port earlier.

Changed in version 6.1.0.3 of package base: Enabled buffering and buffer-mode adjustments via file-stream-buffer-mode, and set the port’s initial buffer mode to that ofin.

Produces an input port that draws bytes from in, but converts the byte stream using (bytes-open-converter encoding-str "UTF-8"). In addition, if convert-newlines? is true, then decoded sequences that correspond to UTF-8 encodings of "\r\n","\r\u0085", "\r", "\u0085", and "\u2028"are all converted to the UTF-8 encoding of "\n".

If error-bytes is provided and not #f, then the given byte sequence is used in place of bytes from in that trigger conversion errors. Otherwise, if a conversion is encountered,enc-error is called, which must raise an exception.

If close? is true, then closing the result input port also closes in. The name argument is used as the name of the result input port.

In non-buffered mode, the resulting input port attempts to draw bytes from in only as needed to satisfy requests. Toward that end, the input port assumes that at least n bytes must be read to satisfy a request for n bytes. (This is true even if the port has already drawn some bytes, as long as those bytes form an incomplete encoding sequence.)

Produces an output port that directs bytes to out, but converts its byte stream using (bytes-open-converter "UTF-8" encoding-str). In addition, if newline-bytes is not#f, then bytes written to the port that are the UTF-8 encoding of "\n" are first converted tonewline-bytes (before applying the convert from UTF-8 toencoding-str).

If error-bytes is provided and not #f, then the given byte sequence is used in place of bytes that have been sent to the output port and that trigger conversion errors. Otherwise, enc-error is called, which must raise an exception.

If close? is true, then closing the result output port also closes out. The name argument is used as the name of the result output port.

The resulting port supports buffering, and the initial buffer mode is(or (file-stream-buffer-mode out) 'block). In 'blockmode, the port’s buffer is flushed only when it is full or a flush is requested explicitly. In 'line mode, the buffer is flushed whenever a newline or carriage-return byte is written to the port. In'none mode, the port’s buffer is flushed after every write. Implicit flushes for 'line or 'none leave bytes in the buffer when they are part of an incomplete encoding sequence.

The resulting output port does not support atomic writes. An explicit flush or special-write to the output port can hang if the most recently written bytes form an incomplete encoding sequence.

When the port is buffered, a flush callback is registered with the current plumber to flush the buffer.

Returns an input port that draws directly from in. Closing the resulting port closes in only if close? is#t.

The new port is initialized with the port read handler ofin, but setting the handler on the result port does not affect reading directly from in.

Returns an output port that propagates data directly toout. Closing the resulting port closes out only ifclose? is #t.

The new port is initialized with the port display handler andport write handler of out, but setting the handlers on the result port does not affect writing directly to out.

Produces an input port that is equivalent to in except in how it reports location information (and possibly its name). The resulting port’s content starts with the remaining content of in, and it starts at the given line, column, and position. A #f for the line or column means that the line and column will always be reported as #f.

The line and column values are used only if line counting is enabled for in and for the resulting port, typically through port-count-lines!. The columnvalue determines the column for the first line (i.e., the one numberedline), and later lines start at column 0. The givenposition is used even if line counting is not enabled.

When line counting is on for the resulting port, reading fromin instead of the resulting port increments location reports from the resulting port. Otherwise, the resulting port’s position does not increment when data is read from in.

If close? is true, then closing the resulting port also closes in. If close? is #f, then closing the resulting port does not close in.

The name argument is used as the name for the resulting port; the default value keeps the same name as in.

Like relocate-input-port, but for output ports.

Like relocate-input-port, except that arbitrary position information can be produced (when line counting is enabled) viaget-location, which is used as for make-input-port. Ifget-location is #f, then the port counts lines in the usual way starting from init-pos, independent of locations reported by in.

If count-lines! is supplied, it is called when line counting is enabled for the resulting port. The default is void.

Like transplant-input-port, but for output ports.

Creates a port that draws from in, but each result from the port’s read and peek procedures (in the sense of make-input-port) is filtered by read-wrap andpeek-wrap. The filtering procedures each receive both the arguments and results of the read and peek procedures on infor each call.

If close? is true, then closing the resulting port also closes in.

Produces an input port that is equivalent to in, except that when in produces a procedure to access a special value,proc is applied to the procedure to allow the special value to be replaced with an alternative. The proc is called with the special-value procedure and the byte string that was given to the port’s read or peek function (see make-input-port), and the result is used as the read or peek function’s result. Theproc can modify the byte string to substitute a byte for the special value, but the byte string is guaranteed only to hold at least one byte.

If close? is true, then closing the resulting input port also closes in.

13.1.10.3 Port Events🔗

Returns a synchronizable event that is ready whenin produces an eof. If in produces a mid-stream eof, the eof is consumed by the event only if the event is chosen in a synchronization.

If attempting to read from in raises an exception during a synchronization attempt, then the exception may be reported during the synchronization attempt, but it will silently discarded if some another event in the same synchronization is selected or if some other event raises an exception first.

Changed in version 7.5.0.3 of package base: Changed handling of read errors so they are propagated to a synchronization attempt, instead of treated as unhandled errors in a background thread.

Returns a synchronizable event that is ready when kbytes can be read from in, or when an end-of-file is encountered in in. If k is 0, then the event is ready immediately with "". For non-zero k, if no bytes are available before an end-of-file, the event’s result iseof. Otherwise, the event’s result is a byte string of up tok bytes, which contains as many bytes as are available (up tok) before an available end-of-file. (The result is a byte string of less than k bytes only when an end-of-file is encountered.)

Bytes are read from the port if and only if the event is chosen in a synchronization, and the returned bytes always represent contiguous bytes in the port’s stream.

The event can be synchronized multiple times—even concurrently—and each synchronization corresponds to a distinct read request.

The in must support progress events, and it must not produce a special non-byte value during the read attempt.

Exceptions attempting to read from in are handled in the same way as by eof-evt.

Like read-bytes-evt, except that the read bytes are placed into bstr, and the number of bytes to read corresponds to(bytes-length bstr). The event’s result is eithereof or the number of read bytes.

The bstr may be mutated any time after the first synchronization attempt on the event and until either the event is selected, a non-#f progress-evt is ready, or the current custodian (at the time of synchronization) is shut down. Note that there is no time bound otherwise on when bstrmight be mutated if the event is not selected by a synchronzation; nevertheless, multiple synchronization attempts can use the same result from read-bytes!-evt as long as there is no intervening read on in until one of the synchronization attempts selects the event.

Exceptions attempting to read from in are handled in the same way as by eof-evt.

Like read-bytes!-evt, except that the event reads only as many bytes as are immediately available, after at least one byte or one eof becomes available.

Like read-bytes-evt, but for character strings instead of byte strings.

Like read-bytes!-evt, but for a character string instead of a byte string.

(read-line-evt in [mode]) → evt?
in : input-port?
mode : (or/c 'linefeed 'return 'return-linefeed 'any 'any-one) = 'linefeed

Returns a synchronizable event that is ready when a line of characters or end-of-file can be read from in. The meaning of mode is the same as for read-line. The event result is the read line of characters (not including the line separator).

A line is read from the port if and only if the event is chosen in a synchronization, and the returned line always represents contiguous bytes in the port’s stream.

Exceptions attempting to read from in are handled in the same way as by eof-evt.

(read-bytes-line-evt in [mode]) → evt?
in : input-port?
mode : (or/c 'linefeed 'return 'return-linefeed 'any 'any-one) = 'linefeed

Like read-line-evt, but returns a byte string instead of a string.

Like the read-bytes-evt, etc., functions, but for peeking. Theskip argument indicates the number of bytes to skip, andprogress-evt indicates an event that effectively cancels the peek (so that the event never becomes ready). The progress-evtargument can be #f, in which case the event is never canceled.

Returns a synchronizable event that is ready whenpattern matches the stream of bytes/characters fromin; see also regexp-match. The event’s value is the result of the match, in the same form as the result ofregexp-match.

If pattern does not require a start-of-stream match, then bytes skipped to complete the match are read and discarded when the event is chosen in a synchronization.

Bytes are read from the port if and only if the event is chosen in a synchronization, and the returned match always represents contiguous bytes in the port’s stream. If not-yet-available bytes from the port might contribute to the match, the event is not ready. Similarly, ifpattern begins with a start-of-stream ^ and thepattern does not initially match, then the event cannot become ready until bytes have been read from the port.

The event can be synchronized multiple times—even concurrently—and each synchronization corresponds to a distinct match request.

The in port must support progress events. If inreturns a special non-byte value during the match attempt, it is treated like eof.

Exceptions attempting to read from in are handled in the same way as by eof-evt.

13.1.10.4 Copying Streams🔗

Reads data from in, converts it using(bytes-open-converter from-encoding to-encoding) and writes the converted bytes toout. The convert-stream procedure returns after reaching eof in in.

If opening the converter fails, the exn:fail exception is raised. Similarly, if a conversion error occurs at any point while reading from in, thenexn:fail exception is raised.

Reads data from in and writes it back out to out, returning when in produces eof. The copy is efficient, and it is without significant buffer delays (i.e., a byte that becomes available on in is immediately transferred toout, even if future reads on in must block). Ifin produces a special non-byte value, it is transferred toout using write-special.

This function is often called from a “background” thread to continuously pump data from one stream to another.

If multiple outs are provided, data from in is written to every out. The different outs block output to each other, because each block of data read from inis written completely to one out before moving to the nextout. The outs are written in the provided order, so non-blocking ports (e.g., file output ports) should be placed first in the argument list.