{-# language NamedFieldPuns #-}

module Kafka.TaggedField
  ( TaggedField(..)
  , parser
  , parserMany
  ) where

import Kafka.Parser.Context (Context)
import Data.Bytes.Parser (Parser)
import Data.Primitive (SmallArray)
import Data.Bytes (Bytes)
import Data.Word (Word32)

import qualified Data.Bytes.Parser.Leb128 as Leb128
import qualified Data.Bytes.Parser as Parser
import qualified Kafka.Parser.Context as Ctx
import qualified Kafka.Parser

data TaggedField = TaggedField
  { TaggedField -> Word32
tag :: !Word32
  , TaggedField -> Bytes
contents :: {-# UNPACK #-} !Bytes
  } deriving (Int -> TaggedField -> ShowS
[TaggedField] -> ShowS
TaggedField -> String
(Int -> TaggedField -> ShowS)
-> (TaggedField -> String)
-> ([TaggedField] -> ShowS)
-> Show TaggedField
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> TaggedField -> ShowS
showsPrec :: Int -> TaggedField -> ShowS
$cshow :: TaggedField -> String
show :: TaggedField -> String
$cshowList :: [TaggedField] -> ShowS
showList :: [TaggedField] -> ShowS
Show)

parserMany :: Context -> Parser Context s (SmallArray TaggedField)
parserMany :: forall s. Context -> Parser Context s (SmallArray TaggedField)
parserMany Context
ctx = (Context -> Parser Context s TaggedField)
-> Context -> Parser Context s (SmallArray TaggedField)
forall s a.
(Context -> Parser Context s a)
-> Context -> Parser Context s (SmallArray a)
Kafka.Parser.varintLengthPrefixedArray Context -> Parser Context s TaggedField
forall s. Context -> Parser Context s TaggedField
parser Context
ctx

parser :: Context -> Parser Context s TaggedField
parser :: forall s. Context -> Parser Context s TaggedField
parser Context
ctx = do
  Word32
tag <- Context -> Parser Context s Word32
forall e s. e -> Parser e s Word32
Leb128.word32 (Field -> Context -> Context
Ctx.Field Field
Ctx.TaggedFieldTag Context
ctx)
  Word32
len <- Context -> Parser Context s Word32
forall e s. e -> Parser e s Word32
Leb128.word32 (Field -> Context -> Context
Ctx.Field Field
Ctx.TaggedFieldLength Context
ctx)
  Bytes
contents <- Context -> Int -> Parser Context s Bytes
forall e s. e -> Int -> Parser e s Bytes
Parser.take (Field -> Context -> Context
Ctx.Field Field
Ctx.TaggedFieldContents Context
ctx) (Word32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word32
len)
  TaggedField -> Parser Context s TaggedField
forall a. a -> Parser Context s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure TaggedField{Word32
tag :: Word32
tag :: Word32
tag,Bytes
contents :: Bytes
contents :: Bytes
contents}