@@ -34,7 +34,7 @@ module Data.Text.Foreign
34
34
#if defined(ASSERTS)
35
35
import Control.Exception (assert )
36
36
#endif
37
- import Control.Monad.ST.Unsafe (unsafeIOToST )
37
+ import Control.Monad.ST.Unsafe (unsafeSTToIO )
38
38
import Data.ByteString.Unsafe (unsafePackCStringLen , unsafeUseAsCStringLen )
39
39
import Data.Text.Encoding (decodeUtf8 , encodeUtf8 )
40
40
import Data.Text.Internal (Text (.. ), empty )
@@ -44,8 +44,7 @@ import Data.Word (Word8)
44
44
import Foreign.C.String (CStringLen )
45
45
import Foreign.ForeignPtr (ForeignPtr , mallocForeignPtrArray )
46
46
import Foreign.Marshal.Alloc (allocaBytes )
47
- import Foreign.Ptr (Ptr , castPtr , plusPtr )
48
- import Foreign.Storable (peek , poke )
47
+ import Foreign.Ptr (Ptr , castPtr )
49
48
import qualified Data.Text.Array as A
50
49
51
50
-- $interop
@@ -68,20 +67,11 @@ newtype I8 = I8 Int
68
67
fromPtr :: Ptr Word8 -- ^ source array
69
68
-> I8 -- ^ length of source array (in 'Word8' units)
70
69
-> IO Text
71
- fromPtr _ (I8 0 ) = return empty
72
- fromPtr ptr (I8 len) =
73
- #if defined(ASSERTS)
74
- assert (len > 0 ) $
75
- #endif
76
- return $! Text arr 0 len
77
- where
78
- arr = A. run (A. new len >>= copy)
79
- copy marr = loop ptr 0
80
- where
81
- loop ! p ! i | i == len = return marr
82
- | otherwise = do
83
- A. unsafeWrite marr i =<< unsafeIOToST (peek p)
84
- loop (p `plusPtr` 1 ) (i + 1 )
70
+ fromPtr ptr (I8 len) = unsafeSTToIO $ do
71
+ dst <- A. new len
72
+ A. copyFromPointer dst 0 ptr len
73
+ arr <- A. unsafeFreeze dst
74
+ return $! Text arr 0 len
85
75
86
76
-- $lowlevel
87
77
--
@@ -130,13 +120,7 @@ splitAtWord8 (I8 n) t@(Text arr off len)
130
120
-- | /O(n)/ Copy a 'Text' to an array. The array is assumed to be big
131
121
-- enough to hold the contents of the entire 'Text'.
132
122
unsafeCopyToPtr :: Text -> Ptr Word8 -> IO ()
133
- unsafeCopyToPtr (Text arr off len) ptr = loop ptr off
134
- where
135
- end = off + len
136
- loop ! p ! i | i == end = return ()
137
- | otherwise = do
138
- poke p (A. unsafeIndex arr i)
139
- loop (p `plusPtr` 1 ) (i + 1 )
123
+ unsafeCopyToPtr (Text arr off len) ptr = unsafeSTToIO $ A. copyToPointer arr off ptr len
140
124
141
125
-- | /O(n)/ Perform an action on a temporary, mutable copy of a
142
126
-- 'Text'. The copy is freed as soon as the action returns.
0 commit comments