{- |
Copyright  : Will Thompson, Iñaki García Etxebarria and Jonas Platte
License    : LGPL-2.1
Maintainer : Iñaki García Etxebarria (inaki@blueleaf.cc)

A 'GI.Gio.Interfaces.DatagramBased.DatagramBased' is a networking interface for representing datagram-based
communications. It is a more or less direct mapping of the core parts of the
BSD socket API in a portable GObject interface. It is implemented by
'GI.Gio.Objects.Socket.Socket', which wraps the UNIX socket API on UNIX and winsock2 on Windows.

'GI.Gio.Interfaces.DatagramBased.DatagramBased' is entirely platform independent, and is intended to be used
alongside higher-level networking APIs such as 'GI.Gio.Objects.IOStream.IOStream'.

It uses vectored scatter\/gather I\/O by default, allowing for many messages
to be sent or received in a single call. Where possible, implementations of
the interface should take advantage of vectored I\/O to minimise processing
or system calls. For example, 'GI.Gio.Objects.Socket.Socket' uses @/recvmmsg()/@ and @/sendmmsg()/@ where
possible. Callers should take advantage of scatter\/gather I\/O (the use of
multiple buffers per message) to avoid unnecessary copying of data to
assemble or disassemble a message.

Each 'GI.Gio.Interfaces.DatagramBased.DatagramBased' operation has a timeout parameter which may be negative
for blocking behaviour, zero for non-blocking behaviour, or positive for
timeout behaviour. A blocking operation blocks until finished or there is an
error. A non-blocking operation will return immediately with a
'GI.Gio.Enums.IOErrorEnumWouldBlock' error if it cannot make progress. A timeout operation
will block until the operation is complete or the timeout expires; if the
timeout expires it will return what progress it made, or
'GI.Gio.Enums.IOErrorEnumTimedOut' if no progress was made. To know when a call would
successfully run you can call 'GI.Gio.Interfaces.DatagramBased.datagramBasedConditionCheck' or
'GI.Gio.Interfaces.DatagramBased.datagramBasedConditionWait'. You can also use
'GI.Gio.Interfaces.DatagramBased.datagramBasedCreateSource' and attach it to a 'GI.GLib.Structs.MainContext.MainContext' to get
callbacks when I\/O is possible.

When running a non-blocking operation applications should always be able to
handle getting a 'GI.Gio.Enums.IOErrorEnumWouldBlock' error even when some other function
said that I\/O was possible. This can easily happen in case of a race
condition in the application, but it can also happen for other reasons. For
instance, on Windows a socket is always seen as writable until a write
returns 'GI.Gio.Enums.IOErrorEnumWouldBlock'.

As with 'GI.Gio.Objects.Socket.Socket', @/GDatagramBaseds/@ can be either connection oriented (for
example, SCTP) or connectionless (for example, UDP). @/GDatagramBaseds/@ must be
datagram-based, not stream-based. The interface does not cover connection
establishment — use methods on the underlying type to establish a connection
before sending and receiving data through the 'GI.Gio.Interfaces.DatagramBased.DatagramBased' API. For
connectionless socket types the target\/source address is specified or
received in each I\/O operation.

Like most other APIs in GLib, 'GI.Gio.Interfaces.DatagramBased.DatagramBased' is not inherently thread safe.
To use a 'GI.Gio.Interfaces.DatagramBased.DatagramBased' concurrently from multiple threads, you must
implement your own locking.

/Since: 2.48/
-}

#define ENABLE_OVERLOADING (MIN_VERSION_haskell_gi_overloading(1,0,0) \
       && !defined(__HADDOCK_VERSION__))

module GI.Gio.Interfaces.DatagramBased
    (

-- * Exported types
    DatagramBased(..)                       ,
    noDatagramBased                         ,
    IsDatagramBased                         ,
    toDatagramBased                         ,


 -- * Methods
-- ** conditionCheck #method:conditionCheck#

#if ENABLE_OVERLOADING
    DatagramBasedConditionCheckMethodInfo   ,
#endif
    datagramBasedConditionCheck             ,


-- ** conditionWait #method:conditionWait#

#if ENABLE_OVERLOADING
    DatagramBasedConditionWaitMethodInfo    ,
#endif
    datagramBasedConditionWait              ,


-- ** createSource #method:createSource#

#if ENABLE_OVERLOADING
    DatagramBasedCreateSourceMethodInfo     ,
#endif
    datagramBasedCreateSource               ,


-- ** receiveMessages #method:receiveMessages#

#if ENABLE_OVERLOADING
    DatagramBasedReceiveMessagesMethodInfo  ,
#endif
    datagramBasedReceiveMessages            ,


-- ** sendMessages #method:sendMessages#

#if ENABLE_OVERLOADING
    DatagramBasedSendMessagesMethodInfo     ,
#endif
    datagramBasedSendMessages               ,




    ) where

import Data.GI.Base.ShortPrelude
import qualified Data.GI.Base.ShortPrelude as SP
import qualified Data.GI.Base.Overloading as O
import qualified Prelude as P

import qualified Data.GI.Base.Attributes as GI.Attributes
import qualified Data.GI.Base.ManagedPtr as B.ManagedPtr
import qualified Data.GI.Base.GClosure as B.GClosure
import qualified Data.GI.Base.GError as B.GError
import qualified Data.GI.Base.GVariant as B.GVariant
import qualified Data.GI.Base.GValue as B.GValue
import qualified Data.GI.Base.GParamSpec as B.GParamSpec
import qualified Data.GI.Base.CallStack as B.CallStack
import qualified Data.GI.Base.Properties as B.Properties
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as Map
import qualified Foreign.Ptr as FP
import qualified GHC.OverloadedLabels as OL

import qualified GI.GLib.Flags as GLib.Flags
import qualified GI.GLib.Structs.Source as GLib.Source
import qualified GI.GObject.Objects.Object as GObject.Object
import {-# SOURCE #-} qualified GI.Gio.Objects.Cancellable as Gio.Cancellable
import {-# SOURCE #-} qualified GI.Gio.Structs.InputMessage as Gio.InputMessage
import {-# SOURCE #-} qualified GI.Gio.Structs.OutputMessage as Gio.OutputMessage

-- interface DatagramBased 
-- | Memory-managed wrapper type.
newtype DatagramBased = DatagramBased (ManagedPtr DatagramBased)
-- | A convenience alias for `Nothing` :: `Maybe` `DatagramBased`.
noDatagramBased :: Maybe DatagramBased
noDatagramBased = Nothing

#if ENABLE_OVERLOADING
type instance O.SignalList DatagramBased = DatagramBasedSignalList
type DatagramBasedSignalList = ('[ '("notify", GObject.Object.ObjectNotifySignalInfo)] :: [(Symbol, *)])

#endif

foreign import ccall "g_datagram_based_get_type"
    c_g_datagram_based_get_type :: IO GType

instance GObject DatagramBased where
    gobjectType = c_g_datagram_based_get_type


-- | Type class for types which can be safely cast to `DatagramBased`, for instance with `toDatagramBased`.
class (GObject o, O.IsDescendantOf DatagramBased o) => IsDatagramBased o
instance (GObject o, O.IsDescendantOf DatagramBased o) => IsDatagramBased o

instance O.HasParentTypes DatagramBased
type instance O.ParentTypes DatagramBased = '[GObject.Object.Object]

-- | Cast to `DatagramBased`, for types for which this is known to be safe. For general casts, use `Data.GI.Base.ManagedPtr.castTo`.
toDatagramBased :: (MonadIO m, IsDatagramBased o) => o -> m DatagramBased
toDatagramBased = liftIO . unsafeCastTo DatagramBased

#if ENABLE_OVERLOADING
instance O.HasAttributeList DatagramBased
type instance O.AttributeList DatagramBased = DatagramBasedAttributeList
type DatagramBasedAttributeList = ('[ ] :: [(Symbol, *)])
#endif

#if ENABLE_OVERLOADING
#endif

#if ENABLE_OVERLOADING
type family ResolveDatagramBasedMethod (t :: Symbol) (o :: *) :: * where
    ResolveDatagramBasedMethod "bindProperty" o = GObject.Object.ObjectBindPropertyMethodInfo
    ResolveDatagramBasedMethod "bindPropertyFull" o = GObject.Object.ObjectBindPropertyFullMethodInfo
    ResolveDatagramBasedMethod "conditionCheck" o = DatagramBasedConditionCheckMethodInfo
    ResolveDatagramBasedMethod "conditionWait" o = DatagramBasedConditionWaitMethodInfo
    ResolveDatagramBasedMethod "createSource" o = DatagramBasedCreateSourceMethodInfo
    ResolveDatagramBasedMethod "forceFloating" o = GObject.Object.ObjectForceFloatingMethodInfo
    ResolveDatagramBasedMethod "freezeNotify" o = GObject.Object.ObjectFreezeNotifyMethodInfo
    ResolveDatagramBasedMethod "getv" o = GObject.Object.ObjectGetvMethodInfo
    ResolveDatagramBasedMethod "isFloating" o = GObject.Object.ObjectIsFloatingMethodInfo
    ResolveDatagramBasedMethod "notify" o = GObject.Object.ObjectNotifyMethodInfo
    ResolveDatagramBasedMethod "notifyByPspec" o = GObject.Object.ObjectNotifyByPspecMethodInfo
    ResolveDatagramBasedMethod "receiveMessages" o = DatagramBasedReceiveMessagesMethodInfo
    ResolveDatagramBasedMethod "ref" o = GObject.Object.ObjectRefMethodInfo
    ResolveDatagramBasedMethod "refSink" o = GObject.Object.ObjectRefSinkMethodInfo
    ResolveDatagramBasedMethod "runDispose" o = GObject.Object.ObjectRunDisposeMethodInfo
    ResolveDatagramBasedMethod "sendMessages" o = DatagramBasedSendMessagesMethodInfo
    ResolveDatagramBasedMethod "stealData" o = GObject.Object.ObjectStealDataMethodInfo
    ResolveDatagramBasedMethod "stealQdata" o = GObject.Object.ObjectStealQdataMethodInfo
    ResolveDatagramBasedMethod "thawNotify" o = GObject.Object.ObjectThawNotifyMethodInfo
    ResolveDatagramBasedMethod "unref" o = GObject.Object.ObjectUnrefMethodInfo
    ResolveDatagramBasedMethod "watchClosure" o = GObject.Object.ObjectWatchClosureMethodInfo
    ResolveDatagramBasedMethod "getData" o = GObject.Object.ObjectGetDataMethodInfo
    ResolveDatagramBasedMethod "getProperty" o = GObject.Object.ObjectGetPropertyMethodInfo
    ResolveDatagramBasedMethod "getQdata" o = GObject.Object.ObjectGetQdataMethodInfo
    ResolveDatagramBasedMethod "setData" o = GObject.Object.ObjectSetDataMethodInfo
    ResolveDatagramBasedMethod "setDataFull" o = GObject.Object.ObjectSetDataFullMethodInfo
    ResolveDatagramBasedMethod "setProperty" o = GObject.Object.ObjectSetPropertyMethodInfo
    ResolveDatagramBasedMethod l o = O.MethodResolutionFailed l o

instance (info ~ ResolveDatagramBasedMethod t DatagramBased, O.MethodInfo info DatagramBased p) => OL.IsLabel t (DatagramBased -> p) where
#if MIN_VERSION_base(4,10,0)
    fromLabel = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#else
    fromLabel _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#endif

#endif

-- method DatagramBased::condition_check
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "datagram_based", argType = TInterface (Name {namespace = "Gio", name = "DatagramBased"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GDatagramBased", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "condition", argType = TInterface (Name {namespace = "GLib", name = "IOCondition"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GIOCondition mask to check", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Just (TInterface (Name {namespace = "GLib", name = "IOCondition"}))
-- throws : False
-- Skip return : False

foreign import ccall "g_datagram_based_condition_check" g_datagram_based_condition_check ::
    Ptr DatagramBased ->                    -- datagram_based : TInterface (Name {namespace = "Gio", name = "DatagramBased"})
    CUInt ->                                -- condition : TInterface (Name {namespace = "GLib", name = "IOCondition"})
    IO CUInt

{- |
Checks on the readiness of /@datagramBased@/ to perform operations. The
operations specified in /@condition@/ are checked for and masked against the
currently-satisfied conditions on /@datagramBased@/. The result is returned.

'GI.GLib.Flags.IOConditionIn' will be set in the return value if data is available to read with
'GI.Gio.Interfaces.DatagramBased.datagramBasedReceiveMessages', or if the connection is closed remotely
(EOS); and if the datagram_based has not been closed locally using some
implementation-specific method (such as 'GI.Gio.Objects.Socket.socketClose' or
'GI.Gio.Objects.Socket.socketShutdown' with /@shutdownRead@/ set, if it’s a 'GI.Gio.Objects.Socket.Socket').

If the connection is shut down or closed (by calling 'GI.Gio.Objects.Socket.socketClose' or
'GI.Gio.Objects.Socket.socketShutdown' with /@shutdownRead@/ set, if it’s a 'GI.Gio.Objects.Socket.Socket', for
example), all calls to this function will return 'GI.Gio.Enums.IOErrorEnumClosed'.

'GI.GLib.Flags.IOConditionOut' will be set if it is expected that at least one byte can be sent
using 'GI.Gio.Interfaces.DatagramBased.datagramBasedSendMessages' without blocking. It will not be set
if the datagram_based has been closed locally.

'GI.GLib.Flags.IOConditionHup' will be set if the connection has been closed locally.

'GI.GLib.Flags.IOConditionErr' will be set if there was an asynchronous error in transmitting data
previously enqueued using 'GI.Gio.Interfaces.DatagramBased.datagramBasedSendMessages'.

Note that on Windows, it is possible for an operation to return
'GI.Gio.Enums.IOErrorEnumWouldBlock' even immediately after
'GI.Gio.Interfaces.DatagramBased.datagramBasedConditionCheck' has claimed that the 'GI.Gio.Interfaces.DatagramBased.DatagramBased' is
ready for writing. Rather than calling 'GI.Gio.Interfaces.DatagramBased.datagramBasedConditionCheck' and
then writing to the 'GI.Gio.Interfaces.DatagramBased.DatagramBased' if it succeeds, it is generally better to
simply try writing right away, and try again later if the initial attempt
returns 'GI.Gio.Enums.IOErrorEnumWouldBlock'.

It is meaningless to specify 'GI.GLib.Flags.IOConditionErr' or 'GI.GLib.Flags.IOConditionHup' in /@condition@/; these
conditions will always be set in the output if they are true. Apart from
these flags, the output is guaranteed to be masked by /@condition@/.

This call never blocks.

/Since: 2.48/
-}
datagramBasedConditionCheck ::
    (B.CallStack.HasCallStack, MonadIO m, IsDatagramBased a) =>
    a
    {- ^ /@datagramBased@/: a 'GI.Gio.Interfaces.DatagramBased.DatagramBased' -}
    -> [GLib.Flags.IOCondition]
    {- ^ /@condition@/: a 'GI.GLib.Flags.IOCondition' mask to check -}
    -> m [GLib.Flags.IOCondition]
    {- ^ __Returns:__ the 'GI.GLib.Flags.IOCondition' mask of the current state -}
datagramBasedConditionCheck datagramBased condition = liftIO $ do
    datagramBased' <- unsafeManagedPtrCastPtr datagramBased
    let condition' = gflagsToWord condition
    result <- g_datagram_based_condition_check datagramBased' condition'
    let result' = wordToGFlags result
    touchManagedPtr datagramBased
    return result'

#if ENABLE_OVERLOADING
data DatagramBasedConditionCheckMethodInfo
instance (signature ~ ([GLib.Flags.IOCondition] -> m [GLib.Flags.IOCondition]), MonadIO m, IsDatagramBased a) => O.MethodInfo DatagramBasedConditionCheckMethodInfo a signature where
    overloadedMethod _ = datagramBasedConditionCheck

#endif

-- method DatagramBased::condition_wait
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "datagram_based", argType = TInterface (Name {namespace = "Gio", name = "DatagramBased"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GDatagramBased", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "condition", argType = TInterface (Name {namespace = "GLib", name = "IOCondition"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GIOCondition mask to wait for", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "timeout", argType = TBasicType TInt64, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the maximum time (in microseconds) to wait, 0 to not block, or -1\n  to block indefinitely", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = True, argDoc = Documentation {rawDocText = Just "a #GCancellable", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Just (TBasicType TBoolean)
-- throws : True
-- Skip return : False

foreign import ccall "g_datagram_based_condition_wait" g_datagram_based_condition_wait ::
    Ptr DatagramBased ->                    -- datagram_based : TInterface (Name {namespace = "Gio", name = "DatagramBased"})
    CUInt ->                                -- condition : TInterface (Name {namespace = "GLib", name = "IOCondition"})
    Int64 ->                                -- timeout : TBasicType TInt64
    Ptr Gio.Cancellable.Cancellable ->      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    Ptr (Ptr GError) ->                     -- error
    IO CInt

{- |
Waits for up to /@timeout@/ microseconds for condition to become true on
/@datagramBased@/. If the condition is met, 'True' is returned.

If /@cancellable@/ is cancelled before the condition is met, or if /@timeout@/ is
reached before the condition is met, then 'False' is returned and /@error@/ is
set appropriately ('GI.Gio.Enums.IOErrorEnumCancelled' or 'GI.Gio.Enums.IOErrorEnumTimedOut').

/Since: 2.48/
-}
datagramBasedConditionWait ::
    (B.CallStack.HasCallStack, MonadIO m, IsDatagramBased a, Gio.Cancellable.IsCancellable b) =>
    a
    {- ^ /@datagramBased@/: a 'GI.Gio.Interfaces.DatagramBased.DatagramBased' -}
    -> [GLib.Flags.IOCondition]
    {- ^ /@condition@/: a 'GI.GLib.Flags.IOCondition' mask to wait for -}
    -> Int64
    {- ^ /@timeout@/: the maximum time (in microseconds) to wait, 0 to not block, or -1
  to block indefinitely -}
    -> Maybe (b)
    {- ^ /@cancellable@/: a 'GI.Gio.Objects.Cancellable.Cancellable' -}
    -> m ()
    {- ^ /(Can throw 'Data.GI.Base.GError.GError')/ -}
datagramBasedConditionWait datagramBased condition timeout cancellable = liftIO $ do
    datagramBased' <- unsafeManagedPtrCastPtr datagramBased
    let condition' = gflagsToWord condition
    maybeCancellable <- case cancellable of
        Nothing -> return nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    onException (do
        _ <- propagateGError $ g_datagram_based_condition_wait datagramBased' condition' timeout maybeCancellable
        touchManagedPtr datagramBased
        whenJust cancellable touchManagedPtr
        return ()
     ) (do
        return ()
     )

#if ENABLE_OVERLOADING
data DatagramBasedConditionWaitMethodInfo
instance (signature ~ ([GLib.Flags.IOCondition] -> Int64 -> Maybe (b) -> m ()), MonadIO m, IsDatagramBased a, Gio.Cancellable.IsCancellable b) => O.MethodInfo DatagramBasedConditionWaitMethodInfo a signature where
    overloadedMethod _ = datagramBasedConditionWait

#endif

-- method DatagramBased::create_source
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "datagram_based", argType = TInterface (Name {namespace = "Gio", name = "DatagramBased"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GDatagramBased", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "condition", argType = TInterface (Name {namespace = "GLib", name = "IOCondition"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GIOCondition mask to monitor", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = True, argDoc = Documentation {rawDocText = Just "a #GCancellable", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Just (TInterface (Name {namespace = "GLib", name = "Source"}))
-- throws : False
-- Skip return : False

foreign import ccall "g_datagram_based_create_source" g_datagram_based_create_source ::
    Ptr DatagramBased ->                    -- datagram_based : TInterface (Name {namespace = "Gio", name = "DatagramBased"})
    CUInt ->                                -- condition : TInterface (Name {namespace = "GLib", name = "IOCondition"})
    Ptr Gio.Cancellable.Cancellable ->      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    IO (Ptr GLib.Source.Source)

{- |
Creates a 'GI.GLib.Structs.Source.Source' that can be attached to a 'GI.GLib.Structs.MainContext.MainContext' to monitor for
the availability of the specified /@condition@/ on the 'GI.Gio.Interfaces.DatagramBased.DatagramBased'. The
'GI.GLib.Structs.Source.Source' keeps a reference to the /@datagramBased@/.

The callback on the source is of the 'GI.Gio.Callbacks.DatagramBasedSourceFunc' type.

It is meaningless to specify 'GI.GLib.Flags.IOConditionErr' or 'GI.GLib.Flags.IOConditionHup' in /@condition@/; these
conditions will always be reported in the callback if they are true.

If non-'Nothing', /@cancellable@/ can be used to cancel the source, which will
cause the source to trigger, reporting the current condition (which is
likely 0 unless cancellation happened at the same time as a condition
change). You can check for this in the callback using
'GI.Gio.Objects.Cancellable.cancellableIsCancelled'.

/Since: 2.48/
-}
datagramBasedCreateSource ::
    (B.CallStack.HasCallStack, MonadIO m, IsDatagramBased a, Gio.Cancellable.IsCancellable b) =>
    a
    {- ^ /@datagramBased@/: a 'GI.Gio.Interfaces.DatagramBased.DatagramBased' -}
    -> [GLib.Flags.IOCondition]
    {- ^ /@condition@/: a 'GI.GLib.Flags.IOCondition' mask to monitor -}
    -> Maybe (b)
    {- ^ /@cancellable@/: a 'GI.Gio.Objects.Cancellable.Cancellable' -}
    -> m GLib.Source.Source
    {- ^ __Returns:__ a newly allocated 'GI.GLib.Structs.Source.Source' -}
datagramBasedCreateSource datagramBased condition cancellable = liftIO $ do
    datagramBased' <- unsafeManagedPtrCastPtr datagramBased
    let condition' = gflagsToWord condition
    maybeCancellable <- case cancellable of
        Nothing -> return nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    result <- g_datagram_based_create_source datagramBased' condition' maybeCancellable
    checkUnexpectedReturnNULL "datagramBasedCreateSource" result
    result' <- (wrapBoxed GLib.Source.Source) result
    touchManagedPtr datagramBased
    whenJust cancellable touchManagedPtr
    return result'

#if ENABLE_OVERLOADING
data DatagramBasedCreateSourceMethodInfo
instance (signature ~ ([GLib.Flags.IOCondition] -> Maybe (b) -> m GLib.Source.Source), MonadIO m, IsDatagramBased a, Gio.Cancellable.IsCancellable b) => O.MethodInfo DatagramBasedCreateSourceMethodInfo a signature where
    overloadedMethod _ = datagramBasedCreateSource

#endif

-- method DatagramBased::receive_messages
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "datagram_based", argType = TInterface (Name {namespace = "Gio", name = "DatagramBased"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GDatagramBased", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "messages", argType = TCArray False (-1) 2 (TInterface (Name {namespace = "Gio", name = "InputMessage"})), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "an array of #GInputMessage structs", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "num_messages", argType = TBasicType TUInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the number of elements in @messages", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "flags", argType = TBasicType TInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "an int containing #GSocketMsgFlags flags for the overall operation", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "timeout", argType = TBasicType TInt64, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the maximum time (in microseconds) to wait, 0 to not block, or -1\n  to block indefinitely", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = True, argDoc = Documentation {rawDocText = Just "a %GCancellable", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : [Arg {argCName = "num_messages", argType = TBasicType TUInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the number of elements in @messages", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- returnType : Just (TBasicType TInt)
-- throws : True
-- Skip return : False

foreign import ccall "g_datagram_based_receive_messages" g_datagram_based_receive_messages ::
    Ptr DatagramBased ->                    -- datagram_based : TInterface (Name {namespace = "Gio", name = "DatagramBased"})
    Ptr Gio.InputMessage.InputMessage ->    -- messages : TCArray False (-1) 2 (TInterface (Name {namespace = "Gio", name = "InputMessage"}))
    Word32 ->                               -- num_messages : TBasicType TUInt
    Int32 ->                                -- flags : TBasicType TInt
    Int64 ->                                -- timeout : TBasicType TInt64
    Ptr Gio.Cancellable.Cancellable ->      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    Ptr (Ptr GError) ->                     -- error
    IO Int32

{- |
Receive one or more data messages from /@datagramBased@/ in one go.

/@messages@/ must point to an array of 'GI.Gio.Structs.InputMessage.InputMessage' structs and
/@numMessages@/ must be the length of this array. Each 'GI.Gio.Structs.InputMessage.InputMessage'
contains a pointer to an array of 'GI.Gio.Structs.InputVector.InputVector' structs describing the
buffers that the data received in each message will be written to.

/@flags@/ modify how all messages are received. The commonly available
arguments for this are available in the 'GI.Gio.Flags.SocketMsgFlags' enum, but the
values there are the same as the system values, and the flags
are passed in as-is, so you can pass in system-specific flags too. These
flags affect the overall receive operation. Flags affecting individual
messages are returned in 'GI.Gio.Structs.InputMessage.InputMessage'.@/flags/@.

The other members of 'GI.Gio.Structs.InputMessage.InputMessage' are treated as described in its
documentation.

If /@timeout@/ is negative the call will block until /@numMessages@/ have been
received, the connection is closed remotely (EOS), /@cancellable@/ is cancelled,
or an error occurs.

If /@timeout@/ is 0 the call will return up to /@numMessages@/ without blocking,
or 'GI.Gio.Enums.IOErrorEnumWouldBlock' if no messages are queued in the operating system
to be received.

If /@timeout@/ is positive the call will block on the same conditions as if
/@timeout@/ were negative. If the timeout is reached
before any messages are received, 'GI.Gio.Enums.IOErrorEnumTimedOut' is returned,
otherwise it will return the number of messages received before timing out.
(Note: This is effectively the behaviour of @MSG_WAITFORONE@ with
@/recvmmsg()/@.)

To be notified when messages are available, wait for the 'GI.GLib.Flags.IOConditionIn' condition.
Note though that you may still receive 'GI.Gio.Enums.IOErrorEnumWouldBlock' from
'GI.Gio.Interfaces.DatagramBased.datagramBasedReceiveMessages' even if you were previously notified of a
'GI.GLib.Flags.IOConditionIn' condition.

If the remote peer closes the connection, any messages queued in the
underlying receive buffer will be returned, and subsequent calls to
'GI.Gio.Interfaces.DatagramBased.datagramBasedReceiveMessages' will return 0 (with no error set).

If the connection is shut down or closed (by calling 'GI.Gio.Objects.Socket.socketClose' or
'GI.Gio.Objects.Socket.socketShutdown' with /@shutdownRead@/ set, if it’s a 'GI.Gio.Objects.Socket.Socket', for
example), all calls to this function will return 'GI.Gio.Enums.IOErrorEnumClosed'.

On error -1 is returned and /@error@/ is set accordingly. An error will only
be returned if zero messages could be received; otherwise the number of
messages successfully received before the error will be returned. If
/@cancellable@/ is cancelled, 'GI.Gio.Enums.IOErrorEnumCancelled' is returned as with any
other error.

/Since: 2.48/
-}
datagramBasedReceiveMessages ::
    (B.CallStack.HasCallStack, MonadIO m, IsDatagramBased a, Gio.Cancellable.IsCancellable b) =>
    a
    {- ^ /@datagramBased@/: a 'GI.Gio.Interfaces.DatagramBased.DatagramBased' -}
    -> [Gio.InputMessage.InputMessage]
    {- ^ /@messages@/: an array of 'GI.Gio.Structs.InputMessage.InputMessage' structs -}
    -> Int32
    {- ^ /@flags@/: an int containing 'GI.Gio.Flags.SocketMsgFlags' flags for the overall operation -}
    -> Int64
    {- ^ /@timeout@/: the maximum time (in microseconds) to wait, 0 to not block, or -1
  to block indefinitely -}
    -> Maybe (b)
    {- ^ /@cancellable@/: a @/GCancellable/@ -}
    -> m Int32
    {- ^ __Returns:__ number of messages received, or -1 on error. Note that the number
    of messages received may be smaller than /@numMessages@/ if /@timeout@/ is
    zero or positive, if the peer closed the connection, or if /@numMessages@/
    was larger than @UIO_MAXIOV@ (1024), in which case the caller may re-try
    to receive the remaining messages. /(Can throw 'Data.GI.Base.GError.GError')/ -}
datagramBasedReceiveMessages datagramBased messages flags timeout cancellable = liftIO $ do
    let numMessages = fromIntegral $ length messages
    datagramBased' <- unsafeManagedPtrCastPtr datagramBased
    messages' <- mapM unsafeManagedPtrGetPtr messages
    messages'' <- packBlockArray 56 messages'
    maybeCancellable <- case cancellable of
        Nothing -> return nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    onException (do
        result <- propagateGError $ g_datagram_based_receive_messages datagramBased' messages'' numMessages flags timeout maybeCancellable
        touchManagedPtr datagramBased
        mapM_ touchManagedPtr messages
        whenJust cancellable touchManagedPtr
        freeMem messages''
        return result
     ) (do
        freeMem messages''
     )

#if ENABLE_OVERLOADING
data DatagramBasedReceiveMessagesMethodInfo
instance (signature ~ ([Gio.InputMessage.InputMessage] -> Int32 -> Int64 -> Maybe (b) -> m Int32), MonadIO m, IsDatagramBased a, Gio.Cancellable.IsCancellable b) => O.MethodInfo DatagramBasedReceiveMessagesMethodInfo a signature where
    overloadedMethod _ = datagramBasedReceiveMessages

#endif

-- method DatagramBased::send_messages
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "datagram_based", argType = TInterface (Name {namespace = "Gio", name = "DatagramBased"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GDatagramBased", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "messages", argType = TCArray False (-1) 2 (TInterface (Name {namespace = "Gio", name = "OutputMessage"})), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "an array of #GOutputMessage structs", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "num_messages", argType = TBasicType TUInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the number of elements in @messages", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "flags", argType = TBasicType TInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "an int containing #GSocketMsgFlags flags", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "timeout", argType = TBasicType TInt64, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the maximum time (in microseconds) to wait, 0 to not block, or -1\n  to block indefinitely", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = True, argDoc = Documentation {rawDocText = Just "a %GCancellable", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : [Arg {argCName = "num_messages", argType = TBasicType TUInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the number of elements in @messages", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- returnType : Just (TBasicType TInt)
-- throws : True
-- Skip return : False

foreign import ccall "g_datagram_based_send_messages" g_datagram_based_send_messages ::
    Ptr DatagramBased ->                    -- datagram_based : TInterface (Name {namespace = "Gio", name = "DatagramBased"})
    Ptr Gio.OutputMessage.OutputMessage ->  -- messages : TCArray False (-1) 2 (TInterface (Name {namespace = "Gio", name = "OutputMessage"}))
    Word32 ->                               -- num_messages : TBasicType TUInt
    Int32 ->                                -- flags : TBasicType TInt
    Int64 ->                                -- timeout : TBasicType TInt64
    Ptr Gio.Cancellable.Cancellable ->      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    Ptr (Ptr GError) ->                     -- error
    IO Int32

{- |
Send one or more data messages from /@datagramBased@/ in one go.

/@messages@/ must point to an array of 'GI.Gio.Structs.OutputMessage.OutputMessage' structs and
/@numMessages@/ must be the length of this array. Each 'GI.Gio.Structs.OutputMessage.OutputMessage'
contains an address to send the data to, and a pointer to an array of
'GI.Gio.Structs.OutputVector.OutputVector' structs to describe the buffers that the data to be sent
for each message will be gathered from.

/@flags@/ modify how the message is sent. The commonly available arguments
for this are available in the 'GI.Gio.Flags.SocketMsgFlags' enum, but the
values there are the same as the system values, and the flags
are passed in as-is, so you can pass in system-specific flags too.

The other members of 'GI.Gio.Structs.OutputMessage.OutputMessage' are treated as described in its
documentation.

If /@timeout@/ is negative the call will block until /@numMessages@/ have been
sent, /@cancellable@/ is cancelled, or an error occurs.

If /@timeout@/ is 0 the call will send up to /@numMessages@/ without blocking,
or will return 'GI.Gio.Enums.IOErrorEnumWouldBlock' if there is no space to send messages.

If /@timeout@/ is positive the call will block on the same conditions as if
/@timeout@/ were negative. If the timeout is reached before any messages are
sent, 'GI.Gio.Enums.IOErrorEnumTimedOut' is returned, otherwise it will return the number
of messages sent before timing out.

To be notified when messages can be sent, wait for the 'GI.GLib.Flags.IOConditionOut' condition.
Note though that you may still receive 'GI.Gio.Enums.IOErrorEnumWouldBlock' from
'GI.Gio.Interfaces.DatagramBased.datagramBasedSendMessages' even if you were previously notified of a
'GI.GLib.Flags.IOConditionOut' condition. (On Windows in particular, this is very common due to
the way the underlying APIs work.)

If the connection is shut down or closed (by calling 'GI.Gio.Objects.Socket.socketClose' or
'GI.Gio.Objects.Socket.socketShutdown' with /@shutdownWrite@/ set, if it’s a 'GI.Gio.Objects.Socket.Socket', for
example), all calls to this function will return 'GI.Gio.Enums.IOErrorEnumClosed'.

On error -1 is returned and /@error@/ is set accordingly. An error will only
be returned if zero messages could be sent; otherwise the number of messages
successfully sent before the error will be returned. If /@cancellable@/ is
cancelled, 'GI.Gio.Enums.IOErrorEnumCancelled' is returned as with any other error.

/Since: 2.48/
-}
datagramBasedSendMessages ::
    (B.CallStack.HasCallStack, MonadIO m, IsDatagramBased a, Gio.Cancellable.IsCancellable b) =>
    a
    {- ^ /@datagramBased@/: a 'GI.Gio.Interfaces.DatagramBased.DatagramBased' -}
    -> [Gio.OutputMessage.OutputMessage]
    {- ^ /@messages@/: an array of 'GI.Gio.Structs.OutputMessage.OutputMessage' structs -}
    -> Int32
    {- ^ /@flags@/: an int containing 'GI.Gio.Flags.SocketMsgFlags' flags -}
    -> Int64
    {- ^ /@timeout@/: the maximum time (in microseconds) to wait, 0 to not block, or -1
  to block indefinitely -}
    -> Maybe (b)
    {- ^ /@cancellable@/: a @/GCancellable/@ -}
    -> m Int32
    {- ^ __Returns:__ number of messages sent, or -1 on error. Note that the number of
    messages sent may be smaller than /@numMessages@/ if /@timeout@/ is zero
    or positive, or if /@numMessages@/ was larger than @UIO_MAXIOV@ (1024), in
    which case the caller may re-try to send the remaining messages. /(Can throw 'Data.GI.Base.GError.GError')/ -}
datagramBasedSendMessages datagramBased messages flags timeout cancellable = liftIO $ do
    let numMessages = fromIntegral $ length messages
    datagramBased' <- unsafeManagedPtrCastPtr datagramBased
    messages' <- mapM unsafeManagedPtrGetPtr messages
    messages'' <- packBlockArray 40 messages'
    maybeCancellable <- case cancellable of
        Nothing -> return nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    onException (do
        result <- propagateGError $ g_datagram_based_send_messages datagramBased' messages'' numMessages flags timeout maybeCancellable
        touchManagedPtr datagramBased
        mapM_ touchManagedPtr messages
        whenJust cancellable touchManagedPtr
        freeMem messages''
        return result
     ) (do
        freeMem messages''
     )

#if ENABLE_OVERLOADING
data DatagramBasedSendMessagesMethodInfo
instance (signature ~ ([Gio.OutputMessage.OutputMessage] -> Int32 -> Int64 -> Maybe (b) -> m Int32), MonadIO m, IsDatagramBased a, Gio.Cancellable.IsCancellable b) => O.MethodInfo DatagramBasedSendMessagesMethodInfo a signature where
    overloadedMethod _ = datagramBasedSendMessages

#endif