packages feed

ipldm-1.0.0.0: dagcbor/IPLD/DagCBOR.hs

-- | Module      : IPLD.DagCBOR
--   Description : DagCBOR general utilities
--   Copyright   : Zoey McBride (c) 2026
--   License     : AGPL-3.0-or-later
--   Maintainer  : zoeymcbride@mailbox.org
--   Stability   : experimental
module IPLD.DagCBOR (decodeFile) where

import Data.ByteString.Lazy qualified as LBS
import Data.XCodec.BinaryTranscoder qualified as BXC
import IPLD.DM qualified as DM
import IPLD.DM.Decoder qualified as DM
import IPLD.DagCBOR.Decoder qualified as DagCBOR
import IPLD.DagCBOR.Decoder.Errors

-- | Reads a DAG-CBOR encoded file at filepath and gives back the root node.
decodeFile :: FilePath -> IO (Okay DM.Node)
decodeFile filepath = do
  contents <- LBS.readFile filepath
  return $
    -- Applies the DM decoder as the DagCBOR decoderMethod
    case DagCBOR.decoderMethod DM.decoder contents of
      Left err -> Left err
      Right (Result node trailing)
        | not (BXC.null trailing) -> Left TrailingBytes
        | otherwise -> Right node