packages feed

mfmts-1.2.0.0: cid/MultiFormats/CID/Extractor.hs

-- | Module      : MultiFormats.CID.Extractor
--   Description : Provides extracting types for CID
--   Copyright   : Zoey McBride (c) 2026
--   License     : AGPL-3.0-or-later
--   Maintainer  : zoeymcbride@mailbox.org
--   Stability   : experimental
--
-- This file provides a type-class `Extractor` for extracting CID data from a
-- ByteString. It also provides the type-alias `Extraction` for the function
-- signature of extracting valid data from the top of a ByteString.
module MultiFormats.CID.Extractor
  ( Extractor (extractor),
    Extraction,
  )
where

import Data.Bifunctor (first)
import Control.DeepSeq (force)
import Data.XCodec.BinaryTranscoder (BinaryTranscoder)
import MultiFormats.CID.Errors
import MultiFormats.VarInt (VarInt, extractVarInt)

-- | Alias for `extractor` method. Extracts `a` from ByteString.
type Extraction a t = t -> Okay (a, t)

-- | Generic function signature for extracting CID components.
class (BinaryTranscoder t) => Extractor a t where
  extractor :: t -> Okay (a, t)

-- | Extractor for VarInts in CID data. Converts VarInt.Error to CID.Error.
instance (BinaryTranscoder t) => Extractor VarInt t where
  extractor =
    -- Either reconstruct the either or strictly evaulate into the context.
    either (Left . InvalidVarInt) (Right . first force) . extractVarInt