on master help sign in
Add a copy function
35acc5eBryan O'Sullivan
Data/Text.hs+19
@@ -183,6 +183,9 @@ module Data.Text
183
183
184 -- -* Ordered text
184 -- -* Ordered text
185 -- , sort
185 -- , sort
186+
187+ -- * Low level operations
188+ , copy
186 ) where
189 ) where
187
190
188import Prelude (Char, Bool(..), Int, Maybe(..), String,
191import Prelude (Char, Bool(..), Int, Maybe(..), String,
@@ -1577,3 +1580,19 @@ emptyError fun = P.error $ "Data.Text." ++ fun ++ ": empty input"
1577
1580
1578overflowError :: String -> a
1581overflowError :: String -> a
1579overflowError fun = P.error $ "Data.Text." ++ fun ++ ": size overflow"
1582overflowError fun = P.error $ "Data.Text." ++ fun ++ ": size overflow"
1583+
1584+-- | /O(n)/ Make a distinct copy of the given string, sharing no
1585+-- storage with the original string.
1586+--
1587+-- As an example, suppose you read a large string, of which you need
1588+-- only a small portion. If you do not use 'copy', the entire original
1589+-- array will be kept alive in memory by the smaller string. Making a
1590+-- copy \"breaks the link\" to the original array, allowing it to be
1591+-- garbage collected if there are no other live references to it.
1592+copy :: Text -> Text
1593+copy (Text arr off len) = Text (A.run go) 0 len
1594+ where
1595+ go = do
1596+ marr <- A.new len
1597+ A.copyI marr 0 arr off len
1598+ return marr
tests/Tests/Properties.hs+4−1
@@ -733,6 +733,8 @@ t_take_drop_16 m t = T.append (takeWord16 n t) (dropWord16 n t) == t
733 where n = small m
733 where n = small m
734t_use_from t = monadicIO $ assert . (==t) =<< run (useAsPtr t fromPtr)
734t_use_from t = monadicIO $ assert . (==t) =<< run (useAsPtr t fromPtr)
735
735
736+t_copy t = T.copy t == t
737+
736-- Regression tests.
738-- Regression tests.
737s_filter_eq s = S.filter p t == S.streamList (filter p s)
739s_filter_eq s = S.filter p t == S.streamList (filter p s)
738 where p = (/= S.last t)
740 where p = (/= S.last t)
@@ -1197,6 +1199,7 @@ tests =
1197 testProperty "t_dropWord16" t_dropWord16,
1199 testProperty "t_dropWord16" t_dropWord16,
1198 testProperty "t_takeWord16" t_takeWord16,
1200 testProperty "t_takeWord16" t_takeWord16,
1199 testProperty "t_take_drop_16" t_take_drop_16,
1201 testProperty "t_take_drop_16" t_take_drop_16,
1200− testProperty "t_use_from" t_use_from
1202+ testProperty "t_use_from" t_use_from,
1203+ testProperty "t_copy" t_copy
1201 ]
1204 ]
1202 ]
1205 ]