write-image-util.scm 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. ; Copyright (c) 1993-2008 by Richard Kelsey and Jonathan Rees. See file COPYING.
  2. ; Utilities for writing images.
  3. ; The page character is used to mark the ends of the user and prelude sections
  4. ; of image files.
  5. (define *status* (enum errors no-errors))
  6. (define (image-write-status)
  7. *status*)
  8. (define-syntax write-check
  9. (syntax-rules ()
  10. ((write-check exp)
  11. (if (eq? *status* (enum errors no-errors))
  12. (set! *status* exp)))))
  13. (define image-buffer-size 4096)
  14. (define *image-port*)
  15. (define *image-buffer*)
  16. (define *image-buffer-pointer*)
  17. (define (write-header-integer n)
  18. (write-check (write-integer n *image-port*))
  19. (write-check (write-char #\newline *image-port*)))
  20. (define page-character (ascii->char 12))
  21. (define (write-page)
  22. (write-check (write-char page-character *image-port*)))
  23. (define (buffer-contents)
  24. (address-difference *image-buffer-pointer*
  25. *image-buffer*))
  26. (define (image-write-init port)
  27. (set! *image-port* port)
  28. (set! *image-buffer* (allocate-memory image-buffer-size))
  29. (set! *image-buffer-pointer* *image-buffer*)
  30. (set! *status* (enum errors no-errors))
  31. (not (null-address? *image-buffer*)))
  32. (define (image-write-terminate)
  33. (deallocate-memory *image-buffer*))
  34. ; Writing buffers.
  35. (define (write-descriptor descriptor)
  36. (word-set! *image-buffer-pointer* descriptor)
  37. (set! *image-buffer-pointer* (address1+ *image-buffer-pointer*))
  38. (maybe-empty-image-buffer))
  39. (define (write-image-block start size)
  40. (let ((available (- image-buffer-size (buffer-contents))))
  41. (cond ((<= size available)
  42. (copy-image-data start size))
  43. ((<= size image-buffer-size)
  44. (copy-image-data start available)
  45. (copy-image-data (address+ start available) (- size available)))
  46. (else
  47. (empty-image-buffer!)
  48. (write-check (write-block *image-port* start size))))
  49. (unspecific)))
  50. (define (copy-image-data start size)
  51. (copy-memory! start *image-buffer-pointer* size)
  52. (set! *image-buffer-pointer* (address+ *image-buffer-pointer* size))
  53. (maybe-empty-image-buffer))
  54. (define (maybe-empty-image-buffer)
  55. (if (= (buffer-contents)
  56. image-buffer-size)
  57. (empty-image-buffer!)))
  58. (define (empty-image-buffer!)
  59. (let ((have (buffer-contents)))
  60. (cond ((< 0 have)
  61. (write-check (write-block *image-port* *image-buffer* have))
  62. (set! *image-buffer-pointer* *image-buffer*)))))