Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Text.IO.Utf8 module #503

Merged
merged 10 commits into from
Mar 11, 2023
44 changes: 44 additions & 0 deletions src/Data/Text/IO/Utf8.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
-- |
-- Module : Data.Text.IO.Utf8
-- Copyright : (c) 2009, 2010 Bryan O'Sullivan,
-- (c) 2009 Simon Marlow
oberblastmeister marked this conversation as resolved.
Show resolved Hide resolved
-- License : BSD-style
-- Maintainer : [email protected]
-- Portability : GHC
--
-- Efficient UTF-8 support for text I\/O.
module Data.Text.IO.Utf8
(
readFile
, writeFile
, appendFile
) where

import Prelude hiding (readFile, writeFile, appendFile)
import Control.Exception (evaluate)
import Control.Monad ((<=<))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)

decodeUtf8IO :: ByteString -> IO Text
decodeUtf8IO = evaluate . decodeUtf8
oberblastmeister marked this conversation as resolved.
Show resolved Hide resolved

encodeUtf8IO :: Text -> IO ByteString
encodeUtf8IO = evaluate . encodeUtf8
oberblastmeister marked this conversation as resolved.
Show resolved Hide resolved

-- | The 'readFile' function reads a file and returns the contents of
-- the file as a string. The entire file is read strictly, as with
oberblastmeister marked this conversation as resolved.
Show resolved Hide resolved
-- 'getContents'.
readFile :: FilePath -> IO Text
readFile = decodeUtf8IO <=< B.readFile
oberblastmeister marked this conversation as resolved.
Show resolved Hide resolved

-- | Write a string to a file. The file is truncated to zero length
-- before writing begins.
writeFile :: FilePath -> Text -> IO ()
writeFile fp = B.writeFile fp <=< encodeUtf8IO

-- | Write a string to the end of a file.
appendFile :: FilePath -> Text -> IO ()
appendFile fp = B.appendFile fp <=< encodeUtf8IO