on 0.4 help sign in
text/Data/Text/UnsafeChar.hs
80 lines 2.3 kB history raw
1{-# LANGUAGE MagicHash #-}
3-- |
4-- Module : Data.Text.UnsafeChar
5-- Copyright : (c) Tom Harper 2008-2009,
6-- (c) Bryan O'Sullivan 2009,
7-- (c) Duncan Coutts 2009
8--
9-- License : BSD-style
10-- Maintainer : bos@serpentine.com, rtharper@aftereternity.co.uk,
11-- duncan@haskell.org
12-- Stability : experimental
13-- Portability : GHC
14--
15-- Fast character manipulation functions.
16module Data.Text.UnsafeChar
17 (
18 unsafeChr
19 , unsafeChr8
20 , unsafeChr32
21 , unsafeWrite
22 -- , unsafeWriteRev
23 ) where
25import Control.Exception (assert)
26import Control.Monad.ST (ST)
27import Data.Bits ((.&.))
28import Data.Char (ord)
29import Data.Text.UnsafeShift (shiftR)
30import GHC.Exts (Char(..), chr#, word2Int#)
31import GHC.Word (Word8(..), Word16(..), Word32(..))
32import qualified Data.Text.Array as A
34unsafeChr :: Word16 -> Char
35unsafeChr (W16# w#) = C# (chr# (word2Int# w#))
36{-# INLINE unsafeChr #-}
38unsafeChr8 :: Word8 -> Char
39unsafeChr8 (W8# w#) = C# (chr# (word2Int# w#))
40{-# INLINE unsafeChr8 #-}
42unsafeChr32 :: Word32 -> Char
43unsafeChr32 (W32# w#) = C# (chr# (word2Int# w#))
44{-# INLINE unsafeChr32 #-}
46unsafeWrite :: A.MArray s Word16 -> Int -> Char -> ST s Int
47unsafeWrite marr i c
48 | n < 0x10000 = do
49 assert (i >= 0) . assert (i < A.length marr) $
50 A.unsafeWrite marr i (fromIntegral n)
51 return (i+1)
52 | otherwise = do
53 assert (i >= 0) . assert (i < A.length marr - 1) $
54 A.unsafeWrite marr i lo
55 A.unsafeWrite marr (i+1) hi
56 return (i+2)
57 where n = ord c
58 m = n - 0x10000
59 lo = fromIntegral $ (m `shiftR` 10) + 0xD800
60 hi = fromIntegral $ (m .&. 0x3FF) + 0xDC00
61{-# INLINE unsafeWrite #-}
63{-
64unsafeWriteRev :: A.MArray s Word16 -> Int -> Char -> ST s Int
65unsafeWriteRev marr i c
66 | n < 0x10000 = do
67 assert (i >= 0) . assert (i < A.length marr) $
68 A.unsafeWrite marr i (fromIntegral n)
69 return (i-1)
70 | otherwise = do
71 assert (i >= 1) . assert (i < A.length marr) $
72 A.unsafeWrite marr (i-1) lo
73 A.unsafeWrite marr i hi
74 return (i-2)
75 where n = ord c
76 m = n - 0x10000
77 lo = fromIntegral $ (m `shiftR` 10) + 0xD800
78 hi = fromIntegral $ (m .&. 0x3FF) + 0xDC00
79{-# INLINE unsafeWriteRev #-}
80-}