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 function to read UTF-8 files #459

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
`relude` uses [PVP Versioning][1].
The changelog is available [on GitHub][2].

## 1.2.2 - Unreleased ##

- [#459](https://github.com/kowainik/relude/pull/459):
Add `Relude.File.readFileUtf8`.

## 1.2.1.0 – Oct 4, 2023

- [#439](https://github.com/kowainik/relude/issues/439):
Expand Down
27 changes: 25 additions & 2 deletions src/Relude/File.hs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{-# LANGUAGE Safe #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE Safe #-}

{- |
Module : Relude.File
Expand Down Expand Up @@ -53,12 +54,16 @@ module Relude.File
, readFileLBS
, writeFileLBS
, appendFileLBS

-- * Reading in UTF-8
, readFileUtf8
) where

import Relude.Base (FilePath, IO)
import Relude.Function ((.))
import Relude.Functor (fmap)
import Relude.Monad.Reexport (MonadIO (..))
import Relude.String (ByteString, LByteString, LText, Text)
import Relude.String (ByteString, ConvertUtf8 (..), LByteString, LText, String, Text)

import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
Expand Down Expand Up @@ -191,3 +196,21 @@ appendFileLBS :: MonadIO m => FilePath -> LByteString -> m ()
appendFileLBS p = liftIO . LBS.appendFile p
{-# SPECIALIZE appendFileLBS :: FilePath -> LByteString -> IO () #-}
{-# INLINE appendFileLBS #-}

----------------------------------------------------------------------------
-- UTF-8
----------------------------------------------------------------------------

{- | 'MonadIO'-lifted strict file reading with the assumption that it contains
text in UTF-8 (or just ASCII) encoding.

Invalid byte sequences that don't represent characters will be converted to
U+FFFD replacement characters (@decodeUtf8Lenient@).

@since 1.2.2
-}
readFileUtf8 :: (MonadIO m, ConvertUtf8 r ByteString) => FilePath -> m r
readFileUtf8 = liftIO . fmap decodeUtf8 . BS.readFile
{-# SPECIALIZE readFileUtf8 :: FilePath -> IO Text #-}
{-# SPECIALIZE readFileUtf8 :: FilePath -> IO String #-}
{-# INLINE readFileUtf8 #-}