module Streamly.External.Zip.Internal.Error where

import Control.Exception
import qualified Data.ByteString.Char8 as BC
import Foreign.C.Types
import Foreign.Marshal
import Streamly.External.Zip.Internal.Foreign
import Text.Printf

data Error = Error !String !String

instance Show Error where
  show :: Error -> String
show (Error String
ctx String
msg) = String -> String -> ShowS
forall r. PrintfType r => String -> r
printf String
"streamly-zip; %s; %s" String
ctx String
msg

instance Exception Error

throwError :: String -> String -> m a
throwError :: forall (m :: * -> *) a. String -> String -> m a
throwError String
ctx String
msg = Error -> m a
forall a e. Exception e => e -> a
throw (Error -> m a) -> Error -> m a
forall a b. (a -> b) -> a -> b
$ String -> String -> Error
Error String
ctx String
msg

libzipErrToString :: CInt -> IO String
libzipErrToString :: CInt -> IO String
libzipErrToString CInt
err = IO String -> IO String
forall a. IO a -> IO a
mask_ (IO String -> IO String) -> IO String -> IO String
forall a b. (a -> b) -> a -> b
$ do
  Ptr Zip_error_t
errp <- Int -> IO (Ptr Zip_error_t)
forall a. Int -> IO (Ptr a)
mallocBytes Int
zip_error_t_size
  Ptr Zip_error_t -> CInt -> IO ()
c_zip_error_init_with_code Ptr Zip_error_t
errp CInt
err
  String
str <- ByteString -> String
BC.unpack (ByteString -> String) -> IO ByteString -> IO String
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Ptr Zip_error_t -> IO (Ptr CChar)
c_zip_error_strerror Ptr Zip_error_t
errp IO (Ptr CChar) -> (Ptr CChar -> IO ByteString) -> IO ByteString
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Ptr CChar -> IO ByteString
BC.packCString)
  Ptr Zip_error_t -> IO ()
c_zip_error_fini Ptr Zip_error_t
errp
  String -> IO String
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return String
str