@@ -45,6 +45,10 @@ module Data.Text.Encoding
45 , encodeUtf16BE
45 , encodeUtf16BE
46 , encodeUtf32LE
46 , encodeUtf32LE
47 , encodeUtf32BE
47 , encodeUtf32BE
49+ -- * Generic encoding of Text
50import Control.Exception (evaluate, try)
54import Control.Exception (evaluate, try)
@@ -56,6 +60,8 @@ import Control.Monad.ST (unsafeIOToST, unsafeSTToIO)
56import Data.Bits ((.&.))
60import Data.Bits ((.&.))
57import Data.ByteString as B
61import Data.ByteString as B
58import Data.ByteString.Internal as B
62import Data.ByteString.Internal as B
63+import Data.ByteString.Lazy.Builder.Internal as B
64+import Data.ByteString.Lazy.Builder.BasicEncoding.Internal as B
59import Data.Text.Encoding.Error (OnDecodeError, UnicodeException, strictDecode)
65import Data.Text.Encoding.Error (OnDecodeError, UnicodeException, strictDecode)
60import Data.Text.Internal (Text(..), textP)
66import Data.Text.Internal (Text(..), textP)
61import Data.Text.UnsafeChar (ord, unsafeWrite)
67import Data.Text.UnsafeChar (ord, unsafeWrite)
@@ -278,3 +284,29 @@ encodeUtf32BE txt = E.unstream (E.restreamUtf32BE (F.stream txt))
278foreign import ccall unsafe "_hs_text_decode_utf8" c_decode_utf8
284foreign import ccall unsafe "_hs_text_decode_utf8" c_decode_utf8
279 :: MutableByteArray# s -> Ptr CSize
285 :: MutableByteArray# s -> Ptr CSize
280 -> Ptr Word8 -> Ptr Word8 -> IO (Ptr Word8)
286 -> Ptr Word8 -> Ptr Word8 -> IO (Ptr Word8)
288+-- | Encode all elements of a 'F.Stream' using a 'B.BoundedEncoding'.
289+{-# INLINE encodeStreamWithB #-}
290+encodeStreamWithB :: B.BoundedEncoding a -> F.Stream a -> B.Builder
291+encodeStreamWithB be =
292+ \(F.Stream next s0 _) -> B.builder $ step next s0
294+ bound = B.sizeBound be
295+ step next s0 k (B.BufferRange op0 ope0) =
298+ go s !op = case next s of
299+ F.Done -> k (B.BufferRange op ope0)
300+ F.Skip s' -> go s' op
302+ | op `plusPtr` bound <= ope0 -> B.runB be x op >>= go s'
304+ return $ B.bufferFull bound op (step next s k)
308+-- | /Subject to fusion./
309+-- Encode all 'Char's of a 'T.Text' using a 'B.BoundedEncoding'.
310+{-# INLINE encodeTextWithB #-}
311+encodeTextWithB :: B.BoundedEncoding Char -> Text -> B.Builder
312+encodeTextWithB be = encodeStreamWithB be . F.stream