1(*
2    Title:      Standard Basis Library: Byte Structure and signature
3    Author:     David Matthews
4    Copyright   David Matthews 1999, 2005, 2015
5
6    This library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Lesser General Public
8    License version 2.1 as published by the Free Software Foundation.
9    
10    This library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14    
15    You should have received a copy of the GNU Lesser General Public
16    License along with this library; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18    under the terms of that licence.
19*)
20
21signature BYTE =
22sig
23    val byteToChar : Word8.word -> char
24    val charToByte : char -> Word8.word
25    val bytesToString : Word8Vector.vector -> string
26    val stringToBytes : string -> Word8Vector.vector
27    val unpackStringVec : Word8VectorSlice.slice -> string
28    val unpackString : Word8ArraySlice.slice -> string
29    val packString : Word8Array.array * int * Substring.substring -> unit
30end;
31
32structure Byte: BYTE =
33    struct
34        (* Chars and Word8.word values are both tagged integers in the
35           range 0..255. *)
36        fun byteToChar (w: Word8.word): char = RunCall.unsafeCast w
37        fun charToByte (c: char) : Word8.word = RunCall.unsafeCast c
38
39        (* Conversion between Word8Vector.vector and string is just a cast. *)
40        val bytesToString = LibrarySupport.w8vectorToString
41        and stringToBytes = LibrarySupport.w8vectorFromString
42
43        fun unpackStringVec slice : string = bytesToString(Word8VectorSlice.vector slice)
44        fun unpackString slice : string = bytesToString(Word8ArraySlice.vector slice)
45
46        fun packString(array: Word8Array.array, i, s: substring) =
47        let
48            val (str, offset, size) = Substring.base s
49            val slice = Word8VectorSlice.slice(stringToBytes str, offset, SOME size)
50        in
51            Word8ArraySlice.copyVec{src=slice, dst=array, di=i}
52        end
53    end;
54
55