-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathText.hs
78 lines (61 loc) · 2.27 KB
/
Text.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
{-# LANGUAGE ForeignFunctionInterface, UnliftedFFITypes, JavaScriptFFI,
UnboxedTuples, DeriveDataTypeable, GHCForeignImportPrim,
MagicHash, FlexibleInstances, BangPatterns, Rank2Types, CPP #-}
{- | Conversion between 'Data.Text.Text' and 'Data.JSString.JSString'
-}
module Data.JSString.Text
( textToJSString
, textFromJSString
, lazyTextToJSString
, lazyTextFromJSString
, textFromJSVal
, lazyTextFromJSVal
) where
import GHCJS.Prim
import GHC.Exts (ByteArray#, Int(..), Int#, Any)
import Control.DeepSeq
import qualified Data.Text.Array as A
import qualified Data.Text as T
import qualified Data.Text.Internal as T
import qualified Data.Text.Lazy as TL
import Data.JSString.Internal.Type
import Unsafe.Coerce
textToJSString :: T.Text -> JSString
textToJSString (T.Text (A.Array ba) (I# offset) (I# length)) =
js_toString ba offset length
{-# INLINE textToJSString #-}
textFromJSString :: JSString -> T.Text
textFromJSString j =
case js_fromString j of
(# _ , 0# #) -> T.empty
(# ba, length #) -> T.Text (A.Array ba) 0 (I# length)
{-# INLINE textFromJSString #-}
lazyTextToJSString :: TL.Text -> JSString
lazyTextToJSString t = rnf t `seq` js_lazyTextToString (unsafeCoerce t)
{-# INLINE lazyTextToJSString #-}
lazyTextFromJSString :: JSString -> TL.Text
lazyTextFromJSString = TL.fromStrict . textFromJSString
{-# INLINE lazyTextFromJSString #-}
-- | returns the empty Text if not a string
textFromJSVal :: JSVal -> T.Text
textFromJSVal j = case js_fromString' j of
(# _, 0# #) -> T.empty
(# ba, length #) -> T.Text (A.Array ba) 0 (I# length)
{-# INLINE textFromJSVal #-}
-- | returns the empty Text if not a string
lazyTextFromJSVal :: JSVal -> TL.Text
lazyTextFromJSVal = TL.fromStrict . textFromJSVal
{-# INLINE lazyTextFromJSVal #-}
-- ----------------------------------------------------------------------------
foreign import javascript unsafe
"h$textToString"
js_toString :: ByteArray# -> Int# -> Int# -> JSString
foreign import javascript unsafe
"h$textFromString"
js_fromString :: JSString -> (# ByteArray#, Int# #)
foreign import javascript unsafe
"h$textFromString"
js_fromString' :: JSVal -> (# ByteArray#, Int# #)
foreign import javascript unsafe
"h$lazyTextToString"
js_lazyTextToString :: Any -> JSString