-- Copyright 2026 Biglup Labs
-- SPDX-License-Identifier: Apache-2.0
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE OverloadedStrings #-}

-- | One CBOR item with its exact encoding preserved. Equality and ordering
-- compare encoded bytes, so different encodings of the same value can differ.
-- Construction checks that the native reader accepts exactly one complete item;
-- it does not enforce canonical encoding, schema rules, tag semantics, or UTF-8
-- validity of arbitrary nested text. 'decodeText' validates UTF-8 explicitly.
--
-- Scalar codecs and ordered collection codecs construct and inspect ordinary
-- Haskell values. Collection encoding preserves the exact bytes of each child.
--
-- @
-- import qualified Cometa.Encoding.Cbor as Cbor
--
-- main :: IO ()
-- main = do
--   result <- Cbor.encodeInteger 42
--   print (Cbor.toHex <$> result)
-- @
module Cometa.Encoding.Cbor
  ( Cbor,

    -- * Import and exact representation
    fromBytes,
    fromHex,
    toBytes,
    toHex,

    -- * Primitive values
    encodeInteger,
    decodeInteger,
    encodeByteString,
    decodeByteString,
    encodeText,
    decodeText,
    encodeBool,
    decodeBool,
    decodeDouble,
    decodeSimple,
    encodeUndefined,

    -- * Ordered collections
    encodeArray,
    decodeArray,
    encodeMap,
    decodeMap,
  )
where

-- IMPORTS --------------------------------------------------------------------

import Cometa.Error (Error (..))
import Cometa.Internal.Error (fromNativeFailure)
import qualified Cometa.Internal.FFI.Cbor as Native
import qualified Cometa.Internal.FFI.Native as Status
import Cometa.Internal.Failure (NativeFailure (..))
import qualified Cometa.Internal.Hex as Hex
import Cometa.Internal.Ownership (copyStaticText, withOwnedOutput)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import Data.Word (Word8)
import Foreign.C.String (CString)
import Foreign.C.Types (CDouble (..), CInt, CSize)
import Foreign.Marshal.Alloc (alloca, allocaBytes)
import Foreign.Ptr (Ptr, castPtr, nullPtr)
import Foreign.Storable (peek, poke)

-- TYPES ----------------------------------------------------------------------

-- | A complete, native-reader-accepted CBOR item. Encoded bytes are retained
-- without normalization. Equality is representation-sensitive; ordering is
-- lexicographic byte ordering. 'Show' is diagnostic, not an interchange format.
newtype Cbor = Cbor ByteString
  deriving (Cbor -> Cbor -> Bool
(Cbor -> Cbor -> Bool) -> (Cbor -> Cbor -> Bool) -> Eq Cbor
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Cbor -> Cbor -> Bool
== :: Cbor -> Cbor -> Bool
$c/= :: Cbor -> Cbor -> Bool
/= :: Cbor -> Cbor -> Bool
Eq, Eq Cbor
Eq Cbor =>
(Cbor -> Cbor -> Ordering)
-> (Cbor -> Cbor -> Bool)
-> (Cbor -> Cbor -> Bool)
-> (Cbor -> Cbor -> Bool)
-> (Cbor -> Cbor -> Bool)
-> (Cbor -> Cbor -> Cbor)
-> (Cbor -> Cbor -> Cbor)
-> Ord Cbor
Cbor -> Cbor -> Bool
Cbor -> Cbor -> Ordering
Cbor -> Cbor -> Cbor
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: Cbor -> Cbor -> Ordering
compare :: Cbor -> Cbor -> Ordering
$c< :: Cbor -> Cbor -> Bool
< :: Cbor -> Cbor -> Bool
$c<= :: Cbor -> Cbor -> Bool
<= :: Cbor -> Cbor -> Bool
$c> :: Cbor -> Cbor -> Bool
> :: Cbor -> Cbor -> Bool
$c>= :: Cbor -> Cbor -> Bool
>= :: Cbor -> Cbor -> Bool
$cmax :: Cbor -> Cbor -> Cbor
max :: Cbor -> Cbor -> Cbor
$cmin :: Cbor -> Cbor -> Cbor
min :: Cbor -> Cbor -> Cbor
Ord, Int -> Cbor -> ShowS
[Cbor] -> ShowS
Cbor -> String
(Int -> Cbor -> ShowS)
-> (Cbor -> String) -> ([Cbor] -> ShowS) -> Show Cbor
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Cbor -> ShowS
showsPrec :: Int -> Cbor -> ShowS
$cshow :: Cbor -> String
show :: Cbor -> String
$cshowList :: [Cbor] -> ShowS
showList :: [Cbor] -> ShowS
Show)

-- DEFINITIONS ----------------------------------------------------------------

-- | Accept exactly one complete item, preserving all input bytes. Empty input,
-- malformed structures and trailing bytes return 'NativeError'. This structural
-- check does not assert schema, tag semantics, canonicality, or nested UTF-8.
-- Allocation and decoding failures return 'NativeError'.
fromBytes :: ByteString -> IO (Either Error Cbor)
fromBytes :: ByteString -> IO (Either Error Cbor)
fromBytes ByteString
bytes = ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error Cbor))
-> IO (Either Error Cbor)
forall value.
ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes ByteString
bytes ((Ptr Word8 -> CSize -> IO (Either Error Cbor))
 -> IO (Either Error Cbor))
-> (Ptr Word8 -> CSize -> IO (Either Error Cbor))
-> IO (Either Error Cbor)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
input CSize
size ->
  (() -> Cbor) -> Either Error () -> Either Error Cbor
forall a b. (a -> b) -> Either Error a -> Either Error b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Cbor -> () -> Cbor
forall a b. a -> b -> a
const (ByteString -> Cbor
Cbor ByteString
bytes)) (Either Error () -> Either Error Cbor)
-> IO (Either Error ()) -> IO (Either Error Cbor)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> (CString -> CSize -> IO NativeCode) -> IO (Either Error ())
runStatus Text
"cbor.fromBytes" (Ptr Word8 -> CSize -> CString -> CSize -> IO NativeCode
Native.cValidate Ptr Word8
input CSize
size)

-- | Accept nonempty, even-length ASCII hexadecimal text in either case, with
-- no whitespace or prefix, then perform 'fromBytes' validation. Malformed hex
-- returns 'InvalidHex'. The resulting bytes retain their original CBOR form.
fromHex :: Text -> IO (Either Error Cbor)
fromHex :: Text -> IO (Either Error Cbor)
fromHex Text
text
  | Text -> Bool
Text.null Text
text = Either Error Cbor -> IO (Either Error Cbor)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Cbor
forall a b. a -> Either a b
Left Error
InvalidHex)
  | Bool
otherwise = IO (Either Error Cbor)
-> (ByteString -> IO (Either Error Cbor))
-> Maybe ByteString
-> IO (Either Error Cbor)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Either Error Cbor -> IO (Either Error Cbor)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Cbor
forall a b. a -> Either a b
Left Error
InvalidHex)) ByteString -> IO (Either Error Cbor)
fromBytes (Text -> Maybe ByteString
Hex.decodeHex Text
text)

-- | Retrieve the exact encoded item bytes without normalization.
toBytes :: Cbor -> ByteString
toBytes :: Cbor -> ByteString
toBytes (Cbor ByteString
bytes) = ByteString
bytes

-- | Encode the exact item bytes as lowercase ASCII hex, without a prefix.
toHex :: Cbor -> Text
toHex :: Cbor -> Text
toHex = ByteString -> Text
Hex.encodeHex (ByteString -> Text) -> (Cbor -> ByteString) -> Cbor -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Cbor -> ByteString
toBytes

-- | Encode an untagged primitive integer using the shortest native encoding.
-- The supported inclusive range is @-2^64@ through @2^64 - 1@. Values outside
-- this range return 'InvalidCborInteger'; tagged bignums are not encoded here.
encodeInteger :: Integer -> IO (Either Error Cbor)
encodeInteger :: Integer -> IO (Either Error Cbor)
encodeInteger Integer
value
  | Integer
value Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer -> Integer
forall a. Num a => a -> a
negate (Integer
2 Integer -> Int -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
^ (Int
64 :: Int)) Bool -> Bool -> Bool
|| Integer
value Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Integer
2 Integer -> Int -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
^ (Int
64 :: Int) = Either Error Cbor -> IO (Either Error Cbor)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Cbor
forall a b. a -> Either a b
Left (Integer -> Error
InvalidCborInteger Integer
value))
  | Bool
otherwise = Text
-> (Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode)
-> IO (Either Error Cbor)
encodeResult Text
"cbor.encodeInteger" (CInt
-> Word64
-> Ptr (Ptr NativeBuffer)
-> CString
-> CSize
-> IO NativeCode
Native.cEncodeInteger (Bool -> CInt
flag (Integer
value Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
0)) Word64
argument)
  where
    argument :: Word64
argument = Integer -> Word64
forall a. Num a => Integer -> a
fromInteger (if Integer
value Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
0 then Integer -> Integer
forall a. Num a => a -> a
negate Integer
value Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
1 else Integer
value)

-- | Decode an untagged primitive integer exactly, including the full unsigned
-- and negative 64-bit CBOR ranges. Tagged bignums and other types return
-- 'NativeError'. Nonminimal integer encodings are accepted without modification.
decodeInteger :: Cbor -> IO (Either Error Integer)
decodeInteger :: Cbor -> IO (Either Error Integer)
decodeInteger Cbor
cbor = ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error Integer))
-> IO (Either Error Integer)
forall value.
ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes (Cbor -> ByteString
toBytes Cbor
cbor) ((Ptr Word8 -> CSize -> IO (Either Error Integer))
 -> IO (Either Error Integer))
-> (Ptr Word8 -> CSize -> IO (Either Error Integer))
-> IO (Either Error Integer)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
input CSize
size ->
  (Ptr CInt -> IO (Either Error Integer))
-> IO (Either Error Integer)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr CInt -> IO (Either Error Integer))
 -> IO (Either Error Integer))
-> (Ptr CInt -> IO (Either Error Integer))
-> IO (Either Error Integer)
forall a b. (a -> b) -> a -> b
$ \Ptr CInt
negative -> (Ptr Word64 -> IO (Either Error Integer))
-> IO (Either Error Integer)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr Word64 -> IO (Either Error Integer))
 -> IO (Either Error Integer))
-> (Ptr Word64 -> IO (Either Error Integer))
-> IO (Either Error Integer)
forall a b. (a -> b) -> a -> b
$ \Ptr Word64
argument ->
    (CString -> CSize -> IO (Either NativeFailure Integer))
-> IO (Either Error Integer)
forall value.
(CString -> CSize -> IO (Either NativeFailure value))
-> IO (Either Error value)
withDiagnostic ((CString -> CSize -> IO (Either NativeFailure Integer))
 -> IO (Either Error Integer))
-> (CString -> CSize -> IO (Either NativeFailure Integer))
-> IO (Either Error Integer)
forall a b. (a -> b) -> a -> b
$ \CString
diagnostic CSize
capacity -> do
      NativeCode
code <- Ptr Word8
-> CSize
-> Ptr CInt
-> Ptr Word64
-> CString
-> CSize
-> IO NativeCode
Native.cDecodeInteger Ptr Word8
input CSize
size Ptr CInt
negative Ptr Word64
argument CString
diagnostic CSize
capacity
      Text
-> NativeCode -> IO Integer -> IO (Either NativeFailure Integer)
forall value.
Text -> NativeCode -> IO value -> IO (Either NativeFailure value)
statusResult Text
"cbor.decodeInteger" NativeCode
code (IO Integer -> IO (Either NativeFailure Integer))
-> IO Integer -> IO (Either NativeFailure Integer)
forall a b. (a -> b) -> a -> b
$ do
        CInt
sign <- Ptr CInt -> IO CInt
forall a. Storable a => Ptr a -> IO a
peek Ptr CInt
negative
        Integer
magnitude <- Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Word64 -> Integer) -> IO Word64 -> IO Integer
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Ptr Word64 -> IO Word64
forall a. Storable a => Ptr a -> IO a
peek Ptr Word64
argument
        Integer -> IO Integer
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (if CInt
sign CInt -> CInt -> Bool
forall a. Eq a => a -> a -> Bool
/= CInt
0 then Integer -> Integer
forall a. Num a => a -> a
negate Integer
magnitude Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
1 else Integer
magnitude)

-- | Encode bytes as a definite-length CBOR byte string. Empty bytes are valid.
encodeByteString :: ByteString -> IO (Either Error Cbor)
encodeByteString :: ByteString -> IO (Either Error Cbor)
encodeByteString = Text -> Bool -> ByteString -> IO (Either Error Cbor)
encodeString Text
"cbor.encodeByteString" Bool
False

-- | Decode a CBOR byte string, concatenating indefinite-length chunks in order.
-- Empty strings are valid. Other types return 'NativeError'.
decodeByteString :: Cbor -> IO (Either Error ByteString)
decodeByteString :: Cbor -> IO (Either Error ByteString)
decodeByteString = Text -> Bool -> Cbor -> IO (Either Error ByteString)
decodeString Text
"cbor.decodeByteString" Bool
False

-- | Encode Unicode text as one definite-length UTF-8 CBOR text string.
-- Empty text and embedded NUL characters are preserved.
encodeText :: Text -> IO (Either Error Cbor)
encodeText :: Text -> IO (Either Error Cbor)
encodeText = Text -> Bool -> ByteString -> IO (Either Error Cbor)
encodeString Text
"cbor.encodeText" Bool
True (ByteString -> IO (Either Error Cbor))
-> (Text -> ByteString) -> Text -> IO (Either Error Cbor)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> ByteString
Text.encodeUtf8

-- | Decode a CBOR text string and validate UTF-8. Each indefinite-length
-- chunk must independently contain valid UTF-8; multibyte sequences cannot span
-- chunk boundaries. Invalid UTF-8 returns 'InvalidCborUtf8'; structural or type
-- failures return 'NativeError'. Empty text and embedded NUL characters survive.
decodeText :: Cbor -> IO (Either Error Text)
decodeText :: Cbor -> IO (Either Error Text)
decodeText Cbor
cbor = case ByteString -> Maybe (Word8, ByteString)
ByteString.uncons (Cbor -> ByteString
toBytes Cbor
cbor) of
  Just (Word8
127, ByteString
body) -> case ByteString -> Maybe (ByteString, Word8)
ByteString.unsnoc ByteString
body of
    Just (ByteString
interior, Word8
255) -> do
      Either Error [Cbor]
chunks <- ByteString -> IO (Either Error [Cbor])
readTextChunks ByteString
interior
      case Either Error [Cbor]
chunks of
        Left Error
failure -> Either Error Text -> IO (Either Error Text)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Text
forall a b. a -> Either a b
Left Error
failure)
        Right [Cbor]
values -> [Text] -> [Cbor] -> IO (Either Error Text)
decodeTextValues [] [Cbor]
values
    Maybe (ByteString, Word8)
_ -> Either Error Text -> IO (Either Error Text)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Text
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"cbor.decodeText"))
  Maybe (Word8, ByteString)
_ -> Cbor -> IO (Either Error Text)
decodeTextValue Cbor
cbor

-- | Encode a Boolean as its native CBOR simple value.
encodeBool :: Bool -> IO (Either Error Cbor)
encodeBool :: Bool -> IO (Either Error Cbor)
encodeBool Bool
value = Text
-> (Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode)
-> IO (Either Error Cbor)
encodeResult Text
"cbor.encodeBool" (CInt -> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode
Native.cEncodeBool (Bool -> CInt
flag Bool
value))

-- | Decode an untagged Boolean. Null, undefined and other types return 'NativeError'.
decodeBool :: Cbor -> IO (Either Error Bool)
decodeBool :: Cbor -> IO (Either Error Bool)
decodeBool Cbor
cbor = ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error Bool))
-> IO (Either Error Bool)
forall value.
ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes (Cbor -> ByteString
toBytes Cbor
cbor) ((Ptr Word8 -> CSize -> IO (Either Error Bool))
 -> IO (Either Error Bool))
-> (Ptr Word8 -> CSize -> IO (Either Error Bool))
-> IO (Either Error Bool)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
input CSize
size -> (Ptr CInt -> IO (Either Error Bool)) -> IO (Either Error Bool)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr CInt -> IO (Either Error Bool)) -> IO (Either Error Bool))
-> (Ptr CInt -> IO (Either Error Bool)) -> IO (Either Error Bool)
forall a b. (a -> b) -> a -> b
$ \Ptr CInt
output ->
  (CString -> CSize -> IO (Either NativeFailure Bool))
-> IO (Either Error Bool)
forall value.
(CString -> CSize -> IO (Either NativeFailure value))
-> IO (Either Error value)
withDiagnostic ((CString -> CSize -> IO (Either NativeFailure Bool))
 -> IO (Either Error Bool))
-> (CString -> CSize -> IO (Either NativeFailure Bool))
-> IO (Either Error Bool)
forall a b. (a -> b) -> a -> b
$ \CString
diagnostic CSize
capacity -> do
    NativeCode
code <- Ptr Word8 -> CSize -> Ptr CInt -> CString -> CSize -> IO NativeCode
Native.cDecodeBool Ptr Word8
input CSize
size Ptr CInt
output CString
diagnostic CSize
capacity
    Text -> NativeCode -> IO Bool -> IO (Either NativeFailure Bool)
forall value.
Text -> NativeCode -> IO value -> IO (Either NativeFailure value)
statusResult Text
"cbor.decodeBool" NativeCode
code ((CInt -> CInt -> Bool
forall a. Eq a => a -> a -> Bool
/= CInt
0) (CInt -> Bool) -> IO CInt -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Ptr CInt -> IO CInt
forall a. Storable a => Ptr a -> IO a
peek Ptr CInt
output)

-- | Decode an untagged IEEE half-, single- or double-precision value as a
-- 'Double'. Signed zero, infinities and NaN are accepted. Integer items are not
-- coerced to floating point; other types return 'NativeError'. The original
-- encoding remains unchanged. NaN payload bits are not an interchange guarantee.
decodeDouble :: Cbor -> IO (Either Error Double)
decodeDouble :: Cbor -> IO (Either Error Double)
decodeDouble Cbor
cbor = ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error Double))
-> IO (Either Error Double)
forall value.
ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes (Cbor -> ByteString
toBytes Cbor
cbor) ((Ptr Word8 -> CSize -> IO (Either Error Double))
 -> IO (Either Error Double))
-> (Ptr Word8 -> CSize -> IO (Either Error Double))
-> IO (Either Error Double)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
input CSize
size -> (Ptr CDouble -> IO (Either Error Double))
-> IO (Either Error Double)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr CDouble -> IO (Either Error Double))
 -> IO (Either Error Double))
-> (Ptr CDouble -> IO (Either Error Double))
-> IO (Either Error Double)
forall a b. (a -> b) -> a -> b
$ \Ptr CDouble
output ->
  (CString -> CSize -> IO (Either NativeFailure Double))
-> IO (Either Error Double)
forall value.
(CString -> CSize -> IO (Either NativeFailure value))
-> IO (Either Error value)
withDiagnostic ((CString -> CSize -> IO (Either NativeFailure Double))
 -> IO (Either Error Double))
-> (CString -> CSize -> IO (Either NativeFailure Double))
-> IO (Either Error Double)
forall a b. (a -> b) -> a -> b
$ \CString
diagnostic CSize
capacity -> do
    NativeCode
code <- Ptr Word8
-> CSize -> Ptr CDouble -> CString -> CSize -> IO NativeCode
Native.cDecodeDouble Ptr Word8
input CSize
size Ptr CDouble
output CString
diagnostic CSize
capacity
    Text -> NativeCode -> IO Double -> IO (Either NativeFailure Double)
forall value.
Text -> NativeCode -> IO value -> IO (Either NativeFailure value)
statusResult Text
"cbor.decodeDouble" NativeCode
code ((\(CDouble Double
value) -> Double
value) (CDouble -> Double) -> IO CDouble -> IO Double
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Ptr CDouble -> IO CDouble
forall a. Storable a => Ptr a -> IO a
peek Ptr CDouble
output)

-- | Decode the number of a simple value: false is 20, true is 21, null is 22
-- and undefined is 23. Unassigned byte values and nonminimal two-byte encodings
-- accepted by the reader are retained. Floating-point and other major types
-- return 'NativeError'. This does not interpret application-specific meanings.
decodeSimple :: Cbor -> IO (Either Error Word8)
decodeSimple :: Cbor -> IO (Either Error Word8)
decodeSimple Cbor
cbor = ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error Word8))
-> IO (Either Error Word8)
forall value.
ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes (Cbor -> ByteString
toBytes Cbor
cbor) ((Ptr Word8 -> CSize -> IO (Either Error Word8))
 -> IO (Either Error Word8))
-> (Ptr Word8 -> CSize -> IO (Either Error Word8))
-> IO (Either Error Word8)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
input CSize
size -> (Ptr Word8 -> IO (Either Error Word8)) -> IO (Either Error Word8)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr Word8 -> IO (Either Error Word8)) -> IO (Either Error Word8))
-> (Ptr Word8 -> IO (Either Error Word8))
-> IO (Either Error Word8)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
output ->
  (CString -> CSize -> IO (Either NativeFailure Word8))
-> IO (Either Error Word8)
forall value.
(CString -> CSize -> IO (Either NativeFailure value))
-> IO (Either Error value)
withDiagnostic ((CString -> CSize -> IO (Either NativeFailure Word8))
 -> IO (Either Error Word8))
-> (CString -> CSize -> IO (Either NativeFailure Word8))
-> IO (Either Error Word8)
forall a b. (a -> b) -> a -> b
$ \CString
diagnostic CSize
capacity -> do
    NativeCode
code <- Ptr Word8
-> CSize -> Ptr Word8 -> CString -> CSize -> IO NativeCode
Native.cDecodeSimple Ptr Word8
input CSize
size Ptr Word8
output CString
diagnostic CSize
capacity
    Text -> NativeCode -> IO Word8 -> IO (Either NativeFailure Word8)
forall value.
Text -> NativeCode -> IO value -> IO (Either NativeFailure value)
statusResult Text
"cbor.decodeSimple" NativeCode
code (Ptr Word8 -> IO Word8
forall a. Storable a => Ptr a -> IO a
peek Ptr Word8
output)

-- | Encode CBOR undefined (@f7@), distinct from null, an absent field and false.
-- Use 'decodeSimple' to inspect its simple-value number, 23.
encodeUndefined :: IO (Either Error Cbor)
encodeUndefined :: IO (Either Error Cbor)
encodeUndefined = Text
-> (Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode)
-> IO (Either Error Cbor)
encodeResult Text
"cbor.encodeUndefined" Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode
Native.cEncodeUndefined

-- | Encode an array in list order with a definite-length outer encoding.
-- Every child's bytes remain exact, including nonminimal or indefinite forms.
encodeArray :: [Cbor] -> IO (Either Error Cbor)
encodeArray :: [Cbor] -> IO (Either Error Cbor)
encodeArray [Cbor]
items = Text -> Bool -> Int -> [Cbor] -> IO (Either Error Cbor)
encodeCollection Text
"cbor.encodeArray" Bool
False ([Cbor] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Cbor]
items) [Cbor]
items

-- | Decode a definite or indefinite array into its ordered encoded children.
-- Child bytes remain exact. Other types return 'NativeError'.
decodeArray :: Cbor -> IO (Either Error [Cbor])
decodeArray :: Cbor -> IO (Either Error [Cbor])
decodeArray = Text -> Bool -> Cbor -> IO (Either Error [Cbor])
decodeCollection Text
"cbor.decodeArray" Bool
False

-- | Encode map entries in list order, preserving duplicate keys. The outer
-- map uses definite length; every encoded key and value remains byte-exact.
-- No sorting, key deduplication, or schema validation is performed.
encodeMap :: [(Cbor, Cbor)] -> IO (Either Error Cbor)
encodeMap :: [(Cbor, Cbor)] -> IO (Either Error Cbor)
encodeMap [(Cbor, Cbor)]
entries = Text -> Bool -> Int -> [Cbor] -> IO (Either Error Cbor)
encodeCollection Text
"cbor.encodeMap" Bool
True ([(Cbor, Cbor)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Cbor, Cbor)]
entries) (((Cbor, Cbor) -> [Cbor]) -> [(Cbor, Cbor)] -> [Cbor]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\(Cbor
key, Cbor
value) -> [Cbor
key, Cbor
value]) [(Cbor, Cbor)]
entries)

-- | Decode a definite or indefinite map into ordered key/value pairs,
-- preserving duplicate keys and each child's exact encoding. Other types
-- return 'NativeError'. Missing values are structural decoding failures.
decodeMap :: Cbor -> IO (Either Error [(Cbor, Cbor)])
decodeMap :: Cbor -> IO (Either Error [(Cbor, Cbor)])
decodeMap Cbor
cbor = do
  Either Error [Cbor]
result <- Text -> Bool -> Cbor -> IO (Either Error [Cbor])
decodeCollection Text
"cbor.decodeMap" Bool
True Cbor
cbor
  Either Error [(Cbor, Cbor)] -> IO (Either Error [(Cbor, Cbor)])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error [Cbor]
result Either Error [Cbor]
-> ([Cbor] -> Either Error [(Cbor, Cbor)])
-> Either Error [(Cbor, Cbor)]
forall a b.
Either Error a -> (a -> Either Error b) -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= [(Cbor, Cbor)] -> [Cbor] -> Either Error [(Cbor, Cbor)]
forall {b}. [(b, b)] -> [b] -> Either Error [(b, b)]
pairEntries [])
  where
    pairEntries :: [(b, b)] -> [b] -> Either Error [(b, b)]
pairEntries [(b, b)]
accumulated [] = [(b, b)] -> Either Error [(b, b)]
forall a b. b -> Either a b
Right ([(b, b)] -> [(b, b)]
forall a. [a] -> [a]
reverse [(b, b)]
accumulated)
    pairEntries [(b, b)]
accumulated (b
key : b
value : [b]
rest) = [(b, b)] -> [b] -> Either Error [(b, b)]
pairEntries ((b
key, b
value) (b, b) -> [(b, b)] -> [(b, b)]
forall a. a -> [a] -> [a]
: [(b, b)]
accumulated) [b]
rest
    pairEntries [(b, b)]
_ [b
_] = Error -> Either Error [(b, b)]
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"cbor.decodeMap")

-- | Validate chunks one at a time, stopping at the first failure. Only copied
-- Haskell values remain live while the final text is concatenated.
decodeTextValues :: [Text] -> [Cbor] -> IO (Either Error Text)
decodeTextValues :: [Text] -> [Cbor] -> IO (Either Error Text)
decodeTextValues [Text]
accumulated [] = Either Error Text -> IO (Either Error Text)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text -> Either Error Text
forall a b. b -> Either a b
Right ([Text] -> Text
Text.concat ([Text] -> [Text]
forall a. [a] -> [a]
reverse [Text]
accumulated)))
decodeTextValues [Text]
accumulated (Cbor
value : [Cbor]
rest) = do
  Either Error Text
result <- Cbor -> IO (Either Error Text)
decodeTextValue Cbor
value
  case Either Error Text
result of
    Left Error
failure -> Either Error Text -> IO (Either Error Text)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Text
forall a b. a -> Either a b
Left Error
failure)
    Right Text
text -> [Text] -> [Cbor] -> IO (Either Error Text)
decodeTextValues (Text
text Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: [Text]
accumulated) [Cbor]
rest

-- | Check UTF-8 after the native text buffer has been copied and released.
decodeTextValue :: Cbor -> IO (Either Error Text)
decodeTextValue :: Cbor -> IO (Either Error Text)
decodeTextValue Cbor
cbor = do
  Either Error ByteString
result <- Text -> Bool -> Cbor -> IO (Either Error ByteString)
decodeString Text
"cbor.decodeText" Bool
True Cbor
cbor
  Either Error Text -> IO (Either Error Text)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error Text -> IO (Either Error Text))
-> Either Error Text -> IO (Either Error Text)
forall a b. (a -> b) -> a -> b
$ case Either Error ByteString
result of
    Left Error
failure -> Error -> Either Error Text
forall a b. a -> Either a b
Left Error
failure
    Right ByteString
bytes -> case ByteString -> Either UnicodeException Text
Text.decodeUtf8' ByteString
bytes of
      Left UnicodeException
_ -> Error -> Either Error Text
forall a b. a -> Either a b
Left Error
InvalidCborUtf8
      Right Text
text -> Text -> Either Error Text
forall a b. b -> Either a b
Right Text
text

encodeString :: Text -> Bool -> ByteString -> IO (Either Error Cbor)
encodeString :: Text -> Bool -> ByteString -> IO (Either Error Cbor)
encodeString Text
operation Bool
text ByteString
bytes = ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error Cbor))
-> IO (Either Error Cbor)
forall value.
ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes ByteString
bytes ((Ptr Word8 -> CSize -> IO (Either Error Cbor))
 -> IO (Either Error Cbor))
-> (Ptr Word8 -> CSize -> IO (Either Error Cbor))
-> IO (Either Error Cbor)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
input CSize
size ->
  Text
-> (Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode)
-> IO (Either Error Cbor)
encodeResult Text
operation (CInt
-> Ptr Word8
-> CSize
-> Ptr (Ptr NativeBuffer)
-> CString
-> CSize
-> IO NativeCode
Native.cEncodeString (Bool -> CInt
flag Bool
text) Ptr Word8
input CSize
size)

decodeString :: Text -> Bool -> Cbor -> IO (Either Error ByteString)
decodeString :: Text -> Bool -> Cbor -> IO (Either Error ByteString)
decodeString Text
operation Bool
text Cbor
cbor = ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall value.
ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes (Cbor -> ByteString
toBytes Cbor
cbor) ((Ptr Word8 -> CSize -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr Word8 -> CSize -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
input CSize
size ->
  (CString -> CSize -> IO (Either NativeFailure ByteString))
-> IO (Either Error ByteString)
forall value.
(CString -> CSize -> IO (Either NativeFailure value))
-> IO (Either Error value)
withDiagnostic ((CString -> CSize -> IO (Either NativeFailure ByteString))
 -> IO (Either Error ByteString))
-> (CString -> CSize -> IO (Either NativeFailure ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \CString
diagnostic CSize
capacity ->
    Text
-> (Ptr (Ptr NativeBuffer) -> IO NativeCode)
-> IO (Either NativeFailure ByteString)
copyBuffer Text
operation (\Ptr (Ptr NativeBuffer)
output -> CInt
-> Ptr Word8
-> CSize
-> Ptr (Ptr NativeBuffer)
-> CString
-> CSize
-> IO NativeCode
Native.cDecodeString (Bool -> CInt
flag Bool
text) Ptr Word8
input CSize
size Ptr (Ptr NativeBuffer)
output CString
diagnostic CSize
capacity)

encodeCollection :: Text -> Bool -> Int -> [Cbor] -> IO (Either Error Cbor)
encodeCollection :: Text -> Bool -> Int -> [Cbor] -> IO (Either Error Cbor)
encodeCollection Text
operation Bool
mapEntries Int
count [Cbor]
items =
  ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error Cbor))
-> IO (Either Error Cbor)
forall value.
ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes ([ByteString] -> ByteString
ByteString.concat ((Cbor -> ByteString) -> [Cbor] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map Cbor -> ByteString
toBytes [Cbor]
items)) ((Ptr Word8 -> CSize -> IO (Either Error Cbor))
 -> IO (Either Error Cbor))
-> (Ptr Word8 -> CSize -> IO (Either Error Cbor))
-> IO (Either Error Cbor)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
input CSize
size ->
    Text
-> (Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode)
-> IO (Either Error Cbor)
encodeResult Text
operation (CInt
-> CSize
-> Ptr Word8
-> CSize
-> Ptr (Ptr NativeBuffer)
-> CString
-> CSize
-> IO NativeCode
Native.cEncodeCollection (Bool -> CInt
flag Bool
mapEntries) (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
count) Ptr Word8
input CSize
size)

-- | Keep one reader alive through the complete cursor loop. Each child buffer
-- is copied and released before the next iteration; one end-state slot is reused.
decodeCollection :: Text -> Bool -> Cbor -> IO (Either Error [Cbor])
decodeCollection :: Text -> Bool -> Cbor -> IO (Either Error [Cbor])
decodeCollection Text
operation Bool
mapEntries Cbor
cbor = ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error [Cbor]))
-> IO (Either Error [Cbor])
forall value.
ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes (Cbor -> ByteString
toBytes Cbor
cbor) ((Ptr Word8 -> CSize -> IO (Either Error [Cbor]))
 -> IO (Either Error [Cbor]))
-> (Ptr Word8 -> CSize -> IO (Either Error [Cbor]))
-> IO (Either Error [Cbor])
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
input CSize
size ->
  (CString -> CSize -> IO (Either NativeFailure [Cbor]))
-> IO (Either Error [Cbor])
forall value.
(CString -> CSize -> IO (Either NativeFailure value))
-> IO (Either Error value)
withDiagnostic ((CString -> CSize -> IO (Either NativeFailure [Cbor]))
 -> IO (Either Error [Cbor]))
-> (CString -> CSize -> IO (Either NativeFailure [Cbor]))
-> IO (Either Error [Cbor])
forall a b. (a -> b) -> a -> b
$ \CString
diagnostic CSize
capacity ->
    Text
-> (Ptr (Ptr NativeReader) -> IO ())
-> (Ptr (Ptr NativeReader) -> IO NativeCode)
-> (Ptr NativeReader -> IO (Either NativeFailure [Cbor]))
-> IO (Either NativeFailure [Cbor])
forall native value.
Text
-> (Ptr (Ptr native) -> IO ())
-> (Ptr (Ptr native) -> IO NativeCode)
-> (Ptr native -> IO (Either NativeFailure value))
-> IO (Either NativeFailure value)
withOwnedOutput Text
operation Ptr (Ptr NativeReader) -> IO ()
Native.cReaderUnref (\Ptr (Ptr NativeReader)
output -> Ptr Word8
-> CSize
-> Ptr (Ptr NativeReader)
-> CString
-> CSize
-> IO NativeCode
Native.cReaderNew Ptr Word8
input CSize
size Ptr (Ptr NativeReader)
output CString
diagnostic CSize
capacity) ((Ptr NativeReader -> IO (Either NativeFailure [Cbor]))
 -> IO (Either NativeFailure [Cbor]))
-> (Ptr NativeReader -> IO (Either NativeFailure [Cbor]))
-> IO (Either NativeFailure [Cbor])
forall a b. (a -> b) -> a -> b
$ \Ptr NativeReader
reader -> do
      NativeCode
code <- Ptr NativeReader -> CInt -> CString -> CSize -> IO NativeCode
Native.cCollectionStart Ptr NativeReader
reader (Bool -> CInt
flag Bool
mapEntries) CString
diagnostic CSize
capacity
      if NativeCode
code NativeCode -> NativeCode -> Bool
forall a. Eq a => a -> a -> Bool
/= NativeCode
Status.success
        then Text -> NativeCode -> IO [Cbor] -> IO (Either NativeFailure [Cbor])
forall value.
Text -> NativeCode -> IO value -> IO (Either NativeFailure value)
statusResult Text
operation NativeCode
code ([Cbor] -> IO [Cbor]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [])
        else (Ptr CInt -> IO (Either NativeFailure [Cbor]))
-> IO (Either NativeFailure [Cbor])
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr CInt -> IO (Either NativeFailure [Cbor]))
 -> IO (Either NativeFailure [Cbor]))
-> (Ptr CInt -> IO (Either NativeFailure [Cbor]))
-> IO (Either NativeFailure [Cbor])
forall a b. (a -> b) -> a -> b
$ \Ptr CInt
atEnd -> Ptr NativeReader
-> CString
-> CSize
-> Ptr CInt
-> [Cbor]
-> IO (Either NativeFailure [Cbor])
readChildren Ptr NativeReader
reader CString
diagnostic CSize
capacity Ptr CInt
atEnd []
  where
    readChildren :: Ptr NativeReader
-> CString
-> CSize
-> Ptr CInt
-> [Cbor]
-> IO (Either NativeFailure [Cbor])
readChildren Ptr NativeReader
reader CString
diagnostic CSize
capacity Ptr CInt
atEnd [Cbor]
accumulated = do
      NativeCode
code <- Ptr NativeReader
-> CInt -> Ptr CInt -> CString -> CSize -> IO NativeCode
Native.cCollectionAtEnd Ptr NativeReader
reader (Bool -> CInt
flag Bool
mapEntries) Ptr CInt
atEnd CString
diagnostic CSize
capacity
      if NativeCode
code NativeCode -> NativeCode -> Bool
forall a. Eq a => a -> a -> Bool
/= NativeCode
Status.success
        then Text -> NativeCode -> IO [Cbor] -> IO (Either NativeFailure [Cbor])
forall value.
Text -> NativeCode -> IO value -> IO (Either NativeFailure value)
statusResult Text
operation NativeCode
code ([Cbor] -> IO [Cbor]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [])
        else do
          Bool
finished <- (CInt -> CInt -> Bool
forall a. Eq a => a -> a -> Bool
/= CInt
0) (CInt -> Bool) -> IO CInt -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Ptr CInt -> IO CInt
forall a. Storable a => Ptr a -> IO a
peek Ptr CInt
atEnd
          if Bool
finished
            then do
              NativeCode
endCode <- Ptr NativeReader -> CInt -> CString -> CSize -> IO NativeCode
Native.cCollectionEnd Ptr NativeReader
reader (Bool -> CInt
flag Bool
mapEntries) CString
diagnostic CSize
capacity
              Text -> NativeCode -> IO [Cbor] -> IO (Either NativeFailure [Cbor])
forall value.
Text -> NativeCode -> IO value -> IO (Either NativeFailure value)
statusResult Text
operation NativeCode
endCode ([Cbor] -> IO [Cbor]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Cbor] -> [Cbor]
forall a. [a] -> [a]
reverse [Cbor]
accumulated))
            else do
              Either NativeFailure ByteString
child <- Text
-> (Ptr (Ptr NativeBuffer) -> IO NativeCode)
-> IO (Either NativeFailure ByteString)
copyBuffer Text
operation (\Ptr (Ptr NativeBuffer)
output -> Ptr NativeReader
-> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode
Native.cReadItem Ptr NativeReader
reader Ptr (Ptr NativeBuffer)
output CString
diagnostic CSize
capacity)
              case Either NativeFailure ByteString
child of
                Left NativeFailure
failure -> Either NativeFailure [Cbor] -> IO (Either NativeFailure [Cbor])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (NativeFailure -> Either NativeFailure [Cbor]
forall a b. a -> Either a b
Left NativeFailure
failure)
                Right ByteString
bytes -> Ptr NativeReader
-> CString
-> CSize
-> Ptr CInt
-> [Cbor]
-> IO (Either NativeFailure [Cbor])
readChildren Ptr NativeReader
reader CString
diagnostic CSize
capacity Ptr CInt
atEnd (ByteString -> Cbor
Cbor ByteString
bytes Cbor -> [Cbor] -> [Cbor]
forall a. a -> [a] -> [a]
: [Cbor]
accumulated)

-- | Re-read the interior of a validated indefinite text item as definite text
-- chunks. Each copied chunk outlives its native buffer; one scoped reader owns
-- the cursor. A decreasing byte count prevents a non-advancing native loop.
readTextChunks :: ByteString -> IO (Either Error [Cbor])
readTextChunks :: ByteString -> IO (Either Error [Cbor])
readTextChunks ByteString
bytes
  | ByteString -> Bool
ByteString.null ByteString
bytes = Either Error [Cbor] -> IO (Either Error [Cbor])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Cbor] -> Either Error [Cbor]
forall a b. b -> Either a b
Right [])
  | Bool
otherwise = ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error [Cbor]))
-> IO (Either Error [Cbor])
forall value.
ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes ByteString
bytes ((Ptr Word8 -> CSize -> IO (Either Error [Cbor]))
 -> IO (Either Error [Cbor]))
-> (Ptr Word8 -> CSize -> IO (Either Error [Cbor]))
-> IO (Either Error [Cbor])
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
input CSize
size ->
      (CString -> CSize -> IO (Either NativeFailure [Cbor]))
-> IO (Either Error [Cbor])
forall value.
(CString -> CSize -> IO (Either NativeFailure value))
-> IO (Either Error value)
withDiagnostic ((CString -> CSize -> IO (Either NativeFailure [Cbor]))
 -> IO (Either Error [Cbor]))
-> (CString -> CSize -> IO (Either NativeFailure [Cbor]))
-> IO (Either Error [Cbor])
forall a b. (a -> b) -> a -> b
$ \CString
diagnostic CSize
capacity ->
        Text
-> (Ptr (Ptr NativeReader) -> IO ())
-> (Ptr (Ptr NativeReader) -> IO NativeCode)
-> (Ptr NativeReader -> IO (Either NativeFailure [Cbor]))
-> IO (Either NativeFailure [Cbor])
forall native value.
Text
-> (Ptr (Ptr native) -> IO ())
-> (Ptr (Ptr native) -> IO NativeCode)
-> (Ptr native -> IO (Either NativeFailure value))
-> IO (Either NativeFailure value)
withOwnedOutput Text
"cbor.decodeText" Ptr (Ptr NativeReader) -> IO ()
Native.cReaderUnref (\Ptr (Ptr NativeReader)
output -> Ptr Word8
-> CSize
-> Ptr (Ptr NativeReader)
-> CString
-> CSize
-> IO NativeCode
Native.cReaderNew Ptr Word8
input CSize
size Ptr (Ptr NativeReader)
output CString
diagnostic CSize
capacity) ((Ptr NativeReader -> IO (Either NativeFailure [Cbor]))
 -> IO (Either NativeFailure [Cbor]))
-> (Ptr NativeReader -> IO (Either NativeFailure [Cbor]))
-> IO (Either NativeFailure [Cbor])
forall a b. (a -> b) -> a -> b
$ \Ptr NativeReader
reader ->
          (Ptr CSize -> IO (Either NativeFailure [Cbor]))
-> IO (Either NativeFailure [Cbor])
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr CSize -> IO (Either NativeFailure [Cbor]))
 -> IO (Either NativeFailure [Cbor]))
-> (Ptr CSize -> IO (Either NativeFailure [Cbor]))
-> IO (Either NativeFailure [Cbor])
forall a b. (a -> b) -> a -> b
$ \Ptr CSize
remaining -> Ptr NativeReader
-> CString
-> CSize
-> Ptr CSize
-> Maybe CSize
-> [Cbor]
-> IO (Either NativeFailure [Cbor])
readChunks Ptr NativeReader
reader CString
diagnostic CSize
capacity Ptr CSize
remaining Maybe CSize
forall a. Maybe a
Nothing []
  where
    readChunks :: Ptr NativeReader
-> CString
-> CSize
-> Ptr CSize
-> Maybe CSize
-> [Cbor]
-> IO (Either NativeFailure [Cbor])
readChunks Ptr NativeReader
reader CString
diagnostic CSize
capacity Ptr CSize
remaining Maybe CSize
previous [Cbor]
accumulated = do
      NativeCode
code <- Ptr NativeReader -> Ptr CSize -> CString -> CSize -> IO NativeCode
Native.cReaderRemaining Ptr NativeReader
reader Ptr CSize
remaining CString
diagnostic CSize
capacity
      if NativeCode
code NativeCode -> NativeCode -> Bool
forall a. Eq a => a -> a -> Bool
/= NativeCode
Status.success
        then Text -> NativeCode -> IO [Cbor] -> IO (Either NativeFailure [Cbor])
forall value.
Text -> NativeCode -> IO value -> IO (Either NativeFailure value)
statusResult Text
"cbor.decodeText" NativeCode
code ([Cbor] -> IO [Cbor]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [])
        else do
          CSize
count <- Ptr CSize -> IO CSize
forall a. Storable a => Ptr a -> IO a
peek Ptr CSize
remaining
          if CSize
count CSize -> CSize -> Bool
forall a. Eq a => a -> a -> Bool
== CSize
0
            then Either NativeFailure [Cbor] -> IO (Either NativeFailure [Cbor])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Cbor] -> Either NativeFailure [Cbor]
forall a b. b -> Either a b
Right ([Cbor] -> [Cbor]
forall a. [a] -> [a]
reverse [Cbor]
accumulated))
            else
              if Bool -> (CSize -> Bool) -> Maybe CSize -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (CSize
count CSize -> CSize -> Bool
forall a. Ord a => a -> a -> Bool
>=) Maybe CSize
previous
                then Either NativeFailure [Cbor] -> IO (Either NativeFailure [Cbor])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (NativeFailure -> Either NativeFailure [Cbor]
forall a b. a -> Either a b
Left (Text -> NativeFailure
NativeContractFailure Text
"cbor.decodeText"))
                else do
                  Either NativeFailure ByteString
chunk <- Text
-> (Ptr (Ptr NativeBuffer) -> IO NativeCode)
-> IO (Either NativeFailure ByteString)
copyBuffer Text
"cbor.decodeText" (\Ptr (Ptr NativeBuffer)
output -> Ptr NativeReader
-> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode
Native.cReadTextChunk Ptr NativeReader
reader Ptr (Ptr NativeBuffer)
output CString
diagnostic CSize
capacity)
                  case Either NativeFailure ByteString
chunk of
                    Left NativeFailure
failure -> Either NativeFailure [Cbor] -> IO (Either NativeFailure [Cbor])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (NativeFailure -> Either NativeFailure [Cbor]
forall a b. a -> Either a b
Left NativeFailure
failure)
                    Right ByteString
value -> Ptr NativeReader
-> CString
-> CSize
-> Ptr CSize
-> Maybe CSize
-> [Cbor]
-> IO (Either NativeFailure [Cbor])
readChunks Ptr NativeReader
reader CString
diagnostic CSize
capacity Ptr CSize
remaining (CSize -> Maybe CSize
forall a. a -> Maybe a
Just CSize
count) (ByteString -> Cbor
Cbor ByteString
value Cbor -> [Cbor] -> [Cbor]
forall a. a -> [a] -> [a]
: [Cbor]
accumulated)

-- | Copy and release one owned writer result before constructing a Cbor value.
-- Unlike decoded string content, an encoded item must never be empty.
encodeResult :: Text -> (Ptr (Ptr Native.NativeBuffer) -> CString -> CSize -> IO Status.NativeCode) -> IO (Either Error Cbor)
encodeResult :: Text
-> (Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode)
-> IO (Either Error Cbor)
encodeResult Text
operation Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode
encode = do
  Either Error ByteString
result <- (CString -> CSize -> IO (Either NativeFailure ByteString))
-> IO (Either Error ByteString)
forall value.
(CString -> CSize -> IO (Either NativeFailure value))
-> IO (Either Error value)
withDiagnostic ((CString -> CSize -> IO (Either NativeFailure ByteString))
 -> IO (Either Error ByteString))
-> (CString -> CSize -> IO (Either NativeFailure ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \CString
diagnostic CSize
capacity -> Text
-> (Ptr (Ptr NativeBuffer) -> IO NativeCode)
-> IO (Either NativeFailure ByteString)
copyBuffer Text
operation (\Ptr (Ptr NativeBuffer)
output -> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode
encode Ptr (Ptr NativeBuffer)
output CString
diagnostic CSize
capacity)
  Either Error Cbor -> IO (Either Error Cbor)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error Cbor -> IO (Either Error Cbor))
-> Either Error Cbor -> IO (Either Error Cbor)
forall a b. (a -> b) -> a -> b
$ case Either Error ByteString
result of
    Left Error
failure -> Error -> Either Error Cbor
forall a b. a -> Either a b
Left Error
failure
    Right ByteString
bytes
      | ByteString -> Bool
ByteString.null ByteString
bytes -> Error -> Either Error Cbor
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
operation)
      | Bool
otherwise -> Cbor -> Either Error Cbor
forall a b. b -> Either a b
Right (ByteString -> Cbor
Cbor ByteString
bytes)

-- | Consume one output reference on every exit, including partial native
-- failures. Copy borrowed storage before release; a zero-length decoded string
-- is valid even when its native buffer has no data pointer.
copyBuffer :: Text -> (Ptr (Ptr Native.NativeBuffer) -> IO Status.NativeCode) -> IO (Either NativeFailure ByteString)
copyBuffer :: Text
-> (Ptr (Ptr NativeBuffer) -> IO NativeCode)
-> IO (Either NativeFailure ByteString)
copyBuffer Text
operation Ptr (Ptr NativeBuffer) -> IO NativeCode
acquire = Text
-> (Ptr (Ptr NativeBuffer) -> IO ())
-> (Ptr (Ptr NativeBuffer) -> IO NativeCode)
-> (Ptr NativeBuffer -> IO (Either NativeFailure ByteString))
-> IO (Either NativeFailure ByteString)
forall native value.
Text
-> (Ptr (Ptr native) -> IO ())
-> (Ptr (Ptr native) -> IO NativeCode)
-> (Ptr native -> IO (Either NativeFailure value))
-> IO (Either NativeFailure value)
withOwnedOutput Text
operation Ptr (Ptr NativeBuffer) -> IO ()
Native.cBufferUnref Ptr (Ptr NativeBuffer) -> IO NativeCode
acquire ((Ptr NativeBuffer -> IO (Either NativeFailure ByteString))
 -> IO (Either NativeFailure ByteString))
-> (Ptr NativeBuffer -> IO (Either NativeFailure ByteString))
-> IO (Either NativeFailure ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr NativeBuffer
buffer -> do
  CSize
size <- Ptr NativeBuffer -> IO CSize
Native.cBufferSize Ptr NativeBuffer
buffer
  Ptr Word8
storage <- Ptr NativeBuffer -> IO (Ptr Word8)
Native.cBufferData Ptr NativeBuffer
buffer
  if CSize -> Integer
forall a. Integral a => a -> Integer
toInteger CSize
size Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int
forall a. Bounded a => a
maxBound :: Int) Bool -> Bool -> Bool
|| (CSize
size CSize -> CSize -> Bool
forall a. Eq a => a -> a -> Bool
/= CSize
0 Bool -> Bool -> Bool
&& Ptr Word8
storage Ptr Word8 -> Ptr Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Ptr Word8
forall a. Ptr a
nullPtr)
    then Either NativeFailure ByteString
-> IO (Either NativeFailure ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (NativeFailure -> Either NativeFailure ByteString
forall a b. a -> Either a b
Left (Text -> NativeFailure
NativeContractFailure Text
operation))
    else
      if CSize
size CSize -> CSize -> Bool
forall a. Eq a => a -> a -> Bool
== CSize
0
        then Either NativeFailure ByteString
-> IO (Either NativeFailure ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> Either NativeFailure ByteString
forall a b. b -> Either a b
Right ByteString
ByteString.empty)
        else ByteString -> Either NativeFailure ByteString
forall a b. b -> Either a b
Right (ByteString -> Either NativeFailure ByteString)
-> IO ByteString -> IO (Either NativeFailure ByteString)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CStringLen -> IO ByteString
ByteString.packCStringLen (Ptr Word8 -> CString
forall a b. Ptr a -> Ptr b
castPtr Ptr Word8
storage, CSize -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral CSize
size)

runStatus :: Text -> (CString -> CSize -> IO Status.NativeCode) -> IO (Either Error ())
runStatus :: Text -> (CString -> CSize -> IO NativeCode) -> IO (Either Error ())
runStatus Text
operation CString -> CSize -> IO NativeCode
call = (CString -> CSize -> IO (Either NativeFailure ()))
-> IO (Either Error ())
forall value.
(CString -> CSize -> IO (Either NativeFailure value))
-> IO (Either Error value)
withDiagnostic ((CString -> CSize -> IO (Either NativeFailure ()))
 -> IO (Either Error ()))
-> (CString -> CSize -> IO (Either NativeFailure ()))
-> IO (Either Error ())
forall a b. (a -> b) -> a -> b
$ \CString
diagnostic CSize
capacity -> do
  NativeCode
code <- CString -> CSize -> IO NativeCode
call CString
diagnostic CSize
capacity
  Text -> NativeCode -> IO () -> IO (Either NativeFailure ())
forall value.
Text -> NativeCode -> IO value -> IO (Either NativeFailure value)
statusResult Text
operation NativeCode
code (() -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())

-- | Inspect output slots only after success; preserve exact native status codes.
statusResult :: Text -> Status.NativeCode -> IO value -> IO (Either NativeFailure value)
statusResult :: forall value.
Text -> NativeCode -> IO value -> IO (Either NativeFailure value)
statusResult Text
operation NativeCode
code IO value
action
  | NativeCode
code NativeCode -> NativeCode -> Bool
forall a. Eq a => a -> a -> Bool
== NativeCode
Status.success = value -> Either NativeFailure value
forall a b. b -> Either a b
Right (value -> Either NativeFailure value)
-> IO value -> IO (Either NativeFailure value)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO value
action
  | Bool
otherwise = do
      Text
message <- NativeCode -> IO CString
Status.cErrorMessage NativeCode
code IO CString -> (CString -> IO Text) -> IO Text
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CString -> IO Text
copyStaticText
      Either NativeFailure value -> IO (Either NativeFailure value)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (NativeFailure -> Either NativeFailure value
forall a b. a -> Either a b
Left (Text -> Integer -> Text -> NativeFailure
NativeFailure Text
operation (NativeCode -> Integer
forall a. Integral a => a -> Integer
toInteger NativeCode
code) Text
message))

-- | Keep caller-owned diagnostic storage alive through the native operation
-- and its cleanup, then copy a failure message before releasing that storage.
-- Acquisition helpers retain responsibility for all owned output references.
withDiagnostic :: (CString -> CSize -> IO (Either NativeFailure value)) -> IO (Either Error value)
withDiagnostic :: forall value.
(CString -> CSize -> IO (Either NativeFailure value))
-> IO (Either Error value)
withDiagnostic CString -> CSize -> IO (Either NativeFailure value)
action = Int
-> (CString -> IO (Either Error value)) -> IO (Either Error value)
forall a b. Int -> (Ptr a -> IO b) -> IO b
allocaBytes Int
1024 ((CString -> IO (Either Error value)) -> IO (Either Error value))
-> (CString -> IO (Either Error value)) -> IO (Either Error value)
forall a b. (a -> b) -> a -> b
$ \CString
diagnostic -> do
  CString -> CChar -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke CString
diagnostic CChar
0
  Either NativeFailure value
result <- CString -> CSize -> IO (Either NativeFailure value)
action CString
diagnostic CSize
1024
  case Either NativeFailure value
result of
    Right value
value -> Either Error value -> IO (Either Error value)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (value -> Either Error value
forall a b. b -> Either a b
Right value
value)
    Left failure :: NativeFailure
failure@(NativeContractFailure Text
_) -> Either Error value -> IO (Either Error value)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error value
forall a b. a -> Either a b
Left (NativeFailure -> Error
fromNativeFailure NativeFailure
failure))
    Left (NativeFailure Text
operation Integer
code Text
fallback) -> do
      Text
message <- CString -> IO Text
copyStaticText CString
diagnostic
      Either Error value -> IO (Either Error value)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error value
forall a b. a -> Either a b
Left (NativeFailure -> Error
fromNativeFailure (Text -> Integer -> Text -> NativeFailure
NativeFailure Text
operation Integer
code (if Text -> Bool
Text.null Text
message then Text
fallback else Text
message))))

-- | Borrow immutable Haskell bytes for one synchronous native scope. C must
-- finish using the pointer before this continuation returns.
withBytes :: ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes :: forall value.
ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value
withBytes ByteString
bytes Ptr Word8 -> CSize -> IO value
action = ByteString -> (CStringLen -> IO value) -> IO value
forall a. ByteString -> (CStringLen -> IO a) -> IO a
ByteString.useAsCStringLen ByteString
bytes ((CStringLen -> IO value) -> IO value)
-> (CStringLen -> IO value) -> IO value
forall a b. (a -> b) -> a -> b
$ \(CString
storage, Int
size) -> Ptr Word8 -> CSize -> IO value
action (CString -> Ptr Word8
forall a b. Ptr a -> Ptr b
castPtr CString
storage) (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
size)

flag :: Bool -> CInt
flag :: Bool -> CInt
flag Bool
value = if Bool
value then CInt
1 else CInt
0