lib/Byte-struct.ss
#lang scheme/base

(require (planet chongkai/sml/ml-package)
         scheme/match
         (only-in (planet chongkai/sml/ml-primitives)
                  SOME-datatype SOME? SOME SOME-content
                  NONE-datatype NONE? NONE
                  Subscript-datatype Subscript? Subscript))

(provide Byte-struct)

(define-package Byte-struct
  (byteToChar charToByte bytesToString stringToBytes unpackStringVec unpackString packString)
  
  (define unpackStringVec
    (match-lambda
      ((vector vec i (? NONE?))
       (bytes->string/latin-1 (subbytes vec i)))
      ((vector vec i (? SOME? (app SOME-content e)))
       (bytes->string/latin-1 (subbytes vec i e)))))
  
  (define packString
    (match-lambda
      ((vector arr i (vector s i2 n))
       (call-with-exception-handler
        (lambda (e)
          (if (exn:break? e)
              e
              (Subscript (current-continuation-marks))))
        (lambda ()
          (bytes-copy! arr i
                       (string->bytes/latin-1
                        (substring s i2 (+ i2 n)))))))))
  
  (define byteToChar integer->char)
  (define charToByte char->integer)
  (define bytesToString bytes->string/latin-1)
  (define stringToBytes string->bytes/latin-1)
  (define unpackString unpackStringVec))