packages feed

mfmts-1.1.0.0: cid/MultiFormats/CID/Component/Decoder.hs

-- | Module      : MultiFormats.CID.Component.Decoder
--   Description : Parses CID bytes from a multibase encoded string
--   Copyright   : Zoey McBride (c) 2026
--   License     : AGPL-3.0-or-later
--   Maintainer  : zoeymcbride@mailbox.org
--   Stability   : experimental
module MultiFormats.CID.Component.Decoder (Decoder (Decoder)) where

import Data.BaseSystem.BinaryTranscoder (BinaryTranscoder)
import Data.Text qualified as Text
import MultiFormats.CID.Component.Version (isTextCIDv0)
import MultiFormats.CID.Errors
import MultiFormats.CID.Parser
import MultiFormats.MultiBase.DigitTranscoder (hasValidPrefix)
import MultiFormats.MultiBase.DigitTranscoder qualified as DXC

-- | Implements decoding CID from String's base encoding.
newtype Decoder b = Decoder b

-- | Decodes a CID to bytes.
instance (BinaryTranscoder b) => Parser (Decoder b) where
  parser str =
    let choosedecoder
          | Text.null str = Left (InvalidData EmptyCID)
          | isTextCIDv0 str = Right DXC.decodeCIDv0
          | hasValidPrefix str = Right DXC.decodeFromPrefix
          | otherwise = Left (InvalidEncoding UnknownBasePrefix)
     in choosedecoder >>= \decoder ->
          case decoder str of
            Nothing -> Left (InvalidEncoding ImproperDigit)
            Just bytes -> Right (Decoder bytes)