textual-ports.scm 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. ;;;; textual-ports.scm --- Textual I/O on ports
  2. ;;;; Copyright (C) 2016 Free Software Foundation, Inc.
  3. ;;;;
  4. ;;;; This library is free software; you can redistribute it and/or
  5. ;;;; modify it under the terms of the GNU Lesser General Public
  6. ;;;; License as published by the Free Software Foundation; either
  7. ;;;; version 3 of the License, or (at your option) any later version.
  8. ;;;;
  9. ;;;; This library is distributed in the hope that it will be useful,
  10. ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. ;;;; Lesser General Public License for more details.
  13. ;;;;
  14. ;;;; You should have received a copy of the GNU Lesser General Public
  15. ;;;; License along with this library; if not, write to the Free Software
  16. ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. ;;; Commentary:
  18. ;;;
  19. ;;; Code:
  20. (define-module (ice-9 textual-ports)
  21. #:use-module (ice-9 ports internal)
  22. #:use-module (ice-9 binary-ports)
  23. #:use-module (ice-9 rdelim)
  24. #:re-export (get-string-n!
  25. put-char
  26. put-string)
  27. #:export (get-char
  28. unget-char
  29. unget-string
  30. lookahead-char
  31. get-string-n
  32. get-string-all
  33. get-line))
  34. (define (get-char port)
  35. (read-char port))
  36. (define (lookahead-char port)
  37. (peek-char port))
  38. (define (unget-char port char)
  39. (unread-char char port))
  40. (define* (unget-string port string #:optional (start 0)
  41. (count (- (string-length string) start)))
  42. (unread-string (if (and (zero? start)
  43. (= count (string-length string)))
  44. string
  45. (substring/shared string start (+ start count)))
  46. port))
  47. (define (get-line port)
  48. (read-line port 'trim))
  49. (define (get-string-all port)
  50. (read-string port))
  51. (define (get-string-n port count)
  52. "Read up to @var{count} characters from @var{port}.
  53. If no characters could be read before encountering the end of file,
  54. return the end-of-file object, otherwise return a string containing
  55. the characters read."
  56. (let* ((s (make-string count))
  57. (rv (get-string-n! port s 0 count)))
  58. (cond ((eof-object? rv) rv)
  59. ((= rv count) s)
  60. (else (substring/shared s 0 rv)))))