c27544f5c921258b46c14bd395d44c12d05cc8a5
[packages/text.git] / Data / Text / Show.hs
1 {-# LANGUAGE CPP, MagicHash #-}
2 {-# OPTIONS_GHC -fno-warn-orphans #-}
3 #if __GLASGOW_HASKELL__ >= 702
4 {-# LANGUAGE Trustworthy #-}
5 #endif
6
7 -- |
8 -- Module : Data.Text.Show
9 -- Copyright : (c) 2009-2015 Bryan O'Sullivan
10 --
11 -- License : BSD-style
12 -- Maintainer : bos@serpentine.com
13 -- Stability : experimental
14 -- Portability : GHC
15
16 module Data.Text.Show
17 (
18 singleton
19 , unpack
20 ) where
21
22 import Control.Monad.ST (ST)
23 import Data.Text.Internal (Text(..), empty_, safe)
24 import Data.Text.Internal.Fusion (stream, unstream)
25 import Data.Text.Internal.Unsafe.Char (unsafeWrite)
26 import GHC.Prim (Addr#)
27 import qualified Data.Text.Array as A
28 import qualified Data.Text.Internal.Fusion.Common as S
29
30 #if __GLASGOW_HASKELL__ >= 702
31 import qualified GHC.CString as GHC
32 #else
33 import qualified GHC.Base as GHC
34 #endif
35
36 instance Show Text where
37 showsPrec p ps r = showsPrec p (unpack ps) r
38
39 -- | /O(n)/ Convert a 'Text' into a 'String'. Subject to fusion.
40 unpack :: Text -> String
41 unpack = S.unstreamList . stream
42 {-# INLINE [1] unpack #-}
43
44 -- | /O(n)/ Convert a literal string into a Text. Subject to fusion.
45 unpackCString# :: Addr# -> Text
46 unpackCString# addr# = unstream (S.streamCString# addr#)
47 {-# NOINLINE unpackCString# #-}
48
49 {-# RULES "TEXT literal" forall a.
50 unstream (S.map safe (S.streamList (GHC.unpackCString# a)))
51 = unpackCString# a #-}
52
53 {-# RULES "TEXT literal UTF8" forall a.
54 unstream (S.map safe (S.streamList (GHC.unpackCStringUtf8# a)))
55 = unpackCString# a #-}
56
57 {-# RULES "TEXT empty literal"
58 unstream (S.map safe (S.streamList []))
59 = empty_ #-}
60
61 {-# RULES "TEXT singleton literal" forall a.
62 unstream (S.map safe (S.streamList [a]))
63 = singleton_ a #-}
64
65 -- | /O(1)/ Convert a character into a Text. Subject to fusion.
66 -- Performs replacement on invalid scalar values.
67 singleton :: Char -> Text
68 singleton = unstream . S.singleton . safe
69 {-# INLINE [1] singleton #-}
70
71 {-# RULES "TEXT singleton" forall a.
72 unstream (S.singleton (safe a))
73 = singleton_ a #-}
74
75 -- This is intended to reduce inlining bloat.
76 singleton_ :: Char -> Text
77 singleton_ c = Text (A.run x) 0 len
78 where x :: ST s (A.MArray s)
79 x = do arr <- A.new len
80 _ <- unsafeWrite arr 0 d
81 return arr
82 len | d < '\x10000' = 1
83 | otherwise = 2
84 d = safe c
85 {-# NOINLINE singleton_ #-}