PasteRack.org
Paste # 33804
2023-05-02 15:56:15

Fork as a new paste.

Paste viewed 1308 times.


Embed:

Copy everything read from an input port to a string output port

  1. #lang racket/base
  2.  
  3. ;; Contract: (-> input-port? output-port? input-port?)
  4. (define (make-logging-input-port original logger)
  5.   (make-input-port
  6.    (object-name original)
  7.    (lambda (buffer) ; reader
  8.      (let ([nbytes (read-bytes! buffer original)])
  9.        (unless (eof-object? nbytes)
  10.          (write-bytes buffer logger 0 nbytes))
  11.        nbytes))
  12.    (lambda (buffer skip-len evt) ; peek
  13.      (peek-bytes! buffer skip-len original))
  14.    (lambda () (close-input-port original))))
  15.  
  16.  
  17.  
  18. (define logging-port (open-output-string))
  19. (parameterize ([current-input-port (make-logging-input-port (current-input-port) logging-port)])
  20.   (display "Enter some text: ")
  21.   (flush-output)
  22.   (printf "You entered ~S according to read-line~%" (read-line))
  23.   (printf "The string log says you entered ~S~%" (get-output-string logging-port)))

=>

Enter some text: You entered #<eof> according to read-line

The string log says you entered ""