mfmts-1.0.0.0: cid/MultiFormats/CID/Internal/CIDDecoder.hs
-- | Module : MultiFormats.CID.Internal.CIDDecoder
-- 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.Internal.CIDDecoder (CIDDecoder (CIDDecoder)) where
import Data.ByteString (ByteString)
import MultiFormats.CID.Errors
import MultiFormats.CID.Internal.CIDVersion (isCIDv0Str)
import MultiFormats.CID.Parser
import MultiFormats.MultiBase (decodeCIDv0, decodeFromPrefix, hasValidPrefix)
-- | Implements decoding CID from String's base encoding.
newtype CIDDecoder = CIDDecoder ByteString
-- | Decodes a CID to bytes.
instance Parser CIDDecoder where
parser str =
let choosedecoder
| null str = Left (InvalidData EmptyCID)
| isCIDv0Str str = Right decodeCIDv0
| hasValidPrefix str = Right decodeFromPrefix
| otherwise = Left (InvalidEncoding UnknownBasePrefix)
in choosedecoder >>= \decoder ->
case decoder str of
Nothing -> Left (InvalidEncoding ImproperDigit)
Just bytes -> Right (CIDDecoder bytes)