56e95a5434a8376b2aa3f928da6445679401c79b
[ghc-hetmet.git] / ghc / compiler / utils / UnicodeUtil.lhs
1 Various Unicode-related utilities.
2
3 \begin{code}
4 module UnicodeUtil(
5     stringToUtf8, intsToUtf8
6   ) where
7
8 #include "HsVersions.h"
9
10 import Panic ( panic )
11 import Char  ( chr, ord )
12 \end{code}
13
14 \begin{code}
15 stringToUtf8 :: String -> String
16 stringToUtf8 s = intsToUtf8 (map ord s)
17
18 intsToUtf8 :: [Int] -> String
19 intsToUtf8 []       = ""
20 intsToUtf8 (c:s)
21     | c >= 1 && c <= 0x7F = chr c : intsToUtf8 s
22     | c < 0           = panic ("charToUtf8 ("++show c++")")
23     | c <= 0x7FF      = chr (0xC0 + c `div`       0x40           ) :
24                         chr (0x80 + c                  `mod` 0x40) :
25                         intsToUtf8 s
26     | c <= 0xFFFF     = chr (0xE0 + c `div`     0x1000           ) :
27                         chr (0x80 + c `div`       0x40 `mod` 0x40) :
28                         chr (0x80 + c                  `mod` 0x40) :
29                         intsToUtf8 s
30     | c <= 0x10FFFF   = chr (0xF0 + c `div`    0x40000           ) :
31                         chr (0x80 + c `div`     0x1000 `mod` 0x40) :
32                         chr (0x80 + c `div`       0x40 `mod` 0x40) :
33                         chr (0x80 + c                  `mod` 0x40) :
34                         intsToUtf8 s
35     | otherwise       = panic ("charToUtf8 "++show c)
36 \end{code}