ascii.scm 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. ; -*- Mode: Scheme; Syntax: Scheme; Package: Scheme; -*-
  2. ; Part of Scheme 48 1.9. See file COPYING for notices and license.
  3. ; Authors: Richard Kelsey, Jonathan Rees, Mike Sperber
  4. ;;;; Portable definitions of char->ascii and ascii->char
  5. ; Don't detabify this file!
  6. ; This module defines char->ascii and ascii->char in terms of
  7. ; char->integer and integer->char, with no assumptions about the encoding.
  8. ; Portable except maybe for the strings that contain tab, page, and
  9. ; carriage return characters. Those can be flushed if necessary.
  10. (define ascii-limit 128)
  11. (define ascii-chars
  12. (let* ((ascii-chars (make-vector ascii-limit #f))
  13. (unusual (lambda (s)
  14. (if (or (not (= (string-length s) 1))
  15. (let ((c (string-ref s 0)))
  16. (or (char=? c #\space)
  17. (char=? c #\newline))))
  18. (assertion-violation 'ascii-chars "unusual whitespace character lost" s)
  19. s)))
  20. (init (lambda (i s)
  21. (do ((i i (+ i 1))
  22. (j 0 (+ j 1)))
  23. ((= j (string-length s)))
  24. (vector-set! ascii-chars i (string-ref s j))))))
  25. (init 9 (unusual " ")) ;tab
  26. (init 12 (unusual " ")) ;page
  27. (init 13 (unusual " ")) ;carriage return
  28. (init 10 (string #\newline))
  29. (init 32 " !\"#$%&'()*+,-./0123456789:;<=>?")
  30. (init 64 "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_")
  31. (init 96 "`abcdefghijklmnopqrstuvwxyz{|}~")
  32. ascii-chars))
  33. (define (ascii->char n)
  34. (or (vector-ref ascii-chars n)
  35. (assertion-violation 'ascii->char "not a standard character's ASCII code" n)))
  36. (define native-chars
  37. (let ((end (vector-length ascii-chars)))
  38. (let loop ((i 0)
  39. (least #f)
  40. (greatest #f))
  41. (cond ((= i end)
  42. (let ((v (make-vector (+ (- greatest least) 1) #f)))
  43. (do ((i 0 (+ i 1)))
  44. ((= i end) (cons least v))
  45. (let ((c (vector-ref ascii-chars i)))
  46. (if c
  47. (vector-set! v (- (char->integer c) least) i))))))
  48. (else
  49. (let ((c (vector-ref ascii-chars i)))
  50. (if c
  51. (let ((n (char->integer c)))
  52. (loop (+ i 1)
  53. (if least (min least n) n)
  54. (if greatest (max greatest n) n)))
  55. (loop (+ i 1) least greatest))))))))
  56. (define (char->ascii char)
  57. (or (vector-ref (cdr native-chars)
  58. (- (char->integer char) (car native-chars)))
  59. (assertion-violation 'char->ascii "not a standard character" char)))
  60. (define ascii-whitespaces '(32 10 9 12 13)) ;space linefeed tab page return