Commits

Bryan O'Sullivan  committed 02096df

Add a copy function

This fixes gh-48

  • Participants
  • Parent commits 6228517

Comments (0)

Files changed (2)

File Data/Text.hs

 
     -- -* Ordered text
     -- , sort
+
+    -- * Low level operations
+    , copy
     ) where
 
 import Prelude (Char, Bool(..), Int, Maybe(..), String,
 
 overflowError :: String -> a
 overflowError fun = P.error $ "Data.Text." ++ fun ++ ": size overflow"
+
+-- | /O(n)/ Make a distinct copy of the given string, sharing no
+-- storage with the original string.
+--
+-- As an example, suppose you read a large string, of which you need
+-- only a small portion.  If you do not use 'copy', the entire original
+-- array will be kept alive in memory by the smaller string. Making a
+-- copy \"breaks the link\" to the original array, allowing it to be
+-- garbage collected if there are no other live references to it.
+copy :: Text -> Text
+copy (Text arr off len) = Text (A.run go) 0 len
+  where
+    go = do
+      marr <- A.new len
+      A.copyI marr 0 arr off len
+      return marr

File tests/Tests/Properties.hs

   where n = small m
 t_use_from t = monadicIO $ assert . (==t) =<< run (useAsPtr t fromPtr)
 
+t_copy t = T.copy t == t
+
 -- Regression tests.
 s_filter_eq s = S.filter p t == S.streamList (filter p s)
     where p = (/= S.last t)
       testProperty "t_dropWord16" t_dropWord16,
       testProperty "t_takeWord16" t_takeWord16,
       testProperty "t_take_drop_16" t_take_drop_16,
-      testProperty "t_use_from" t_use_from
+      testProperty "t_use_from" t_use_from,
+      testProperty "t_copy" t_copy
     ]
   ]