-- Compression.hs: OpenPGP (RFC9580) compression conduits
-- Copyright © 2012-2026  Clint Adams
-- This software is released under the terms of the Expat license.
-- (See the LICENSE file).

module Data.Conduit.OpenPGP.Compression
  ( conduitCompress
  , conduitDecompress
  ) where

import Codec.Encryption.OpenPGP.Compression
import Codec.Encryption.OpenPGP.Types
import Control.Monad.Trans.Resource (MonadThrow, throwM)
import Data.Conduit
import qualified Data.Conduit.List as CL

conduitCompress :: MonadThrow m => CompressionAlgorithm -> ConduitT Pkt Pkt m ()
conduitCompress algo = CL.consume >>= \ps -> yield (compressPkts algo ps)

-- | Decompress OpenPGP Compressed Data packets.  Decompression failures,
-- empty payloads, zero-length results, and marker-only payloads are reported
-- via 'MonadThrow' rather than silently dropped.
conduitDecompress :: MonadThrow m => ConduitT Pkt Pkt m ()
conduitDecompress = awaitForever $ \pkt ->
  case decompressPkt pkt of
    Left err   -> throwM (userError (renderCompressionError err))
    Right pkts -> mapM_ yield pkts
