[Word8] to filesystem encoded String

My, GHC makes this hard.
This commit is contained in:
Joey Hess 2012-06-20 12:51:25 -04:00
parent dbe7d0e7fe
commit ee2acd474f

View file

@ -13,6 +13,8 @@ import Foreign.C
import System.IO
import System.IO.Unsafe
import qualified Data.Hash.MD5 as MD5
import Data.Word
import Data.Bits.Utils
{- Sets a Handle to use the filesystem encoding. This causes data
- written or read from it to be encoded/decoded the same
@ -29,7 +31,7 @@ withFilePath :: FilePath -> (CString -> IO a) -> IO a
withFilePath fp f = Encoding.getFileSystemEncoding
>>= \enc -> GHC.withCString enc fp f
{- Encodes a FilePath into a Str, applying the filesystem encoding.
{- Encodes a FilePath into a Md5.Str, applying the filesystem encoding.
-
- This use of unsafePerformIO is belived to be safe; GHC's interface
- only allows doing this conversion with CStrings, and the CString buffer
@ -41,3 +43,15 @@ encodeFilePath :: FilePath -> MD5.Str
encodeFilePath fp = MD5.Str $ unsafePerformIO $ do
enc <- Encoding.getFileSystemEncoding
GHC.withCString enc fp $ GHC.peekCString Encoding.char8
{- Converts a [Word8] to a FilePath, encoding using the filesystem encoding.
-
- w82c produces a String, which may contain Chars that are invalid
- unicode. From there, this is really a simple matter of applying the
- file system encoding, only complicated by GHC's interface to doing so.
-}
{-# NOINLINE encodeW8 #-}
encodeW8 :: [Word8] -> FilePath
encodeW8 w8 = unsafePerformIO $ do
enc <- Encoding.getFileSystemEncoding
GHC.withCString Encoding.char8 (w82s w8) $ GHC.peekCString enc