
module UTF8
  ( peekUTF8String, peekUTF8StringLen
  ) where

import Control.Monad (when, liftM)
import Data.Char
import Data.Word (Word8)
import Foreign.C.String
import Foreign.Ptr
import Foreign.Marshal.Array
import Foreign.Storable
import GHC.Base (unsafeChr)


nullByte :: Word8
nullByte = 0

peekUTF8String :: CString -> IO String
peekUTF8String cs = fromUTF8Ptr0 (castPtr cs)

peekUTF8StringLen :: CStringLen -> IO String
peekUTF8StringLen (cs, len) = fromUTF8Ptr (len-1) (castPtr cs) ""


fromUTF8Ptr0 :: Ptr Word8 -> IO String
fromUTF8Ptr0 p = do
  len <- lengthArray0 nullByte p
  fromUTF8Ptr (len-1) p ""

fromUTF8Ptr :: Int -> Ptr Word8 -> String -> IO String
fromUTF8Ptr bytes p acc
  | () `seq` bytes `seq` p `seq` acc `seq` False = undefined
  | bytes < 0 = return acc
  | otherwise = do
  x <- liftM fromIntegral (peekElemOff p bytes)
  case () of
    _ | x == 0 -> error ("fromUTF8Ptr: zero byte found in string as position " ++ show bytes)
      | x <= 0x7F -> fromUTF8Ptr (bytes-1) p (unsafeChr x:acc)
      | x <= 0xBF && bytes == 0 -> error "fromUTF8Ptr: surrogate at start of string"
      | x <= 0xBF -> fromUTF8Ptr (bytes-1) p acc
      | otherwise -> do
          c <- readUTF8Char x bytes p
          fromUTF8Ptr (bytes-1) p (c:acc)


readUTF8Char :: Int -> Int -> Ptr Word8 -> IO Char
readUTF8Char x offset p
  | () `seq` x `seq` offset `seq` p `seq` False = undefined
  | otherwise =
  case () of
    _ | x == 0 -> err x
      | x <= 0x7F -> return (unsafeChr x)
      | x <= 0xBF -> err x
      | x <= 0xDF -> do
          x1 <- liftM fromIntegral (peekElemOff p (offset + 1))
          return (unsafeChr (
            ((x - 0xC0) * 64)
            + (x1 - 0x80)
            ))
      | x <= 0xEF -> do
          x1 <- liftM fromIntegral (peekElemOff p (offset + 1))
          x2 <- liftM fromIntegral (peekElemOff p (offset + 2))
          return (unsafeChr (
            ((x - 0xE0) * 4096)
            + ((x1 - 0x80) * 64)
            + (x2 - 0x80)
            ))
      | x <= 0xF7 -> do
          x1 <- liftM fromIntegral (peekElemOff p (offset + 1))
          x2 <- liftM fromIntegral (peekElemOff p (offset + 2))
          x3 <- liftM fromIntegral (peekElemOff p (offset + 3))
          return (unsafeChr (
            ((x - 0xF0) * 262144)
            + ((x1 - 0x80) * 4096)
            + ((x2 - 0x80) * 64)
            + (x3 - 0x80)
            ))
     | otherwise -> err x
  where
    err x = error ("readUTF8Char: illegal UTF-8 character " ++ show x)
