packages feed

keid-core-0.2.0.0: src/Resource/Compressed/Zstd.hs

module Resource.Compressed.Zstd where

import RIO

import Data.ByteString.Internal qualified as ByteString.Internal
import Data.ByteString.Unsafe qualified as ByteString.Unsafe
import Data.Typeable (typeOf)
import Foreign (Ptr)
import Foreign qualified
import Foreign.C.Types (CSize(..))
import RIO.ByteString qualified as ByteString
import RIO.FilePath (takeExtension)
import System.IO.Unsafe (unsafePerformIO)

import Codec.Compression.Zstd (Decompress)
import Codec.Compression.Zstd qualified as Zstd
import Codec.Compression.Zstd.FFI qualified as ZstdFFI

foreign import ccall safe "ZSTD_decompress"
  decompressInto :: Ptr dst -> CSize -> Ptr src -> CSize -> IO CSize

decompress :: ByteString -> Decompress
decompress bytes =
  unsafePerformIO $
    ByteString.Unsafe.unsafeUseAsCStringLen bytes \(src, srcSize) -> do
      expected <- ZstdFFI.getDecompressedSize src (fromIntegral srcSize)
      if expected == 0 then
        pure Zstd.Skip
      else if expected > fromIntegral (maxBound :: Int) then
        pure $ Zstd.Error "invalid compressed payload size"
      else do
        dst <- ByteString.Internal.mallocByteString (fromIntegral expected)
        Foreign.withForeignPtr dst \dstPtr ->
          ZstdFFI.checkError (decompressInto dstPtr (fromIntegral expected) src (fromIntegral srcSize)) <&> \case
            Left err ->
              Zstd.Error err
            Right size ->
              Zstd.Decompress $ ByteString.Internal.BS dst (fromIntegral size)

-- * Compressed container

newtype Compressed a = Compressed { getCompressed :: a }

compressBytes :: ByteString -> Compressed ByteString
compressBytes = Compressed . Zstd.compress Zstd.maxCLevel

decompressBytes :: Compressed ByteString -> Either CompressedError ByteString
decompressBytes (Compressed bytes) =
  case decompress bytes of
    Zstd.Decompress buf ->
      Right buf
    Zstd.Skip ->
      Right mempty
    Zstd.Error str ->
      Left $ ZstdError (fromString str)

instance Typeable a => Show (Compressed a) where
  show (Compressed x) = "Compressed " <> show (typeOf x)

data CompressedError
  = ZstdError Text
  | EmptyFile FilePath
  deriving (Eq, Show)

instance Exception CompressedError

-- * Loading files

fromFileWith :: MonadIO m => (ByteString -> m b) -> (FilePath -> m b) -> FilePath -> m b
fromFileWith withBS withFilePath filePath
  | elem (takeExtension filePath) compressedExts =
      loadCompressed withBS filePath
  | otherwise =
      withFilePath filePath

loadCompressed :: MonadIO m => (ByteString -> m b) -> FilePath -> m b
loadCompressed withBS filePath = do
  bytes <- ByteString.readFile filePath
  case decompressBytes (Compressed bytes) of
    Right buf ->
      if ByteString.null buf then
        throwIO $ EmptyFile filePath
      else
        withBS buf
    Left err ->
      throwIO err

compressedExts :: [FilePath]
compressedExts =
  [ ".zst"
  , ".zstd"
  ]