uv
March 26, 2026 ยท View on GitHub
{#uvmodule}
uv
The uv module contains C++ wrappers for libuv.
Classes
| Name | Description |
|---|---|
Handle | Wrapper class for managing uv_handle_t variants. |
ScopedLoop | RAII wrapper for a libuv event loop. Automatically closes and deletes the loop on destruction. |
HandleStorage | Extra storage placed around a raw libuv handle for close-time cleanup hooks. |
Context | Shared libuv handle context. |
BasicEvent | Default request callback event carrying a libuv status code. |
Request | Wrapper class for managing uv_req_t variants. |
ConnectReq | Asynchronous connection request for TCP sockets and named pipes. |
GetAddrInfoEvent | Callback event delivered when a [GetAddrInfoReq](#getaddrinforeq) resolves. |
GetAddrInfoReq | DNS resolver request to get the IP address of a hostname. |
Typedefs
| Return | Name | Description |
|---|---|---|
uv_loop_t | Loop | Alias for a libuv event loop instance. |
{#loop}
Loop
uv_loop_t Loop()
Alias for a libuv event loop instance.
Functions
| Return | Name | Description |
|---|---|---|
Loop * | defaultLoop inline | Returns the process-wide default libuv event loop. |
void | runLoop inline | Runs the given event loop using the specified run mode. Blocks until the loop exits (when using UV_RUN_DEFAULT). |
void | stopLoop inline | Stops the given event loop, causing uv_run to return after the current iteration. |
Loop * | createLoop inline | Allocates and initializes a new libuv event loop. The caller is responsible for closing and deleting the returned loop. |
bool | closeLoop inline | Closes the given event loop, releasing internal resources. All handles must be closed before calling this. |
HandleStorage< T > * | handleStorage inline | Returns the extended storage wrapper that owns handle. |
void | setHandleCloseCleanup inline | Registers a cleanup callback that runs when handle finally closes. |
void | clearHandleCloseCleanup inline | Clears any pending close-time cleanup callback registered on handle. |
auto | withHandleContext inline | Wraps callback so it only runs while the owning handle is still alive. Captures the intrusive [Context](#context-1) token, rehydrates the typed owner on entry, and suppresses invocation if the handle has already been deleted. |
T & | createRequest inline | Allocate a heap-owned [Request](#request) of type T and attach callback to it. |
T & | createRetainedRequest inline | Allocate a heap-owned [Request](#request) of type T whose callback retains additional state until completion. |
{#defaultloop}
defaultLoop
inline
inline Loop * defaultLoop()
Returns the process-wide default libuv event loop.
Returns
Pointer to the default uv_loop_t.
{#runloop}
runLoop
inline
inline void runLoop(Loop * loop, uv_run_mode mode) = default
Runs the given event loop using the specified run mode. Blocks until the loop exits (when using UV_RUN_DEFAULT).
Parameters
-
loopEvent loop to run. Defaults to the default loop. -
modelibuv run mode:UV_RUN_DEFAULT,UV_RUN_ONCE, orUV_RUN_NOWAIT.
{#stoploop}
stopLoop
inline
inline void stopLoop(Loop * loop) = default
Stops the given event loop, causing uv_run to return after the current iteration.
Parameters
loopEvent loop to stop. Defaults to the default loop.
{#createloop}
createLoop
inline
inline Loop * createLoop()
Allocates and initializes a new libuv event loop. The caller is responsible for closing and deleting the returned loop.
Returns
Pointer to a newly initialized uv_loop_t.
{#closeloop}
closeLoop
inline
inline bool closeLoop(Loop * loop)
Closes the given event loop, releasing internal resources. All handles must be closed before calling this.
Parameters
loopEvent loop to close.
Returns
True on success, false if the loop still has active handles.
{#handlestorage}
handleStorage
inline
template<typename T> inline HandleStorage< T > * handleStorage(T * handle)
Returns the extended storage wrapper that owns handle.
Parameters
handleRawlibuvhandle pointer previously allocated by[Context](#context-1)<T>.
{#sethandleclosecleanup}
setHandleCloseCleanup
inline
template<typename T> inline void setHandleCloseCleanup(T * handle, void * data, void(*)(void *) cleanup)
Registers a cleanup callback that runs when handle finally closes.
Parameters
-
handleRawlibuvhandle pointer. -
dataUser data passed back tocleanup. -
cleanupFunction invoked exactly once when the handle storage is released.
{#clearhandleclosecleanup}
clearHandleCloseCleanup
inline
template<typename T> inline void clearHandleCloseCleanup(T * handle)
Clears any pending close-time cleanup callback registered on handle.
Parameters
handleRawlibuvhandle pointer.
{#withhandlecontext}
withHandleContext
inline
template<typename Owner, typename Callback> inline auto withHandleContext(Owner & owner, Callback && callback)
Wraps callback so it only runs while the owning handle is still alive. Captures the intrusive [Context](#context-1) token, rehydrates the typed owner on entry, and suppresses invocation if the handle has already been deleted.
Parameters
-
ownerOwning handle instance. -
callbackCallable that receivesOwner&followed by the libuv callback args.
{#createrequest}
createRequest
inline
template<typename T> inline T & createRequest(std::function< void(const typename T::Event &)> callback)
Allocate a heap-owned [Request](#request) of type T and attach callback to it.
The returned reference is valid until the request's defaultCallback fires and deletes the object.
Parameters
TA specialization of[Request](#request).
Parameters
callbackCompletion handler; receives aT::Eventon completion.
Returns
Reference to the newly allocated request.
{#createretainedrequest}
createRetainedRequest
inline
template<typename T, typename Retained, typename Callback> inline T & createRetainedRequest(Retained && retained, Callback && callback)
Allocate a heap-owned [Request](#request) of type T whose callback retains additional state until completion.
This is the standard way to bind request completion to handle lifetime or other retained context without hand-rolling per-call capture logic.
Parameters
-
TA specialization of[Request](#request). -
RetainedRetained object type copied or moved into the callback. -
CallbackCallable invoked ascallback(retained, event).
Parameters
-
retainedExtra state to keep alive until the request completes. -
callbackCompletion handler receiving the retained state and event.
Returns
Reference to the newly allocated request.
{#handle-2}
Handle
#include <icy/handle.h>
Subclassed by:
Stream< uv_pipe_t >,Stream< uv_tcp_t >,Stream< T >
Wrapper class for managing uv_handle_t variants.
This class manages the handle during its lifecycle and safely handles the asynchronous destruction mechanism.
Public Methods
| Return | Name | Description |
|---|---|---|
Handle inline | Construct the handle bound to the given event loop. | |
bool | init inline | Initialize the underlying libuv handle by calling f with the loop, the raw handle pointer, and any additional args. |
bool | invoke inline | Invoke a libuv function f with args on the initialized handle. |
void | invokeOrThrow inline | Invoke a libuv function f with args, throwing on failure. |
void | close virtual inline | Close and destroy the handle. |
void | ref inline | Re-reference the handle with the event loop after a previous [unref()](#unref). |
void | unref inline | Unreference the handle from the event loop. |
bool | initialized const inline | Return true if the handle has been successfully initialized via [init()](#init-2). |
bool | active virtual const inline | Return true when the handle is active (libuv uv_is_active). |
bool | closing virtual const inline | Return true if uv_close has been called and the handle is awaiting its close callback (libuv uv_is_closing). |
bool | closed virtual const inline | Return true if the handle has been fully closed (context released). |
const icy::Error & | error const inline | Return the last error set on this handle, or a default-constructed [Error](base.md#error) if no error has occurred. |
void | setError virtual inline | Set the error state and invoke [onError()](#onerror). |
void | setUVError inline | Translate a libuv error code into an [Error](base.md#error) and call [setError()](#seterror). |
void | setAndThrowError inline | Set the error state from a libuv error code and throw a std::runtime_error. |
void | throwLastError inline | Throw a std::runtime_error if the handle currently holds an error. |
uv::Loop * | loop const inline | Return the event loop this handle is bound to. |
void | reset inline | Close the current handle (if open) and allocate a fresh [Context](#context-1), leaving the handle ready to be re-initialized via [init()](#init-2). |
Handle * | get const inline | Return the raw libuv handle pointer cast to [Handle](#handle-2). |
std::thread::id | tid const inline | Return the ID of the thread that constructed this handle. |
IntrusivePtr< Context< T > > | context const inline | Return the raw [Context](#context-1) that owns the libuv handle memory. |
void | setCloseCleanup inline | |
void | clearCloseCleanup inline | |
void | assertThread const inline | Throw std::logic_error if called from any thread other than the thread that constructed this handle. |
{#handle-3}
Handle
inline
inline Handle(uv::Loop * loop)
Construct the handle bound to the given event loop.
Parameters
loopEvent loop to associate this handle with. Defaults to the process-wide default loop.
{#init-2}
init
inline
template<typename F, typename... Args> inline bool init(F && f, Args &&... args)
Initialize the underlying libuv handle by calling f with the loop, the raw handle pointer, and any additional args.
Must be called exactly once before any other operations. Throws std::logic_error if the handle is already initialized or the context is invalid.
Parameters
-
flibuv init function (e.g.uv_tcp_init). -
argsAdditional arguments forwarded after the loop and handle pointer.
Returns
true on success; false and sets the error state on failure.
{#invoke}
invoke
inline
template<typename F, typename... Args> inline bool invoke(F && f, Args &&... args)
Invoke a libuv function f with args on the initialized handle.
Throws std::logic_error if the handle is not yet initialized. Sets the error state and returns false if f returns a libuv error code.
Parameters
-
flibuv function to call. -
argsArguments forwarded tof.
Returns
true on success; false on libuv error.
{#invokeorthrow}
invokeOrThrow
inline
template<typename F, typename... Args> inline void invokeOrThrow(const std::string & message, F && f, Args &&... args)
Invoke a libuv function f with args, throwing on failure.
Identical to [invoke()](#invoke) but throws a std::runtime_error with message prepended if f returns a libuv error code. Must not be called from inside a libuv callback.
Parameters
-
messageError message prefix used in the thrown exception. -
flibuv function to call. -
argsArguments forwarded tof.
{#close-11}
close
virtual inline
virtual inline void close()
Close and destroy the handle.
Releases the [Context](#context-1) (which schedules the async uv_close) and then fires [onClose()](#onclose). Safe to call more than once; subsequent calls are no-ops.
{#ref}
ref
inline
inline void ref()
Re-reference the handle with the event loop after a previous [unref()](#unref).
When all handles are unref'd the loop exits automatically. This call reverses that. Has no effect if the handle is not initialized.
{#unref}
unref
inline
inline void unref()
Unreference the handle from the event loop.
The loop will exit when all active handles are unref'd, even if this handle is still alive. Has no effect if the handle is not initialized.
{#initialized-1}
initialized
const inline
inline bool initialized() const
Return true if the handle has been successfully initialized via [init()](#init-2).
{#active}
active
virtual const inline
virtual inline bool active() const
Return true when the handle is active (libuv uv_is_active).
"Active" has type-specific meaning: a timer is active while counting, a stream is active while connected, etc.
{#closing-1}
closing
virtual const inline
virtual inline bool closing() const
Return true if uv_close has been called and the handle is awaiting its close callback (libuv uv_is_closing).
{#closed}
closed
virtual const inline
virtual inline bool closed() const
Return true if the handle has been fully closed (context released).
{#error-4}
error
const inline
inline const icy::Error & error() const
Return the last error set on this handle, or a default-constructed [Error](base.md#error) if no error has occurred.
{#seterror}
setError
virtual inline
virtual inline void setError(const Error & error)
Set the error state and invoke [onError()](#onerror).
Parameters
errorError value to store and propagate.
{#setuverror}
setUVError
inline
inline void setUVError(int err, std::string prefix)
Translate a libuv error code into an [Error](base.md#error) and call [setError()](#seterror).
Safe to call from inside libuv callbacks.
Parameters
-
errlibuv error code (negative integer). -
prefixHuman-readable prefix prepended to the formatted message.
{#setandthrowerror}
setAndThrowError
inline
inline void setAndThrowError(int err, std::string prefix)
Set the error state from a libuv error code and throw a std::runtime_error.
Must not be called from inside libuv callbacks; use [setUVError()](#setuverror) there.
Parameters
-
errlibuv error code (negative integer). -
prefixHuman-readable prefix prepended to the thrown message.
{#throwlasterror}
throwLastError
inline
inline void throwLastError(std::string prefix)
Throw a std::runtime_error if the handle currently holds an error.
The stored error's message is re-formatted with prefix before throwing. No-op if the handle is not in an error state.
Parameters
prefixHuman-readable prefix used when re-formatting the message.
{#loop-2}
loop
const inline
inline uv::Loop * loop() const
Return the event loop this handle is bound to.
Asserts that the caller is on the owning thread.
Returns
Pointer to the associated [uv::Loop](#loop).
{#reset-3}
reset
inline
inline void reset()
Close the current handle (if open) and allocate a fresh [Context](#context-1), leaving the handle ready to be re-initialized via [init()](#init-2).
{#get-2}
get
const inline
template<typename Handle> inline Handle * get() const
Return the raw libuv handle pointer cast to [Handle](#handle-2).
Returns nullptr if the context has been released (handle closed). Asserts that the caller is on the owning thread.
Parameters
[Handle](#handle-2)Target type; defaults to the native handle typeT.
Returns
Pointer to the underlying libuv handle, or nullptr.
{#tid}
tid
const inline
inline std::thread::id tid() const
Return the ID of the thread that constructed this handle.
All handle operations must be performed on this thread.
Returns
std::thread::id of the owning thread.
{#context-3}
context
const inline
inline IntrusivePtr< Context< T > > context() const
Return the raw [Context](#context-1) that owns the libuv handle memory.
Primarily for use by subclasses and libuv callbacks that need to access the underlying libuv handle memory.
Returns
A retained reference to the [Context](#context-1), or an empty reference if closed.
{#setclosecleanup}
setCloseCleanup
inline
template<typename U> inline void setCloseCleanup(U * data)
{#clearclosecleanup}
clearCloseCleanup
inline
inline void clearCloseCleanup()
{#assertthread}
assertThread
const inline
inline void assertThread() const
Throw std::logic_error if called from any thread other than the thread that constructed this handle.
Protected Attributes
| Return | Name | Description |
|---|---|---|
uv::Loop * | _loop | |
IntrusivePtr< Context< T > > | _context | |
std::thread::id | _tid | |
Error | _error |
{#_loop}
_loop
uv::Loop * _loop
{#_context}
_context
IntrusivePtr< Context< T > > _context
{#_tid}
_tid
std::thread::id _tid = std::this_thread::get_id()
{#_error-1}
_error
Error _error
Protected Methods
| Return | Name | Description |
|---|---|---|
void | onError virtual inline | Called by [setError()](#seterror) after the error state has been updated. |
void | onClose virtual inline | Called by [close()](#close-11) after the context has been released. |
Handle | NonCopyable and NonMovable. | |
Handle | Deleted constructor. |
{#onerror}
onError
virtual inline
virtual inline void onError(const Error & error)
Called by [setError()](#seterror) after the error state has been updated.
Override to react to errors. The default implementation is a no-op.
Parameters
errorThe error that was set.
{#onclose}
onClose
virtual inline
virtual inline void onClose()
Called by [close()](#close-11) after the context has been released.
Override to perform cleanup on handle closure. The default implementation is a no-op.
{#handle-4}
Handle
Handle(const Handle &) = delete
NonCopyable and NonMovable.
{#handle-5}
Handle
Handle(Handle &&) = delete
Deleted constructor.
Public Types
| Name | Description |
|---|---|
Type | Define the native handle type. |
{#type-7}
Type
T Type()
Define the native handle type.
{#scopedloop}
ScopedLoop
#include <icy/loop.h>
RAII wrapper for a libuv event loop. Automatically closes and deletes the loop on destruction.
Public Attributes
| Return | Name | Description |
|---|---|---|
Loop * | loop |
{#loop-1}
loop
Loop * loop
Public Methods
| Return | Name | Description |
|---|---|---|
ScopedLoop inline | ||
operator Loop * const inline | Implicit conversion to Loop* for use with libuv APIs. | |
Loop * | get const inline | Returns the raw event loop pointer. |
ScopedLoop | Deleted constructor. | |
ScopedLoop | Deleted constructor. |
{#scopedloop-1}
ScopedLoop
inline
inline ScopedLoop()
{#operatorloop}
operator Loop *
const inline
inline operator Loop *() const
Implicit conversion to Loop* for use with libuv APIs.
{#get-1}
get
const inline
inline Loop * get() const
Returns the raw event loop pointer.
Returns
Pointer to the underlying uv_loop_t.
{#scopedloop-2}
ScopedLoop
ScopedLoop(const ScopedLoop &) = delete
Deleted constructor.
{#scopedloop-3}
ScopedLoop
ScopedLoop(ScopedLoop &&) = delete
Deleted constructor.
{#handlestorage-1}
HandleStorage
#include <icy/handle.h>
Extra storage placed around a raw libuv handle for close-time cleanup hooks.
Public Attributes
| Return | Name | Description |
|---|---|---|
T | handle | Embedded raw libuv handle object. |
void * | closeData | Opaque cleanup payload invoked on close. |
void(* | closeCleanup | Cleanup function for closeData. |
{#handle}
handle
T handle {}
Embedded raw libuv handle object.
{#closedata}
closeData
void * closeData = nullptr
Opaque cleanup payload invoked on close.
{#closecleanup}
closeCleanup
void(* closeCleanup = nullptr
Cleanup function for closeData.
{#context-1}
Context
#include <icy/handle.h>
Inherits:
RefCounted< Context< T > >
Shared libuv handle context.
Public Attributes
| Return | Name | Description |
|---|---|---|
Handle< T > * | handle | |
HandleStorage< T > * | storage | |
T * | ptr | |
bool | initialized | |
bool | deleted |
{#handle-1}
handle
Handle< T > * handle = nullptr
{#storage}
storage
HandleStorage< T > * storage = new <T>
{#ptr-3}
ptr
T * ptr = &->
{#initialized}
initialized
bool initialized = false
{#deleted}
deleted
bool deleted = false
Public Methods
| Return | Name | Description |
|---|---|---|
Context inline | ||
Owner * | owner const inline |
{#context-2}
Context
inline
inline Context(Handle< T > * h)
{#owner}
owner
const inline
template<typename Owner> inline Owner * owner() const
{#basicevent}
BasicEvent
#include <icy/request.h>
Default request callback event carrying a libuv status code.
Public Attributes
| Return | Name | Description |
|---|---|---|
int | status | libuv result: 0 on success, negative on error. |
{#status}
status
int status
libuv result: 0 on success, negative on error.
{#request}
Request
#include <icy/request.h>
Wrapper class for managing uv_req_t variants.
This class provides safe access to the parent handle in case the handle gets destroyed before the request callback returns, and should be used whenever the handle pointer is accessed via the callback.
Public Attributes
| Return | Name | Description |
|---|---|---|
T | req | The underlying libuv request object. |
std::function< void(const E &)> | callback | Called when the request completes. |
{#req}
req
T req
The underlying libuv request object.
{#callback}
callback
std::function< void(const E &)> callback
Called when the request completes.
Public Methods
| Return | Name | Description |
|---|---|---|
Request inline | Construct the request and set req.data to this so callbacks can recover the wrapper pointer. | |
auto | invoke inline | Call f with args. If f returns a non-zero libuv error code, the callback is invoked immediately with that status. |
auto | invoke inline | Call f with args. Overload for void-returning functions; no error checking is performed. |
{#request-1}
Request
inline
inline Request()
Construct the request and set req.data to this so callbacks can recover the wrapper pointer.
{#invoke-1}
invoke
inline
template<typename F, typename... Args> inline auto invoke(F && f, Args &&... args)
Call f with args. If f returns a non-zero libuv error code, the callback is invoked immediately with that status.
Enabled only when f returns a non-void type (i.e. an error code).
Parameters
-
flibuv function to call. -
argsArguments forwarded tof.
Returns
true (non-zero = success) if f returned 0; false on error.
{#invoke-2}
invoke
inline
template<typename F, typename... Args> inline auto invoke(F && f, Args &&... args)
Call f with args. Overload for void-returning functions; no error checking is performed.
Parameters
-
fFunction to call. -
argsArguments forwarded tof.
Public Static Methods
| Return | Name | Description |
|---|---|---|
void | defaultCallback static inline | Standard libuv completion callback. Invokes callback with the status event and then deletes the [Request](#request) wrapper. |
{#defaultcallback}
defaultCallback
static inline
static inline void defaultCallback(T * req, int status)
Standard libuv completion callback. Invokes callback with the status event and then deletes the [Request](#request) wrapper.
Parameters
-
reqThe completed libuv request. -
statuslibuv status code (0 on success, negative on error).
Public Types
| Name | Description |
|---|---|
Type | |
Event |
{#type-8}
Type
T Type()
{#event}
Event
E Event()
{#connectreq}
ConnectReq
#include <icy/request.h>
Inherits:
Request< uv_connect_t >
Asynchronous connection request for TCP sockets and named pipes.
Public Methods
| Return | Name | Description |
|---|---|---|
ConnectReq inline | Construct and set req.data to this. | |
auto | connect inline | Initiate a TCP connection to addr on handle. |
auto | connect inline | Initiate a named-pipe connection to name on handle. |
{#connectreq-1}
ConnectReq
inline
inline ConnectReq()
Construct and set req.data to this.
{#connect}
connect
inline
inline auto connect(uv_tcp_t * handle, const struct sockaddr * addr)
Initiate a TCP connection to addr on handle.
Parameters
-
handleInitializeduv_tcp_tto connect. -
addrTarget address (IPv4 or IPv6sockaddr).
Returns
true if the connect request was submitted successfully.
{#connect-1}
connect
inline
inline auto connect(uv_pipe_t * handle, const char * name)
Initiate a named-pipe connection to name on handle.
Parameters
-
handleInitializeduv_pipe_tto connect. -
nameFilesystem path (Unix) or named-pipe name (Windows).
Returns
true if the connect request was submitted successfully.
{#getaddrinfoevent}
GetAddrInfoEvent
#include <icy/request.h>
Callback event delivered when a [GetAddrInfoReq](#getaddrinforeq) resolves.
Public Attributes
| Return | Name | Description |
|---|---|---|
int | status | libuv status: 0 on success, negative on error. |
struct addrinfo * | addr | Resolved address list; freed after the callback returns. |
{#status-1}
status
int status
libuv status: 0 on success, negative on error.
{#addr}
addr
struct addrinfo * addr = nullptr
Resolved address list; freed after the callback returns.
{#getaddrinforeq}
GetAddrInfoReq
#include <icy/request.h>
DNS resolver request to get the IP address of a hostname.
Public Methods
| Return | Name | Description |
|---|---|---|
GetAddrInfoReq inline | Construct and set req.data to this. | |
auto | resolve inline | Begin asynchronous DNS resolution of host at port. |
{#getaddrinforeq-1}
GetAddrInfoReq
inline
inline GetAddrInfoReq()
Construct and set req.data to this.
{#resolve}
resolve
inline
inline auto resolve(const std::string & host, int port, uv::Loop * loop)
Begin asynchronous DNS resolution of host at port.
The result is delivered to callback as a [GetAddrInfoEvent](#getaddrinfoevent). The addrinfo pointer in the event is freed immediately after the callback returns; do not retain it.
Parameters
-
hostHostname or numeric IP address string to resolve. -
portPort number; converted to a service string forgetaddrinfo. -
loopEvent loop on which to run the resolution.
Returns
true if the request was submitted successfully.
Public Static Methods
| Return | Name | Description |
|---|---|---|
void | getAddrInfoCallback static inline | libuv completion callback for uv_getaddrinfo. |
{#getaddrinfocallback}
getAddrInfoCallback
static inline
static inline void getAddrInfoCallback(Request::Type * req, int status, struct addrinfo * res)
libuv completion callback for uv_getaddrinfo.
Invokes the stored callback with the resolved address list, then frees the addrinfo chain and deletes the wrapper.
Parameters
-
reqThe completeduv_getaddrinfo_trequest. -
statuslibuv status code. -
resResolved address list (freed after callback returns).
Public Types
| Name | Description |
|---|---|
Request |
{#request-2}
Request
uv::Request< uv_getaddrinfo_t, GetAddrInfoEvent > Request()