on master help sign in
Add a copy function

This fixes gh-48

commit35acc5eda9f831e1d8c6b3de254e8396c94b47aa authorBryan O'Sullivan <bos@serpentine.com> dateSun 21 Apr 2013, 11:58 (13 years ago) parent6cbbdd6
2 files changed+23−1
Data/Text.hs+19 tests/Tests/Properties.hs+4−1
Data/Text.hs+19
@@ -183,6 +183,9 @@ module Data.Text
183183
184184 -- -* Ordered text
185185 -- , sort
186+
187+ -- * Low level operations
188+ , copy
186189 ) where
187190
188191import Prelude (Char, Bool(..), Int, Maybe(..), String,
@@ -1577,3 +1580,19 @@ emptyError fun = P.error $ "Data.Text." ++ fun ++ ": empty input"
15771580
15781581overflowError :: String -> a
15791582overflowError 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
733733 where n = small m
734734t_use_from t = monadicIO $ assert . (==t) =<< run (useAsPtr t fromPtr)
735735
736+t_copy t = T.copy t == t
737+
736738-- Regression tests.
737739s_filter_eq s = S.filter p t == S.streamList (filter p s)
738740 where p = (/= S.last t)
@@ -1197,6 +1199,7 @@ tests =
11971199 testProperty "t_dropWord16" t_dropWord16,
11981200 testProperty "t_takeWord16" t_takeWord16,
11991201 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
12011204 ]
12021205 ]