Import Upstream version 20180207
[hcoop/debian/mlton.git] / lib / mlton / basic / char0.sml
CommitLineData
7f918cf1
CE
1(* Copyright (C) 2009 Matthew Fluet.
2 * Copyright (C) 1999-2006 Henry Cejtin, Matthew Fluet, Suresh
3 * Jagannathan, and Stephen Weeks.
4 *
5 * MLton is released under a BSD-style license.
6 * See the file MLton-LICENSE for details.
7 *)
8
9structure Char0 : CHAR0 =
10struct
11
12structure Array = Pervasive.Array
13structure Int = Pervasive.Int
14structure String = Pervasive.String
15open Pervasive.Char
16
17type t = char
18
19val dash = #"-"
20val dquote = #"\""
21val newline = #"\n"
22val space = #" "
23val toInt = ord
24val fromInt = chr
25val escapeSML = toString
26val escapeC = toCString
27val toString = String.str
28val equals: t * t -> bool = op =
29val toWord8 = Byte.charToByte
30val fromWord8 = Byte.byteToChar
31
32val {max, min, compare, ...} = Relation0.lessEqual {< = op <, equals = equals}
33
34fun digitToInt (c: t): int option =
35 if isDigit c
36 then SOME (ord c - ord #"0")
37 else NONE
38
39fun fromDigit (d: int): t =
40 if let open Int in 0 <= d andalso d < 10 end
41 then chr (d + ord #"0")
42 else Error.bug "Char0.fromDigit"
43
44fun output (c, out) = TextIO.output (out, toString c)
45
46val numChars = ord maxChar + 1
47
48fun memoize (f: t -> 'a): t -> 'a =
49 let val a = Array.tabulate (numChars, f o chr)
50 in fn c => Array.sub (a, ord c)
51 end
52
53fun toHexDigit (c: t): int =
54 if #"0" <= c andalso c <= #"9"
55 then ord c - ord #"0"
56 else if #"a" <= c andalso c <= #"f"
57 then ord c - ord #"a" + 10
58 else if #"A" <= c andalso c <= #"F"
59 then ord c - ord #"A" + 10
60 else Error.bug "Char0.charToHexDigit"
61
62fun fromHexDigit (n: int): char = String.sub ("0123456789ABCDEF", n)
63
64end