Skip to content

Commit 0d2c43e

Browse files
committed
Implement Data.Text.map explicitly
1 parent eba656a commit 0d2c43e

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/Data/Text.hs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -619,7 +619,28 @@ compareLength t n = S.compareLengthI (stream t) n
619619
--
620620
-- Performs replacement on invalid scalar values.
621621
map :: (Char -> Char) -> Text -> Text
622-
map f t = unstream (S.map (safe . f) (stream t))
622+
map f = go
623+
where
624+
go (Text src o l) = runST $ do
625+
marr <- A.new (l + 4)
626+
outer marr (l + 4) o 0
627+
where
628+
outer :: forall s. A.MArray s -> Int -> Int -> Int -> ST s Text
629+
outer !dst !dstLen = inner
630+
where
631+
inner !srcOff !dstOff
632+
| srcOff >= l + o = do
633+
A.shrinkM dst dstOff
634+
arr <- A.unsafeFreeze dst
635+
return (Text arr 0 dstOff)
636+
| dstOff + 4 > dstLen = do
637+
let !dstLen' = dstLen + (l + o) - srcOff + 4
638+
dst' <- A.resizeM dst dstLen'
639+
outer dst' dstLen' srcOff dstOff
640+
| otherwise = do
641+
let !(Iter c d) = iterArray src srcOff
642+
d' <- unsafeWrite dst dstOff (safe (f c))
643+
inner (srcOff + d) (dstOff + d')
623644
{-# INLINE [1] map #-}
624645

625646
{-# RULES

src/Data/Text/Lazy.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,7 @@ compareLength t n = S.compareLengthI (stream t) n
556556
-- each element of @t@. Performs replacement on
557557
-- invalid scalar values.
558558
map :: (Char -> Char) -> Text -> Text
559-
map f t = unstream (S.map (safe . f) (stream t))
559+
map f = foldrChunks (Chunk . T.map f) Empty
560560
{-# INLINE [1] map #-}
561561

562562
{-# RULES

0 commit comments

Comments
 (0)