base
May 10, 2026 · View on GitHub
{#basemodule}
base
The base module contains reusable cross platform tools and utilities.
Namespaces
| Name | Description |
|---|---|
hex | Hexadecimal encoding and decoding helpers. |
ipc | Classes for inter-process communication. |
test | Modern unit testing framework. |
time | Classes and functions for handling time. |
base64 | Base64 encoding and decoding helpers. |
deleter | Deleter helpers for objects managed through custom destruction routines. |
numeric | Integer parsing and formatting helpers. |
basic | Interface classes. |
fs | Cross-platform filesystem path and file helpers. |
util | Miscellaneous string, parsing, and version utilities. |
Classes
| Name | Description |
|---|---|
Pipe | Named pipe / stdio stream built on uv_pipe_t. |
Idler | Asynchronous type that triggers callbacks when the event loop is idle. |
Queue | Thread-safe queue container. |
RunnableQueue | Queue of runnable tasks for sequential execution. |
SyncQueue | SyncQueue extends Synchronizer to implement a synchronized FIFO queue which receives T objects from any thread and synchronizes them for safe consumption by the associated event loop. |
AsyncQueue | AsyncQueue is a thread-based queue which receives packets from any thread source and dispatches them asynchronously. |
Timer | Asynchronous event based timer. |
MutableBuffer | The MutableBuffer class provides a safe representation of a buffer that can be modified. It does not own the underlying data, and so is cheap to copy or assign. |
ConstBuffer | The ConstBuffer class provides a safe representation of a buffer that cannot be modified. It does not own the underlying data, and so is cheap to copy or assign. |
BitReader | Class for reading binary streams. |
BitWriter | Class for reading/writing binary streams. |
DynamicBitWriter | Class for reading/writing dynamically resizable binary streams. |
LogWriter | Log output stream writer. |
AsyncLogWriter | Thread based log output stream writer. |
Logger | Logger class. |
LogChannel | Named log output channel with configurable severity level and formatting. |
ConsoleChannel | Log channel that writes formatted messages to standard output. |
FileChannel | Log channel that writes formatted messages to a file. |
RotatingFileChannel | Log channel that writes to time-rotated log files. |
RefCounted | Base class for intrusive reference counting. |
IntrusivePtr | Intrusive smart pointer for RefCounted objects. |
Random | Random implements a pseudo random number generator (PRNG) using the Mersenne Twister algorithm (std::mt19937). |
Runner | Runner is a virtual interface for implementing asynchronous objects such as threads and futures. |
Signal< RT(Args...), MutexT > | Thread-safe signal and slot implementation for callback-based event dispatch. |
Stream | Basic stream type for sockets and pipes. |
Thread | Platform-independent wrapper around an operating system thread. |
Process | Spawns and manages a child process with stdin/stdout/stderr pipes. |
Timeout | Timeout counter which expires after a given delay. Delay is specified in milliseconds. |
TimedToken | Token that expires after the specified duration. |
Timestamp | A Timestamp stores a monotonic* time value with (theoretical) microseconds resolution. Timestamps can be compared with each other and simple arithmetics are supported. |
Timespan | A class that represents time spans up to microsecond resolution. |
DateTime | This class represents an instant in time, expressed in years, months, days, hours, minutes, seconds and milliseconds based on the Gregorian calendar. The class is mainly useful for conversions between UTC, Julian day and Gregorian calendar dates. |
Timezone | This class provides information about the current timezone. |
LocalDateTime | This class represents an instant in local time (as opposed to UTC), expressed in years, months, days, hours, minutes, seconds and milliseconds based on the Gregorian calendar. |
DateTimeFormat | Definition of date/time formats and various constants used by DateTimeFormatter and DateTimeParser. |
DateTimeFormatter | This class converts dates and times into strings, supporting a variety of standard and custom formats. |
DateTimeParser | This class provides a method for parsing dates and times from strings. All parsing methods do their best to parse a meaningful result, even from malformed input strings. |
Stopwatch | A simple facility to measure time intervals with microsecond resolution. |
ThreadedStreamReader | Threaded stream reader class. |
StreamWriter | Packet stream writer class. |
State | State class for state machines. |
Stateful | State machine implementation. |
IRegistry | Abstract interface for object registries. |
Singleton | Helper template class for managing singleton objects allocated on the heap. |
KeyedStore | A keyed store of unique_ptr values with optional lifecycle hooks. Not thread-safe; designed for single-threaded event loop contexts. |
KVCollection | A keyed value store (values stored by copy, not pointer). |
NVCollection | A storage container for a name value collections. This collection can store multiple entries for each name, and it's getters are case-insensitive. |
Application | Main icey application class. |
SyncPacketQueue | Synchronized packet queue for event loop integration. |
AsyncPacketQueue | Thread-based asynchronous packet dispatch queue. |
RateLimiter | Token bucket rate limiter for throttling message send frequency. |
PacketStreamAdapter | This class is a wrapper for integrating external classes with the a PacketStream's data flow and state machine. |
PacketProcessor | This class is a virtual interface for creating PacketStreamAdapters which process that and emit the IPacket type. |
PacketStream | Processes and broadcasts IPackets through a configurable adapter graph. |
Synchronizer | Synchronizer enables any thread to communicate with the associated event loop via synchronized callbacks. |
TimedManager | Timed pointer manager |
IPacketCreationStrategy | Abstract strategy for creating typed packets from raw buffer data. |
PacketFactory | Priority-ordered factory that creates typed packets from raw buffers using registered strategies. |
StreamManager | Manages a named collection of PacketStream instances with lifecycle callbacks. |
IDiagnostic | Abstract interface for diagnostic information providers. |
AsyncDiagnostic | Asynchronous diagnostic information collector. |
DiagnosticManager | Registry and manager for diagnostic providers. |
PacketTransaction | Request/response transaction with timeout and retry logic. |
Task | Abstract base class for implementing asynchronous tasks. |
TaskRunner | Runner for tasks that inherit the [Task](#task) interface. |
IPacket | The basic packet type which is passed around the icey system. IPacket can be extended for each protocol to enable polymorphic processing and callbacks using PacketStream and friends. |
FlagPacket | Packet for sending bitwise flags along the packet stream. |
RawPacket | RawPacket is the default data packet type which consists of an optionally managed char pointer and a size value. |
Configuration | Configuration is an abstract base class for managing different kinds of configuration storage back ends such as JSON, XML, or database. |
ScopedConfiguration | ScopedConfiguration provides multiple levels of configuration for a module. Multiple levels means that there is a module level scope, and a default scope. When a property is accessed, the module scope value will be used if available, otherwise the default scope value will be used. |
Error | Basic error type. |
LogStream | No-op log record used when logging is compiled out. |
NullSharedMutex | No-op mutex for single-threaded signal usage. When all signal operations occur on a single libuv event loop thread, the shared_mutex is unnecessary overhead. |
Bitwise | Container for smart management of bitwise integer flags. |
AbstractDelegate | Abstract delegate interface. |
FunctionDelegate | The [FunctionDelegate](#functiondelegate) contains a std::function. |
ClassDelegate | The [ClassDelegate](#classdelegate) contains a pointer to a class member. |
ConstClassDelegate | The [ConstClassDelegate](#constclassdelegate) contains a pointer to a const class member. |
PolymorphicDelegate | Polymorphic function delegate. |
OptionParser | Command-line option parser. |
ShutdownCmd | Shutdown command packet for signalling process termination. |
PacketAdapterReference | Provides a reference to a PacketStreamAdapter with optional ownership. |
PacketStreamState | State machine states for PacketStream. |
PacketCreationStrategy | This template class implements an adapter that sits between an SignalBase and an object receiving notifications from it. |
SharedLibrary | Loads a shared library at runtime and resolves exported symbols. |
DiagnosticState | State definitions for diagnostic providers. |
TransactionState | State machine states for PacketTransaction. |
IPacketInfo | An abstract interface for packet sources to provide extra information about packets. |
Enumerations
| Name | Description |
|---|---|
Level | Logging severity levels used by Logger and LogChannel. |
ByteOrder | Byte-order policy used when reading or writing multi-byte integers. |
PacketRetention | Describes how an adapter treats incoming packet lifetime beyond the current synchronous call chain. |
PacketFlags | Flags which determine how the packet is handled by the PacketStream. |
{#level}
Level
enum Level
Logging severity levels used by Logger and LogChannel.
| Value | Description |
|---|---|
Trace | Most verbose diagnostic output. |
Debug | Debug-only diagnostic output. |
Info | Normal informational output. |
Warn | Warning output for recoverable problems. |
Error | Error output for failed operations. |
Fatal | Fatal output immediately before termination. |
{#byteorder}
ByteOrder
enum ByteOrder
Byte-order policy used when reading or writing multi-byte integers.
| Value | Description |
|---|---|
Network | Default, use network byte order (big endian). |
Host | Use the native order of the host. |
{#packetretention}
PacketRetention
enum PacketRetention
Describes how an adapter treats incoming packet lifetime beyond the current synchronous call chain.
Borrowed adapters must finish using the packet before emit()/process() returns. Cloned and Retained adapters are explicit ownership boundaries: callers may mutate or free borrowed input only after such a boundary, or after the whole synchronous write/emit call has returned.
| Value | Description |
|---|---|
Borrowed | Packet is only used synchronously during the current emit/process call. |
Cloned | Adapter makes its own copy before deferred or asynchronous use. |
Retained | Adapter retains the original packet object beyond the current call chain. |
{#packetflags}
PacketFlags
enum PacketFlags
Flags which determine how the packet is handled by the PacketStream.
| Value | Description |
|---|---|
NoModify | The packet should not be modified by processors. |
Final | The final packet in the stream. |
Typedefs
| Return | Name | Description |
|---|---|---|
std::vector< char > | Buffer | Core buffer type. |
LogChannel | NullChannel | Null log channel. |
Signal< void()> | NullSignal | Zero-argument signal alias used for simple local event notifications. |
Signal< RT, std::shared_mutex > | ThreadSignal | Cross-thread signal variant. |
Signal< RT, NullSharedMutex > | LocalSignal | Compatibility alias for the single-threaded fast path. |
uv_process_options_t | ProcessOptions | Raw libuv process spawn options passed through to uv_spawn. |
std::map< std::string, std::string > | StringMap | Generic string-to-string map used for headers, options, and environment-style metadata. |
std::vector< std::string > | StringVec | Generic string vector used for argument lists and ordered string collections. |
std::map< std::string, std::string > | OptionMap | Command Line Option Parser. |
Signal< void(IPacket &)> | PacketSignal | Signal that broadcasts [IPacket](#ipacket) types. |
PacketStreamAdapter | PacketSource | For 0.8.x compatibility. |
PacketProcessor | IPacketizer | Compatibility alias for a packet processor that packetizes stream output. |
PacketProcessor | IDepacketizer | For 0.8.x compatibility. |
std::vector< PacketAdapterReference::Ptr > | PacketAdapterVec | Ordered list of packet adapter references used for sources and processors. |
std::vector< PacketStream * > | PacketStreamVec | Non-owning list of packet stream pointers used for graph traversal helpers. |
std::vector< PacketStream::Ptr > | PacketStreamPtrVec | Owning list of packet stream handles retained across stream graphs. |
std::unique_ptr< IPacketCreationStrategy > | PacketCreationStrategyPtr | Owning handle for one packet creation strategy. |
std::vector< PacketCreationStrategyPtr > | PacketCreationStrategyList | Ordered list of packet creation strategies consulted by a packet factory. |
{#buffer-2}
Buffer
std::vector< char > Buffer()
Core buffer type.
{#nullchannel}
NullChannel
LogChannel NullChannel()
Null log channel.
Redifine the base [LogChannel](#logchannel) as NullChannel so it can be logically used as a disabled log channel.
{#nullsignal}
NullSignal
Signal< void()> NullSignal()
Zero-argument signal alias used for simple local event notifications.
{#threadsignal}
ThreadSignal
template<typename RT> Signal< RT, std::shared_mutex > ThreadSignal()
Cross-thread signal variant.
{#localsignal}
LocalSignal
template<typename RT> Signal< RT, NullSharedMutex > LocalSignal()
Compatibility alias for the single-threaded fast path.
{#processoptions}
ProcessOptions
uv_process_options_t ProcessOptions()
Raw libuv process spawn options passed through to uv_spawn.
{#stringmap}
StringMap
std::map< std::string, std::string > StringMap()
Generic string-to-string map used for headers, options, and environment-style metadata.
{#stringvec}
StringVec
std::vector< std::string > StringVec()
Generic string vector used for argument lists and ordered string collections.
{#optionmap}
OptionMap
std::map< std::string, std::string > OptionMap()
Command Line Option Parser.
{#packetsignal}
PacketSignal
Signal< void(IPacket &)> PacketSignal()
Signal that broadcasts [IPacket](#ipacket) types.
{#packetsource}
PacketSource
PacketStreamAdapter PacketSource()
For 0.8.x compatibility.
{#ipacketizer}
IPacketizer
PacketProcessor IPacketizer()
Compatibility alias for a packet processor that packetizes stream output.
{#idepacketizer}
IDepacketizer
PacketProcessor IDepacketizer()
For 0.8.x compatibility.
{#packetadaptervec}
PacketAdapterVec
std::vector< PacketAdapterReference::Ptr > PacketAdapterVec()
Ordered list of packet adapter references used for sources and processors.
{#packetstreamvec}
PacketStreamVec
std::vector< PacketStream * > PacketStreamVec()
Non-owning list of packet stream pointers used for graph traversal helpers.
{#packetstreamptrvec}
PacketStreamPtrVec
std::vector< PacketStream::Ptr > PacketStreamPtrVec()
Owning list of packet stream handles retained across stream graphs.
{#packetcreationstrategyptr}
PacketCreationStrategyPtr
std::unique_ptr< IPacketCreationStrategy > PacketCreationStrategyPtr()
Owning handle for one packet creation strategy.
{#packetcreationstrategylist}
PacketCreationStrategyList
std::vector< PacketCreationStrategyPtr > PacketCreationStrategyList()
Ordered list of packet creation strategies consulted by a packet factory.
Functions
| Return | Name | Description |
|---|---|---|
void | runOnce | Schedules func to run once at the beginning of the next event loop iteration. Uses a uv_prepare_t handle that self-destructs after the first invocation. |
std::string | formatError inline | Formats a human-readable error string from a message and a libuv error code. If err is not UV_UNKNOWN, the libuv error description is appended after a colon. |
void | throwError inline | Throws a std::runtime_error with a formatted error message. |
MutableBuffer | mutableBuffer inline | Creates a [MutableBuffer](#mutablebuffer) from an arbitrary pointer and size. |
MutableBuffer | mutableBuffer inline | Creates a [MutableBuffer](#mutablebuffer) from a std::string. |
MutableBuffer | mutableBuffer inline | Creates a [MutableBuffer](#mutablebuffer) from a const std::string. Casts away constness; use with care. |
MutableBuffer | mutableBuffer inline | Creates a [MutableBuffer](#mutablebuffer) from a const std::vector. Casts away constness; use with care. |
MutableBuffer | mutableBuffer inline | Creates a [MutableBuffer](#mutablebuffer) from a Buffer. |
MutableBuffer | mutableBuffer inline | Creates a [MutableBuffer](#mutablebuffer) from a const Buffer. Casts away constness; use with care. |
ConstBuffer | constBuffer inline | Creates a [ConstBuffer](#constbuffer) from an arbitrary pointer and size. |
ConstBuffer | constBuffer inline | Creates a [ConstBuffer](#constbuffer) from a std::string. |
ConstBuffer | constBuffer inline | Creates a [ConstBuffer](#constbuffer) from a std::vector. |
constexpr ConstBuffer | constBuffer inline | Creates a [ConstBuffer](#constbuffer) from a [MutableBuffer](#mutablebuffer). |
ConstBuffer | constBuffer inline | Creates a [ConstBuffer](#constbuffer) from a Buffer. |
ConstBuffer | constBuffer inline | Creates a [ConstBuffer](#constbuffer) from a const Buffer. Casts away constness internally; use with care. |
constexpr PointerToPodType | bufferCast inline | Casts a [MutableBuffer](#mutablebuffer) to a specified pointer-to-POD type. |
constexpr PointerToPodType | bufferCast inline | Casts a [ConstBuffer](#constbuffer) to a specified pointer-to-POD type. |
Level | getLevelFromString inline | Converts a log level string to its corresponding Level enum value. Unrecognized strings default to [Level::Trace](#namespaceicy_1aad3e81b3cd2daab89338dae9b5323f6badd4ec0ac4e58f7c32a01244ae91150b1). |
const char * | getStringFromLevel inline | Converts a Level enum value to its lowercase string representation. |
void | logArgs | Write a single logging argument into the destination stream. |
void | logArgs | Write multiple logging arguments into the destination stream in order. |
constexpr const char * | str_end | Return a pointer to the null terminator of a C string. |
constexpr bool | str_slant | Return true if the C string contains a forward or back slash. |
constexpr const char * | r_slant | Walk backward to the character after the last path separator. |
constexpr const char * | _fileName | Return the filename portion of a compile-time path string. |
std::string | _methodName inline | Extract the class-qualified method name from a compiler pretty-function string. |
void | deleteLater inline | Schedules deferred deletion of ptr on the next event loop iteration. This is essential for deleting objects that may still be referenced by pending libuv callbacks (e.g. socket adapters with in-flight I/O). Uses a self-cleaning uv_idle_t handle that fires once and then closes itself. |
IntrusivePtr< T > | makeIntrusive | Creates an IntrusivePtr managing a newly heap-allocated T. Equivalent to std::make_shared. |
std::shared_ptr< internal::Slot< RT, Args... > > | slot | Creates a slot that binds a non-const class member function to an instance. |
std::shared_ptr< internal::Slot< RT, Args... > > | slot | Creates a slot that wraps a free (static) function pointer. |
void | swap inline | Exchange two DateTime values. |
void | swap inline | Exchange two LocalDateTime values. |
void | swap inline | Exchange two Timestamp values. |
void | swap inline | Exchange two Timespan values. |
std::string | getExePath | Cross-platform utilities. |
std::string | getCwd | Return the current working directory. |
uint64_t | getFreeMemory | Returns the current amount of free memory. |
uint64_t | getTotalMemory | Returns the current amount of used memory. |
int | numCpuCores | Returns the number of CPU cores. |
void | sleep | Pause the current thread for the given ms duration. |
void | pause | Pause the current thread until enter is pressed. |
std::string | getHostname | Return the system hostname. |
std::string | getEnv | Return an environment variable or the default value. |
bool | getEnvBool | Return an environment variable boolean or the default value. The variable must be 1 or true for this function to return true. |
void | set8 inline | Writes a single byte at the given offset in memory. |
uint8_t | get8 inline | Reads a single byte at the given offset from memory. |
void | setBE16 inline | Writes a 16-bit value to memory in big-endian byte order. |
void | setBE32 inline | Writes a 32-bit value to memory in big-endian byte order. |
void | setBE64 inline | Writes a 64-bit value to memory in big-endian byte order. |
uint16_t | getBE16 inline | Reads a 16-bit big-endian value from memory. |
uint32_t | getBE32 inline | Reads a 32-bit big-endian value from memory. |
uint64_t | getBE64 inline | Reads a 64-bit big-endian value from memory. |
void | setLE16 inline | Writes a 16-bit value to memory in little-endian byte order. |
void | setLE32 inline | Writes a 32-bit value to memory in little-endian byte order. |
void | setLE64 inline | Writes a 64-bit value to memory in little-endian byte order. |
uint16_t | getLE16 inline | Reads a 16-bit little-endian value from memory. |
uint32_t | getLE32 inline | Reads a 32-bit little-endian value from memory. |
uint64_t | getLE64 inline | Reads a 64-bit little-endian value from memory. |
bool | isBigEndian inline | Returns true if the host CPU is big-endian. |
uint16_t | hostToNetwork16 inline | Converts a 16-bit value from host byte order to network (big-endian) byte order. |
uint32_t | hostToNetwork32 inline | Converts a 32-bit value from host byte order to network (big-endian) byte order. |
uint64_t | hostToNetwork64 inline | Converts a 64-bit value from host byte order to network (big-endian) byte order. |
uint16_t | networkToHost16 inline | Converts a 16-bit value from network (big-endian) byte order to host byte order. |
uint32_t | networkToHost32 inline | Converts a 32-bit value from network (big-endian) byte order to host byte order. |
uint64_t | networkToHost64 inline | Converts a 64-bit value from network (big-endian) byte order to host byte order. |
void | onShutdownSignal inline | Installs a SIGINT handler on the given event loop. When the signal fires, callback is invoked with opaque and the signal handle is closed. |
void | waitForShutdown inline | Installs a SIGINT handler and runs the event loop until shutdown. Equivalent to calling [onShutdownSignal()](#onshutdownsignal) then uv_run(). |
std::shared_ptr< internal::Slot< RT, IT & > > | packetSlot | Creates a signal slot that filters by packet subtype PT before invoking method. |
constexpr unsigned | [`operator | `](#operator-9) |
RawPacket | rawPacket inline | Constructs a non-owning RawPacket from a mutable buffer (borrowed pointer). |
RawPacket | rawPacket inline | Constructs an owning RawPacket from a const buffer (data is copied). |
RawPacket | rawPacket inline | Constructs a non-owning RawPacket from a raw mutable pointer (borrowed). |
RawPacket | rawPacket inline | Constructs an owning RawPacket from a const char pointer (data is copied). |
{#runonce}
runOnce
template<typename Function, typename... Args> void runOnce(uv::Loop * loop, Function && func, Args &&... args)
Schedules func to run once at the beginning of the next event loop iteration. Uses a uv_prepare_t handle that self-destructs after the first invocation.
Parameters
-
loopEvent loop on which to schedule the callback. -
funcCallable to invoke on the next loop tick. -
argsArguments forwarded to func.
{#formaterror}
formatError
inline
inline std::string formatError(std::string_view message, int err)
Formats a human-readable error string from a message and a libuv error code. If err is not UV_UNKNOWN, the libuv error description is appended after a colon.
Parameters
-
messageDescriptive context for the error. -
errlibuv error code (e.g. from a faileduv_*call). Defaults toUV_UNKNOWN.
Returns
Formatted error string.
{#throwerror}
throwError
inline
inline void throwError(std::string_view message, int err)
Throws a std::runtime_error with a formatted error message.
Parameters
-
messageDescriptive context for the error. -
errlibuv error code to append. Defaults toUV_UNKNOWN.
{#mutablebuffer-1}
mutableBuffer
inline
template<typename T> inline MutableBuffer mutableBuffer(T data, size_t size)
Creates a [MutableBuffer](#mutablebuffer) from an arbitrary pointer and size.
Parameters
TPointer type; must be implicitly castable tovoid*.
Parameters
-
dataPointer to the start of the memory region. -
sizeNumber of bytes in the region.
Returns
[MutableBuffer](#mutablebuffer) referencing the given memory.
{#mutablebuffer-2}
mutableBuffer
inline
inline MutableBuffer mutableBuffer(std::string & str)
Creates a [MutableBuffer](#mutablebuffer) from a std::string.
Parameters
strSource string. Must remain valid while the buffer is in use.
Returns
[MutableBuffer](#mutablebuffer) wrapping the string's internal storage.
{#mutablebuffer-3}
mutableBuffer
inline
inline MutableBuffer mutableBuffer(const std::string & str)
Creates a [MutableBuffer](#mutablebuffer) from a const std::string. Casts away constness; use with care.
Parameters
strSource string. Must remain valid while the buffer is in use.
Returns
[MutableBuffer](#mutablebuffer) wrapping the string's internal storage.
{#mutablebuffer-4}
mutableBuffer
inline
template<typename T> inline MutableBuffer mutableBuffer(const std::vector< T > & vec)
Creates a [MutableBuffer](#mutablebuffer) from a const std::vector. Casts away constness; use with care.
Parameters
TElement type of the vector.
Parameters
vecSource vector. Must remain valid while the buffer is in use.
Returns
[MutableBuffer](#mutablebuffer) wrapping the vector's internal storage.
{#mutablebuffer-5}
mutableBuffer
inline
inline MutableBuffer mutableBuffer(Buffer & buf)
Creates a [MutableBuffer](#mutablebuffer) from a Buffer.
Parameters
bufSource buffer. Must remain valid while the buffer is in use.
Returns
[MutableBuffer](#mutablebuffer) wrapping the buffer's data.
{#mutablebuffer-6}
mutableBuffer
inline
inline MutableBuffer mutableBuffer(const Buffer & buf)
Creates a [MutableBuffer](#mutablebuffer) from a const Buffer. Casts away constness; use with care.
Parameters
bufSource buffer. Must remain valid while the buffer is in use.
Returns
[MutableBuffer](#mutablebuffer) wrapping the buffer's data.
{#constbuffer-1}
constBuffer
inline
template<typename T> inline ConstBuffer constBuffer(T data, size_t size)
Creates a [ConstBuffer](#constbuffer) from an arbitrary pointer and size.
Parameters
TPointer type; must be implicitly castable toconst void*.
Parameters
-
dataPointer to the start of the memory region. -
sizeNumber of bytes in the region.
Returns
[ConstBuffer](#constbuffer) referencing the given memory.
{#constbuffer-2}
constBuffer
inline
inline ConstBuffer constBuffer(const std::string & str)
Creates a [ConstBuffer](#constbuffer) from a std::string.
Parameters
strSource string. Must remain valid while the buffer is in use.
Returns
[ConstBuffer](#constbuffer) wrapping the string's internal storage.
{#constbuffer-3}
constBuffer
inline
template<typename T> inline ConstBuffer constBuffer(const std::vector< T > & vec)
Creates a [ConstBuffer](#constbuffer) from a std::vector.
Parameters
TElement type of the vector.
Parameters
vecSource vector. Must remain valid while the buffer is in use.
Returns
[ConstBuffer](#constbuffer) wrapping the vector's internal storage.
{#constbuffer-4}
constBuffer
inline
inline constexpr ConstBuffer constBuffer(const MutableBuffer & buf)
Creates a [ConstBuffer](#constbuffer) from a [MutableBuffer](#mutablebuffer).
Parameters
bufSource mutable buffer.
Returns
[ConstBuffer](#constbuffer) referencing the same memory region.
{#constbuffer-5}
constBuffer
inline
template<typename T> inline ConstBuffer constBuffer(Buffer & buf)
Creates a [ConstBuffer](#constbuffer) from a Buffer.
Parameters
TUnused; kept for overload symmetry.
Parameters
bufSource buffer. Must remain valid while the buffer is in use.
Returns
[ConstBuffer](#constbuffer) wrapping the buffer's data.
{#constbuffer-6}
constBuffer
inline
template<typename T> inline ConstBuffer constBuffer(const Buffer & buf)
Creates a [ConstBuffer](#constbuffer) from a const Buffer. Casts away constness internally; use with care.
Parameters
TUnused; kept for overload symmetry.
Parameters
bufSource buffer. Must remain valid while the buffer is in use.
Returns
[ConstBuffer](#constbuffer) wrapping the buffer's data.
{#buffercast}
bufferCast
inline
template<typename PointerToPodType> inline constexpr PointerToPodType bufferCast(const MutableBuffer & b)
Casts a [MutableBuffer](#mutablebuffer) to a specified pointer-to-POD type.
Parameters
PointerToPodTypeTarget pointer type (e.g.char*,uint8_t*).
Parameters
bSource mutable buffer.
Returns
Pointer to the buffer's data, cast to PointerToPodType.
{#buffercast-1}
bufferCast
inline
template<typename PointerToPodType> inline constexpr PointerToPodType bufferCast(const ConstBuffer & b)
Casts a [ConstBuffer](#constbuffer) to a specified pointer-to-POD type.
Parameters
PointerToPodTypeTarget pointer type (e.g.const char*,const uint8_t*).
Parameters
bSource const buffer.
Returns
Pointer to the buffer's data, cast to PointerToPodType.
{#getlevelfromstring}
getLevelFromString
inline
inline Level getLevelFromString(const char * level)
Converts a log level string to its corresponding Level enum value. Unrecognized strings default to [Level::Trace](#namespaceicy_1aad3e81b3cd2daab89338dae9b5323f6badd4ec0ac4e58f7c32a01244ae91150b1).
Parameters
levelLowercase level string: "trace", "debug", "info", "warn", "error", or "fatal".
Returns
The matching Level enum value.
{#getstringfromlevel}
getStringFromLevel
inline
inline const char * getStringFromLevel(Level level)
Converts a Level enum value to its lowercase string representation.
Parameters
levelThe log level to convert.
Returns
Lowercase C string: "trace", "debug", "info", "warn", "error", or "fatal".
{#logargs}
logArgs
template<typename T> void logArgs(std::ostream & o, T && t)
Write a single logging argument into the destination stream.
Parameters
-
oDestination stream. -
tArgument to append with operator<<.
{#logargs-1}
logArgs
template<typename T, typename... Args> void logArgs(std::ostream & o, T && t, Args &&... args)
Write multiple logging arguments into the destination stream in order.
Parameters
-
oDestination stream. -
tFirst argument to append. -
argsRemaining arguments to append recursively.
{#str_end}
str_end
constexpr const char * str_end(const char * str)
Return a pointer to the null terminator of a C string.
{#str_slant}
str_slant
constexpr bool str_slant(const char * str)
Return true if the C string contains a forward or back slash.
{#r_slant}
r_slant
constexpr const char * r_slant(const char * str)
Walk backward to the character after the last path separator.
{#_filename}
_fileName
constexpr const char * _fileName(const char * str)
Return the filename portion of a compile-time path string.
{#_methodname}
_methodName
inline
inline std::string _methodName(std::string_view fsig)
Extract the class-qualified method name from a compiler pretty-function string.
{#deletelater}
deleteLater
inline
template<typename T> inline void deleteLater(T * ptr, uv::Loop * loop)
Schedules deferred deletion of ptr on the next event loop iteration. This is essential for deleting objects that may still be referenced by pending libuv callbacks (e.g. socket adapters with in-flight I/O). Uses a self-cleaning uv_idle_t handle that fires once and then closes itself.
Parameters
TType of the object to delete.
Parameters
-
ptrObject to delete. Does nothing if nullptr. -
loopEvent loop on which to schedule the deletion.
{#makeintrusive}
makeIntrusive
template<typename T, typename... Args> IntrusivePtr< T > makeIntrusive(Args &&... args)
Creates an IntrusivePtr managing a newly heap-allocated T. Equivalent to std::make_shared.
Parameters
TType to construct; must inherit from RefCounted.
Parameters
argsArguments forwarded to T's constructor.
Returns
IntrusivePtr
{#slot}
slot
template<class Class, class RT, typename... Args> std::shared_ptr< internal::Slot< RT, Args... > > slot(Class * instance, RT(Class::*)(Args...) method, int id, int priority)
Creates a slot that binds a non-const class member function to an instance.
The returned SlotPtr can be passed to Signal::attach() or operator+=, and to Signal::detach() or operator-= to disconnect it later.
Parameters
-
ClassThe class that owns the member function. -
RTReturn type of the member function. -
ArgsParameter types of the member function.
Parameters
-
instancePointer to the object on whichmethodwill be called. -
methodPointer to the non-const member function to bind. -
idExplicit slot ID to assign; pass-1to auto-assign. -
priorityHigher values are called first; pass-1for default ordering.
Returns
A SlotPtr ready to attach to a compatible [Signal](#signal).
Creates a slot that binds a const class member function to an instance. Uses the same slot ID and priority rules as the non-const overload above.
{#slot-1}
slot
template<class RT, typename... Args> std::shared_ptr< internal::Slot< RT, Args... > > slot(RT(*)(Args...) method, int id, int priority)
Creates a slot that wraps a free (static) function pointer.
Parameters
-
RTReturn type of the function. -
ArgsParameter types of the function.
Parameters
-
methodPointer to the free function to bind. -
idExplicit slot ID to assign; pass-1to auto-assign. -
priorityHigher values are called first; pass-1for default ordering.
Returns
A SlotPtr ready to attach to a compatible [Signal](#signal).
{#swap-2}
swap
inline
inline void swap(DateTime & d1, DateTime & d2)
Exchange two DateTime values.
{#swap-3}
swap
inline
inline void swap(LocalDateTime & d1, LocalDateTime & d2)
Exchange two LocalDateTime values.
{#swap-4}
swap
inline
inline void swap(Timestamp & s1, Timestamp & s2)
Exchange two Timestamp values.
{#swap-5}
swap
inline
inline void swap(Timespan & s1, Timespan & s2)
Exchange two Timespan values.
{#getexepath}
getExePath
std::string getExePath()
Cross-platform utilities.
Returns the current executable path.
{#getcwd}
getCwd
std::string getCwd()
Return the current working directory.
{#getfreememory}
getFreeMemory
uint64_t getFreeMemory()
Returns the current amount of free memory.
{#gettotalmemory}
getTotalMemory
uint64_t getTotalMemory()
Returns the current amount of used memory.
{#numcpucores}
numCpuCores
int numCpuCores()
Returns the number of CPU cores.
{#sleep}
sleep
void sleep(int ms)
Pause the current thread for the given ms duration.
{#pause}
pause
void pause()
Pause the current thread until enter is pressed.
{#gethostname}
getHostname
std::string getHostname()
Return the system hostname.
{#getenv}
getEnv
std::string getEnv(std::string_view name, std::string_view defaultValue)
Return an environment variable or the default value.
{#getenvbool}
getEnvBool
bool getEnvBool(std::string_view name)
Return an environment variable boolean or the default value. The variable must be 1 or true for this function to return true.
{#set8}
set8
inline
inline void set8(void * memory, size_t offset, uint8_t v)
Writes a single byte at the given offset in memory.
Parameters
-
memoryPointer to the destination buffer. -
offsetByte offset within the buffer. -
vValue to write.
{#get8}
get8
inline
inline uint8_t get8(const void * memory, size_t offset)
Reads a single byte at the given offset from memory.
Parameters
-
memoryPointer to the source buffer. -
offsetByte offset within the buffer.
Returns
The byte value at the specified offset.
{#setbe16}
setBE16
inline
inline void setBE16(void * memory, uint16_t v)
Writes a 16-bit value to memory in big-endian byte order.
Parameters
-
memoryPointer to the destination buffer (must be at least 2 bytes). -
vValue to write.
{#setbe32}
setBE32
inline
inline void setBE32(void * memory, uint32_t v)
Writes a 32-bit value to memory in big-endian byte order.
Parameters
-
memoryPointer to the destination buffer (must be at least 4 bytes). -
vValue to write.
{#setbe64}
setBE64
inline
inline void setBE64(void * memory, uint64_t v)
Writes a 64-bit value to memory in big-endian byte order.
Parameters
-
memoryPointer to the destination buffer (must be at least 8 bytes). -
vValue to write.
{#getbe16}
getBE16
inline
inline uint16_t getBE16(const void * memory)
Reads a 16-bit big-endian value from memory.
Parameters
memoryPointer to the source buffer (must be at least 2 bytes).
Returns
The 16-bit value in host byte order.
{#getbe32}
getBE32
inline
inline uint32_t getBE32(const void * memory)
Reads a 32-bit big-endian value from memory.
Parameters
memoryPointer to the source buffer (must be at least 4 bytes).
Returns
The 32-bit value in host byte order.
{#getbe64}
getBE64
inline
inline uint64_t getBE64(const void * memory)
Reads a 64-bit big-endian value from memory.
Parameters
memoryPointer to the source buffer (must be at least 8 bytes).
Returns
The 64-bit value in host byte order.
{#setle16}
setLE16
inline
inline void setLE16(void * memory, uint16_t v)
Writes a 16-bit value to memory in little-endian byte order.
Parameters
-
memoryPointer to the destination buffer (must be at least 2 bytes). -
vValue to write.
{#setle32}
setLE32
inline
inline void setLE32(void * memory, uint32_t v)
Writes a 32-bit value to memory in little-endian byte order.
Parameters
-
memoryPointer to the destination buffer (must be at least 4 bytes). -
vValue to write.
{#setle64}
setLE64
inline
inline void setLE64(void * memory, uint64_t v)
Writes a 64-bit value to memory in little-endian byte order.
Parameters
-
memoryPointer to the destination buffer (must be at least 8 bytes). -
vValue to write.
{#getle16}
getLE16
inline
inline uint16_t getLE16(const void * memory)
Reads a 16-bit little-endian value from memory.
Parameters
memoryPointer to the source buffer (must be at least 2 bytes).
Returns
The 16-bit value in host byte order.
{#getle32}
getLE32
inline
inline uint32_t getLE32(const void * memory)
Reads a 32-bit little-endian value from memory.
Parameters
memoryPointer to the source buffer (must be at least 4 bytes).
Returns
The 32-bit value in host byte order.
{#getle64}
getLE64
inline
inline uint64_t getLE64(const void * memory)
Reads a 64-bit little-endian value from memory.
Parameters
memoryPointer to the source buffer (must be at least 8 bytes).
Returns
The 64-bit value in host byte order.
{#isbigendian}
isBigEndian
inline
inline bool isBigEndian()
Returns true if the host CPU is big-endian.
Returns
true if the host byte order is big-endian, false if little-endian.
{#hosttonetwork16}
hostToNetwork16
inline
inline uint16_t hostToNetwork16(uint16_t n)
Converts a 16-bit value from host byte order to network (big-endian) byte order.
Parameters
nValue in host byte order.
Returns
Value in network byte order.
{#hosttonetwork32}
hostToNetwork32
inline
inline uint32_t hostToNetwork32(uint32_t n)
Converts a 32-bit value from host byte order to network (big-endian) byte order.
Parameters
nValue in host byte order.
Returns
Value in network byte order.
{#hosttonetwork64}
hostToNetwork64
inline
inline uint64_t hostToNetwork64(uint64_t n)
Converts a 64-bit value from host byte order to network (big-endian) byte order.
Parameters
nValue in host byte order.
Returns
Value in network byte order.
{#networktohost16}
networkToHost16
inline
inline uint16_t networkToHost16(uint16_t n)
Converts a 16-bit value from network (big-endian) byte order to host byte order.
Parameters
nValue in network byte order.
Returns
Value in host byte order.
{#networktohost32}
networkToHost32
inline
inline uint32_t networkToHost32(uint32_t n)
Converts a 32-bit value from network (big-endian) byte order to host byte order.
Parameters
nValue in network byte order.
Returns
Value in host byte order.
{#networktohost64}
networkToHost64
inline
inline uint64_t networkToHost64(uint64_t n)
Converts a 64-bit value from network (big-endian) byte order to host byte order.
Parameters
nValue in network byte order.
Returns
Value in host byte order.
{#onshutdownsignal}
onShutdownSignal
inline
inline void onShutdownSignal(std::function< void(void *)> callback, void * opaque, uv::Loop * loop)
Installs a SIGINT handler on the given event loop. When the signal fires, callback is invoked with opaque and the signal handle is closed.
Parameters
-
callbackOptional function called on SIGINT. -
opaqueOptional user data pointer passed to the callback. -
loopEvent loop to attach the signal watcher to.
{#waitforshutdown}
waitForShutdown
inline
inline void waitForShutdown(std::function< void(void *)> callback, void * opaque, uv::Loop * loop)
Installs a SIGINT handler and runs the event loop until shutdown. Equivalent to calling [onShutdownSignal()](#onshutdownsignal) then uv_run().
Parameters
-
callbackOptional function called on SIGINT before the loop exits. -
opaqueOptional user data pointer passed to the callback. -
loopEvent loop to run.
{#packetslot}
packetSlot
template<class Class, class RT, class PT, class IT> std::shared_ptr< internal::Slot< RT, IT & > > packetSlot(Class * instance, RT(Class::*)(PT &) method, int id, int priority)
Creates a signal slot that filters by packet subtype PT before invoking method.
The returned slot is connected to a PacketSignal (which broadcasts [IPacket](#ipacket)&). The slot performs a dynamic_cast on each received packet; if the cast succeeds, the listener method is called with the derived type PT. Non-matching packets are silently ignored.
Parameters
-
ClassListener class type. -
RTReturn type of the listener method. -
PTDerived packet type the listener expects (must derive fromIT). -
ITBase packet interface type; defaults to[IPacket](#ipacket).
Parameters
-
instancePointer to the listener object. -
methodMember function pointer onClassaccepting aPT&. -
idOptional slot identifier; -1 for automatic assignment. -
priorityOptional slot priority; higher values run first.
Returns
A shared slot suitable for connecting to a PacketSignal.
{#operator-9}
operator|
constexpr unsigned operator|(PacketFlags lhs, PacketFlags rhs)
Combine PacketFlags values into a bitmask.
{#rawpacket-1}
rawPacket
inline
inline RawPacket rawPacket(const MutableBuffer & buf, unsigned flags, std::unique_ptr< IPacketInfo > info)
Constructs a non-owning RawPacket from a mutable buffer (borrowed pointer).
{#rawpacket-2}
rawPacket
inline
inline RawPacket rawPacket(const ConstBuffer & buf, unsigned flags, std::unique_ptr< IPacketInfo > info)
Constructs an owning RawPacket from a const buffer (data is copied).
{#rawpacket-3}
rawPacket
inline
inline RawPacket rawPacket(char * data, size_t size, unsigned flags, std::unique_ptr< IPacketInfo > info)
Constructs a non-owning RawPacket from a raw mutable pointer (borrowed).
{#rawpacket-4}
rawPacket
inline
inline RawPacket rawPacket(const char * data, size_t size, unsigned flags, std::unique_ptr< IPacketInfo > info)
Constructs an owning RawPacket from a const char pointer (data is copied).
{#hex}
hex
Hexadecimal encoding and decoding helpers.
Classes
| Name | Description |
|---|---|
Decoder | Hex decoder. |
Encoder | Hex encoder. |
Functions
| Return | Name | Description |
|---|---|---|
std::string | encode inline | Converts the STL container to Hex. |
{#encode-14}
encode
inline
template<typename T> inline std::string encode(const T & bytes)
Converts the STL container to Hex.
{#decoder}
Decoder
#include <icy/hex.h>
Inherits:
Decoder
Hex decoder.
Public Attributes
| Return | Name | Description |
|---|---|---|
char | lastbyte |
{#lastbyte}
lastbyte
char lastbyte
Public Methods
| Return | Name | Description |
|---|---|---|
Decoder inline | ||
ssize_t | decode virtual inline | Decodes hex-encoded input to binary. Whitespace in the input is ignored. A trailing unpaired nibble is buffered and prepended on the next call. |
ssize_t | finalize virtual inline | No-op finalizer; hex decoding has no pending output state. |
bool | readnext inline | Reads the next non-whitespace character from inbuf, prepending any buffered lastbyte before consuming from the stream. |
int | nybble inline | Converts an ASCII hex character to its 4-bit integer value. |
bool | iswspace inline | Returns true if c is an ASCII whitespace character (space, CR, tab, LF). |
{#decoder-1}
Decoder
inline
inline Decoder()
{#decode-4}
decode
virtual inline
virtual inline ssize_t decode(const char * inbuf, size_t nread, char * outbuf)
Decodes hex-encoded input to binary. Whitespace in the input is ignored. A trailing unpaired nibble is buffered and prepended on the next call.
Parameters
-
inbufHex-encoded input buffer. -
nreadNumber of bytes to read from inbuf. -
outbufDestination buffer; must have capacity >= nread / 2.
Returns
Number of decoded bytes written to outbuf.
{#finalize}
finalize
virtual inline
virtual inline ssize_t finalize(char *)
No-op finalizer; hex decoding has no pending output state.
Returns
Always 0.
{#readnext}
readnext
inline
inline bool readnext(const char * inbuf, size_t nread, size_t & rpos, char & c)
Reads the next non-whitespace character from inbuf, prepending any buffered lastbyte before consuming from the stream.
Parameters
-
inbufInput buffer. -
nreadTotal bytes in inbuf. -
rposCurrent read position; advanced on each consumed byte. -
cOutput: the next non-whitespace character.
Returns
true if more input remains after c was read, false otherwise.
{#nybble}
nybble
inline
inline int nybble(const int n)
Converts an ASCII hex character to its 4-bit integer value.
Parameters
nASCII character ('0'-'9', 'a'-'f', 'A'-'F').
Returns
Integer value in the range [0, 15].
Exceptions
std::runtime_errorif n is not a valid hex character.
{#iswspace}
iswspace
inline
inline bool iswspace(const char c)
Returns true if c is an ASCII whitespace character (space, CR, tab, LF).
Parameters
cCharacter to test.
Returns
true if c is whitespace.
{#encoder-1}
Encoder
#include <icy/hex.h>
Inherits:
Encoder
Hex encoder.
Public Attributes
| Return | Name | Description |
|---|---|---|
int | _linePos | |
int | _lineLength | |
int | _uppercase |
{#_linepos}
_linePos
int _linePos
{#_linelength}
_lineLength
int _lineLength
{#_uppercase}
_uppercase
int _uppercase
Public Methods
| Return | Name | Description |
|---|---|---|
Encoder inline | ||
ssize_t | encode virtual inline | Encodes binary input as lowercase hex characters, optionally inserting newlines every _lineLength output characters. |
ssize_t | finalize virtual inline | No-op finalizer; hex encoding has no pending state. |
void | setUppercase inline | Controls whether encoded output uses uppercase hex digits (A-F) or lowercase (a-f). |
void | setLineLength inline | Sets the maximum number of output characters per line before a newline is inserted. Set to 0 to disable line wrapping. |
{#encoder-2}
Encoder
inline
inline Encoder()
{#encode-15}
encode
virtual inline
virtual inline ssize_t encode(const char * inbuf, size_t nread, char * outbuf)
Encodes binary input as lowercase hex characters, optionally inserting newlines every _lineLength output characters.
Parameters
-
inbufInput buffer to encode. -
nreadNumber of bytes to read from inbuf. -
outbufDestination buffer; must have capacity >= nread * 2 + nread/_lineLength + 1.
Returns
Number of bytes written to outbuf.
{#finalize-1}
finalize
virtual inline
virtual inline ssize_t finalize(char *)
No-op finalizer; hex encoding has no pending state.
Returns
Always 0.
{#setuppercase}
setUppercase
inline
inline void setUppercase(bool flag)
Controls whether encoded output uses uppercase hex digits (A-F) or lowercase (a-f).
Parameters
flagtrue for uppercase, false for lowercase.
{#setlinelength}
setLineLength
inline
inline void setLineLength(int lineLength)
Sets the maximum number of output characters per line before a newline is inserted. Set to 0 to disable line wrapping.
Parameters
lineLengthCharacters per line.
{#ipc}
ipc
Classes for inter-process communication.
Classes
| Name | Description |
|---|---|
Queue | IPC queue is for safely passing templated actions between threads and processes. |
SyncQueue | IPC synchronization queue is for passing templated actions between threads and the event loop we are synchronizing with. |
Action | Default action type for executing synchronized callbacks. |
Typedefs
| Return | Name | Description |
|---|---|---|
ipc::Queue< ipc::Action > | ActionQueue | |
ipc::SyncQueue< ipc::Action > | ActionSyncQueue |
{#actionqueue}
ActionQueue
ipc::Queue< ipc::Action > ActionQueue()
{#actionsyncqueue}
ActionSyncQueue
ipc::SyncQueue< ipc::Action > ActionSyncQueue()
{#queue-1}
Queue
#include <icy/ipc.h>
Subclassed by:
SyncQueue< TAction >
IPC queue is for safely passing templated actions between threads and processes.
Public Methods
| Return | Name | Description |
|---|---|---|
Queue inline | ||
void | push virtual inline | Pushes an action onto the queue and triggers a post notification. Takes ownership of action; the queue deletes it after execution. Thread-safe. |
TAction * | pop virtual inline | Removes and returns the next action from the front of the queue. The caller takes ownership of the returned pointer. Thread-safe. |
void | runSync virtual inline | Drains the queue by invoking and deleting every pending action in order. Must be called from the thread that owns the event loop. |
void | close virtual inline | Closes the underlying notification handle. No-op in the base implementation. |
void | post virtual inline | Signals the event loop that new actions are available. No-op in the base implementation. |
void | waitForSync inline | Blocks the calling thread until the queue is empty or the timeout elapses. Polls every 10 ms. Logs a warning if the timeout is reached. |
{#queue-2}
Queue
inline
inline Queue()
{#push-1}
push
virtual inline
virtual inline void push(TAction * action)
Pushes an action onto the queue and triggers a post notification. Takes ownership of action; the queue deletes it after execution. Thread-safe.
Parameters
actionHeap-allocated action to enqueue.
{#pop}
pop
virtual inline
virtual inline TAction * pop()
Removes and returns the next action from the front of the queue. The caller takes ownership of the returned pointer. Thread-safe.
Returns
Pointer to the next action, or nullptr if the queue is empty.
{#runsync}
runSync
virtual inline
virtual inline void runSync()
Drains the queue by invoking and deleting every pending action in order. Must be called from the thread that owns the event loop.
{#close-17}
close
virtual inline
virtual inline void close()
Closes the underlying notification handle. No-op in the base implementation.
{#post}
post
virtual inline
virtual inline void post()
Signals the event loop that new actions are available. No-op in the base implementation.
{#waitforsync}
waitForSync
inline
inline void waitForSync(std::chrono::milliseconds timeout)
Blocks the calling thread until the queue is empty or the timeout elapses. Polls every 10 ms. Logs a warning if the timeout is reached.
Parameters
timeoutMaximum time to wait (default: 5000 ms).
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::mutex | _mutex | |
std::deque< TAction * > | _actions |
{#_mutex-7}
_mutex
std::mutex _mutex
{#_actions}
_actions
std::deque< TAction * > _actions
{#syncqueue-1}
SyncQueue
#include <icy/ipc.h>
Inherits:
Action >
IPC synchronization queue is for passing templated actions between threads and the event loop we are synchronizing with.
Public Methods
| Return | Name | Description |
|---|---|---|
SyncQueue inline | Constructs a SyncQueue bound to the given libuv event loop. | |
void | close virtual inline | Closes the underlying Synchronizer handle and stops loop wakeups. |
void | post virtual inline | Wakes up the event loop so pending actions are dispatched via runSync(). |
Synchronizer & | sync virtual inline | Returns a reference to the internal Synchronizer. |
{#syncqueue-2}
SyncQueue
inline
inline SyncQueue(uv::Loop * loop)
Constructs a SyncQueue bound to the given libuv event loop.
Parameters
loopEvent loop to synchronize with (default: the process-wide default loop).
{#close-18}
close
virtual inline
virtual inline void close()
Closes the underlying Synchronizer handle and stops loop wakeups.
{#post-1}
post
virtual inline
virtual inline void post()
Wakes up the event loop so pending actions are dispatched via runSync().
{#sync}
sync
virtual inline
virtual inline Synchronizer & sync()
Returns a reference to the internal Synchronizer.
Returns
Reference to the Synchronizer used for loop wakeup.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Synchronizer | _sync |
{#_sync}
_sync
Synchronizer _sync
{#action}
Action
#include <icy/ipc.h>
Default action type for executing synchronized callbacks.
Public Attributes
| Return | Name | Description |
|---|---|---|
Callback | target | The callable to invoke when the action is dispatched. |
void * | arg | Optional opaque pointer passed to the callback. |
std::string | data | Optional string payload passed to the callback. |
{#target}
target
Callback target
The callable to invoke when the action is dispatched.
{#arg}
arg
void * arg
Optional opaque pointer passed to the callback.
{#data}
data
std::string data
Optional string payload passed to the callback.
Public Methods
| Return | Name | Description |
|---|---|---|
Action inline | Constructs an Action with the given callback, optional argument, and optional data. |
{#action-1}
Action
inline
inline Action(Callback target, void * arg, const std::string & data)
Constructs an Action with the given callback, optional argument, and optional data.
Parameters
-
targetCallback to invoke on dispatch. -
argOpaque pointer passed to the callback (default: nullptr). -
dataString payload passed to the callback (default: empty).
Public Types
| Name | Description |
|---|---|
Callback |
{#callback-1}
Callback
std::function< void(const Action &)> Callback()
{#test}
test
Modern unit testing framework.
Classes
| Name | Description |
|---|---|
FunctionTest | Test wrapper for standalone test functions. |
Test | Test wrapper class. |
TestRunner | Test manager queue. |
Typedefs
| Return | Name | Description |
|---|---|---|
std::list< Test * > | TestList | |
std::list< std::string > | SErrorist | |
std::map< Test *, SErrorist > | ErrorMap |
{#testlist}
TestList
std::list< Test * > TestList()
{#serrorist}
SErrorist
std::list< std::string > SErrorist()
{#errormap}
ErrorMap
std::map< Test *, SErrorist > ErrorMap()
Functions
| Return | Name | Description |
|---|---|---|
void | init | Initialize the test environment. |
int | finalize | Finalize the test environment. |
void | runAll | Run all tests. |
void | describe | Describe a test environment implemented by the given lambda function. |
void | describe | Describe a test environment implemented by the given test instance. |
void | expectImpl | Expect asserts that a condition is true (use expect() as defined below). |
bool | waitFor | Run the event loop until a condition is met or timeout expires. Returns true if the condition was satisfied, false on timeout. Useful for testing async operations that complete via libuv callbacks. |
{#init-7}
init
void init()
Initialize the test environment.
{#finalize-2}
finalize
int finalize()
Finalize the test environment.
Destroy the TestRunner singleton instance and return the exit code.
{#runall}
runAll
void runAll()
Run all tests.
{#describe}
describe
void describe(const std::string & name, std::function< void()> target)
Describe a test environment implemented by the given lambda function.
{#describe-1}
describe
void describe(const std::string & name, Test * test)
Describe a test environment implemented by the given test instance.
{#expectimpl}
expectImpl
void expectImpl(bool passed, const char * assert, const char * file, long line)
Expect asserts that a condition is true (use expect() as defined below).
{#waitfor}
waitFor
bool waitFor(std::function< bool()> condition, int timeoutMs)
Run the event loop until a condition is met or timeout expires. Returns true if the condition was satisfied, false on timeout. Useful for testing async operations that complete via libuv callbacks.
{#functiontest}
FunctionTest
#include <icy/test.h>
Inherits:
Test
Test wrapper for standalone test functions.
Public Attributes
| Return | Name | Description |
|---|---|---|
std::function< void()> | target |
{#target-1}
target
std::function< void()> target
Public Methods
| Return | Name | Description |
|---|---|---|
FunctionTest inline | #### Parameters |
{#functiontest-1}
FunctionTest
inline
inline FunctionTest(std::function< void()> target, const std::string & name)
Parameters
-
targetLambda or function to execute as the test body. -
nameHuman-readable test name.
Protected Methods
| Return | Name | Description |
|---|---|---|
void | run virtual inline | Called by the TestRunner to run the test. |
{#run-1}
run
virtual inline
virtual inline void run()
Called by the TestRunner to run the test.
{#test-1}
Test
#include <icy/test.h>
Subclassed by:
FunctionTest
Test wrapper class.
This class is for implementing any kind of unit test that can be executed by a [TestRunner](#testrunner).
Public Attributes
| Return | Name | Description |
|---|---|---|
std::string | name | The name of the test. |
SErrorist | errors | A list of test errors. |
double | duration | The test run duration for benchmarking. |
{#name-4}
name
std::string name
The name of the test.
{#errors}
errors
SErrorist errors
A list of test errors.
{#duration-1}
duration
double duration
The test run duration for benchmarking.
Public Methods
| Return | Name | Description |
|---|---|---|
Test | #### Parameters | |
~Test virtual | Should remain protected. | |
void | run | Called by the TestRunner to run the test. |
bool | passed | Return true when the test passed without errors. |
{#test-2}
Test
Test(const std::string & name)
Parameters
nameHuman-readable name displayed in test output.
{#test-3}
~Test
virtual
virtual ~Test()
Should remain protected.
{#run-2}
run
void run()
Called by the TestRunner to run the test.
{#passed}
passed
bool passed()
Return true when the test passed without errors.
Protected Methods
| Return | Name | Description |
|---|---|---|
Test | Deleted constructor. |
{#test-4}
Test
Test(const Test & test) = delete
Deleted constructor.
{#testrunner}
TestRunner
#include <icy/test.h>
Test manager queue.
The [TestRunner](#testrunner) is a queue in charge of running one or many tests.
When [run()](#run-3) the [TestRunner](#testrunner) loops through each test in the list calling the test's [run()](#run-3) method.
Public Methods
| Return | Name | Description |
|---|---|---|
TestRunner | ||
void | add | Adds a test to the runner and prints its name to stdout. |
Test * | get const | Return a pointer to the test matching the given name, or nullptr if no matching test exists. |
void | run | Runs all registered tests sequentially, printing results to stdout. |
void | clear | Destroy and clears all managed tests. |
Test * | current const | Return the currently active Test or nullptr. |
TestList | tests const | Return the list of tests. |
ErrorMap | errors const | Return a map of tests and errors. |
bool | passed const | Return true if all tests passed. |
{#testrunner-1}
TestRunner
TestRunner()
{#add}
add
void add(Test * test)
Adds a test to the runner and prints its name to stdout.
Parameters
testNon-null pointer to the test; the runner takes ownership.
{#get-3}
get
const
Test * get(std::string_view name) const
Return a pointer to the test matching the given name, or nullptr if no matching test exists.
Parameters
nameTest name to search for.
Returns
Matching test pointer or nullptr.
{#run-3}
run
void run()
Runs all registered tests sequentially, printing results to stdout.
{#clear-1}
clear
void clear()
Destroy and clears all managed tests.
{#current}
current
const
Test * current() const
Return the currently active Test or nullptr.
{#tests}
tests
const
TestList tests() const
Return the list of tests.
{#errors-1}
errors
const
ErrorMap errors() const
Return a map of tests and errors.
{#passed-1}
passed
const
bool passed() const
Return true if all tests passed.
Public Static Methods
| Return | Name | Description |
|---|---|---|
TestRunner & | getDefault static | Return the default [TestRunner](#testrunner) singleton, although [TestRunner](#testrunner) instances may also be initialized individually. |
{#getdefault-1}
getDefault
static
static TestRunner & getDefault()
Return the default [TestRunner](#testrunner) singleton, although [TestRunner](#testrunner) instances may also be initialized individually.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::mutex | _mutex | |
TestList | _tests | |
Test * | _current |
{#_mutex-8}
_mutex
std::mutex _mutex
{#_tests}
_tests
TestList _tests
{#_current}
_current
Test * _current
{#time-3}
time
Classes and functions for handling time.
Functions
| Return | Name | Description |
|---|---|---|
std::time_t | now | Returns the current wall-clock time as a UTC time_t (seconds since epoch). |
double | clockSecs | Returns the elapsed process time in decimal seconds using a monotonic clock. |
std::string | print | Formats a broken-down time value using the given strftime format string. |
std::string | printLocal | Formats the current local time using the given strftime format string. |
std::string | printUTC | Formats the current UTC time using the given strftime format string. |
std::tm | toLocal | Converts a time_t value to a broken-down local time structure. Uses thread-safe native functions (localtime_r / localtime_s). |
std::tm | toUTC | Converts a time_t value to a broken-down UTC time structure. Uses thread-safe native functions (gmtime_r / gmtime_s). |
std::string | getLocal | Returns the current local time as an ISO8601 formatted string. |
std::string | getUTC | Returns the current UTC time as an ISO8601 formatted string. |
uint64_t | hrtime | Returns the current high-resolution monotonic time in nanoseconds. |
{#now}
now
std::time_t now()
Returns the current wall-clock time as a UTC time_t (seconds since epoch).
Returns
Current UTC time in seconds since the Unix epoch.
{#clocksecs}
clockSecs
double clockSecs()
Returns the elapsed process time in decimal seconds using a monotonic clock.
Returns
Process time in seconds.
{#print-7}
std::string print(const std::tm & dt, const char * fmt)
Formats a broken-down time value using the given strftime format string.
Parameters
-
dtBroken-down time to format. -
fmtstrftime format string (default: ISO8601Format).
Returns
Formatted time string.
{#printlocal}
printLocal
std::string printLocal(const char * fmt)
Formats the current local time using the given strftime format string.
Parameters
fmtstrftime format string (default: ISO8601Format).
Returns
Formatted local time string.
{#printutc}
printUTC
std::string printUTC(const char * fmt)
Formats the current UTC time using the given strftime format string.
Parameters
fmtstrftime format string (default: ISO8601Format).
Returns
Formatted UTC time string.
{#tolocal}
toLocal
std::tm toLocal(const std::time_t & time)
Converts a time_t value to a broken-down local time structure. Uses thread-safe native functions (localtime_r / localtime_s).
Parameters
timeUTC time value to convert.
Returns
Broken-down local time.
{#toutc}
toUTC
std::tm toUTC(const std::time_t & time)
Converts a time_t value to a broken-down UTC time structure. Uses thread-safe native functions (gmtime_r / gmtime_s).
Parameters
timeUTC time value to convert.
Returns
Broken-down UTC time.
{#getlocal}
getLocal
std::string getLocal()
Returns the current local time as an ISO8601 formatted string.
Returns
ISO8601 local time string.
{#getutc}
getUTC
std::string getUTC()
Returns the current UTC time as an ISO8601 formatted string.
Returns
ISO8601 UTC time string.
{#hrtime}
hrtime
uint64_t hrtime()
Returns the current high-resolution monotonic time in nanoseconds.
Returns
Current time in nanoseconds (suitable for measuring intervals).
Variables
| Return | Name | Description |
|---|---|---|
const int64_t | kNumMillisecsPerSec static | Constants for calculating time. |
const int64_t | kNumMicrosecsPerSec static | |
const int64_t | kNumNanosecsPerSec static | |
const int64_t | kNumMicrosecsPerMillisec static | |
const int64_t | kNumNanosecsPerMillisec static | |
const int64_t | kNumNanosecsPerMicrosec static | |
const char * | ISO8601Format static | The date/time format defined in the ISO 8601 standard. This is the default format used throughout the library for consistency. |
{#knummillisecspersec}
kNumMillisecsPerSec
static
const int64_t kNumMillisecsPerSec = (1000)
Constants for calculating time.
{#knummicrosecspersec}
kNumMicrosecsPerSec
static
const int64_t kNumMicrosecsPerSec = (1000000)
{#knumnanosecspersec}
kNumNanosecsPerSec
static
const int64_t kNumNanosecsPerSec = (1000000000)
{#knummicrosecspermillisec}
kNumMicrosecsPerMillisec
static
const int64_t kNumMicrosecsPerMillisec = kNumMicrosecsPerSec / kNumMillisecsPerSec
{#knumnanosecspermillisec}
kNumNanosecsPerMillisec
static
const int64_t kNumNanosecsPerMillisec = kNumNanosecsPerSec / kNumMillisecsPerSec
{#knumnanosecspermicrosec}
kNumNanosecsPerMicrosec
static
const int64_t kNumNanosecsPerMicrosec = kNumNanosecsPerSec / kNumMicrosecsPerSec
{#iso8601format}
ISO8601Format
static
const char * ISO8601Format = "%Y-%m-%dT%H:%M:%SZ"
The date/time format defined in the ISO 8601 standard. This is the default format used throughout the library for consistency.
Examples: 2005-01-01T12:00:00+01:00 2005-01-01T11:00:00Z
{#base64}
base64
Base64 encoding and decoding helpers.
Classes
| Name | Description |
|---|---|
Decoder | Base64 decoder. |
Encoder | Base64 encoder. |
Functions
| Return | Name | Description |
|---|---|---|
size_t | encodedBufferCapacity inline | Returns a safe temporary buffer size for encoding up to inputSize bytes. Includes padding/newline slack so callers can reuse the same buffer for finalize(). |
std::string | encode inline | Encodes an STL byte container to a Base64 string. |
std::string | decode inline | Decodes a Base64-encoded STL container to a binary string. |
{#encodedbuffercapacity}
encodedBufferCapacity
inline
inline size_t encodedBufferCapacity(size_t inputSize, int lineLength)
Returns a safe temporary buffer size for encoding up to inputSize bytes. Includes padding/newline slack so callers can reuse the same buffer for finalize().
{#encode-16}
encode
inline
template<typename T> inline std::string encode(const T & bytes, int lineLength)
Encodes an STL byte container to a Base64 string.
Parameters
TContainer type with asize()method and contiguousoperator[].
Parameters
-
bytesInput data container. -
lineLengthCharacters per line in the output (0 disables wrapping).
Returns
Base64-encoded string.
{#decode-5}
decode
inline
template<typename T> inline std::string decode(const T & bytes)
Decodes a Base64-encoded STL container to a binary string.
Parameters
TContainer type with asize()method and contiguousoperator[].
Parameters
bytesInput Base64 data container.
Returns
Decoded binary string.
Variables
| Return | Name | Description |
|---|---|---|
constexpr int | BUFFER_SIZE | |
constexpr int | LINE_LENGTH |
{#buffer_size}
BUFFER_SIZE
constexpr int BUFFER_SIZE = 16384
{#line_length}
LINE_LENGTH
constexpr int LINE_LENGTH = 72
{#decoder-2}
Decoder
#include <icy/base64.h>
Inherits:
Decoder
Base64 decoder.
Public Attributes
| Return | Name | Description |
|---|---|---|
internal::decodestate | _state | |
int | _buffersize |
{#_state}
_state
internal::decodestate _state
{#_buffersize}
_buffersize
int _buffersize
Public Methods
| Return | Name | Description |
|---|---|---|
Decoder inline | #### Parameters | |
ssize_t | decode inline | Decodes a single Base64 character to its 6-bit value. |
ssize_t | decode virtual inline | Decodes a raw Base64 buffer into binary data. |
void | decode inline | Decodes the entire input stream and writes binary output to ostrm. Resets the decoder state after completion. |
{#decoder-3}
Decoder
inline
inline Decoder(int buffersize)
Parameters
buffersizeInternal read buffer size in bytes.
{#decode-6}
decode
inline
inline ssize_t decode(char value_in)
Decodes a single Base64 character to its 6-bit value.
Parameters
value_inBase64 character.
Returns
Decoded 6-bit value, or a negative sentinel on invalid input.
{#decode-7}
decode
virtual inline
virtual inline ssize_t decode(const char * inbuf, size_t nread, char * outbuf)
Decodes a raw Base64 buffer into binary data.
Parameters
-
inbufInput Base64 characters. -
nreadNumber of characters to decode. -
outbufOutput buffer; must be at leastnread * 3 / 4bytes.
Returns
Number of binary bytes written.
{#decode-8}
decode
inline
inline void decode(std::istream & istrm, std::ostream & ostrm)
Decodes the entire input stream and writes binary output to ostrm. Resets the decoder state after completion.
Parameters
-
istrmSource stream of Base64 data. -
ostrmDestination stream for decoded binary output.
{#encoder-3}
Encoder
#include <icy/base64.h>
Inherits:
Encoder
Base64 encoder.
Public Attributes
| Return | Name | Description |
|---|---|---|
internal::encodestate | _state | |
int | _buffersize |
{#_state-1}
_state
internal::encodestate _state
{#_buffersize-1}
_buffersize
int _buffersize
Public Methods
| Return | Name | Description |
|---|---|---|
Encoder inline | #### Parameters | |
void | encode inline | Encodes the entire input stream and writes Base64 output to ostrm. Resets the encoder state after completion. |
void | encode inline | Encodes a string to Base64 and appends the result to out. Resets the encoder state after completion. |
ssize_t | encode virtual inline | Encodes a raw buffer, writing Base64 characters to outbuf. May be called multiple times before calling [finalize()](#finalize-3). |
ssize_t | finalize virtual inline | Writes any pending padding and resets the encoder state. Must be called once after all [encode()](#encode-17) calls to flush the final block. |
void | setLineLength inline | Sets the line wrap length for encoded output (0 disables line wrapping). |
{#encoder-4}
Encoder
inline
inline Encoder(int buffersize)
Parameters
buffersizeInternal read buffer size in bytes.
{#encode-17}
encode
inline
inline void encode(std::istream & istrm, std::ostream & ostrm)
Encodes the entire input stream and writes Base64 output to ostrm. Resets the encoder state after completion.
Parameters
-
istrmSource stream to encode. -
ostrmDestination stream for Base64 output.
{#encode-18}
encode
inline
inline void encode(const std::string & in, std::string & out)
Encodes a string to Base64 and appends the result to out. Resets the encoder state after completion.
Parameters
-
inInput string. -
outOutput string to which Base64 characters are appended.
{#encode-19}
encode
virtual inline
virtual inline ssize_t encode(const char * inbuf, size_t nread, char * outbuf)
Encodes a raw buffer, writing Base64 characters to outbuf. May be called multiple times before calling [finalize()](#finalize-3).
Parameters
-
inbufInput binary data. -
nreadNumber of bytes to encode. -
outbufOutput buffer; must be at leastnread * 4 / 3 + 4bytes.
Returns
Number of Base64 characters written.
{#finalize-3}
finalize
virtual inline
virtual inline ssize_t finalize(char * outbuf)
Writes any pending padding and resets the encoder state. Must be called once after all [encode()](#encode-17) calls to flush the final block.
Parameters
outbufOutput buffer; must be at least 5 bytes.
Returns
Number of characters written.
{#setlinelength-1}
setLineLength
inline
inline void setLineLength(int lineLength)
Sets the line wrap length for encoded output (0 disables line wrapping).
Parameters
lineLengthCharacters per line; use 0 to disable.
{#deleter-2}
deleter
Deleter helpers for objects managed through custom destruction routines.
Classes
| Name | Description |
|---|---|
Array | Deleter functor for array pointers. Calls delete[] on the pointer. |
Dispose | Deleter functor that calls dispose() on the pointer. Useful with std::unique_ptr for objects that require a dispose() call rather than direct deletion. |
{#array}
Array
Deleter functor for array pointers. Calls delete[] on the pointer.
Public Methods
| Return | Name | Description |
|---|---|---|
void | operator() inline | Calls delete[] on ptr if non-null. |
{#operator-10}
operator()
inline
inline void operator()(T * ptr)
Calls delete[] on ptr if non-null.
Parameters
ptrArray pointer to delete; may be nullptr.
{#dispose-1}
Dispose
Deleter functor that calls dispose() on the pointer. Useful with std::unique_ptr for objects that require a dispose() call rather than direct deletion.
Public Methods
| Return | Name | Description |
|---|---|---|
void | operator() inline | Calls ptr->dispose() if ptr is non-null. |
{#operator-11}
operator()
inline
inline void operator()(T * ptr)
Calls ptr->dispose() if ptr is non-null.
Parameters
ptrPointer to dispose; may be nullptr.
{#numeric}
numeric
Integer parsing and formatting helpers.
Functions
| Return | Name | Description |
|---|---|---|
void | format | Formats an integer value in decimal notation. |
void | format | Formats an integer value in decimal notation, right justified in a field having at least the specified width. |
void | format0 | Formats an integer value in decimal notation, right justified and zero-padded in a field having at least the specified width. |
void | formatHex | Formats an int value in hexadecimal notation. The value is treated as unsigned. |
void | formatHex | Formats an int value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width. The value is treated as unsigned. |
void | format | Formats an unsigned int value in decimal notation. |
void | format | Formats an unsigned int value in decimal notation, right justified in a field having at least the specified width. |
void | format0 | Formats an unsigned int value in decimal notation, right justified and zero-padded in a field having at least the specified width. |
void | formatHex | Formats an unsigned int value in hexadecimal notation. |
void | formatHex | Formats an unsigned int value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width. |
void | format | Formats a long value in decimal notation. |
void | format | Formats a long value in decimal notation, right justified in a field having at least the specified width. |
void | format0 | Formats a long value in decimal notation, right justified and zero-padded in a field having at least the specified width. |
void | formatHex | Formats a long value in hexadecimal notation. The value is treated as unsigned. |
void | formatHex | Formats a long value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width. The value is treated as unsigned. |
void | format | Formats an unsigned long value in decimal notation. |
void | format | Formats an unsigned long value in decimal notation, right justified in a field having at least the specified width. |
void | format0 | Formats an unsigned long value in decimal notation, right justified and zero-padded in a field having at least the specified width. |
void | formatHex | Formats an unsigned long value in hexadecimal notation. |
void | formatHex | Formats an unsigned long value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width. |
void | format | Formats a 64-bit integer value in decimal notation. |
void | format | Formats a 64-bit integer value in decimal notation, right justified in a field having at least the specified width. |
void | format0 | Formats a 64-bit integer value in decimal notation, right justified and zero-padded in a field having at least the specified width. |
void | formatHex | Formats a 64-bit integer value in hexadecimal notation. The value is treated as unsigned. |
void | formatHex | Formats a 64-bit integer value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width. The value is treated as unsigned. |
void | format | Formats an unsigned 64-bit integer value in decimal notation. |
void | format | Formats an unsigned 64-bit integer value in decimal notation, right justified in a field having at least the specified width. |
void | format0 | Formats an unsigned 64-bit integer value in decimal notation, right justified and zero-padded in a field having at least the specified width. |
void | formatHex | Formats an unsigned 64-bit integer value in hexadecimal notation. |
void | formatHex | Formats an unsigned 64-bit integer value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width. |
{#format-8}
format
void format(std::string & str, int value)
Formats an integer value in decimal notation.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#format-9}
format
void format(std::string & str, int value, int width)
Formats an integer value in decimal notation, right justified in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with spaces on the left.
{#format0}
format0
void format0(std::string & str, int value, int width)
Formats an integer value in decimal notation, right justified and zero-padded in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#formathex}
formatHex
void formatHex(std::string & str, int value)
Formats an int value in hexadecimal notation. The value is treated as unsigned.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#formathex-1}
formatHex
void formatHex(std::string & str, int value, int width)
Formats an int value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width. The value is treated as unsigned.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#format-10}
format
void format(std::string & str, unsigned value)
Formats an unsigned int value in decimal notation.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#format-11}
format
void format(std::string & str, unsigned value, int width)
Formats an unsigned int value in decimal notation, right justified in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with spaces on the left.
{#format0-1}
format0
void format0(std::string & str, unsigned int value, int width)
Formats an unsigned int value in decimal notation, right justified and zero-padded in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#formathex-2}
formatHex
void formatHex(std::string & str, unsigned value)
Formats an unsigned int value in hexadecimal notation.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#formathex-3}
formatHex
void formatHex(std::string & str, unsigned value, int width)
Formats an unsigned int value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#format-12}
format
void format(std::string & str, long value)
Formats a long value in decimal notation.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#format-13}
format
void format(std::string & str, long value, int width)
Formats a long value in decimal notation, right justified in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with spaces on the left.
{#format0-2}
format0
void format0(std::string & str, long value, int width)
Formats a long value in decimal notation, right justified and zero-padded in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#formathex-4}
formatHex
void formatHex(std::string & str, long value)
Formats a long value in hexadecimal notation. The value is treated as unsigned.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#formathex-5}
formatHex
void formatHex(std::string & str, long value, int width)
Formats a long value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width. The value is treated as unsigned.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#format-14}
format
void format(std::string & str, unsigned long value)
Formats an unsigned long value in decimal notation.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#format-15}
format
void format(std::string & str, unsigned long value, int width)
Formats an unsigned long value in decimal notation, right justified in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with spaces on the left.
{#format0-3}
format0
void format0(std::string & str, unsigned long value, int width)
Formats an unsigned long value in decimal notation, right justified and zero-padded in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#formathex-6}
formatHex
void formatHex(std::string & str, unsigned long value)
Formats an unsigned long value in hexadecimal notation.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#formathex-7}
formatHex
void formatHex(std::string & str, unsigned long value, int width)
Formats an unsigned long value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#format-16}
format
void format(std::string & str, std::int64_t value)
Formats a 64-bit integer value in decimal notation.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#format-17}
format
void format(std::string & str, std::int64_t value, int width)
Formats a 64-bit integer value in decimal notation, right justified in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with spaces on the left.
{#format0-4}
format0
void format0(std::string & str, std::int64_t value, int width)
Formats a 64-bit integer value in decimal notation, right justified and zero-padded in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#formathex-8}
formatHex
void formatHex(std::string & str, std::int64_t value)
Formats a 64-bit integer value in hexadecimal notation. The value is treated as unsigned.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#formathex-9}
formatHex
void formatHex(std::string & str, std::int64_t value, int width)
Formats a 64-bit integer value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width. The value is treated as unsigned.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#format-18}
format
void format(std::string & str, uint64_t value)
Formats an unsigned 64-bit integer value in decimal notation.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#format-19}
format
void format(std::string & str, uint64_t value, int width)
Formats an unsigned 64-bit integer value in decimal notation, right justified in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with spaces on the left.
{#format0-5}
format0
void format0(std::string & str, uint64_t value, int width)
Formats an unsigned 64-bit integer value in decimal notation, right justified and zero-padded in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#formathex-10}
formatHex
void formatHex(std::string & str, uint64_t value)
Formats an unsigned 64-bit integer value in hexadecimal notation.
Parameters
-
strOutput string to append to. -
valueValue to format.
{#formathex-11}
formatHex
void formatHex(std::string & str, uint64_t value, int width)
Formats an unsigned 64-bit integer value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width.
Parameters
-
strOutput string to append to. -
valueValue to format. -
widthMinimum field width; padded with zeros on the left.
{#basic}
basic
Interface classes.
Classes
| Name | Description |
|---|---|
Decoder | Abstract interface for stream decoders. |
Encoder | Abstract interface for stream encoders. |
Runnable | Abstract interface for classes that can be run and cancelled. |
Sendable | Abstract interface for classes that can be sent and cancelled. |
Startable | Abstract interface for a classes that can be started and stopped. |
{#decoder-4}
Decoder
#include <icy/interface.h>
Abstract interface for stream decoders.
Public Methods
| Return | Name | Description |
|---|---|---|
Decoder | Defaulted constructor. | |
ssize_t | decode | Decodes nread bytes from inbuf and writes decoded output to outbuf. |
ssize_t | finalize virtual inline | Flushes any buffered state and writes final output to outbuf. |
{#decoder-5}
Decoder
Decoder() = default
Defaulted constructor.
{#decode-9}
decode
ssize_t decode(const char * inbuf, size_t nread, char * outbuf)
Decodes nread bytes from inbuf and writes decoded output to outbuf.
Parameters
-
inbufEncoded input buffer. -
nreadNumber of bytes to decode from inbuf. -
outbufDestination buffer for decoded output.
Returns
Number of bytes written to outbuf, or -1 on error.
{#finalize-4}
finalize
virtual inline
virtual inline ssize_t finalize(char * outbuf)
Flushes any buffered state and writes final output to outbuf.
Parameters
outbufDestination buffer for any remaining output.
Returns
Number of bytes written, or 0 if nothing to flush.
{#encoder-5}
Encoder
#include <icy/interface.h>
Abstract interface for stream encoders.
Public Methods
| Return | Name | Description |
|---|---|---|
Encoder | Defaulted constructor. | |
ssize_t | encode | Encodes nread bytes from inbuf and writes encoded output to outbuf. |
ssize_t | finalize virtual inline | Flushes any buffered state and writes final output to outbuf. |
{#encoder-6}
Encoder
Encoder() = default
Defaulted constructor.
{#encode-20}
encode
ssize_t encode(const char * inbuf, size_t nread, char * outbuf)
Encodes nread bytes from inbuf and writes encoded output to outbuf.
Parameters
-
inbufRaw input buffer to encode. -
nreadNumber of bytes to encode from inbuf. -
outbufDestination buffer for encoded output.
Returns
Number of bytes written to outbuf, or -1 on error.
{#finalize-5}
finalize
virtual inline
virtual inline ssize_t finalize(char * outbuf)
Flushes any buffered state and writes final output to outbuf.
Parameters
outbufDestination buffer for any remaining output.
Returns
Number of bytes written, or 0 if nothing to flush.
{#runnable}
Runnable
#include <icy/interface.h>
Subclassed by:
RunnableQueue< IPacket >,RunnableQueue< PacketT >,PlanarAudioPacket >,PlanarVideoPacket >,AsyncDiagnostic,AsyncLogWriter,RunnableQueue< T >,Task,TaskRunner,MediaCapture,InstallTask
Abstract interface for classes that can be run and cancelled.
Public Methods
| Return | Name | Description |
|---|---|---|
Runnable inline | ||
void | run | The run method will be called by the asynchronous context. |
void | cancel virtual inline | Cancel the current task. The run() method should return ASAP. |
bool | cancelled virtual const inline | Returns true when the task has been cancelled. |
{#runnable-1}
Runnable
inline
inline Runnable()
{#run-4}
run
void run()
The run method will be called by the asynchronous context.
{#cancel-1}
cancel
virtual inline
virtual inline void cancel(bool flag)
Cancel the current task. The run() method should return ASAP.
{#cancelled}
cancelled
virtual const inline
virtual inline bool cancelled() const
Returns true when the task has been cancelled.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::atomic< bool > | exit |
{#exit}
exit
std::atomic< bool > exit
{#sendable}
Sendable
#include <icy/interface.h>
Subclassed by:
PacketTransaction< Message >,PacketTransaction< PacketT >
Abstract interface for classes that can be sent and cancelled.
Public Methods
| Return | Name | Description |
|---|---|---|
bool | send | Initiates the send operation. |
void | cancel | Cancels a pending send operation. |
{#send-9}
send
bool send()
Initiates the send operation.
Returns
true if the send was dispatched successfully, false otherwise.
{#cancel-2}
cancel
void cancel()
Cancels a pending send operation.
{#startable}
Startable
#include <icy/interface.h>
Subclassed by:
ThreadedStreamReader,ICapture,FormWriter
Abstract interface for a classes that can be started and stopped.
Public Methods
| Return | Name | Description |
|---|---|---|
void | start | Starts the object (e.g. begins processing or listening). |
void | stop | Stops the object (e.g. halts processing or closes resources). |
{#start-7}
start
void start()
Starts the object (e.g. begins processing or listening).
{#stop-6}
stop
void stop()
Stops the object (e.g. halts processing or closes resources).
{#fs}
fs
Cross-platform filesystem path and file helpers.
Functions
| Return | Name | Description |
|---|---|---|
std::string | filename | Returns the file name and extension part of the given path. |
std::string | basename | Returns the file name without its extension. |
std::string | dirname | Returns the directory part of the path. |
std::string | extname | Returns the file extension part of the path. |
bool | exists | Returns true if the file or directory exists. |
bool | isdir | Returns true if the path refers to a directory. |
std::int64_t | filesize | Returns the size in bytes of the given file. |
void | readdir | Populates res with the names of all entries in the given directory. |
void | mkdir | Creates a single directory. |
void | mkdirr | Creates a directory and all missing parent directories. |
void | rmdir | Removes an empty directory. |
void | unlink | Deletes a file. |
void | rename | Renames or moves the given file to the target path. |
void | addsep | Appends the platform-specific path separator to path if not already present. |
void | addnode | Appends a path node to path, inserting a separator if necessary. |
std::string | makePath | Joins a base path and a node component into a single path string. |
std::string | normalize | Normalizes a path by resolving . and .. segments and converting separators to the native platform style. |
std::string | transcode | Transcodes a path to the native platform format. On Windows with ICY_UNICODE defined, converts to the Windows-native wide-to-narrow format. On other platforms, returns the path unchanged. |
bool | savefile | Writes size bytes from data to the file at path, creating or overwriting it. |
{#filename}
filename
std::string filename(std::string_view path)
Returns the file name and extension part of the given path.
Parameters
pathFilesystem path to parse.
Returns
Filename component including extension (e.g. "file.txt").
{#basename}
basename
std::string basename(std::string_view path)
Returns the file name without its extension.
Parameters
pathFilesystem path to parse.
Returns
Filename without the extension (e.g. "file").
{#dirname}
dirname
std::string dirname(std::string_view path)
Returns the directory part of the path.
Parameters
pathFilesystem path to parse.
Returns
Directory component including trailing separator (e.g. "/usr/local/").
{#extname}
extname
std::string extname(std::string_view path, bool includeDot)
Returns the file extension part of the path.
Parameters
-
pathFilesystem path to parse. -
includeDotIf true (default), includes the leading dot (e.g. ".txt"); if false, the dot is stripped.
Returns
Extension string, or empty if the path has no extension.
{#exists-1}
exists
bool exists(std::string_view path)
Returns true if the file or directory exists.
Parameters
pathPath to check.
Returns
True if the path exists on the filesystem.
{#isdir}
isdir
bool isdir(std::string_view path)
Returns true if the path refers to a directory.
Parameters
pathPath to check.
Returns
True if the path exists and is a directory.
{#filesize}
filesize
std::int64_t filesize(std::string_view path)
Returns the size in bytes of the given file.
Parameters
pathPath to the file.
Returns
File size in bytes, or -1 if the file does not exist.
{#readdir}
readdir
void readdir(std::string_view path, std::vector< std::string > & res)
Populates res with the names of all entries in the given directory.
Parameters
-
pathPath to the directory to read. -
resVector to receive the list of entry names.
{#mkdir}
mkdir
void mkdir(std::string_view path, int mode)
Creates a single directory.
Parameters
-
pathPath of the directory to create. -
modePermission bits (default: 0755). Ignored on Windows.
{#mkdirr}
mkdirr
void mkdirr(std::string_view path, int mode)
Creates a directory and all missing parent directories.
Parameters
-
pathPath of the directory hierarchy to create. -
modePermission bits (default: 0755). Ignored on Windows.
{#rmdir}
rmdir
void rmdir(std::string_view path)
Removes an empty directory.
Parameters
pathPath of the directory to remove.
{#unlink}
unlink
void unlink(std::string_view path)
Deletes a file.
Parameters
pathPath of the file to delete.
{#rename}
rename
void rename(std::string_view path, std::string_view target)
Renames or moves the given file to the target path.
Parameters
-
pathSource file path. -
targetDestination file path.
{#addsep}
addsep
void addsep(std::string & path)
Appends the platform-specific path separator to path if not already present.
Parameters
pathPath string to modify in place.
{#addnode}
addnode
void addnode(std::string & path, std::string_view node)
Appends a path node to path, inserting a separator if necessary.
Parameters
-
pathBase path string to modify in place. -
nodeDirectory or file name component to append.
{#makepath}
makePath
std::string makePath(std::string_view base, std::string_view node)
Joins a base path and a node component into a single path string.
Parameters
-
baseBase directory path. -
nodeDirectory or file name component to append.
Returns
Joined path string.
{#normalize}
normalize
std::string normalize(std::string_view path)
Normalizes a path by resolving . and .. segments and converting separators to the native platform style.
Parameters
pathPath string to normalize.
Returns
Normalized path string.
{#transcode}
transcode
std::string transcode(std::string_view path)
Transcodes a path to the native platform format. On Windows with ICY_UNICODE defined, converts to the Windows-native wide-to-narrow format. On other platforms, returns the path unchanged.
Parameters
pathPath string to transcode.
Returns
Transcoded path string.
{#savefile}
savefile
bool savefile(std::string_view path, const char * data, size_t size, bool whiny)
Writes size bytes from data to the file at path, creating or overwriting it.
Parameters
-
pathDestination file path. Parent directories must already exist. -
dataPointer to the data to write. -
sizeNumber of bytes to write. -
whinyIf true, throws astd::runtime_erroron failure instead of returning false.
Returns
True on success, false on failure (when whiny is false).
Variables
| Return | Name | Description |
|---|---|---|
const char * | separator | The platform specific path separator string: "/" on unix and "\" on windows. |
const char | delimiter | The platform specific path separator character: '/' on unix and '' on windows. |
{#separator}
separator
const char * separator
The platform specific path separator string: "/" on unix and "\" on windows.
{#delimiter}
delimiter
const char delimiter
The platform specific path separator character: '/' on unix and '' on windows.
{#util}
util
Miscellaneous string, parsing, and version utilities.
Classes
| Name | Description |
|---|---|
Version | Semantic version number with major, minor, and patch fields. |
Functions
| Return | Name | Description |
|---|---|---|
std::string | format | Printf-style string formatting for POD types. |
void | toUnderscore | Replaces all non-alphanumeric characters in str with underscores and converts to lowercase. |
bool | isNumber | Returns true if str consists entirely of digit characters. |
bool | endsWith | Returns true if str ends with the given suffix. |
void | removeSpecialCharacters | Replaces non-alphanumeric characters. Removes all non-alphanumeric characters from str in place. |
void | replaceSpecialCharacters | Replaces all non-alphanumeric characters in str with with in place. |
bool | tryParseHex | Attempts to parse a hex string into an unsigned integer. |
unsigned | parseHex | Parses a hex string into an unsigned integer. |
std::string | dumpbin | Formats the binary contents of data as a hex+ASCII dump string. |
bool | compareVersion | Compares two dot-separated version strings. |
bool | matchNodes | Checks whether node matches xnode by splitting both on delim and comparing element-wise. |
bool | matchNodes | Checks whether params matches xparams element-wise. |
std::string | memAddress | Returns the memory address of ptr as a hex string (e.g. "0x7f3a2b10c0"). |
std::string | itostr | Converts an integer (or any stream-insertable type) to its string representation. |
T | strtoi | Parses a string into integer type T using std::istringstream. Returns 0 if parsing fails. Ensure T has sufficient range for the value. |
uint32_t | randomNumber | Generates a 31-bit pseudo random number using the internal Random instance. |
std::string | randomString | Generates a random alphanumeric string of the given length. |
std::string | randomBinaryString | Generates a random binary string of the given byte length. |
void | split | Splits str on the delimiter string and appends tokens to elems. |
std::vector< std::string > | split | Splits str on the delimiter string and returns the tokens as a vector. |
void | split | Splits str on the delimiter character and appends tokens to elems. |
std::vector< std::string > | split | Splits str on the delimiter character and returns the tokens as a vector. |
S & | replaceInPlace | Replace all occurrences of from in str with to, starting at position start. Modifies and returns str in place. from must not be empty. |
S & | replaceInPlace | Replace all occurrences of from in str with to, starting at position start. C-string overload. Modifies and returns str in place. |
S | replace | Replace all occurences of from (which must not be the empty string) in str with to, starting at position start. |
S | replace | Returns a copy of str with all occurrences of from replaced by to (C-string overload). |
S | trimLeft | Returns a copy of str with all leading whitespace removed. |
S & | trimLeftInPlace | Removes all leading whitespace in str. |
S | trimRight | Returns a copy of str with all trailing whitespace removed. |
S & | trimRightInPlace | Removes all trailing whitespace in str. |
S | trim | Returns a copy of str with all leading and trailing whitespace removed. |
S & | trimInPlace | Removes all leading and trailing whitespace in str. |
S | toUpper | Returns a copy of str containing all upper-case characters. |
S & | toUpperInPlace | Replaces all characters in str with their upper-case counterparts. |
S | toLower | Returns a copy of str containing all lower-case characters. |
S & | toLowerInPlace | Replaces all characters in str with their lower-case counterparts. |
int | icompare inline | Case-insensitive string comparison (locale-independent, ASCII only). |
std::streamsize | copyStreamUnbuffered | Copies all bytes from istr to ostr one byte at a time (no internal buffer). |
std::streamsize | copyStream | Copies all bytes from istr to ostr using an internal buffer. |
std::streamsize | copyToString | Reads all bytes from istr and appends them to str. |
void | clearList inline | Delete all elements from a list of pointers. |
void | clearDeque inline | Delete all elements from a deque of pointers. |
void | clearVector inline | Delete all elements from a vector of pointers. |
void | clearMap inline | Delete all associated values from a map (not the key elements). |
{#format-20}
format
std::string format(const char * fmt, ...)
Printf-style string formatting for POD types.
Parameters
-
fmtprintf format string. -
...Format arguments.
Returns
Formatted string.
{#tounderscore}
toUnderscore
void toUnderscore(std::string & str)
Replaces all non-alphanumeric characters in str with underscores and converts to lowercase.
Parameters
strString to transform in place.
{#isnumber}
isNumber
bool isNumber(std::string_view str)
Returns true if str consists entirely of digit characters.
Parameters
strString to test.
Returns
true if every character in str is a decimal digit.
{#endswith}
endsWith
bool endsWith(std::string_view str, std::string_view suffix)
Returns true if str ends with the given suffix.
Parameters
-
strString to test. -
suffixSuffix to look for.
Returns
true if str ends with suffix.
{#removespecialcharacters}
removeSpecialCharacters
void removeSpecialCharacters(std::string & str, bool allowSpaces)
Replaces non-alphanumeric characters. Removes all non-alphanumeric characters from str in place.
Parameters
-
strString to modify. -
allowSpacesIf true, ASCII spaces are preserved.
{#replacespecialcharacters}
replaceSpecialCharacters
void replaceSpecialCharacters(std::string & str, char with, bool allowSpaces)
Replaces all non-alphanumeric characters in str with with in place.
Parameters
-
strString to modify. -
withReplacement character (default: '_'). -
allowSpacesIf true, ASCII spaces are preserved rather than replaced.
{#tryparsehex}
tryParseHex
bool tryParseHex(std::string_view s, unsigned & value)
Attempts to parse a hex string into an unsigned integer.
Parameters
-
sHex string (with or without 0x prefix). -
valueOutput: parsed value on success.
Returns
true if parsing succeeded, false otherwise.
{#parsehex}
parseHex
unsigned parseHex(std::string_view s)
Parses a hex string into an unsigned integer.
Parameters
sHex string (with or without 0x prefix).
Returns
Parsed value.
Exceptions
std::invalid_argumentif the string is not valid hex.
{#dumpbin}
dumpbin
std::string dumpbin(const char * data, size_t len)
Formats the binary contents of data as a hex+ASCII dump string.
Parameters
-
dataPointer to the buffer to dump. -
lenNumber of bytes to dump.
Returns
Multi-line hex dump string.
{#compareversion}
compareVersion
bool compareVersion(std::string_view l, std::string_view r)
Compares two dot-separated version strings.
Parameters
-
lLeft (local) version string. -
rRight (remote) version string.
Returns
true if l is strictly greater than r, false if l is equal or less.
{#matchnodes}
matchNodes
bool matchNodes(std::string_view node, std::string_view xnode, std::string_view delim)
Checks whether node matches xnode by splitting both on delim and comparing element-wise.
Parameters
-
nodeNode list string to test. -
xnodeExpected node list pattern. -
delimDelimiter used to split both strings (default: "\r\n").
Returns
true if all elements of node match the corresponding elements of xnode.
{#matchnodes-1}
matchNodes
bool matchNodes(const std::vector< std::string > & params, const std::vector< std::string > & xparams)
Checks whether params matches xparams element-wise.
Parameters
-
paramsParameter list to test. -
xparamsExpected parameter list.
Returns
true if every element of params matches the corresponding element of xparams.
{#memaddress}
memAddress
std::string memAddress(const void * ptr)
Returns the memory address of ptr as a hex string (e.g. "0x7f3a2b10c0").
Parameters
ptrPointer whose address to format.
Returns
Hex string representation of the pointer value.
{#itostr}
itostr
template<typename T> std::string itostr(const T & t)
Converts an integer (or any stream-insertable type) to its string representation.
Parameters
TType to convert; must supportoperator<<on std::ostream.
Parameters
tValue to convert.
Returns
String representation of t.
{#strtoi}
strtoi
template<typename T> T strtoi(std::string_view s)
Parses a string into integer type T using std::istringstream. Returns 0 if parsing fails. Ensure T has sufficient range for the value.
Parameters
TTarget integer type.
Parameters
sString to parse.
Returns
Parsed value, or 0 on failure.
{#randomnumber}
randomNumber
uint32_t randomNumber()
Generates a 31-bit pseudo random number using the internal Random instance.
Returns
Pseudo random uint32_t value.
{#randomstring}
randomString
std::string randomString(int size)
Generates a random alphanumeric string of the given length.
Parameters
sizeNumber of characters to generate.
Returns
Random string of length size.
{#randombinarystring}
randomBinaryString
std::string randomBinaryString(int size, bool doBase64)
Generates a random binary string of the given byte length.
Parameters
-
sizeNumber of random bytes to generate. -
doBase64If true, returns the bytes as a base64-encoded string.
Returns
Random binary string, optionally base64-encoded.
{#split}
split
void split(std::string_view str, std::string_view delim, std::vector< std::string > & elems, int limit)
Splits str on the delimiter string and appends tokens to elems.
Parameters
-
strString to split. -
delimDelimiter string. -
elemsOutput vector; tokens are appended to it. -
limitMaximum number of splits (-1 for unlimited).
{#split-1}
split
std::vector< std::string > split(std::string_view str, std::string_view delim, int limit)
Splits str on the delimiter string and returns the tokens as a vector.
Parameters
-
strString to split. -
delimDelimiter string. -
limitMaximum number of splits (-1 for unlimited).
Returns
Vector of token strings.
{#split-2}
split
void split(std::string_view str, char delim, std::vector< std::string > & elems, int limit)
Splits str on the delimiter character and appends tokens to elems.
Parameters
-
strString to split. -
delimDelimiter character. -
elemsOutput vector; tokens are appended to it. -
limitMaximum number of splits (-1 for unlimited).
{#split-3}
split
std::vector< std::string > split(std::string_view str, char delim, int limit)
Splits str on the delimiter character and returns the tokens as a vector.
Parameters
-
strString to split. -
delimDelimiter character. -
limitMaximum number of splits (-1 for unlimited).
Returns
Vector of token strings.
{#replaceinplace}
replaceInPlace
template<class S> S & replaceInPlace(S & str, const S & from, const S & to, typename S::size_type start)
Replace all occurrences of from in str with to, starting at position start. Modifies and returns str in place. from must not be empty.
{#replaceinplace-1}
replaceInPlace
template<class S> S & replaceInPlace(S & str, const typename S::value_type * from, const typename S::value_type * to, typename S::size_type start)
Replace all occurrences of from in str with to, starting at position start. C-string overload. Modifies and returns str in place.
{#replace}
replace
template<class S> S replace(const S & str, const S & from, const S & to, typename S::size_type start)
Replace all occurences of from (which must not be the empty string) in str with to, starting at position start.
{#replace-1}
replace
template<class S> S replace(const S & str, const typename S::value_type * from, const typename S::value_type * to, typename S::size_type start)
Returns a copy of str with all occurrences of from replaced by to (C-string overload).
Parameters
-
strSource string. -
fromSubstring to search for; must not be empty. -
toReplacement string. -
startPosition in str at which to begin searching (default: 0).
Returns
New string with all replacements applied.
{#trimleft}
trimLeft
template<class S> S trimLeft(const S & str)
Returns a copy of str with all leading whitespace removed.
{#trimleftinplace}
trimLeftInPlace
template<class S> S & trimLeftInPlace(S & str)
Removes all leading whitespace in str.
{#trimright}
trimRight
template<class S> S trimRight(const S & str)
Returns a copy of str with all trailing whitespace removed.
{#trimrightinplace}
trimRightInPlace
template<class S> S & trimRightInPlace(S & str)
Removes all trailing whitespace in str.
{#trim}
trim
template<class S> S trim(const S & str)
Returns a copy of str with all leading and trailing whitespace removed.
{#triminplace}
trimInPlace
template<class S> S & trimInPlace(S & str)
Removes all leading and trailing whitespace in str.
{#toupper}
toUpper
template<class S> S toUpper(const S & str)
Returns a copy of str containing all upper-case characters.
{#toupperinplace}
toUpperInPlace
template<class S> S & toUpperInPlace(S & str)
Replaces all characters in str with their upper-case counterparts.
{#tolower}
toLower
template<class S> S toLower(const S & str)
Returns a copy of str containing all lower-case characters.
{#tolowerinplace}
toLowerInPlace
template<class S> S & toLowerInPlace(S & str)
Replaces all characters in str with their lower-case counterparts.
{#icompare}
icompare
inline
inline int icompare(std::string_view a, std::string_view b)
Case-insensitive string comparison (locale-independent, ASCII only).
Parameters
-
aFirst string. -
bSecond string.
Returns
Negative if a < b, zero if a == b, positive if a > b.
{#copystreamunbuffered}
copyStreamUnbuffered
std::streamsize copyStreamUnbuffered(std::istream & istr, std::ostream & ostr)
Copies all bytes from istr to ostr one byte at a time (no internal buffer).
Parameters
-
istrSource stream. -
ostrDestination stream.
Returns
Total number of bytes copied.
{#copystream}
copyStream
std::streamsize copyStream(std::istream & istr, std::ostream & ostr, size_t bufferSize)
Copies all bytes from istr to ostr using an internal buffer.
Parameters
-
istrSource stream. -
ostrDestination stream. -
bufferSizeInternal buffer size in bytes (default: 8192).
Returns
Total number of bytes copied.
{#copytostring}
copyToString
std::streamsize copyToString(std::istream & istr, std::string & str, size_t bufferSize)
Reads all bytes from istr and appends them to str.
Parameters
-
istrSource stream. -
strOutput string to append data to. -
bufferSizeInternal buffer size in bytes (default: 8192).
Returns
Total number of bytes read.
{#clearlist}
clearList
inline
template<typename Val> inline void clearList(std::list< Val * > & L)
Delete all elements from a list of pointers.
{#cleardeque}
clearDeque
inline
template<typename Val> inline void clearDeque(std::deque< Val * > & D)
Delete all elements from a deque of pointers.
{#clearvector}
clearVector
inline
template<typename Val> inline void clearVector(std::vector< Val * > & V)
Delete all elements from a vector of pointers.
{#clearmap}
clearMap
inline
template<typename Key, typename Val> inline void clearMap(std::map< Key, Val * > & M)
Delete all associated values from a map (not the key elements).
{#version}
Version
#include <icy/util.h>
Semantic version number with major, minor, and patch fields.
Public Attributes
| Return | Name | Description |
|---|---|---|
int | major | |
int | minor | |
int | revision | |
int | build |
{#major}
major
int major
{#minor}
minor
int minor
{#revision}
revision
int revision
{#build}
build
int build
Public Methods
| Return | Name | Description |
|---|---|---|
Version inline | Parses a dot-separated version string into up to four numeric fields. Unspecified fields default to 0. Examples: "1.2.3", "2.0", "3.7.8.0". | |
bool | operator< inline | Returns true if this version is strictly less than other. Compares fields in major, minor, revision, build order. |
bool | operator== const inline | Returns true if all four version fields are equal. |
{#version-1}
Version
inline
inline Version(std::string_view version)
Parses a dot-separated version string into up to four numeric fields. Unspecified fields default to 0. Examples: "1.2.3", "2.0", "3.7.8.0".
Parameters
versionDot-separated version string.
{#operator-12}
operator<
inline
inline bool operator<(const Version & other)
Returns true if this version is strictly less than other. Compares fields in major, minor, revision, build order.
Parameters
otherVersion to compare against.
Returns
true if this < other.
{#operator-13}
operator==
const inline
inline bool operator==(const Version & other) const
Returns true if all four version fields are equal.
Parameters
otherVersion to compare against.
Returns
true if this == other.
{#pipe}
Pipe
#include <icy/pipe.h>
Inherits:
Stream< uv_pipe_t >
Named pipe / stdio stream built on uv_pipe_t.
Suitable for inter-process communication and for wrapping process stdio (stdin/stdout/stderr). IPC mode allows passing stream handles between processes over the pipe.
Public Methods
| Return | Name | Description |
|---|---|---|
Pipe | Construct a [Pipe](#pipe) bound to loop without initializing the libuv handle. | |
~Pipe virtual | Destroy the pipe, stopping reads and closing the handle. | |
void | init virtual | Initialize the underlying uv_pipe_t handle. |
bool | readStart virtual | Start reading from the pipe. |
{#pipe}
Pipe
Pipe(uv::Loop * loop)
Construct a [Pipe](#pipe) bound to loop without initializing the libuv handle.
Call [init()](#classicy_1_1Pipe_1a09b32c70eceefd7d2339410b0863ad54) before performing any I/O.
Parameters
loopEvent loop to associate with. Defaults to the process-wide default loop.
{#pipe}
~Pipe
virtual
virtual ~Pipe()
Destroy the pipe, stopping reads and closing the handle.
{#init}
init
virtual
virtual void init(bool ipc)
Initialize the underlying uv_pipe_t handle.
Must be called before [readStart()](#classicy_1_1Pipe_1aa346922ed574ccc39590f7dc3bae7885) or any write operations.
Parameters
ipcSet totrueto enable IPC mode, which allows sending and receiving stream handles alongside data via[write()](#classicy_1_1Stream_1a56926a6ac3ba433aed1414ffb1d20cf0).
{#readstart}
readStart
virtual
virtual bool readStart()
Start reading from the pipe.
Delegates to [Stream](#stream)<uv_pipe_t>::[readStart()](#classicy_1_1Pipe_1aa346922ed574ccc39590f7dc3bae7885). Emits the Read signal as data arrives.
Returns
true if uv_read_start was called successfully.
{#idler}
Idler
#include <icy/idler.h>
Inherits:
Runner
Asynchronous type that triggers callbacks when the event loop is idle.
This class inherits the [Runner](#runner) interface and may be used with any implementation that's powered by an asynchronous [Runner](#runner).
Public Methods
| Return | Name | Description |
|---|---|---|
Idler | Create the idler bound to loop without starting it. | |
Idler inline explicit | Create and immediately start the idler on the default loop. | |
Idler inline explicit | Create and immediately start the idler on the given loop. | |
void | start inline | Start the idler, invoking func (with args) on every idle iteration. |
void | start virtual | Start the idler with a type-erased callback (implements [Runner::start](#classicy_1_1Runner_1a5969e823f1ce0bdd8730d3108bf13fbd)). |
uv::Handle< uv_idle_t > & | handle | #### Returns |
{#idler}
Idler
Idler(uv::Loop * loop)
Create the idler bound to loop without starting it.
Parameters
loopEvent loop to associate with. Defaults to the process-wide default loop.
{#idler}
Idler
inline explicit
template<typename Function, typename... Args> inline explicit Idler(Function && func, Args &&... args)
Create and immediately start the idler on the default loop.
Parameters
-
funcCallable invoked on every idle iteration. -
argsArguments forwarded tofunc.
{#idler}
Idler
inline explicit
template<typename Function, typename... Args> inline explicit Idler(uv::Loop * loop, Function && func, Args &&... args)
Create and immediately start the idler on the given loop.
Parameters
-
loopEvent loop to associate with. -
funcCallable invoked on every idle iteration. -
argsArguments forwarded tofunc.
{#start}
start
inline
template<typename Function, typename... Args> inline void start(Function && func, Args &&... args)
Start the idler, invoking func (with args) on every idle iteration.
The idler always runs in repeating mode; cancel via [Runner::cancel()](#classicy_1_1Runner_1a53b3794fbd4ace235771a4e84f93f1e7). Throws std::logic_error if the handle is already active or the runner context reports it is still running.
Parameters
-
funcCallable invoked each time the event loop is idle. -
argsArguments forwarded tofuncon each invocation.
{#start}
start
virtual
virtual void start(std::function< void()> func)
Start the idler with a type-erased callback (implements [Runner::start](#classicy_1_1Runner_1a5969e823f1ce0bdd8730d3108bf13fbd)).
Parameters
funcCallback invoked on every idle iteration.
{#handle}
handle
uv::Handle< uv_idle_t > & handle()
Returns
Reference to the underlying uv_idle_t handle wrapper.
Protected Attributes
| Return | Name | Description |
|---|---|---|
uv::Handle< uv_idle_t > | _handle |
{#_handle}
_handle
uv::Handle< uv_idle_t > _handle
Protected Methods
| Return | Name | Description |
|---|---|---|
void | init virtual | Initialize the underlying uv_idle_t handle and unref it from the loop. |
bool | async virtual const | #### Returns |
{#init}
init
virtual
virtual void init()
Initialize the underlying uv_idle_t handle and unref it from the loop.
{#async}
async
virtual const
virtual bool async() const
Returns
false; the idler is event-loop-driven, not thread-based.
{#queue}
Queue
#include <icy/queue.h>
Subclassed by:
RunnableQueue< IPacket >,RunnableQueue< PacketT >,PlanarAudioPacket >,PlanarVideoPacket >
Thread-safe queue container.
Public Methods
| Return | Name | Description |
|---|---|---|
void | push inline | Appends an item to the back of the queue (thread-safe). |
void | push inline | Appends an item to the back of the queue by move (thread-safe). |
bool | empty const inline | #### Returns |
T | front const inline | #### Returns |
T | back const inline | #### Returns |
void | pop inline | Removes the front item from the queue (thread-safe). |
void | sort inline | Sorts all queued items using the given comparator (thread-safe). |
size_t | size const inline | #### Returns |
std::deque< T > | queue const inline | #### Returns |
{#push}
push
inline
inline void push(const T & data)
Appends an item to the back of the queue (thread-safe).
Parameters
dataItem to enqueue.
{#push}
push
inline
inline void push(T && data)
Appends an item to the back of the queue by move (thread-safe).
Parameters
dataItem to enqueue.
{#empty}
empty
const inline
inline bool empty() const
Returns
True if the queue contains no items.
{#front}
front
const inline
inline T front() const
Returns
Copy of the front item.
{#back}
back
const inline
inline T back() const
Returns
Copy of the back item.
{#pop}
pop
inline
inline void pop()
Removes the front item from the queue (thread-safe).
{#sort}
sort
inline
template<typename Compare> inline void sort()
Sorts all queued items using the given comparator (thread-safe).
Parameters
CompareComparator type compatible withstd::sort.
{#size}
size
const inline
inline size_t size() const
Returns
Number of items currently in the queue (thread-safe).
{#queue}
queue
const inline
inline std::deque< T > queue() const
Returns
Copy of the underlying deque.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::deque< T > | _queue | |
std::mutex | _mutex |
{#_queue}
_queue
std::deque< T > _queue
{#_mutex}
_mutex
std::mutex _mutex
{#runnablequeue}
RunnableQueue
#include <icy/queue.h>
Inherits:
Queue< T * >,RunnableSubclassed by:AsyncQueue< IPacket >,AsyncQueue< PacketT >,PlanarAudioPacket >,PlanarVideoPacket >,SyncQueue< IPacket >,AsyncQueue< T >,SyncQueue< T >
Queue of runnable tasks for sequential execution.
Public Attributes
| Return | Name | Description |
|---|---|---|
std::function< void(T &)> | ondispatch | The default dispatch function. Must be set before the queue is running. |
{#ondispatch}
ondispatch
std::function< void(T &)> ondispatch
The default dispatch function. Must be set before the queue is running.
Public Methods
| Return | Name | Description |
|---|---|---|
RunnableQueue inline | #### Parameters | |
void | push virtual inline | Push an item onto the queue. The queue takes ownership of the item pointer. |
void | flush virtual inline | Flush all outgoing items. |
void | clear inline | |
void | run virtual inline | Called asynchronously to dispatch queued items. If not timeout is set this method blocks until cancel() is called, otherwise runTimeout() will be called. |
void | runTimeout virtual inline | Called asynchronously to dispatch queued items until the queue is empty or the timeout expires. Pseudo protected for std::bind compatability. |
void | dispatch virtual inline | Dispatch a single item to listeners. |
int | timeout inline | #### Returns |
void | setTimeout inline | Sets the dispatch timeout. Must only be called when the queue is empty. |
size_t | dropped const inline | #### Returns |
{#runnablequeue}
RunnableQueue
inline
inline RunnableQueue(int limit, int timeout)
Parameters
-
limitMaximum number of queued items; oldest are purged when exceeded (0 = unlimited). -
timeoutDispatch timeout in milliseconds; 0 means run until cancel() is called.
{#push}
push
virtual inline
virtual inline void push(T * item)
Push an item onto the queue. The queue takes ownership of the item pointer.
{#flush}
flush
virtual inline
virtual inline void flush()
Flush all outgoing items.
{#clear}
clear
inline
inline void clear()
{#run}
run
virtual inline
virtual inline void run()
Called asynchronously to dispatch queued items. If not timeout is set this method blocks until cancel() is called, otherwise runTimeout() will be called.
{#runtimeout}
runTimeout
virtual inline
virtual inline void runTimeout()
Called asynchronously to dispatch queued items until the queue is empty or the timeout expires. Pseudo protected for std::bind compatability.
{#dispatch}
dispatch
virtual inline
virtual inline void dispatch(T & item)
Dispatch a single item to listeners.
{#timeout}
timeout
inline
inline int timeout()
Returns
Current dispatch timeout in milliseconds.
{#settimeout}
setTimeout
inline
inline void setTimeout(int milliseconds)
Sets the dispatch timeout. Must only be called when the queue is empty.
Parameters
millisecondsNew timeout in milliseconds.
Exceptions
std::logic_errorif the queue is non-empty.
{#dropped}
dropped
const inline
inline size_t dropped() const
Returns
Number of items purged because the queue limit was exceeded.
Protected Attributes
| Return | Name | Description |
|---|---|---|
int | _limit | |
int | _timeout | |
size_t | _dropped |
{#_limit}
_limit
int _limit
{#_timeout}
_timeout
int _timeout
{#_dropped}
_dropped
size_t _dropped = 0
Protected Methods
| Return | Name | Description |
|---|---|---|
RunnableQueue | Deleted constructor. | |
RunnableQueue | Deleted constructor. | |
T * | popNext virtual inline | Pops the next waiting item. |
bool | dispatchNext virtual inline | Pops and dispatches the next waiting item. |
{#runnablequeue}
RunnableQueue
RunnableQueue(const RunnableQueue &) = delete
Deleted constructor.
{#runnablequeue}
RunnableQueue
RunnableQueue(RunnableQueue &&) = delete
Deleted constructor.
{#popnext}
popNext
virtual inline
virtual inline T * popNext()
Pops the next waiting item.
{#dispatchnext}
dispatchNext
virtual inline
virtual inline bool dispatchNext()
Pops and dispatches the next waiting item.
{#syncqueue}
SyncQueue
#include <icy/queue.h>
Inherits:
RunnableQueue< T >Subclassed by:SyncPacketQueue< T >
SyncQueue extends Synchronizer to implement a synchronized FIFO queue which receives T objects from any thread and synchronizes them for safe consumption by the associated event loop.
Public Methods
| Return | Name | Description |
|---|---|---|
SyncQueue inline | #### Parameters | |
~SyncQueue virtual inline | Destruction is deferred to allow enough time for all callbacks to return. | |
void | push virtual inline | Pushes an item onto the queue and wakes the event loop for dispatch. Ownership of item is transferred to the queue. |
void | cancel virtual inline | Cancels the queue and its underlying synchronizer. |
Synchronizer & | sync inline | #### Returns |
{#syncqueue}
SyncQueue
inline
inline SyncQueue(uv::Loop * loop, int limit, int timeout)
Parameters
-
loopEvent loop used by the internal[Synchronizer](#synchronizer). -
limitMaximum queued items; oldest are dropped when exceeded. -
timeoutDispatch timeout in milliseconds passed to[RunnableQueue](#runnablequeue).
{#syncqueue}
~SyncQueue
virtual inline
virtual inline ~SyncQueue()
Destruction is deferred to allow enough time for all callbacks to return.
{#push}
push
virtual inline
virtual inline void push(T * item)
Pushes an item onto the queue and wakes the event loop for dispatch. Ownership of item is transferred to the queue.
Parameters
itemHeap-allocated item to enqueue; the queue takes ownership.
{#cancel}
cancel
virtual inline
virtual inline void cancel(bool flag)
Cancels the queue and its underlying synchronizer.
Parameters
flagTrue to cancel, false to un-cancel.
{#sync}
sync
inline
inline Synchronizer & sync()
Returns
Reference to the underlying [Synchronizer](#synchronizer) handle.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Synchronizer | _sync |
{#_sync}
_sync
Synchronizer _sync
Public Types
| Name | Description |
|---|---|
Queue |
{#queue}
Queue
RunnableQueue< T > Queue()
{#asyncqueue}
AsyncQueue
#include <icy/queue.h>
Inherits:
RunnableQueue< T >Subclassed by:AsyncPacketQueue< PacketT >,PlanarAudioPacket >,PlanarVideoPacket >,AsyncPacketQueue< T >
AsyncQueue is a thread-based queue which receives packets from any thread source and dispatches them asynchronously.
This queue is useful for deferring load from operation critical system devices before performing long running tasks.
The thread will call the RunnableQueue's run() method to constantly flush outgoing packets until cancel() is called.
Public Methods
| Return | Name | Description |
|---|---|---|
AsyncQueue inline | #### Parameters | |
void | cancel virtual inline | Cancels the queue and joins the dispatch thread. |
{#asyncqueue}
AsyncQueue
inline
inline AsyncQueue(int limit)
Parameters
limitMaximum number of queued items before oldest are dropped.
{#cancel}
cancel
virtual inline
virtual inline void cancel(bool flag)
Cancels the queue and joins the dispatch thread.
Parameters
flagTrue to cancel, false to un-cancel.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Thread | _thread |
{#_thread}
_thread
Thread _thread
Public Types
| Name | Description |
|---|---|
Queue |
{#queue}
Queue
RunnableQueue< T > Queue()
{#timer}
Timer
#include <icy/timer.h>
Inherits:
Runner
Asynchronous event based timer.
Public Attributes
| Return | Name | Description |
|---|---|---|
NullSignal | Timeout | Signal that gets triggered on timeout. |
{#timeout}
Timeout
NullSignal Timeout
Signal that gets triggered on timeout.
Public Methods
| Return | Name | Description |
|---|---|---|
Timer | Create a timer without a timeout or interval; values must be set before [start()](#classicy_1_1Timer_1a59e3275d17107212520b362cbf0cb3d5). | |
Timer | Create a one-shot timer that fires after timeout milliseconds. | |
Timer | Create a repeating timer with an initial delay and a repeat period. | |
~Timer virtual | Destructor. | |
void | start | Start the timer using the previously configured timeout and interval. |
void | start virtual | Connect func to the [Timeout](#timeout) signal and start the timer. |
void | stop | Stop the timer. Resets the fire count to zero. |
void | restart | Restart the timer. |
void | again | Reset the countdown without stopping and restarting the timer. |
void | setTimeout | Set the initial delay before the first timeout event. |
void | setInterval | Set the repeat interval (calls uv_timer_set_repeat). |
bool | active const | #### Returns |
std::int64_t | timeout const | #### Returns |
std::int64_t | interval const | #### Returns |
std::int64_t | count | #### Returns |
uv::Handle< uv_timer_t > & | handle | #### Returns |
bool | async virtual const | #### Returns |
{#timer}
Timer
Timer(uv::Loop * loop)
Create a timer without a timeout or interval; values must be set before [start()](#classicy_1_1Timer_1a59e3275d17107212520b362cbf0cb3d5).
Parameters
loopEvent loop to associate with. Defaults to the process-wide default loop.
{#timer}
Timer
Timer(std::int64_t timeout, uv::Loop * loop, std::function< void()> func)
Create a one-shot timer that fires after timeout milliseconds.
If func is provided the timer starts immediately; otherwise call [start()](#classicy_1_1Timer_1a59e3275d17107212520b362cbf0cb3d5) manually.
Parameters
-
timeoutDelay in milliseconds before the first (and only) fire. -
loopEvent loop to associate with. -
funcOptional callback connected to the[Timeout](#timeout)signal and used to start the timer immediately.
{#timer}
Timer
Timer(std::int64_t timeout, std::int64_t interval, uv::Loop * loop, std::function< void()> func)
Create a repeating timer with an initial delay and a repeat period.
Fires once after timeout milliseconds, then repeatedly every interval milliseconds. If func is provided the timer starts immediately; otherwise call [start()](#classicy_1_1Timer_1a59e3275d17107212520b362cbf0cb3d5) manually.
Parameters
-
timeoutInitial delay in milliseconds. -
intervalRepeat period in milliseconds. -
loopEvent loop to associate with. -
funcOptional callback connected to the[Timeout](#timeout)signal and used to start the timer immediately.
{#timer}
~Timer
virtual
virtual ~Timer()
Destructor.
{#start}
start
void start()
Start the timer using the previously configured timeout and interval.
Throws std::logic_error if neither a timeout nor an interval has been set, or if the handle has not been allocated. Has no effect if already active.
{#start}
start
virtual
virtual void start(std::function< void()> func)
Connect func to the [Timeout](#timeout) signal and start the timer.
Parameters
funcCallback invoked on each timeout event.
{#stop}
stop
void stop()
Stop the timer. Resets the fire count to zero.
Has no effect if the timer is not active.
{#restart}
restart
void restart()
Restart the timer.
If the timer is not currently active, behaves like [start()](#classicy_1_1Timer_1a59e3275d17107212520b362cbf0cb3d5). If it is active, calls [again()](#classicy_1_1Timer_1a1479aec7fadd9fdc71a41ed6a51af1c8) to reset the countdown using the repeat value. A timeout or interval must be set beforehand, otherwise [start()](#classicy_1_1Timer_1a59e3275d17107212520b362cbf0cb3d5) will throw std::logic_error.
{#again}
again
void again()
Reset the countdown without stopping and restarting the timer.
For repeating timers this restarts the repeat interval from now. For non-repeating timers this has the same effect as stopping the timer. Throws on error if uv_timer_again fails (e.g. the timer was never started). Resets the fire count to zero.
{#settimeout}
setTimeout
void setTimeout(std::int64_t timeout)
Set the initial delay before the first timeout event.
Has no effect if the timer is currently active.
Parameters
timeoutDelay in milliseconds.
{#setinterval}
setInterval
void setInterval(std::int64_t interval)
Set the repeat interval (calls uv_timer_set_repeat).
Takes effect from the next timeout event. If set from within a timer callback on a repeating timer, the new value is used from the following iteration; on a non-repeating timer the timer will have already stopped.
Parameters
intervalRepeat period in milliseconds; 0 disables repeating.
{#active}
active
const
bool active() const
Returns
true if the timer is currently counting down.
{#timeout}
timeout
const
std::int64_t timeout() const
Returns
The configured initial timeout in milliseconds.
{#interval}
interval
const
std::int64_t interval() const
Returns
The effective repeat interval reported by libuv, in milliseconds.
{#count}
count
std::int64_t count()
Returns
The number of times the timer has fired since the last start or again().
{#handle}
handle
uv::Handle< uv_timer_t > & handle()
Returns
Reference to the underlying uv_timer_t handle wrapper.
{#async}
async
virtual const
virtual bool async() const
Returns
false; the timer is event-loop-driven, not thread-based.
Protected Attributes
| Return | Name | Description |
|---|---|---|
uv::Handle< uv_timer_t > | _handle | |
std::int64_t | _timeout | |
std::int64_t | _interval | |
std::int64_t | _count |
{#_handle}
_handle
uv::Handle< uv_timer_t > _handle
{#_timeout}
_timeout
std::int64_t _timeout
{#_interval}
_interval
std::int64_t _interval
{#_count}
_count
std::int64_t _count
Protected Methods
| Return | Name | Description |
|---|---|---|
Timer | Deleted constructor. | |
Timer | Deleted constructor. | |
void | init |
{#timer}
Timer
Timer(const Timer &) = delete
Deleted constructor.
{#timer}
Timer
Timer(Timer &&) = delete
Deleted constructor.
{#init}
init
void init()
{#mutablebuffer}
MutableBuffer
#include <icy/buffer.h>
The MutableBuffer class provides a safe representation of a buffer that can be modified. It does not own the underlying data, and so is cheap to copy or assign.
Public Methods
| Return | Name | Description |
|---|---|---|
constexpr | MutableBuffer inline | Construct an empty buffer. |
constexpr | MutableBuffer inline | Construct a buffer to represent the given memory range. |
constexpr void * | data const inline | |
constexpr size_t | size const inline | |
char * | cstr const inline | Cast the buffer as a char pointer. |
std::string | str const inline | Returns the buffer as a string. |
{#mutablebuffer}
MutableBuffer
inline
inline constexpr MutableBuffer()
Construct an empty buffer.
{#mutablebuffer}
MutableBuffer
inline
inline constexpr MutableBuffer(void * data, size_t size)
Construct a buffer to represent the given memory range.
{#data}
data
const inline
inline constexpr void * data() const
{#size}
size
const inline
inline constexpr size_t size() const
{#cstr}
cstr
const inline
inline char * cstr() const
Cast the buffer as a char pointer.
{#str}
str
const inline
inline std::string str() const
Returns the buffer as a string.
Protected Attributes
| Return | Name | Description |
|---|---|---|
void * | _data | |
size_t | _size |
{#_data}
_data
void * _data
{#_size}
_size
size_t _size
{#constbuffer}
ConstBuffer
#include <icy/buffer.h>
The ConstBuffer class provides a safe representation of a buffer that cannot be modified. It does not own the underlying data, and so is cheap to copy or assign.
Public Methods
| Return | Name | Description |
|---|---|---|
constexpr | ConstBuffer inline | Construct an empty buffer. |
constexpr | ConstBuffer inline | Construct a buffer to represent the given memory range. |
constexpr | ConstBuffer inline | Construct a non-modifiable buffer from a modifiable one. |
constexpr const void * | data const inline | |
constexpr size_t | size const inline | |
const char * | cstr const inline | Cast the buffer as a const char pointer. |
std::string | str const inline | Returns the buffer as a string. |
{#constbuffer}
ConstBuffer
inline
inline constexpr ConstBuffer()
Construct an empty buffer.
{#constbuffer}
ConstBuffer
inline
inline constexpr ConstBuffer(const void * data, size_t size)
Construct a buffer to represent the given memory range.
{#constbuffer}
ConstBuffer
inline
inline constexpr ConstBuffer(const MutableBuffer & b)
Construct a non-modifiable buffer from a modifiable one.
{#data}
data
const inline
inline constexpr const void * data() const
{#size}
size
const inline
inline constexpr size_t size() const
{#cstr}
cstr
const inline
inline const char * cstr() const
Cast the buffer as a const char pointer.
{#str}
str
const inline
inline std::string str() const
Returns the buffer as a string.
Protected Attributes
| Return | Name | Description |
|---|---|---|
const void * | _data | |
size_t | _size |
{#_data}
_data
const void * _data
{#_size}
_size
size_t _size
{#bitreader}
BitReader
#include <icy/buffer.h>
Class for reading binary streams.
Public Methods
| Return | Name | Description |
|---|---|---|
BitReader | Constructs a [BitReader](#bitreader) over a raw byte array. | |
BitReader | Constructs a [BitReader](#bitreader) over a Buffer. | |
BitReader | Constructs a [BitReader](#bitreader) over a [ConstBuffer](#constbuffer). | |
void | get | Reads a value from the BitReader. Returns false if there isn't enough data left for the specified type. Throws a std::out_of_range exception if reading past the limit. Reads len raw bytes into val. Throws std::out_of_range if insufficient data remains. |
void | get | Reads len bytes and appends them to val. Throws std::out_of_range if insufficient data remains. |
void | getU8 | Reads an unsigned 8-bit integer. Throws std::out_of_range if insufficient data remains. |
void | getU16 | Reads an unsigned 16-bit integer, applying byte-order conversion. Throws std::out_of_range if insufficient data remains. |
void | getU24 | Reads an unsigned 24-bit integer into a 32-bit variable, applying byte-order conversion. Throws std::out_of_range if insufficient data remains. |
void | getU32 | Reads an unsigned 32-bit integer, applying byte-order conversion. Throws std::out_of_range if insufficient data remains. |
void | getU64 | Reads an unsigned 64-bit integer, applying byte-order conversion. Throws std::out_of_range if insufficient data remains. |
char | peek | Peeks at the current byte without advancing the position. |
uint8_t | peekU8 | Peeks at the current byte as a uint8_t without advancing the position. |
uint16_t | peekU16 | Peeks at the next two bytes as a uint16_t without advancing the position. |
uint32_t | peekU24 | Peeks at the next three bytes as a uint32_t without advancing the position. |
uint32_t | peekU32 | Peeks at the next four bytes as a uint32_t without advancing the position. |
uint64_t | peekU64 | Peeks data from the BitReader. -1 is returned if reading past boundary. |
size_t | skipToChar | Advances the position until the given character is found, stopping before it. |
size_t | skipWhitespace | Advances the position past any leading space characters. |
size_t | skipToNextLine | Advances the position past the end of the current line (past the newline). |
size_t | skipNextWord | Advances the position past the next whitespace-delimited word. |
size_t | readNextWord | Reads the next whitespace-delimited word into val. |
size_t | readNextNumber | Reads the next whitespace-delimited decimal number into val. |
size_t | readLine | Reads bytes up to (but not including) the next newline into val. |
size_t | readToNext | Reads bytes up to (but not including) the next occurrence of c into val. |
void | seek | Set position pointer to absolute position. Throws a std::out_of_range exception if the value exceeds the limit. |
void | skip | Set position pointer to relative position. Throws a std::out_of_range exception if the value exceeds the limit. |
size_t | limit const | Returns the read limit. |
size_t | position const inline | Returns the current read position. |
size_t | available const | Returns the number of elements between the current position and the limit. |
const char * | begin const inline | Returns a pointer to the start of the buffer. |
const char * | current const inline | Returns a pointer to the current read position. |
ByteOrder | order const inline | Returns the byte order used for multi-byte integer reads. |
std::string | toString | Returns the remaining unread bytes as a std::string. |
{#bitreader}
BitReader
BitReader(const char * bytes, size_t size, ByteOrder order)
Constructs a [BitReader](#bitreader) over a raw byte array.
Parameters
-
bytesPointer to the start of the data. Must remain valid for the lifetime of the reader. -
sizeNumber of bytes available for reading. -
orderByte order used when reading multi-byte integer types.
{#bitreader}
BitReader
BitReader(const Buffer & buf, ByteOrder order)
Constructs a [BitReader](#bitreader) over a Buffer.
Parameters
-
bufSource buffer. Must remain valid for the lifetime of the reader. -
orderByte order used when reading multi-byte integer types.
{#bitreader}
BitReader
BitReader(const ConstBuffer & pod, ByteOrder order)
Constructs a [BitReader](#bitreader) over a [ConstBuffer](#constbuffer).
Parameters
-
podSource const buffer. Must remain valid for the lifetime of the reader. -
orderByte order used when reading multi-byte integer types.
{#get}
get
void get(char * val, size_t len)
Reads a value from the BitReader. Returns false if there isn't enough data left for the specified type. Throws a std::out_of_range exception if reading past the limit. Reads len raw bytes into val. Throws std::out_of_range if insufficient data remains.
Parameters
-
valDestination buffer; must have capacity of at leastlenbytes. -
lenNumber of bytes to read.
{#get}
get
void get(std::string & val, size_t len)
Reads len bytes and appends them to val. Throws std::out_of_range if insufficient data remains.
Parameters
-
valString to append the read bytes to. -
lenNumber of bytes to read.
{#getu8}
getU8
void getU8(uint8_t & val)
Reads an unsigned 8-bit integer. Throws std::out_of_range if insufficient data remains.
Parameters
valOutput parameter receiving the read value.
{#getu16}
getU16
void getU16(uint16_t & val)
Reads an unsigned 16-bit integer, applying byte-order conversion. Throws std::out_of_range if insufficient data remains.
Parameters
valOutput parameter receiving the read value.
{#getu24}
getU24
void getU24(uint32_t & val)
Reads an unsigned 24-bit integer into a 32-bit variable, applying byte-order conversion. Throws std::out_of_range if insufficient data remains.
Parameters
valOutput parameter receiving the read value.
{#getu32}
getU32
void getU32(uint32_t & val)
Reads an unsigned 32-bit integer, applying byte-order conversion. Throws std::out_of_range if insufficient data remains.
Parameters
valOutput parameter receiving the read value.
{#getu64}
getU64
void getU64(uint64_t & val)
Reads an unsigned 64-bit integer, applying byte-order conversion. Throws std::out_of_range if insufficient data remains.
Parameters
valOutput parameter receiving the read value.
{#peek}
peek
char peek()
Peeks at the current byte without advancing the position.
Returns
Current byte as char, or 0 if at the end of the buffer.
{#peeku8}
peekU8
uint8_t peekU8()
Peeks at the current byte as a uint8_t without advancing the position.
Returns
Current value, or 0 if at the end of the buffer.
{#peeku16}
peekU16
uint16_t peekU16()
Peeks at the next two bytes as a uint16_t without advancing the position.
Returns
Current value with byte-order conversion applied, or 0 on failure.
{#peeku24}
peekU24
uint32_t peekU24()
Peeks at the next three bytes as a uint32_t without advancing the position.
Returns
Current value with byte-order conversion applied, or 0 on failure.
{#peeku32}
peekU32
uint32_t peekU32()
Peeks at the next four bytes as a uint32_t without advancing the position.
Returns
Current value with byte-order conversion applied, or 0 on failure.
{#peeku64}
peekU64
uint64_t peekU64()
Peeks data from the BitReader. -1 is returned if reading past boundary.
{#skiptochar}
skipToChar
size_t skipToChar(char c)
Advances the position until the given character is found, stopping before it.
Parameters
cCharacter to search for.
Returns
Number of bytes skipped.
{#skipwhitespace}
skipWhitespace
size_t skipWhitespace()
Advances the position past any leading space characters.
Returns
Number of bytes skipped.
{#skiptonextline}
skipToNextLine
size_t skipToNextLine()
Advances the position past the end of the current line (past the newline).
Returns
Number of bytes skipped including the newline character.
{#skipnextword}
skipNextWord
size_t skipNextWord()
Advances the position past the next whitespace-delimited word.
Returns
Number of bytes skipped.
{#readnextword}
readNextWord
size_t readNextWord(std::string & val)
Reads the next whitespace-delimited word into val.
Parameters
valString to receive the word.
Returns
Number of bytes consumed.
{#readnextnumber}
readNextNumber
size_t readNextNumber(unsigned int & val)
Reads the next whitespace-delimited decimal number into val.
Parameters
valOutput parameter receiving the parsed unsigned integer.
Returns
Number of bytes consumed.
{#readline}
readLine
size_t readLine(std::string & val)
Reads bytes up to (but not including) the next newline into val.
Parameters
valString to receive the line content.
Returns
Number of bytes consumed including the newline.
{#readtonext}
readToNext
size_t readToNext(std::string & val, char c)
Reads bytes up to (but not including) the next occurrence of c into val.
Parameters
-
valString to receive the read bytes. -
cDelimiter character to stop at.
Returns
Number of bytes consumed.
{#seek}
seek
void seek(size_t val)
Set position pointer to absolute position. Throws a std::out_of_range exception if the value exceeds the limit.
{#skip}
skip
void skip(size_t size)
Set position pointer to relative position. Throws a std::out_of_range exception if the value exceeds the limit.
{#limit}
limit
const
size_t limit() const
Returns the read limit.
{#position}
position
const inline
inline size_t position() const
Returns the current read position.
{#available}
available
const
size_t available() const
Returns the number of elements between the current position and the limit.
{#begin}
begin
const inline
inline const char * begin() const
Returns a pointer to the start of the buffer.
{#current}
current
const inline
inline const char * current() const
Returns a pointer to the current read position.
{#order}
order
const inline
inline ByteOrder order() const
Returns the byte order used for multi-byte integer reads.
{#tostring}
toString
std::string toString()
Returns the remaining unread bytes as a std::string.
Returns
String containing bytes from the current position to the end.
Protected Attributes
| Return | Name | Description |
|---|---|---|
size_t | _position | |
size_t | _limit | |
ByteOrder | _order | |
const char * | _bytes |
{#_position}
_position
size_t _position
{#_limit}
_limit
size_t _limit
{#_order}
_order
ByteOrder _order
{#_bytes}
_bytes
const char * _bytes
Protected Methods
| Return | Name | Description |
|---|---|---|
void | init |
{#init}
init
void init(const char * bytes, size_t size, ByteOrder order)
{#bitwriter}
BitWriter
#include <icy/buffer.h>
Subclassed by:
DynamicBitWriter
Class for reading/writing binary streams.
Note that when using the constructor with the Buffer reference as an argument, the writer will dynamically expand the given buffer when writing passed the buffer capacity. All other cases will throw a std::out_of_range error when writing past the buffer capacity.
Public Methods
| Return | Name | Description |
|---|---|---|
BitWriter | Constructs a [BitWriter](#bitwriter) over a raw byte array with a fixed capacity. | |
BitWriter | Constructs a [BitWriter](#bitwriter) backed by a Buffer. Writes are bounded by the buffer's capacity; use [DynamicBitWriter](#dynamicbitwriter) for auto-resize. | |
BitWriter | Constructs a [BitWriter](#bitwriter) over a [MutableBuffer](#mutablebuffer) with a fixed capacity. | |
void | put virtual | Append bytes to the buffer. Throws a std::out_of_range exception if reading past the limit. |
void | put | Appends the contents of a string. Throws std::out_of_range if capacity is exceeded. |
void | putU8 | Appends an unsigned 8-bit integer. Throws std::out_of_range if capacity is exceeded. |
void | putU16 | Appends an unsigned 16-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded. |
void | putU24 | Appends the low 24 bits of a 32-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded. |
void | putU32 | Appends an unsigned 32-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded. |
void | putU64 | Appends an unsigned 64-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded. |
bool | update virtual | Update a byte range. Throws a std::out_of_range exception if reading past the limit. |
bool | update | Overwrites a previously written string at the given absolute position. |
bool | updateU8 | Overwrites a uint8_t at the given absolute position. |
bool | updateU16 | Overwrites a uint16_t at the given absolute position, with byte-order conversion. |
bool | updateU24 | Overwrites 3 bytes (low 24 bits of val) at the given absolute position, with byte-order conversion. |
bool | updateU32 | Overwrites a uint32_t at the given absolute position, with byte-order conversion. |
bool | updateU64 | Overwrites a uint64_t at the given absolute position, with byte-order conversion. |
void | seek | Set position pointer to absolute position. Throws a std::out_of_range exception if the value exceeds the limit. |
void | skip | Set position pointer to relative position. Throws a std::out_of_range exception if the value exceeds the limit. |
size_t | limit const | Returns the write limit. |
size_t | position const inline | Returns the current write position. |
size_t | available const | Returns the number of elements between the current write position and the limit. |
char * | begin inline | Returns a pointer to the start of the write buffer. |
char * | current inline | Returns a pointer to the current write position. |
const char * | begin const inline | Returns a const pointer to the start of the write buffer. |
const char * | current const inline | Returns a const pointer to the current write position. |
ByteOrder | order const inline | Returns the byte order used for multi-byte integer writes. |
std::string | toString | Returns all bytes written so far as a std::string. |
{#bitwriter}
BitWriter
BitWriter(char * bytes, size_t size, ByteOrder order)
Constructs a [BitWriter](#bitwriter) over a raw byte array with a fixed capacity.
Parameters
-
bytesPointer to the writable buffer. Must remain valid for the writer's lifetime. -
sizeCapacity of the buffer in bytes. -
orderByte order used for multi-byte integer writes.
{#bitwriter}
BitWriter
BitWriter(Buffer & buf, ByteOrder order)
Constructs a [BitWriter](#bitwriter) backed by a Buffer. Writes are bounded by the buffer's capacity; use [DynamicBitWriter](#dynamicbitwriter) for auto-resize.
Parameters
-
bufSource buffer. Must remain valid for the writer's lifetime. -
orderByte order used for multi-byte integer writes.
{#bitwriter}
BitWriter
BitWriter(MutableBuffer & pod, ByteOrder order)
Constructs a [BitWriter](#bitwriter) over a [MutableBuffer](#mutablebuffer) with a fixed capacity.
Parameters
-
podSource mutable buffer. Must remain valid for the writer's lifetime. -
orderByte order used for multi-byte integer writes.
{#put}
put
virtual
virtual void put(const char * val, size_t len)
Append bytes to the buffer. Throws a std::out_of_range exception if reading past the limit.
{#put}
put
void put(const std::string & val)
Appends the contents of a string. Throws std::out_of_range if capacity is exceeded.
Parameters
valString whose bytes are appended.
{#putu8}
putU8
void putU8(uint8_t val)
Appends an unsigned 8-bit integer. Throws std::out_of_range if capacity is exceeded.
Parameters
valValue to write.
{#putu16}
putU16
void putU16(uint16_t val)
Appends an unsigned 16-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded.
Parameters
valValue to write.
{#putu24}
putU24
void putU24(uint32_t val)
Appends the low 24 bits of a 32-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded.
Parameters
valValue to write (only the lower 3 bytes are written).
{#putu32}
putU32
void putU32(uint32_t val)
Appends an unsigned 32-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded.
Parameters
valValue to write.
{#putu64}
putU64
void putU64(uint64_t val)
Appends an unsigned 64-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded.
Parameters
valValue to write.
{#update}
update
virtual
virtual bool update(const char * val, size_t len, size_t pos)
Update a byte range. Throws a std::out_of_range exception if reading past the limit.
{#update}
update
bool update(const std::string & val, size_t pos)
Overwrites a previously written string at the given absolute position.
Parameters
-
valString to write. -
posAbsolute byte offset to overwrite at.
Returns
True on success, false if the range exceeds available space.
{#updateu8}
updateU8
bool updateU8(uint8_t val, size_t pos)
Overwrites a uint8_t at the given absolute position.
Parameters
-
valValue to write. -
posAbsolute byte offset to overwrite at.
Returns
True on success, false if the range exceeds available space.
{#updateu16}
updateU16
bool updateU16(uint16_t val, size_t pos)
Overwrites a uint16_t at the given absolute position, with byte-order conversion.
Parameters
-
valValue to write. -
posAbsolute byte offset to overwrite at.
Returns
True on success, false if the range exceeds available space.
{#updateu24}
updateU24
bool updateU24(uint32_t val, size_t pos)
Overwrites 3 bytes (low 24 bits of val) at the given absolute position, with byte-order conversion.
Parameters
-
valValue to write. -
posAbsolute byte offset to overwrite at.
Returns
True on success, false if the range exceeds available space.
{#updateu32}
updateU32
bool updateU32(uint32_t val, size_t pos)
Overwrites a uint32_t at the given absolute position, with byte-order conversion.
Parameters
-
valValue to write. -
posAbsolute byte offset to overwrite at.
Returns
True on success, false if the range exceeds available space.
{#updateu64}
updateU64
bool updateU64(uint64_t val, size_t pos)
Overwrites a uint64_t at the given absolute position, with byte-order conversion.
Parameters
-
valValue to write. -
posAbsolute byte offset to overwrite at.
Returns
True on success, false if the range exceeds available space.
{#seek}
seek
void seek(size_t val)
Set position pointer to absolute position. Throws a std::out_of_range exception if the value exceeds the limit.
{#skip}
skip
void skip(size_t size)
Set position pointer to relative position. Throws a std::out_of_range exception if the value exceeds the limit.
{#limit}
limit
const
size_t limit() const
Returns the write limit.
{#position}
position
const inline
inline size_t position() const
Returns the current write position.
{#available}
available
const
size_t available() const
Returns the number of elements between the current write position and the limit.
{#begin}
begin
inline
inline char * begin()
Returns a pointer to the start of the write buffer.
{#current}
current
inline
inline char * current()
Returns a pointer to the current write position.
{#begin}
begin
const inline
inline const char * begin() const
Returns a const pointer to the start of the write buffer.
{#current}
current
const inline
inline const char * current() const
Returns a const pointer to the current write position.
{#order}
order
const inline
inline ByteOrder order() const
Returns the byte order used for multi-byte integer writes.
{#tostring}
toString
std::string toString()
Returns all bytes written so far as a std::string.
Returns
String containing bytes from the start of the buffer up to the current position.
Protected Attributes
| Return | Name | Description |
|---|---|---|
size_t | _position | |
size_t | _limit | |
ByteOrder | _order | |
char * | _bytes |
{#_position}
_position
size_t _position
{#_limit}
_limit
size_t _limit
{#_order}
_order
ByteOrder _order
{#_bytes}
_bytes
char * _bytes
Protected Methods
| Return | Name | Description |
|---|---|---|
void | init virtual |
{#init}
init
virtual
virtual void init(char * bytes, size_t size, ByteOrder order)
{#dynamicbitwriter}
DynamicBitWriter
#include <icy/buffer.h>
Inherits:
BitWriter
Class for reading/writing dynamically resizable binary streams.
Note that when using the constructor with the Buffer reference as an argument, the writer will dynamically expand the given buffer when writing passed the buffer capacity. All other cases will throw a std::out_of_range error when writing past the buffer capacity.
Public Methods
| Return | Name | Description |
|---|---|---|
DynamicBitWriter | Constructs a [DynamicBitWriter](#dynamicbitwriter) backed by a dynamically resizable Buffer. The buffer is expanded automatically as data is written. | |
DynamicBitWriter | Constructs a [DynamicBitWriter](#dynamicbitwriter) that inserts data starting at a specific iterator position. | |
void | put virtual | Append bytes to the buffer. Throws a std::out_of_range exception if reading past the limit. |
bool | update virtual | Update a byte range. Throws a std::out_of_range exception if reading past the limit. |
{#dynamicbitwriter}
DynamicBitWriter
DynamicBitWriter(Buffer & buf, ByteOrder order)
Constructs a [DynamicBitWriter](#dynamicbitwriter) backed by a dynamically resizable Buffer. The buffer is expanded automatically as data is written.
Parameters
-
bufBuffer to write into; expanded as needed. -
orderByte order used for multi-byte integer writes.
{#dynamicbitwriter}
DynamicBitWriter
DynamicBitWriter(Buffer & buf, Buffer::iterator offset, ByteOrder order)
Constructs a [DynamicBitWriter](#dynamicbitwriter) that inserts data starting at a specific iterator position.
Parameters
-
bufBuffer to write into; expanded as needed. -
offsetIterator intobufindicating the insertion start point. -
orderByte order used for multi-byte integer writes.
{#put}
put
virtual
virtual void put(const char * val, size_t len)
Append bytes to the buffer. Throws a std::out_of_range exception if reading past the limit.
{#update}
update
virtual
virtual bool update(const char * val, size_t len, size_t pos)
Update a byte range. Throws a std::out_of_range exception if reading past the limit.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Buffer & | _buffer | |
size_t | _offset |
{#_buffer}
_buffer
Buffer & _buffer
{#_offset}
_offset
size_t _offset
{#logwriter}
LogWriter
#include <icy/logger.h>
Subclassed by:
AsyncLogWriter
Log output stream writer.
Public Methods
| Return | Name | Description |
|---|---|---|
LogWriter | ||
void | write virtual | Writes the given log message stream. |
{#logwriter}
LogWriter
LogWriter()
{#write}
write
virtual
virtual void write(std::unique_ptr< LogStream > stream)
Writes the given log message stream.
{#asynclogwriter}
AsyncLogWriter
#include <icy/logger.h>
Thread based log output stream writer.
Public Methods
| Return | Name | Description |
|---|---|---|
AsyncLogWriter | ||
void | write virtual | Queues the given log message stream. |
void | flush | Flushes queued messages. |
void | run virtual | Writes queued messages asynchronously. |
void | clear | Clears all queued messages. |
{#asynclogwriter}
AsyncLogWriter
AsyncLogWriter()
{#write}
write
virtual
virtual void write(std::unique_ptr< LogStream > stream)
Queues the given log message stream.
{#flush}
flush
void flush()
Flushes queued messages.
{#run}
run
virtual
virtual void run()
Writes queued messages asynchronously.
{#clear}
clear
void clear()
Clears all queued messages.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Thread | _thread | |
std::deque< std::unique_ptr< LogStream > > | _pending | |
std::mutex | _mutex |
{#_thread}
_thread
Thread _thread
{#_pending}
_pending
std::deque< std::unique_ptr< LogStream > > _pending
{#_mutex}
_mutex
std::mutex _mutex
Protected Methods
| Return | Name | Description |
|---|---|---|
bool | writeNext |
{#writenext}
writeNext
bool writeNext()
{#logger}
Logger
#include <icy/logger.h>
Logger class.
Public Methods
| Return | Name | Description |
|---|---|---|
Logger | ||
void | add | Adds the given log channel. Takes ownership. |
void | remove | Removes the given log channel by name. |
LogChannel * | get const | Returns the specified log channel. Throws an exception if the channel doesn't exist. |
void | setDefault | Sets the default log to the specified log channel. |
void | setWriter | Sets the log writer instance. Takes ownership. |
LogChannel * | getDefault const | Returns the default log channel, or the nullptr channel if no default channel has been set. |
void | write | Writes the given message to the default log channel. The message will be copied. |
void | write | Writes the given message to the default log channel. |
{#logger}
Logger
Logger()
{#add}
add
void add(std::unique_ptr< LogChannel > channel)
Adds the given log channel. Takes ownership.
{#remove}
remove
void remove(std::string_view name)
Removes the given log channel by name.
{#get}
get
const
LogChannel * get(std::string_view name, bool whiny) const
Returns the specified log channel. Throws an exception if the channel doesn't exist.
{#setdefault}
setDefault
void setDefault(std::string_view name)
Sets the default log to the specified log channel.
{#setwriter}
setWriter
void setWriter(std::unique_ptr< LogWriter > writer)
Sets the log writer instance. Takes ownership.
{#getdefault}
getDefault
const
LogChannel * getDefault() const
Returns the default log channel, or the nullptr channel if no default channel has been set.
{#write}
write
void write(const LogStream & stream)
Writes the given message to the default log channel. The message will be copied.
{#write}
write
void write(std::unique_ptr< LogStream > stream)
Writes the given message to the default log channel.
Public Static Methods
| Return | Name | Description |
|---|---|---|
Logger & | instance static | Returns the default logger singleton. Logger instances may be created separately as needed. |
void | setInstance static | Sets the default logger singleton instance. |
void | destroy static | Destroys the default logger singleton instance. |
{#instance}
instance
static
static Logger & instance()
Returns the default logger singleton. Logger instances may be created separately as needed.
{#setinstance}
setInstance
static
static void setInstance(Logger * logger, bool freeExisting)
Sets the default logger singleton instance.
{#destroy}
destroy
static
static void destroy()
Destroys the default logger singleton instance.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::mutex | _mutex | |
LogChannelMap | _channels | |
LogChannel * | _defaultChannel | |
std::unique_ptr< LogWriter > | _writer |
{#_mutex}
_mutex
std::mutex _mutex
{#_channels}
_channels
LogChannelMap _channels
{#_defaultchannel}
_defaultChannel
LogChannel * _defaultChannel
{#_writer}
_writer
std::unique_ptr< LogWriter > _writer
Protected Methods
| Return | Name | Description |
|---|---|---|
Logger | NonCopyable and NonMovable. | |
Logger | Deleted constructor. |
{#logger}
Logger
Logger(const Logger &) = delete
NonCopyable and NonMovable.
{#logger}
Logger
Logger(Logger &&) = delete
Deleted constructor.
{#logchannel}
LogChannel
#include <icy/logger.h>
Subclassed by:
ConsoleChannel,FileChannel,RotatingFileChannel
Named log output channel with configurable severity level and formatting.
Public Methods
| Return | Name | Description |
|---|---|---|
LogChannel | #### Parameters | |
void | write virtual | Writes a log stream entry to this channel. |
void | write virtual | Writes a plain message to this channel. |
void | format virtual | Formats a log stream entry into the given output stream. |
std::string | name const inline | Returns the channel name. |
Level | level const inline | Returns the minimum severity level. |
std::string | timeFormat const inline | Returns the timestamp format string. |
void | setLevel inline | Sets the minimum severity level. |
void | setTimeFormat inline | Sets the timestamp format string. |
void | setFilter inline | Sets a realm filter; only messages whose realm matches are written. |
{#logchannel}
LogChannel
LogChannel(std::string name, Level level, std::string timeFormat)
Parameters
-
nameUnique channel name. -
levelMinimum severity level; messages below this level are dropped. -
timeFormatstrftime-compatible format string for timestamps.
{#write}
write
virtual
virtual void write(const LogStream & stream)
Writes a log stream entry to this channel.
Parameters
streamThe log stream to write.
{#write}
write
virtual
virtual void write(std::string message, Level level, std::string realm)
Writes a plain message to this channel.
Parameters
-
messageLog message text. -
levelSeverity level for the message. -
realmOptional source realm (e.g. file or class name).
{#format}
format
virtual
virtual void format(const LogStream & stream, std::ostream & ost)
Formats a log stream entry into the given output stream.
Parameters
-
streamThe log stream to format. -
ostThe output stream to write the formatted message into.
{#name}
name
const inline
inline std::string name() const
Returns the channel name.
{#level}
level
const inline
inline Level level() const
Returns the minimum severity level.
{#timeformat}
timeFormat
const inline
inline std::string timeFormat() const
Returns the timestamp format string.
{#setlevel}
setLevel
inline
inline void setLevel(Level level)
Sets the minimum severity level.
Parameters
levelMessages below this level are dropped.
{#settimeformat}
setTimeFormat
inline
inline void setTimeFormat(std::string format)
Sets the timestamp format string.
Parameters
formatstrftime-compatible format string.
{#setfilter}
setFilter
inline
inline void setFilter(std::string filter)
Sets a realm filter; only messages whose realm matches are written.
Parameters
filterRealm substring or pattern to match against.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::string | _name | |
Level | _level | |
std::string | _timeFormat | |
std::string | _filter |
{#_name}
_name
std::string _name
{#_level}
_level
Level _level
{#_timeformat}
_timeFormat
std::string _timeFormat
{#_filter}
_filter
std::string _filter
{#consolechannel}
ConsoleChannel
#include <icy/logger.h>
Inherits:
LogChannel
Log channel that writes formatted messages to standard output.
Public Methods
| Return | Name | Description |
|---|---|---|
ConsoleChannel | #### Parameters | |
void | write virtual | Formats and writes the log stream entry to stdout. Messages below the channel level or filtered by realm are silently dropped. |
{#consolechannel}
ConsoleChannel
ConsoleChannel(std::string name, Level level, std::string timeFormat)
Parameters
-
nameUnique channel name. -
levelMinimum severity level; messages below this level are dropped. -
timeFormatstrftime-compatible format string for timestamps.
{#write}
write
virtual
virtual void write(const LogStream & stream)
Formats and writes the log stream entry to stdout. Messages below the channel level or filtered by realm are silently dropped.
Parameters
streamThe log stream to write.
{#filechannel}
FileChannel
#include <icy/logger.h>
Inherits:
LogChannel
Log channel that writes formatted messages to a file.
Public Methods
| Return | Name | Description |
|---|---|---|
FileChannel | #### Parameters | |
void | write virtual | Formats and writes the log stream entry to the file. Opens the file on first write if not already open. |
void | setPath | Sets the file path and reopens the file stream. |
std::string | path const | Returns the current log file path. |
{#filechannel}
FileChannel
FileChannel(std::string name, std::string path, Level level, std::string timeFormat)
Parameters
-
nameUnique channel name. -
pathPath to the output log file. Directories are created if needed. -
levelMinimum severity level; messages below this level are dropped. -
timeFormatstrftime-compatible format string for timestamps.
{#write}
write
virtual
virtual void write(const LogStream & stream)
Formats and writes the log stream entry to the file. Opens the file on first write if not already open.
Parameters
streamThe log stream to write.
{#setpath}
setPath
void setPath(const std::string & path)
Sets the file path and reopens the file stream.
Parameters
pathPath to the new log file.
{#path}
path
const
std::string path() const
Returns the current log file path.
Returns
Absolute or relative path to the log file.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::ofstream | _fstream | |
std::string | _path |
{#_fstream}
_fstream
std::ofstream _fstream
{#_path}
_path
std::string _path
Protected Methods
| Return | Name | Description |
|---|---|---|
void | open virtual | |
void | close virtual |
{#open}
open
virtual
virtual void open()
{#close}
close
virtual
virtual void close()
{#rotatingfilechannel}
RotatingFileChannel
#include <icy/logger.h>
Inherits:
LogChannel
Log channel that writes to time-rotated log files.
Public Methods
| Return | Name | Description |
|---|---|---|
RotatingFileChannel | #### Parameters | |
void | write virtual | Formats and writes the log stream entry to the current log file. Rotates the file if the rotation interval has elapsed. |
void | rotate virtual | Closes the current log file and opens a new one with a timestamped filename. |
std::string | dir const inline | Returns the directory where log files are written. |
std::string | filename const inline | Returns the filename of the currently open log file. |
int | rotationInterval const inline | Returns the rotation interval in seconds. |
void | setDir inline | Sets the output directory for rotated log files. |
void | setExtension inline | Sets the file extension for rotated log files. |
void | setRotationInterval inline | Sets the rotation interval. |
{#rotatingfilechannel}
RotatingFileChannel
RotatingFileChannel(std::string name, std::string dir, Level level, std::string extension, int rotationInterval, std::string timeFormat)
Parameters
-
nameUnique channel name. -
dirDirectory in which rotated log files are written. -
levelMinimum severity level; messages below this level are dropped. -
extensionFile extension for log files (without leading dot). -
rotationIntervalSeconds between log rotations (default: 12 hours). -
timeFormatstrftime-compatible format string for timestamps.
{#write}
write
virtual
virtual void write(const LogStream & stream)
Formats and writes the log stream entry to the current log file. Rotates the file if the rotation interval has elapsed.
Parameters
streamThe log stream to write.
{#rotate}
rotate
virtual
virtual void rotate()
Closes the current log file and opens a new one with a timestamped filename.
{#dir}
dir
const inline
inline std::string dir() const
Returns the directory where log files are written.
{#filename}
filename
const inline
inline std::string filename() const
Returns the filename of the currently open log file.
{#rotationinterval}
rotationInterval
const inline
inline int rotationInterval() const
Returns the rotation interval in seconds.
{#setdir}
setDir
inline
inline void setDir(std::string dir)
Sets the output directory for rotated log files.
Parameters
dirTarget directory path.
{#setextension}
setExtension
inline
inline void setExtension(std::string ext)
Sets the file extension for rotated log files.
Parameters
extExtension without leading dot (e.g. "log").
{#setrotationinterval}
setRotationInterval
inline
inline void setRotationInterval(int interval)
Sets the rotation interval.
Parameters
intervalNumber of seconds between rotations.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::unique_ptr< std::ofstream > | _fstream | |
std::string | _dir | |
std::string | _filename | |
std::string | _extension | |
int | _rotationInterval | The log rotation interval in seconds. |
time_t | _rotatedAt | The time the log was last rotated. |
{#_fstream}
_fstream
std::unique_ptr< std::ofstream > _fstream
{#_dir}
_dir
std::string _dir
{#_filename}
_filename
std::string _filename
{#_extension}
_extension
std::string _extension
{#_rotationinterval}
_rotationInterval
int _rotationInterval
The log rotation interval in seconds.
{#_rotatedat}
_rotatedAt
time_t _rotatedAt
The time the log was last rotated.
{#refcounted}
RefCounted
#include <icy/memory.h>
Subclassed by:
PacketTransaction< Message >,Context< uv_pipe_t >,Context< uv_tcp_t >,Context< uv_udp_t >,Context< uv_idle_t >,Context< uv_process_t >,Context< uv_async_t >,Context< uv_timer_t >
Base class for intrusive reference counting.
Embeds the refcount in the object itself - no separate control block allocation, no atomic operations. Safe for single-threaded libuv loops.
Usage: inherit from RefCounted
Public Methods
| Return | Name | Description |
|---|---|---|
RefCounted | Defaulted constructor. | |
RefCounted inline | ||
void | addRef const inline | Increments the reference count. Called by IntrusivePtr on acquisition. |
bool | releaseRef const inline | Decrements the reference count. |
int | refCount const inline | Returns the current reference count. |
{#refcounted}
RefCounted
RefCounted() = default
Defaulted constructor.
{#refcounted}
RefCounted
inline
inline RefCounted(const RefCounted &) noexcept
{#addref}
addRef
const inline
inline void addRef() const noexcept
Increments the reference count. Called by IntrusivePtr on acquisition.
{#releaseref}
releaseRef
const inline
inline bool releaseRef() const noexcept
Decrements the reference count.
Returns
true if the count reached zero (caller should delete the object).
{#refcount}
refCount
const inline
inline int refCount() const noexcept
Returns the current reference count.
Returns
Current reference count.
Private Attributes
| Return | Name | Description |
|---|---|---|
int | _refCount |
{#_refcount}
_refCount
int _refCount = 0
{#intrusiveptr}
IntrusivePtr
#include <icy/memory.h>
Intrusive smart pointer for RefCounted objects.
Like std::shared_ptr but with zero allocation overhead:
-
No separate control block (refcount is embedded in the object)
-
Non-atomic refcount (safe for single-threaded libuv loops)
-
Same API as shared_ptr for easy migration
Public Methods
| Return | Name | Description |
|---|---|---|
IntrusivePtr inline | ||
IntrusivePtr inline | ||
IntrusivePtr inline explicit | ||
IntrusivePtr inline | ||
IntrusivePtr inline | ||
IntrusivePtr inline | ||
IntrusivePtr inline | ||
void | reset inline | Releases ownership of the current pointer, decrementing its refcount. The pointer is set to null. |
void | reset inline | Releases the current pointer and takes ownership of p, incrementing its refcount. |
T * | get const inline | Returns the raw pointer without transferring ownership. |
T & | operator* const inline | Dereferences the managed pointer. |
T * | operator-> const inline | Member access on the managed pointer. |
operator bool const inline explicit | Returns true if the pointer is non-null. | |
void | swap inline | Swaps the managed pointer with another IntrusivePtr. |
void | detach inline | Release ownership without decrementing refcount. Used internally for move construction across types. |
bool | operator== const inline | |
bool | operator!= const inline | |
bool | operator== const inline | |
bool | operator!= const inline | |
bool | operator< const inline |
{#intrusiveptr}
IntrusivePtr
inline
inline IntrusivePtr() noexcept
{#intrusiveptr}
IntrusivePtr
inline
inline IntrusivePtr(std::nullptr_t) noexcept
{#intrusiveptr}
IntrusivePtr
inline explicit
inline explicit IntrusivePtr(T * p) noexcept
{#intrusiveptr}
IntrusivePtr
inline
inline IntrusivePtr(const IntrusivePtr & r) noexcept
{#intrusiveptr}
IntrusivePtr
inline
template<typename U> inline IntrusivePtr(const IntrusivePtr< U > & r) noexcept
{#intrusiveptr}
IntrusivePtr
inline
inline IntrusivePtr(IntrusivePtr && r) noexcept
{#intrusiveptr}
IntrusivePtr
inline
template<typename U> inline IntrusivePtr(IntrusivePtr< U > && r) noexcept
{#reset}
reset
inline
inline void reset() noexcept
Releases ownership of the current pointer, decrementing its refcount. The pointer is set to null.
{#reset}
reset
inline
inline void reset(T * p) noexcept
Releases the current pointer and takes ownership of p, incrementing its refcount.
Parameters
pNew raw pointer to manage (may be nullptr).
{#get}
get
const inline
inline T * get() const noexcept
Returns the raw pointer without transferring ownership.
Returns
Raw pointer to the managed object, or nullptr.
{#operator}
operator*
const inline
inline T & operator*() const noexcept
Dereferences the managed pointer.
Returns
Reference to the managed object.
{#operator}
operator->
const inline
inline T * operator->() const noexcept
Member access on the managed pointer.
Returns
Raw pointer to the managed object.
{#operatorbool}
operator bool
const inline explicit
inline explicit operator bool() const noexcept
Returns true if the pointer is non-null.
{#swap}
swap
inline
inline void swap(IntrusivePtr & r) noexcept
Swaps the managed pointer with another IntrusivePtr.
Parameters
rThe other IntrusivePtr to swap with.
{#detach}
detach
inline
inline void detach() noexcept
Release ownership without decrementing refcount. Used internally for move construction across types.
{#operator}
operator==
const inline
inline bool operator==(const IntrusivePtr & r) const noexcept
{#operator}
operator!=
const inline
inline bool operator!=(const IntrusivePtr & r) const noexcept
{#operator}
operator==
const inline
inline bool operator==(std::nullptr_t) const noexcept
{#operator}
operator!=
const inline
inline bool operator!=(std::nullptr_t) const noexcept
{#operator}
operator<
const inline
inline bool operator<(const IntrusivePtr & r) const noexcept
Private Attributes
| Return | Name | Description |
|---|---|---|
T * | _ptr |
{#_ptr}
_ptr
T * _ptr
{#random}
Random
#include <icy/random.h>
Random implements a pseudo random number generator (PRNG) using the Mersenne Twister algorithm (std::mt19937).
Public Methods
| Return | Name | Description |
|---|---|---|
Random | Creates and initializes the PRNG. The stateSize parameter is accepted for API compatibility but is ignored; the engine always uses mt19937's fixed state size. | |
~Random | Destroys the PRNG. | |
void | seed | Seeds the pseudo random generator with the given seed. |
void | seed | Seeds the pseudo random generator with entropy from std::random_device. |
uint32_t | next | Returns the next pseudo random number from the mt19937 engine. |
uint32_t | next | Returns the next pseudo random number in the range [0, n). |
char | nextChar | Returns the next pseudo random byte as a char. |
bool | nextBool | Returns the next pseudo random boolean value. |
float | nextFloat | Returns the next pseudo random float in [0.0, 1.0]. |
double | nextDouble | Returns the next pseudo random double in [0.0, 1.0]. |
{#random}
Random
Random(int stateSize)
Creates and initializes the PRNG. The stateSize parameter is accepted for API compatibility but is ignored; the engine always uses mt19937's fixed state size.
Parameters
stateSizeIgnored; present for API compatibility only.
{#random}
~Random
~Random()
Destroys the PRNG.
{#seed}
seed
void seed(uint32_t seed)
Seeds the pseudo random generator with the given seed.
Parameters
seed32-bit seed value.
{#seed}
seed
void seed()
Seeds the pseudo random generator with entropy from std::random_device.
{#next}
next
uint32_t next()
Returns the next pseudo random number from the mt19937 engine.
Returns
Pseudo random uint32_t value.
{#next}
next
uint32_t next(uint32_t n)
Returns the next pseudo random number in the range [0, n).
Parameters
nUpper bound (exclusive).
Returns
Pseudo random value in [0, n).
{#nextchar}
nextChar
char nextChar()
Returns the next pseudo random byte as a char.
Returns
Pseudo random char value.
{#nextbool}
nextBool
bool nextBool()
Returns the next pseudo random boolean value.
Returns
true or false with equal probability.
{#nextfloat}
nextFloat
float nextFloat()
Returns the next pseudo random float in [0.0, 1.0].
Returns
Pseudo random float value.
{#nextdouble}
nextDouble
double nextDouble()
Returns the next pseudo random double in [0.0, 1.0].
Returns
Pseudo random double value.
Public Static Methods
| Return | Name | Description |
|---|---|---|
void | getSeed static | Fills the buffer with cryptographically random bytes from std::random_device. |
{#getseed}
getSeed
static
static void getSeed(char * seed, unsigned length)
Fills the buffer with cryptographically random bytes from std::random_device.
Parameters
-
seedBuffer to fill. -
lengthNumber of bytes to write into seed.
Private Attributes
| Return | Name | Description |
|---|---|---|
std::mt19937 | _engine |
{#_engine}
_engine
std::mt19937 _engine
{#runner}
Runner
#include <icy/runner.h>
Subclassed by:
Idler,Synchronizer,Thread,Timer
Runner is a virtual interface for implementing asynchronous objects such as threads and futures.
Public Methods
| Return | Name | Description |
|---|---|---|
Runner | ||
void | start | Starts the asynchronous context with the given callback. The callback must remain valid for the lifetime of the [Runner](#runner). |
bool | running const | Returns true if the async context is currently running. |
void | cancel | Signals the async context to stop at the earliest opportunity. |
bool | cancelled const | Returns true if the context has been cancelled. The implementation is responsible for exiting as soon as possible after cancellation. |
bool | repeating const | Returns true if the runner is in repeating mode. |
void | setRepeating | Enables or disables repeating mode. When repeating, the target function is invoked repeatedly until [cancel()](#classicy_1_1Runner_1a53b3794fbd4ace235771a4e84f93f1e7) is called. This normalizes behaviour across thread-based and event-loop-based [Runner](#runner) implementations. Must be called before [start()](#classicy_1_1Runner_1a5969e823f1ce0bdd8730d3108bf13fbd). |
bool | async const | Returns true if the implementation is thread-based. |
std::thread::id | tid const | Returns the native thread ID of the thread running the async context. |
bool | waitForExit | Blocks until the async context exits or the timeout elapses. The context should be cancelled before calling this method. Must be called from outside the runner's own thread to avoid deadlock. |
{#runner}
Runner
Runner()
{#start}
start
void start(std::function< void()> target)
Starts the asynchronous context with the given callback. The callback must remain valid for the lifetime of the [Runner](#runner).
Parameters
targetCallable to invoke when the context runs.
{#running}
running
const
bool running() const
Returns true if the async context is currently running.
Returns
True if the runner's context has been started and has not yet stopped.
{#cancel}
cancel
void cancel()
Signals the async context to stop at the earliest opportunity.
{#cancelled}
cancelled
const
bool cancelled() const
Returns true if the context has been cancelled. The implementation is responsible for exiting as soon as possible after cancellation.
Returns
True if [cancel()](#classicy_1_1Runner_1a53b3794fbd4ace235771a4e84f93f1e7) has been called.
{#repeating}
repeating
const
bool repeating() const
Returns true if the runner is in repeating mode.
Returns
True if the target function is invoked in a loop until cancelled.
{#setrepeating}
setRepeating
void setRepeating(bool flag)
Enables or disables repeating mode. When repeating, the target function is invoked repeatedly until [cancel()](#classicy_1_1Runner_1a53b3794fbd4ace235771a4e84f93f1e7) is called. This normalizes behaviour across thread-based and event-loop-based [Runner](#runner) implementations. Must be called before [start()](#classicy_1_1Runner_1a5969e823f1ce0bdd8730d3108bf13fbd).
Parameters
flagTrue to enable repeating mode, false to run the target once.
{#async}
async
const
bool async() const
Returns true if the implementation is thread-based.
Returns
True for thread-backed runners, false for event-loop-driven runners.
{#tid}
tid
const
std::thread::id tid() const
Returns the native thread ID of the thread running the async context.
Returns
std::thread::id of the runner thread, or a default-constructed ID if not started.
{#waitforexit}
waitForExit
bool waitForExit(int timeout)
Blocks until the async context exits or the timeout elapses. The context should be cancelled before calling this method. Must be called from outside the runner's own thread to avoid deadlock.
Parameters
timeoutMaximum number of milliseconds to wait. Pass 0 to wait indefinitely.
Returns
True if the context exited cleanly, false if the timeout was reached (throws instead).
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::shared_ptr< Context > | _context | Shared pointer to the internal Context. |
{#_context}
_context
std::shared_ptr< Context > _context
Shared pointer to the internal Context.
Protected Methods
| Return | Name | Description |
|---|---|---|
Runner | NonCopyable and NonMovable. | |
Runner | Deleted constructor. |
{#runner}
Runner
Runner(const Runner &) = delete
NonCopyable and NonMovable.
{#runner}
Runner
Runner(Runner &&) = delete
Deleted constructor.
{#signalrtargsmutext}
Signal< RT(Args...), MutexT >
#include <icy/signal.h>
Thread-safe signal and slot implementation for callback-based event dispatch.
Public Methods
| Return | Name | Description |
|---|---|---|
int | attach const inline | Connects a lambda or std::function to the signal. |
int | attach const inline | Connects a pre-constructed SlotPtr to the signal. |
bool | detach const inline | Detaches the slot with the given ID. |
bool | detach const inline | Detaches all slots associated with the given instance pointer. |
bool | detach const inline | Detaches the slot whose delegate compares equal to other->delegate. |
void | detachAll const inline | Detaches and destroys all currently attached slots. |
RT | emit virtual inline | Emits the signal, invoking all live attached slots in priority order. |
std::vector< SlotPtr > | slots const inline | Returns a snapshot copy of the current slot list. |
size_t | nslots const inline | Returns the number of slots currently registered with this signal. |
int | operator+= inline | Attaches a function; equivalent to attach(func). |
int | operator+= inline | Attaches a pre-constructed slot; equivalent to attach(slot). |
bool | operator-= inline | Detaches the slot with the given ID; equivalent to detach(id). |
bool | operator-= inline | Detaches all slots for the given instance; equivalent to detach(instance). |
bool | operator-= inline | Detaches the slot matching slot's delegate; equivalent to detach(slot). |
Signal | Defaulted constructor. | |
Signal inline | Copy constructor; copies the slot list and last-assigned ID from r. | |
Signal & | operator= inline | Copy assignment operator; copies the slot list and last-assigned ID from r. |
{#attach}
attach
const inline
inline int attach(Function const & func, void * instance, int id, int priority) const
Connects a lambda or std::function to the signal.
Parameters
-
funcThe callable to invoke when the signal is emitted. -
instanceOptional owner pointer used for instance-based detach; passnullptrif not applicable. -
idExplicit slot ID to assign; pass-1to auto-assign. -
priorityHigher values are called first; pass-1for default ordering.
Returns
The assigned slot ID, which can be passed to [detach()](#classicy_1_1Signal_3_01RT_07Args_8_8_8_08_00_01MutexT_01_4_1af559f1f6b044f249b3d7b04d80274bab) to disconnect.
{#attach}
attach
const inline
inline int attach(SlotPtr slot) const
Connects a pre-constructed SlotPtr to the signal.
Duplicate slots (matched by delegate equality) are removed before insertion. Slots are kept sorted in descending priority order after insertion.
Parameters
slotThe slot to attach. Must have a valid delegate.
Returns
The assigned slot ID, which can be passed to [detach()](#classicy_1_1Signal_3_01RT_07Args_8_8_8_08_00_01MutexT_01_4_1af559f1f6b044f249b3d7b04d80274bab) to disconnect.
Exceptions
std::logic_errorifslot->idis set explicitly and already in use.
{#detach}
detach
const inline
inline bool detach(int id) const
Detaches the slot with the given ID.
Safe to call from within a slot's callback (the slot is marked dead before erasure).
Parameters
idThe slot ID returned by[attach()](#classicy_1_1Signal_3_01RT_07Args_8_8_8_08_00_01MutexT_01_4_1ab117b8aacf13226bade149c94b6088ed).
Returns
true if a slot was found and removed; false if the ID was not found.
{#detach}
detach
const inline
inline bool detach(const void * instance) const
Detaches all slots associated with the given instance pointer.
Useful for bulk disconnect when an object is destroyed. Matches slots by their stored instance pointer, not by delegate equality.
Parameters
instanceThe owner pointer used when the slots were attached.
Returns
true if at least one slot was removed; false otherwise.
{#detach}
detach
const inline
inline bool detach(SlotPtr other) const
Detaches the slot whose delegate compares equal to other->delegate.
Used by the [slot()](#slot) helper overloads and operator-= to disconnect a specific class-member or function binding by value.
Parameters
otherA slot whose delegate is compared against attached slots.
Returns
true if a matching slot was found and removed; false otherwise.
{#detachall}
detachAll
const inline
inline void detachAll() const
Detaches and destroys all currently attached slots.
Each slot is marked dead before removal. After this call [nslots()](#classicy_1_1Signal_3_01RT_07Args_8_8_8_08_00_01MutexT_01_4_1ab987050a876fe4e983601eae08062587) returns 0.
{#emit}
emit
virtual inline
virtual inline RT emit(Args... args)
Emits the signal, invoking all live attached slots in priority order.
For [Signal](#signal)<bool(...)>: iterates slots and returns true as soon as any slot returns true, stopping further propagation. Returns false if no slot handled the event.
For [Signal](#signal)<void(...)>: calls every live slot unconditionally.
Emission snapshots raw slot pointers under a shared lock, then invokes delegates without holding the lock. Dead slots are swept after the outermost emission returns, allowing attach/detach inside callbacks without copying shared_ptrs on the hot path.
Parameters
argsArguments forwarded to each connected slot.
Returns
For bool return type: true if any slot handled the event, false otherwise. For void return type: nothing.
{#slots}
slots
const inline
inline std::vector< SlotPtr > slots() const
Returns a snapshot copy of the current slot list.
The copy is taken under a shared lock, so it is safe to call concurrently with attach/detach operations. Only currently live slots are returned.
Returns
A vector of SlotPtr representing all currently registered slots.
{#nslots}
nslots
const inline
inline size_t nslots() const
Returns the number of slots currently registered with this signal.
The count is taken under a shared lock. Slots that were concurrently killed but not yet erased may still be included in the count.
Returns
The number of entries in the internal slot list.
{#operator}
operator+=
inline
inline int operator+=(Function const & func)
Attaches a function; equivalent to attach(func).
Returns
Assigned slot ID.
{#operator}
operator+=
inline
inline int operator+=(SlotPtr slot)
Attaches a pre-constructed slot; equivalent to attach(slot).
Returns
Assigned slot ID.
{#operator}
operator-=
inline
inline bool operator-=(int id)
Detaches the slot with the given ID; equivalent to detach(id).
Returns
true if removed.
{#operator}
operator-=
inline
inline bool operator-=(const void * instance)
Detaches all slots for the given instance; equivalent to detach(instance).
Returns
true if any removed.
{#operator}
operator-=
inline
inline bool operator-=(SlotPtr slot)
Detaches the slot matching slot's delegate; equivalent to detach(slot).
Returns
true if removed.
{#signal}
Signal
Signal() = default
Defaulted constructor.
{#signal}
Signal
inline
inline Signal(const Signal & r)
Copy constructor; copies the slot list and last-assigned ID from r.
Parameters
rThe signal to copy from.
{#operator}
operator=
inline
inline Signal & operator=(const Signal & r)
Copy assignment operator; copies the slot list and last-assigned ID from r.
Parameters
rThe signal to copy from.
Returns
Reference to this signal.
Public Types
| Name | Description |
|---|---|
Function | |
SlotPtr | |
Slot |
{#function}
Function
std::function< RT(Args...)> Function()
{#slotptr}
SlotPtr
std::shared_ptr< internal::Slot< RT, Args... > > SlotPtr()
{#slot}
Slot
internal::Slot< RT, Args... > Slot()
Private Attributes
| Return | Name | Description |
|---|---|---|
MutexT | _mutex | |
std::vector< SlotPtr > | _slots | |
size_t | _liveCount | |
int | _lastId | |
EmitDepth | _emitDepth | |
SweepFlag | _needsSweep |
{#_mutex}
_mutex
MutexT _mutex
{#_slots}
_slots
std::vector< SlotPtr > _slots
{#_livecount}
_liveCount
size_t _liveCount = 0
{#_lastid}
_lastId
int _lastId = 0
{#_emitdepth}
_emitDepth
EmitDepth _emitDepth {}
{#_needssweep}
_needsSweep
SweepFlag _needsSweep {}
Private Methods
| Return | Name | Description |
|---|---|---|
size_t | killMatchingLocked const inline | |
size_t | emitDepthLocked const inline | |
void | beginEmitLocked const inline | |
bool | endEmitLocked const inline | |
void | requestSweepLocked const inline | |
bool | consumeSweepRequest const inline | |
void | sweepLocked const inline | |
void | finishEmit inline | |
void | resetEmitState inline |
{#killmatchinglocked}
killMatchingLocked
const inline
template<typename Matcher> inline size_t killMatchingLocked(Matcher && matcher, bool removeAll) const
{#emitdepthlocked}
emitDepthLocked
const inline
inline size_t emitDepthLocked() const
{#beginemitlocked}
beginEmitLocked
const inline
inline void beginEmitLocked() const
{#endemitlocked}
endEmitLocked
const inline
inline bool endEmitLocked() const
{#requestsweeplocked}
requestSweepLocked
const inline
inline void requestSweepLocked() const
{#consumesweeprequest}
consumeSweepRequest
const inline
inline bool consumeSweepRequest() const
{#sweeplocked}
sweepLocked
const inline
inline void sweepLocked() const
{#finishemit}
finishEmit
inline
inline void finishEmit()
{#resetemitstate}
resetEmitState
inline
inline void resetEmitState()
{#stream}
Stream
#include <icy/stream.h>
Inherits:
Handle< T >
Basic stream type for sockets and pipes.
Public Attributes
| Return | Name | Description |
|---|---|---|
Signal< void(const char *, const int &)> | Read | Emitted when data has been received from the peer. |
{#read}
Read
Signal< void(const char *, const int &)> Read
Emitted when data has been received from the peer.
Slot signature: void(const char* data, const int& len)
Public Methods
| Return | Name | Description |
|---|---|---|
Stream inline | Construct the stream bound to loop with a 64 KiB read buffer. | |
~Stream virtual inline | Destroy the stream, stopping reads and freeing pooled write requests. | |
void | close virtual inline | Closes and resets the stream handle. This will close the active socket/pipe and destroy the handle. |
bool | shutdown inline | Send a TCP/pipe shutdown request to the connected peer. |
bool | write inline | Write len bytes from data to the stream. |
bool | writeOwned inline | Write an owned payload buffer to the stream. |
void | setHighWaterMark inline | Set the high water mark for the write queue (default 16MB). When the write queue exceeds this size, write() returns false. |
bool | write inline | Write len bytes from data together with a stream handle over an IPC pipe (uses uv_write2). |
uv_stream_t * | stream inline | Return the underlying uv_stream_t pointer cast from the native handle. |
{#stream}
Stream
inline
inline Stream(uv::Loop * loop)
Construct the stream bound to loop with a 64 KiB read buffer.
Parameters
loopEvent loop to associate this stream with.
{#stream}
~Stream
virtual inline
virtual inline ~Stream()
Destroy the stream, stopping reads and freeing pooled write requests.
{#close}
close
virtual inline
virtual inline void close()
Closes and resets the stream handle. This will close the active socket/pipe and destroy the handle.
If the stream is already closed this call will have no side-effects.
{#shutdown}
shutdown
inline
inline bool shutdown()
Send a TCP/pipe shutdown request to the connected peer.
Issues a half-close: no further writes will be accepted after this, but the stream remains open for reading until the peer also closes.
Returns
true if the shutdown request was submitted successfully; false if the stream is not active.
{#write}
write
inline
inline bool write(const char * data, size_t len)
Write len bytes from data to the stream.
The write is non-blocking; data is buffered by libuv. Returns false without throwing if the stream is inactive, reads have not started, or the internal write queue exceeds the high-water mark.
Parameters
-
dataPointer to the bytes to send. Must remain valid until the write completion callback fires. -
lenNumber of bytes to send.
Returns
true if the write was queued; false on backpressure or if the stream is not in a writable state.
{#writeowned}
writeOwned
inline
inline bool writeOwned(Buffer && buffer)
Write an owned payload buffer to the stream.
The buffer is moved into the queued write request and retained until the libuv completion callback fires. Use this path whenever the caller does not naturally own storage beyond the current stack frame.
Parameters
bufferPayload buffer moved into the async write request.
Returns
true if the write was queued; false on backpressure or if the stream is not in a writable state.
{#sethighwatermark}
setHighWaterMark
inline
inline void setHighWaterMark(size_t bytes)
Set the high water mark for the write queue (default 16MB). When the write queue exceeds this size, write() returns false.
{#write}
write
inline
inline bool write(const char * data, size_t len, uv_stream_t * send)
Write len bytes from data together with a stream handle over an IPC pipe (uses uv_write2).
Only valid for named-pipe handles opened with IPC mode enabled. Throws std::logic_error if called on a non-IPC pipe.
Parameters
-
dataBytes to send alongside the handle. -
lenNumber of bytes to send. -
sendStream handle to pass to the receiving process.
Returns
true if the write was queued; false on error.
{#stream}
stream
inline
inline uv_stream_t * stream()
Return the underlying uv_stream_t pointer cast from the native handle.
Returns
Pointer to the uv_stream_t, or nullptr if the handle is closed.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Buffer | _buffer | |
bool | _started | |
size_t | _highWaterMark | 16MB default write queue limit |
std::vector< uv_write_t * > | _writeReqFree | Freelist for write requests. |
std::vector< OwnedWriteReq * > | _ownedWriteReqFree | Freelist for owned write requests. |
{#_buffer}
_buffer
Buffer _buffer
{#_started}
_started
bool _started {false}
{#_highwatermark}
_highWaterMark
size_t _highWaterMark {16 * 1024 * 1024}
16MB default write queue limit
{#_writereqfree}
_writeReqFree
std::vector< uv_write_t * > _writeReqFree
Freelist for write requests.
{#_ownedwritereqfree}
_ownedWriteReqFree
std::vector< OwnedWriteReq * > _ownedWriteReqFree
Freelist for owned write requests.
Protected Methods
| Return | Name | Description |
|---|---|---|
bool | readStart virtual inline | Begin reading from the stream by registering libuv read callbacks. |
bool | readStop virtual inline | Stop reading from the stream. |
void | onRead virtual inline | Called by handleRead when len bytes of data arrive. |
uv_write_t * | allocWriteReq inline | Return a uv_write_t from the freelist, or allocate a new one if the pool is empty. |
void | freeWriteReq inline | Return req to the freelist, or delete it if the pool is at capacity. |
OwnedWriteReq * | allocOwnedWriteReq inline | |
void | freeOwnedWriteReq inline | |
bool | canQueueWrite inline |
{#readstart}
readStart
virtual inline
virtual inline bool readStart()
Begin reading from the stream by registering libuv read callbacks.
Sets the stream's data pointer to this so callbacks can recover the C++ object. Has no effect and returns false if already started.
Returns
true if uv_read_start was called successfully.
{#readstop}
readStop
virtual inline
virtual inline bool readStop()
Stop reading from the stream.
No further read callbacks will fire after this returns. Has no effect and returns false if not currently started.
Returns
true if uv_read_stop was called successfully.
{#onread}
onRead
virtual inline
virtual inline void onRead(const char * data, size_t len)
Called by handleRead when len bytes of data arrive.
The default implementation emits the Read signal. Override to intercept data before it reaches signal subscribers.
Parameters
-
dataPointer into the read buffer; valid only for this call. -
lenNumber of valid bytes indata.
{#allocwritereq}
allocWriteReq
inline
inline uv_write_t * allocWriteReq()
Return a uv_write_t from the freelist, or allocate a new one if the pool is empty.
Returns
Pointer to an unused uv_write_t.
{#freewritereq}
freeWriteReq
inline
inline void freeWriteReq(uv_write_t * req)
Return req to the freelist, or delete it if the pool is at capacity.
Parameters
reqWrite request to recycle or free.
{#allocownedwritereq}
allocOwnedWriteReq
inline
inline OwnedWriteReq * allocOwnedWriteReq()
{#freeownedwritereq}
freeOwnedWriteReq
inline
inline void freeOwnedWriteReq(OwnedWriteReq * req)
{#canqueuewrite}
canQueueWrite
inline
inline bool canQueueWrite(size_t len)
Public Types
| Name | Description |
|---|---|
Handle |
{#handle}
Handle
uv::Handle< T > Handle()
{#thread}
Thread
#include <icy/thread.h>
Inherits:
Runner
Platform-independent wrapper around an operating system thread.
This class inherits the [Runner](#runner) interface and may be used with any implementation that's powered by an asynchronous [Runner](#runner).
Public Methods
| Return | Name | Description |
|---|---|---|
Thread | Default constructor. | |
Thread inline explicit | Constructs a [Thread](#thread) and immediately starts it with the given function and arguments. | |
~Thread virtual | Destructor. | |
void | start inline | Starts the thread with a variadic function and arguments. The thread is started immediately; the previous thread must have exited before calling again. |
void | start virtual | Starts the thread with a std::function callback. Overrides [Runner::start](#classicy_1_1Runner_1a5969e823f1ce0bdd8730d3108bf13fbd); delegates to the variadic start template. |
void | join | Wait until the thread exits. |
std::thread::id | id const | Return the native thread handle. |
{#thread}
Thread
Thread()
Default constructor.
{#thread}
Thread
inline explicit
template<typename Function, typename... Args> inline explicit Thread(Function && func, Args &&... args)
Constructs a [Thread](#thread) and immediately starts it with the given function and arguments.
Parameters
-
FunctionCallable type. -
ArgsArgument types forwarded to the function.
Parameters
-
funcCallable to execute on the new thread. -
argsArguments forwarded tofunc.
{#thread}
~Thread
virtual
virtual ~Thread()
Destructor.
{#start}
start
inline
template<typename Function, typename... Args> inline void start(Function && func, Args &&... args)
Starts the thread with a variadic function and arguments. The thread is started immediately; the previous thread must have exited before calling again.
Parameters
-
FunctionCallable type. -
ArgsArgument types forwarded to the function.
Parameters
-
funcCallable to execute on the new thread. -
argsArguments forwarded tofunc.
{#start}
start
virtual
virtual void start(std::function< void()> func)
Starts the thread with a std::function callback. Overrides [Runner::start](#classicy_1_1Runner_1a5969e823f1ce0bdd8730d3108bf13fbd); delegates to the variadic start template.
Parameters
funcCallable to execute on the new thread.
{#join}
join
void join()
Wait until the thread exits.
{#id}
id
const
std::thread::id id() const
Return the native thread handle.
Public Static Attributes
| Return | Name | Description |
|---|---|---|
const std::thread::id | mainID static | Accessor for the main thread ID. |
{#mainid}
mainID
static
const std::thread::id mainID
Accessor for the main thread ID.
Public Static Methods
| Return | Name | Description |
|---|---|---|
std::thread::id | currentID static | Return the native thread ID of the current thread. |
{#currentid}
currentID
static
static std::thread::id currentID()
Return the native thread ID of the current thread.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::thread | _thread |
{#_thread}
_thread
std::thread _thread
Protected Methods
| Return | Name | Description |
|---|---|---|
Thread | NonCopyable and NonMovable. | |
Thread | Deleted constructor. | |
bool | async virtual const | Returns true if the implementation is thread-based. |
{#thread}
Thread
Thread(const Thread &) = delete
NonCopyable and NonMovable.
{#thread}
Thread
Thread(Thread &&) = delete
Deleted constructor.
{#async}
async
virtual const
virtual bool async() const
Returns true if the implementation is thread-based.
Returns
True for thread-backed runners, false for event-loop-driven runners.
Public Types
| Name | Description |
|---|---|
Ptr |
{#ptr}
Ptr
std::shared_ptr< Thread > Ptr()
{#process}
Process
#include <icy/process.h>
Spawns and manages a child process with stdin/stdout/stderr pipes.
Public Attributes
| Return | Name | Description |
|---|---|---|
std::string | file | Path to the program to execute. Convenience proxy for options.file. Must be set before [spawn()](#classicy_1_1Process_1a1d4f466c7f2713460ee35954dc6663bc) |
std::string | cwd | Set the current working directory. Convenience proxy for options.cwd. Must be set before [spawn()](#classicy_1_1Process_1a1d4f466c7f2713460ee35954dc6663bc) |
std::vector< std::string > | args | Command line arguments to pass to the process. Convenience proxy for options.args. Must be set before [spawn()](#classicy_1_1Process_1a1d4f466c7f2713460ee35954dc6663bc) |
std::vector< std::string > | env | Environment variables for the process. Each entry should be in "KEY=VALUE" format. If empty, the child inherits the parent environment. Must be set before [spawn()](#classicy_1_1Process_1a1d4f466c7f2713460ee35954dc6663bc) |
std::function< void(std::string)> | onstdout | Stdout callback. Called when a line has been output from the process. |
std::function< void(std::string)> | onstderr | Stderr callback. Called when a line has been output on stderr. |
std::function< void(std::int64_t)> | onexit | Exit callback. Called with process exit status code. |
ProcessOptions | options | LibUV C options. Available for advanced use cases. |
{#file}
file
std::string file
Path to the program to execute. Convenience proxy for options.file. Must be set before [spawn()](#classicy_1_1Process_1a1d4f466c7f2713460ee35954dc6663bc)
{#cwd}
cwd
std::string cwd
Set the current working directory. Convenience proxy for options.cwd. Must be set before [spawn()](#classicy_1_1Process_1a1d4f466c7f2713460ee35954dc6663bc)
{#args}
args
std::vector< std::string > args
Command line arguments to pass to the process. Convenience proxy for options.args. Must be set before [spawn()](#classicy_1_1Process_1a1d4f466c7f2713460ee35954dc6663bc)
{#env}
env
std::vector< std::string > env
Environment variables for the process. Each entry should be in "KEY=VALUE" format. If empty, the child inherits the parent environment. Must be set before [spawn()](#classicy_1_1Process_1a1d4f466c7f2713460ee35954dc6663bc)
{#onstdout}
onstdout
std::function< void(std::string)> onstdout
Stdout callback. Called when a line has been output from the process.
{#onstderr}
onstderr
std::function< void(std::string)> onstderr
Stderr callback. Called when a line has been output on stderr.
{#onexit}
onexit
std::function< void(std::int64_t)> onexit
Exit callback. Called with process exit status code.
{#options}
options
ProcessOptions options
LibUV C options. Available for advanced use cases.
Public Methods
| Return | Name | Description |
|---|---|---|
Process | Constructs a [Process](#process) attached to the given event loop. | |
Process | Constructs a [Process](#process) with initial command-line arguments. | |
~Process | Destructor. | |
Process | Deleted constructor. | |
Process | Deleted constructor. | |
void | spawn | Spawns the process. Options must be properly set. Throws an exception on error. |
bool | kill | Sends a signal to the process. |
int | pid const | Returns the process PID, or 0 if not spawned. |
Pipe & | in | Returns the stdin pipe. |
Pipe & | out | Returns the stdout pipe. |
Pipe & | err | Returns the stderr pipe. |
{#process}
Process
Process(uv::Loop * loop)
Constructs a [Process](#process) attached to the given event loop.
Parameters
loopEvent loop to use for I/O and exit notifications. Defaults to the default loop.
{#process}
Process
Process(std::initializer_list< std::string > args, uv::Loop * loop)
Constructs a [Process](#process) with initial command-line arguments.
Parameters
-
argsInitializer list of argument strings. The first element is typically the executable path. -
loopEvent loop to use for I/O and exit notifications. Defaults to the default loop.
{#process}
~Process
~Process()
Destructor.
{#process}
Process
Process(const Process &) = delete
Deleted constructor.
{#process}
Process
Process(Process &&) = delete
Deleted constructor.
{#spawn}
spawn
void spawn()
Spawns the process. Options must be properly set. Throws an exception on error.
{#kill}
kill
bool kill(int signum)
Sends a signal to the process.
Parameters
signumSignal number to send (default:SIGTERM).
Returns
True if the signal was sent successfully, false if the process is not running or handle is invalid.
{#pid}
pid
const
int pid() const
Returns the process PID, or 0 if not spawned.
{#in}
in
Pipe & in()
Returns the stdin pipe.
{#out}
out
Pipe & out()
Returns the stdout pipe.
{#err}
err
Pipe & err()
Returns the stderr pipe.
Protected Attributes
| Return | Name | Description |
|---|---|---|
uv::Handle< uv_process_t > | _handle | |
Pipe | _stdin | |
Pipe | _stdout | |
Pipe | _stderr | |
uv_stdio_container_t | _stdio | |
std::vector< char * > | _cargs | |
std::vector< char * > | _cenv |
{#_handle}
_handle
uv::Handle< uv_process_t > _handle
{#_stdin}
_stdin
Pipe _stdin
{#_stdout}
_stdout
Pipe _stdout
{#_stderr}
_stderr
Pipe _stderr
{#_stdio}
_stdio
uv_stdio_container_t _stdio
{#_cargs}
_cargs
std::vector< char * > _cargs
{#_cenv}
_cenv
std::vector< char * > _cenv
Protected Methods
| Return | Name | Description |
|---|---|---|
void | init |
{#init}
init
void init()
{#timeout}
Timeout
#include <icy/timeout.h>
Subclassed by:
TimedToken
Timeout counter which expires after a given delay. Delay is specified in milliseconds.
Public Methods
| Return | Name | Description |
|---|---|---|
Timeout | Constructs a Timeout with the given delay. | |
Timeout | Copy constructor. | |
Timeout | Defaulted constructor. | |
bool | running const | Returns true if the timer is currently running. |
void | start | Starts (or restarts) the timer, recording the current time as the start point. |
void | stop | Stops the timer without resetting it. expired() will return false after this call. |
void | reset | Restarts the timer from now, equivalent to calling start(). |
long | remaining const | Returns the number of milliseconds remaining before expiry. Returns 0 if already expired, or the full delay if not running. |
bool | expired const | Returns true if the timer is running and the delay has fully elapsed. |
void | setDelay inline | Sets the expiry delay without restarting the timer. |
long | delay const inline | Returns the configured delay in milliseconds. |
Timeout & | operator= | Copy assignment operator. |
{#timeout}
Timeout
Timeout(long delay, bool autoStart)
Constructs a Timeout with the given delay.
Parameters
-
delayExpiry duration in milliseconds (default: 0). -
autoStartIf true, starts the timer immediately on construction.
{#timeout}
Timeout
Timeout(const Timeout & src)
Copy constructor.
Parameters
srcSource Timeout to copy state from.
{#timeout}
Timeout
Timeout(Timeout && src) = default
Defaulted constructor.
{#running}
running
const
bool running() const
Returns true if the timer is currently running.
Returns
true if start() has been called and stop() has not.
{#start}
start
void start()
Starts (or restarts) the timer, recording the current time as the start point.
{#stop}
stop
void stop()
Stops the timer without resetting it. expired() will return false after this call.
{#reset}
reset
void reset()
Restarts the timer from now, equivalent to calling start().
{#remaining}
remaining
const
long remaining() const
Returns the number of milliseconds remaining before expiry. Returns 0 if already expired, or the full delay if not running.
Returns
Milliseconds until expiry.
{#expired}
expired
const
bool expired() const
Returns true if the timer is running and the delay has fully elapsed.
Returns
true if expired, false if stopped or not yet elapsed.
{#setdelay}
setDelay
inline
inline void setDelay(long delay)
Sets the expiry delay without restarting the timer.
Parameters
delayNew delay in milliseconds.
{#delay}
delay
const inline
inline long delay() const
Returns the configured delay in milliseconds.
Returns
Delay in milliseconds.
{#operator}
operator=
Timeout & operator=(const Timeout & src)
Copy assignment operator.
Parameters
srcSource Timeout to copy state from.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::chrono::steady_clock::time_point | _startAt | |
long | _delay | |
bool | _running |
{#_startat}
_startAt
std::chrono::steady_clock::time_point _startAt
{#_delay}
_delay
long _delay
{#_running}
_running
bool _running
{#timedtoken}
TimedToken
#include <icy/timeout.h>
Inherits:
Timeout
Token that expires after the specified duration.
Public Methods
| Return | Name | Description |
|---|---|---|
TimedToken explicit | Constructs a TimedToken with a randomly generated 32-character ID, started immediately with the given duration. | |
TimedToken explicit | Constructs a TimedToken with an explicit ID, started immediately. | |
std::string | id const inline | Returns the token's identifier string. |
bool | operator== const inline | Compares two tokens by ID. |
bool | operator== const inline | Compares this token's ID against a string. |
{#timedtoken}
TimedToken
explicit
explicit TimedToken(long duration)
Constructs a TimedToken with a randomly generated 32-character ID, started immediately with the given duration.
Parameters
durationLifetime in milliseconds (default: 1000).
{#timedtoken}
TimedToken
explicit
explicit TimedToken(const std::string & id, long duration)
Constructs a TimedToken with an explicit ID, started immediately.
Parameters
-
idToken identifier. -
durationLifetime in milliseconds (default: 1000).
{#id}
id
const inline
inline std::string id() const
Returns the token's identifier string.
Returns
Token ID.
{#operator}
operator==
const inline
inline bool operator==(const TimedToken & r) const
Compares two tokens by ID.
{#operator}
operator==
const inline
inline bool operator==(std::string_view r) const
Compares this token's ID against a string.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::string | _id |
{#_id}
_id
std::string _id
{#timestamp}
Timestamp
#include <icy/datetime.h>
A Timestamp stores a monotonic* time value with (theoretical) microseconds resolution. Timestamps can be compared with each other and simple arithmetics are supported.
[*] Note that Timestamp values are only monotonic as long as the systems's clock is monotonic as well (and not, e.g. set back).
Timestamps are UTC (Coordinated Universal Time) based and thus independent of the timezone in effect on the system.
Public Methods
| Return | Name | Description |
|---|---|---|
Timestamp | Creates a timestamp with the current time. | |
Timestamp | Creates a timestamp from the given time value. | |
Timestamp | Copy constructor. | |
~Timestamp | Destroys the timestamp. | |
void | swap | Swaps the Timestamp with another one. |
void | update | Updates the Timestamp with the current time. |
bool | operator== const inline | |
bool | operator!= const inline | |
bool | operator> const inline | |
bool | operator>= const inline | |
bool | operator< const inline | |
bool | operator<= const inline | |
Timestamp | operator+ const inline | |
Timestamp | operator- const inline | |
TimeDiff | operator- const inline | |
Timestamp & | operator+= inline | |
Timestamp & | operator-= inline | |
std::time_t | epochTime const inline | Returns the timestamp expressed in time_t. time_t base time is midnight, January 1, 1970. Resolution is one second. |
UtcTimeVal | utcTime const inline | Returns the timestamp expressed in UTC-based time. UTC base time is midnight, October 15, 1582. Resolution is 100 nanoseconds. |
TimeVal | epochMicroseconds const inline | Returns the timestamp expressed in microseconds since the Unix epoch, midnight, January 1, 1970. |
TimeDiff | elapsed const inline | Returns the time elapsed since the time denoted by the timestamp. Equivalent to Timestamp() - *this. |
bool | isElapsed const inline | Returns true iff the given interval has passed since the time denoted by the timestamp. |
{#timestamp}
Timestamp
Timestamp()
Creates a timestamp with the current time.
{#timestamp}
Timestamp
Timestamp(TimeVal tv)
Creates a timestamp from the given time value.
{#timestamp}
Timestamp
Timestamp(const Timestamp & other)
Copy constructor.
{#timestamp}
~Timestamp
~Timestamp()
Destroys the timestamp.
{#swap}
swap
void swap(Timestamp & timestamp)
Swaps the Timestamp with another one.
{#update}
update
void update()
Updates the Timestamp with the current time.
{#operator}
operator==
const inline
inline bool operator==(const Timestamp & ts) const
{#operator}
operator!=
const inline
inline bool operator!=(const Timestamp & ts) const
{#operator}
operator>
const inline
inline bool operator>(const Timestamp & ts) const
{#operator}
operator>=
const inline
inline bool operator>=(const Timestamp & ts) const
{#operator}
operator<
const inline
inline bool operator<(const Timestamp & ts) const
{#operator}
operator<=
const inline
inline bool operator<=(const Timestamp & ts) const
{#operator}
operator+
const inline
inline Timestamp operator+(TimeDiff d) const
{#operator}
operator-
const inline
inline Timestamp operator-(TimeDiff d) const
{#operator}
operator-
const inline
inline TimeDiff operator-(const Timestamp & ts) const
{#operator}
operator+=
inline
inline Timestamp & operator+=(TimeDiff d)
{#operator}
operator-=
inline
inline Timestamp & operator-=(TimeDiff d)
{#epochtime}
epochTime
const inline
inline std::time_t epochTime() const
Returns the timestamp expressed in time_t. time_t base time is midnight, January 1, 1970. Resolution is one second.
{#utctime}
utcTime
const inline
inline UtcTimeVal utcTime() const
Returns the timestamp expressed in UTC-based time. UTC base time is midnight, October 15, 1582. Resolution is 100 nanoseconds.
{#epochmicroseconds}
epochMicroseconds
const inline
inline TimeVal epochMicroseconds() const
Returns the timestamp expressed in microseconds since the Unix epoch, midnight, January 1, 1970.
{#elapsed}
elapsed
const inline
inline TimeDiff elapsed() const
Returns the time elapsed since the time denoted by the timestamp. Equivalent to Timestamp() - *this.
{#iselapsed}
isElapsed
const inline
inline bool isElapsed(TimeDiff interval) const
Returns true iff the given interval has passed since the time denoted by the timestamp.
Public Static Methods
| Return | Name | Description |
|---|---|---|
Timestamp | fromEpochTime static | Creates a timestamp from a std::time_t. |
Timestamp | fromUtcTime static | Creates a timestamp from a UTC time value. |
TimeVal | resolution static inline | Returns the resolution in units per second. Since the timestamp has microsecond resolution, the returned value is always 1000000. |
{#fromepochtime}
fromEpochTime
static
static Timestamp fromEpochTime(std::time_t t)
Creates a timestamp from a std::time_t.
{#fromutctime}
fromUtcTime
static
static Timestamp fromUtcTime(UtcTimeVal val)
Creates a timestamp from a UTC time value.
{#resolution}
resolution
static inline
static inline TimeVal resolution()
Returns the resolution in units per second. Since the timestamp has microsecond resolution, the returned value is always 1000000.
Public Types
| Name | Description |
|---|---|
TimeVal | monotonic UTC time value in microsecond resolution |
UtcTimeVal | monotonic UTC time value in 100 nanosecond resolution |
TimeDiff | difference between two timestamps in microseconds |
{#timeval}
TimeVal
std::int64_t TimeVal()
monotonic UTC time value in microsecond resolution
{#utctimeval}
UtcTimeVal
std::int64_t UtcTimeVal()
monotonic UTC time value in 100 nanosecond resolution
{#timediff}
TimeDiff
std::int64_t TimeDiff()
difference between two timestamps in microseconds
Private Attributes
| Return | Name | Description |
|---|---|---|
TimeVal | _ts |
{#_ts}
_ts
TimeVal _ts
{#timespan}
Timespan
#include <icy/datetime.h>
A class that represents time spans up to microsecond resolution.
Public Methods
| Return | Name | Description |
|---|---|---|
Timespan | Creates a zero Timespan. | |
Timespan | Creates a Timespan. | |
Timespan | Creates a Timespan. Useful for creating a Timespan from a struct timeval. | |
Timespan | Creates a Timespan. | |
Timespan | Creates a Timespan from another one. | |
~Timespan | Destroys the Timespan. | |
Timespan & | operator= | Assignment operator. |
Timespan & | operator= | Assignment operator. |
Timespan & | assign | Assigns a new span. |
Timespan & | assign | Assigns a new span. Useful for assigning from a struct timeval. |
void | swap | Swaps the Timespan with another one. |
bool | operator== const inline | |
bool | operator!= const inline | |
bool | operator> const inline | |
bool | operator>= const inline | |
bool | operator< const inline | |
bool | operator<= const inline | |
bool | operator== const inline | |
bool | operator!= const inline | |
bool | operator> const inline | |
bool | operator>= const inline | |
bool | operator< const inline | |
bool | operator<= const inline | |
Timespan | operator+ const | |
Timespan | operator- const | |
Timespan & | operator+= | |
Timespan & | operator-= | |
Timespan | operator+ const | |
Timespan | operator- const | |
Timespan & | operator+= | |
Timespan & | operator-= | |
int | days const inline | Returns the number of days. |
int | hours const inline | Returns the number of hours (0 to 23). |
int | totalHours const inline | Returns the total number of hours. |
int | minutes const inline | Returns the number of minutes (0 to 59). |
int | totalMinutes const inline | Returns the total number of minutes. |
int | seconds const inline | Returns the number of seconds (0 to 59). |
int | totalSeconds const inline | Returns the total number of seconds. |
int | milliseconds const inline | Returns the number of milliseconds (0 to 999). |
TimeDiff | totalMilliseconds const inline | Returns the total number of milliseconds. |
int | microseconds const inline | Returns the fractions of a millisecond in microseconds (0 to 999). |
int | useconds const inline | Returns the fractions of a second in microseconds (0 to 999999). |
TimeDiff | totalMicroseconds const inline | Returns the total number of microseconds. |
{#timespan}
Timespan
Timespan()
Creates a zero Timespan.
{#timespan}
Timespan
Timespan(TimeDiff microseconds)
Creates a Timespan.
{#timespan}
Timespan
Timespan(long seconds, long microseconds)
Creates a Timespan. Useful for creating a Timespan from a struct timeval.
{#timespan}
Timespan
Timespan(int days, int hours, int minutes, int seconds, int microseconds)
Creates a Timespan.
{#timespan}
Timespan
Timespan(const Timespan & timespan)
Creates a Timespan from another one.
{#timespan}
~Timespan
~Timespan()
Destroys the Timespan.
{#operator}
operator=
Timespan & operator=(const Timespan & timespan)
Assignment operator.
{#operator}
operator=
Timespan & operator=(TimeDiff microseconds)
Assignment operator.
{#assign}
assign
Timespan & assign(int days, int hours, int minutes, int seconds, int microseconds)
Assigns a new span.
{#assign}
assign
Timespan & assign(long seconds, long microseconds)
Assigns a new span. Useful for assigning from a struct timeval.
{#swap}
swap
void swap(Timespan & timespan)
Swaps the Timespan with another one.
{#operator}
operator==
const inline
inline bool operator==(const Timespan & ts) const
{#operator}
operator!=
const inline
inline bool operator!=(const Timespan & ts) const
{#operator}
operator>
const inline
inline bool operator>(const Timespan & ts) const
{#operator}
operator>=
const inline
inline bool operator>=(const Timespan & ts) const
{#operator}
operator<
const inline
inline bool operator<(const Timespan & ts) const
{#operator}
operator<=
const inline
inline bool operator<=(const Timespan & ts) const
{#operator}
operator==
const inline
inline bool operator==(TimeDiff microseconds) const
{#operator}
operator!=
const inline
inline bool operator!=(TimeDiff microseconds) const
{#operator}
operator>
const inline
inline bool operator>(TimeDiff microseconds) const
{#operator}
operator>=
const inline
inline bool operator>=(TimeDiff microseconds) const
{#operator}
operator<
const inline
inline bool operator<(TimeDiff microseconds) const
{#operator}
operator<=
const inline
inline bool operator<=(TimeDiff microseconds) const
{#operator}
operator+
const
Timespan operator+(const Timespan & d) const
{#operator}
operator-
const
Timespan operator-(const Timespan & d) const
{#operator}
operator+=
Timespan & operator+=(const Timespan & d)
{#operator}
operator-=
Timespan & operator-=(const Timespan & d)
{#operator}
operator+
const
Timespan operator+(TimeDiff microseconds) const
{#operator}
operator-
const
Timespan operator-(TimeDiff microseconds) const
{#operator}
operator+=
Timespan & operator+=(TimeDiff microseconds)
{#operator}
operator-=
Timespan & operator-=(TimeDiff microseconds)
{#days}
days
const inline
inline int days() const
Returns the number of days.
{#hours}
hours
const inline
inline int hours() const
Returns the number of hours (0 to 23).
{#totalhours}
totalHours
const inline
inline int totalHours() const
Returns the total number of hours.
{#minutes}
minutes
const inline
inline int minutes() const
Returns the number of minutes (0 to 59).
{#totalminutes}
totalMinutes
const inline
inline int totalMinutes() const
Returns the total number of minutes.
{#seconds}
seconds
const inline
inline int seconds() const
Returns the number of seconds (0 to 59).
{#totalseconds}
totalSeconds
const inline
inline int totalSeconds() const
Returns the total number of seconds.
{#milliseconds}
milliseconds
const inline
inline int milliseconds() const
Returns the number of milliseconds (0 to 999).
{#totalmilliseconds}
totalMilliseconds
const inline
inline TimeDiff totalMilliseconds() const
Returns the total number of milliseconds.
{#microseconds}
microseconds
const inline
inline int microseconds() const
Returns the fractions of a millisecond in microseconds (0 to 999).
{#useconds}
useconds
const inline
inline int useconds() const
Returns the fractions of a second in microseconds (0 to 999999).
{#totalmicroseconds}
totalMicroseconds
const inline
inline TimeDiff totalMicroseconds() const
Returns the total number of microseconds.
Public Static Attributes
| Return | Name | Description |
|---|---|---|
const TimeDiff | MILLISECONDS static | The number of microseconds in a millisecond. |
const TimeDiff | SECONDS static | The number of microseconds in a second. |
const TimeDiff | MINUTES static | The number of microseconds in a minute. |
const TimeDiff | HOURS static | The number of microseconds in a hour. |
const TimeDiff | DAYS static | The number of microseconds in a day. |
{#milliseconds}
MILLISECONDS
static
const TimeDiff MILLISECONDS
The number of microseconds in a millisecond.
{#seconds}
SECONDS
static
const TimeDiff SECONDS
The number of microseconds in a second.
{#minutes}
MINUTES
static
const TimeDiff MINUTES
The number of microseconds in a minute.
{#hours}
HOURS
static
const TimeDiff HOURS
The number of microseconds in a hour.
{#days}
DAYS
static
const TimeDiff DAYS
The number of microseconds in a day.
Public Types
| Name | Description |
|---|---|
TimeDiff |
{#timediff}
TimeDiff
Timestamp::TimeDiff TimeDiff()
Private Attributes
| Return | Name | Description |
|---|---|---|
TimeDiff | _span |
{#_span}
_span
TimeDiff _span
{#datetime}
DateTime
#include <icy/datetime.h>
This class represents an instant in time, expressed in years, months, days, hours, minutes, seconds and milliseconds based on the Gregorian calendar. The class is mainly useful for conversions between UTC, Julian day and Gregorian calendar dates.
The date and time stored in a DateTime is always in UTC (Coordinated Universal Time) and thus independent of the timezone in effect on the system.
Conversion calculations are based on algorithms collected and described by Peter Baum at http://vsg.cape.com/~pbaum/date/date0.htm
Internally, this class stores a date/time in two forms (UTC and broken down) for performance reasons. Only use this class for conversions between date/time representations. Use the Timestamp class for everything else.
Notes:
-
Zero is a valid year (in accordance with ISO 8601 and astronomical year numbering)
-
Year zero (0) is a leap year
-
Negative years (years preceding 1 BC) are not supported
For more information, please see:
Public Methods
| Return | Name | Description |
|---|---|---|
DateTime | Creates a DateTime for the current date and time. | |
DateTime | Creates a DateTime for the date and time given in a Timestamp. | |
DateTime | Creates a DateTime for the given Gregorian date and time. | |
DateTime | Creates a DateTime for the given Julian day. | |
DateTime | Creates a DateTime from an UtcTimeVal and a TimeDiff. | |
DateTime | Copy constructor. Creates the DateTime from another one. | |
~DateTime | Destroys the DateTime. | |
DateTime & | operator= | Assigns another DateTime. |
DateTime & | operator= | Assigns a Timestamp. |
DateTime & | operator= | Assigns a Julian day. |
DateTime & | assign | Assigns a Gregorian date and time. |
void | swap | Swaps the DateTime with another one. |
int | year const inline | Returns the year. |
int | month const inline | Returns the month (1 to 12). |
int | week const | Returns the week number within the year. FirstDayOfWeek should be either SUNDAY (0) or MONDAY (1). The returned week number will be from 0 to 53. Week number 1 is the week containing January 4. This is in accordance to ISO 8601. |
int | day const inline | Returns the day witin the month (1 to 31). |
int | dayOfWeek const | Returns the weekday (0 to 6, where 0 = Sunday, 1 = Monday, ..., 6 = Saturday). |
int | dayOfYear const | Returns the number of the day in the year. January 1 is 1, February 1 is 32, etc. |
int | hour const inline | Returns the hour (0 to 23). |
int | hourAMPM const inline | Returns the hour (0 to 12). |
bool | isAM const inline | Returns true if hour < 12;. |
bool | isPM const inline | Returns true if hour >= 12. |
int | minute const inline | Returns the minute (0 to 59). |
int | second const inline | Returns the second (0 to 59). |
int | millisecond const inline | Returns the millisecond (0 to 999) |
int | microsecond const inline | Returns the microsecond (0 to 999) |
double | julianDay const | Returns the julian day for the date and time. |
Timestamp | timestamp const inline | Returns the date and time expressed as a Timestamp. |
Timestamp::UtcTimeVal | utcTime const inline | Returns the date and time expressed in UTC-based time. UTC base time is midnight, October 15, 1582. Resolution is 100 nanoseconds. |
bool | operator== const inline | |
bool | operator!= const inline | |
bool | operator< const inline | |
bool | operator<= const inline | |
bool | operator> const inline | |
bool | operator>= const inline | |
DateTime | operator+ const | |
DateTime | operator- const | |
Timespan | operator- const | |
DateTime & | operator+= | |
DateTime & | operator-= | |
void | makeUTC | Converts a local time into UTC, by applying the given time zone differential. |
void | makeLocal | Converts a UTC time into a local time, by applying the given time zone differential. |
{#datetime}
DateTime
DateTime()
Creates a DateTime for the current date and time.
{#datetime}
DateTime
DateTime(const Timestamp & timestamp)
Creates a DateTime for the date and time given in a Timestamp.
{#datetime}
DateTime
DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond)
Creates a DateTime for the given Gregorian date and time.
-
year is from 0 to 9999.
-
month is from 1 to 12.
-
day is from 1 to 31.
-
hour is from 0 to 23.
-
minute is from 0 to 59.
-
second is from 0 to 59.
-
millisecond is from 0 to 999.
-
microsecond is from 0 to 999.
{#datetime}
DateTime
DateTime(double julianDay)
Creates a DateTime for the given Julian day.
{#datetime}
DateTime
DateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff)
Creates a DateTime from an UtcTimeVal and a TimeDiff.
Mainly used internally by DateTime and friends.
{#datetime}
DateTime
DateTime(const DateTime & dateTime)
Copy constructor. Creates the DateTime from another one.
{#datetime}
~DateTime
~DateTime()
Destroys the DateTime.
{#operator}
operator=
DateTime & operator=(const DateTime & dateTime)
Assigns another DateTime.
{#operator}
operator=
DateTime & operator=(const Timestamp & timestamp)
Assigns a Timestamp.
{#operator}
operator=
DateTime & operator=(double julianDay)
Assigns a Julian day.
{#assign}
assign
DateTime & assign(int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds)
Assigns a Gregorian date and time.
-
year is from 0 to 9999.
-
month is from 1 to 12.
-
day is from 1 to 31.
-
hour is from 0 to 23.
-
minute is from 0 to 59.
-
second is from 0 to 59.
-
millisecond is from 0 to 999.
-
microsecond is from 0 to 999.
{#swap}
swap
void swap(DateTime & dateTime)
Swaps the DateTime with another one.
{#year}
year
const inline
inline int year() const
Returns the year.
{#month}
month
const inline
inline int month() const
Returns the month (1 to 12).
{#week}
week
const
int week(int firstDayOfWeek) const
Returns the week number within the year. FirstDayOfWeek should be either SUNDAY (0) or MONDAY (1). The returned week number will be from 0 to 53. Week number 1 is the week containing January 4. This is in accordance to ISO 8601.
The following example assumes that firstDayOfWeek is MONDAY. For 2005, which started on a Saturday, week 1 will be the week starting on Monday, January 3. January 1 and 2 will fall within week 0 (or the last week of the previous year).
For 2007, which starts on a Monday, week 1 will be the week startung on Monday, January 1. There will be no week 0 in 2007.
{#day}
day
const inline
inline int day() const
Returns the day witin the month (1 to 31).
{#dayofweek}
dayOfWeek
const
int dayOfWeek() const
Returns the weekday (0 to 6, where 0 = Sunday, 1 = Monday, ..., 6 = Saturday).
{#dayofyear}
dayOfYear
const
int dayOfYear() const
Returns the number of the day in the year. January 1 is 1, February 1 is 32, etc.
{#hour}
hour
const inline
inline int hour() const
Returns the hour (0 to 23).
{#hourampm}
hourAMPM
const inline
inline int hourAMPM() const
Returns the hour (0 to 12).
{#isam}
isAM
const inline
inline bool isAM() const
Returns true if hour < 12;.
{#ispm}
isPM
const inline
inline bool isPM() const
Returns true if hour >= 12.
{#minute}
minute
const inline
inline int minute() const
Returns the minute (0 to 59).
{#second}
second
const inline
inline int second() const
Returns the second (0 to 59).
{#millisecond}
millisecond
const inline
inline int millisecond() const
Returns the millisecond (0 to 999)
{#microsecond}
microsecond
const inline
inline int microsecond() const
Returns the microsecond (0 to 999)
{#julianday}
julianDay
const
double julianDay() const
Returns the julian day for the date and time.
{#timestamp}
timestamp
const inline
inline Timestamp timestamp() const
Returns the date and time expressed as a Timestamp.
{#utctime}
utcTime
const inline
inline Timestamp::UtcTimeVal utcTime() const
Returns the date and time expressed in UTC-based time. UTC base time is midnight, October 15, 1582. Resolution is 100 nanoseconds.
{#operator}
operator==
const inline
inline bool operator==(const DateTime & dateTime) const
{#operator}
operator!=
const inline
inline bool operator!=(const DateTime & dateTime) const
{#operator}
operator<
const inline
inline bool operator<(const DateTime & dateTime) const
{#operator}
operator<=
const inline
inline bool operator<=(const DateTime & dateTime) const
{#operator}
operator>
const inline
inline bool operator>(const DateTime & dateTime) const
{#operator}
operator>=
const inline
inline bool operator>=(const DateTime & dateTime) const
{#operator}
operator+
const
DateTime operator+(const Timespan & span) const
{#operator}
operator-
const
DateTime operator-(const Timespan & span) const
{#operator}
operator-
const
Timespan operator-(const DateTime & dateTime) const
{#operator}
operator+=
DateTime & operator+=(const Timespan & span)
{#operator}
operator-=
DateTime & operator-=(const Timespan & span)
{#makeutc}
makeUTC
void makeUTC(int tzd)
Converts a local time into UTC, by applying the given time zone differential.
{#makelocal}
makeLocal
void makeLocal(int tzd)
Converts a UTC time into a local time, by applying the given time zone differential.
Public Static Methods
| Return | Name | Description |
|---|---|---|
bool | isLeapYear static inline | Returns true if the given year is a leap year; false otherwise. |
int | daysOfMonth static | Returns the number of days in the given month and year. Month is from 1 to 12. |
bool | isValid static | Checks if the given date and time is valid (all arguments are within a proper range). |
{#isleapyear}
isLeapYear
static inline
static inline bool isLeapYear(int year)
Returns true if the given year is a leap year; false otherwise.
{#daysofmonth}
daysOfMonth
static
static int daysOfMonth(int year, int month)
Returns the number of days in the given month and year. Month is from 1 to 12.
{#isvalid}
isValid
static
static bool isValid(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond)
Checks if the given date and time is valid (all arguments are within a proper range).
Returns true if all arguments are valid, false otherwise.
Protected Methods
| Return | Name | Description |
|---|---|---|
void | computeGregorian | Computes the Gregorian date for the given Julian day. See http://vsg.cape.com/~pbaum/date/injdimp.htm, section 3.3.1 for the algorithm. |
void | computeDaytime | Extracts the daytime (hours, minutes, seconds, etc.) from the stored utcTime. |
{#computegregorian}
computeGregorian
void computeGregorian(double julianDay)
Computes the Gregorian date for the given Julian day. See http://vsg.cape.com/~pbaum/date/injdimp.htm, section 3.3.1 for the algorithm.
{#computedaytime}
computeDaytime
void computeDaytime()
Extracts the daytime (hours, minutes, seconds, etc.) from the stored utcTime.
Public Types
| Name | Description |
|---|---|
Months | Symbolic names for month numbers (1 to 12). |
DaysOfWeek | Symbolic names for week day numbers (0 to 6). |
{#months}
Months
enum Months
Symbolic names for month numbers (1 to 12).
| Value | Description |
|---|---|
JANUARY | |
FEBRUARY | |
MARCH | |
APRIL | |
MAY | |
JUNE | |
JULY | |
AUGUST | |
SEPTEMBER | |
OCTOBER | |
NOVEMBER | |
DECEMBER |
{#daysofweek}
DaysOfWeek
enum DaysOfWeek
Symbolic names for week day numbers (0 to 6).
| Value | Description |
|---|---|
SUNDAY | |
MONDAY | |
TUESDAY | |
WEDNESDAY | |
THURSDAY | |
FRIDAY | |
SATURDAY |
Private Attributes
| Return | Name | Description |
|---|---|---|
Timestamp::UtcTimeVal | _utcTime | |
short | _year | |
short | _month | |
short | _day | |
short | _hour | |
short | _minute | |
short | _second | |
short | _millisecond | |
short | _microsecond |
{#_utctime}
_utcTime
Timestamp::UtcTimeVal _utcTime
{#_year}
_year
short _year
{#_month}
_month
short _month
{#_day}
_day
short _day
{#_hour}
_hour
short _hour
{#_minute}
_minute
short _minute
{#_second}
_second
short _second
{#_millisecond}
_millisecond
short _millisecond
{#_microsecond}
_microsecond
short _microsecond
Private Methods
| Return | Name | Description |
|---|---|---|
void | checkLimit | Utility functions used to correct the overflow in computeGregorian. |
void | normalize |
{#checklimit}
checkLimit
void checkLimit(short & lower, short & higher, short limit)
Utility functions used to correct the overflow in computeGregorian.
{#normalize}
normalize
void normalize()
{#timezone}
Timezone
#include <icy/datetime.h>
This class provides information about the current timezone.
Public Static Methods
| Return | Name | Description |
|---|---|---|
int | utcOffset static | Returns the offset of local time to UTC, in seconds. local time = UTC + utcOffset() + dst(). |
int | dst static | Returns the daylight saving time offset in seconds if daylight saving time is in use. local time = UTC + utcOffset() + dst(). |
bool | isDst static | Returns true if daylight saving time is in effect for the given time. Depending on the operating system platform this might only work reliably for certain date ranges, as the C library's localtime() function is used. |
int | tzd static | Returns the time zone differential for the current timezone. The timezone differential is computed as utcOffset() + dst() /// and is expressed in seconds. |
std::string | name static | Returns the timezone name currently in effect. |
std::string | standardName static | Returns the timezone name if not daylight saving time is in effect. |
std::string | dstName static | Returns the timezone name if daylight saving time is in effect. |
{#utcoffset}
utcOffset
static
static int utcOffset()
Returns the offset of local time to UTC, in seconds. local time = UTC + utcOffset() + dst().
{#dst}
dst
static
static int dst()
Returns the daylight saving time offset in seconds if daylight saving time is in use. local time = UTC + utcOffset() + dst().
{#isdst}
isDst
static
static bool isDst(const Timestamp & timestamp)
Returns true if daylight saving time is in effect for the given time. Depending on the operating system platform this might only work reliably for certain date ranges, as the C library's localtime() function is used.
{#tzd}
tzd
static
static int tzd()
Returns the time zone differential for the current timezone. The timezone differential is computed as utcOffset() + dst() /// and is expressed in seconds.
{#name}
name
static
static std::string name()
Returns the timezone name currently in effect.
{#standardname}
standardName
static
static std::string standardName()
Returns the timezone name if not daylight saving time is in effect.
{#dstname}
dstName
static
static std::string dstName()
Returns the timezone name if daylight saving time is in effect.
{#localdatetime}
LocalDateTime
#include <icy/datetime.h>
This class represents an instant in local time (as opposed to UTC), expressed in years, months, days, hours, minutes, seconds and milliseconds based on the Gregorian calendar.
In addition to the date and time, the class also maintains a time zone differential, which denotes the difference in seconds from UTC to local time, i.e. UTC = local time - time zone differential.
Although LocalDateTime supports relational and arithmetic operators, all date/time comparisons and date/time arithmetics should be done in UTC, using the DateTime or Timestamp class for better performance. The relational operators normalize the dates/times involved to UTC before carrying out the comparison.
The time zone differential is based on the input date and time and current time zone. A number of constructors accept an explicit time zone differential parameter. These should not be used since daylight savings time processing is impossible since the time zone is unknown. Each of the constructors accepting a tzd parameter have been marked as deprecated and may be removed in a future revision.
Public Methods
| Return | Name | Description |
|---|---|---|
LocalDateTime | Creates a LocalDateTime with the current date/time for the current time zone. | |
LocalDateTime | Creates a LocalDateTime for the given Gregorian local date and time. | |
LocalDateTime | @ deprecated Creates a LocalDateTime for the given Gregorian date and time in the time zone denoted by the time zone differential in tzd. | |
LocalDateTime | Creates a LocalDateTime from the UTC time given in dateTime, using the time zone differential of the current time zone. | |
LocalDateTime | @ deprecated Creates a LocalDateTime from the UTC time given in dateTime, using the given time zone differential. Adjusts dateTime for the given time zone differential. | |
LocalDateTime | @ deprecated Creates a LocalDateTime from the UTC time given in dateTime, using the given time zone differential. If adjust is true, adjusts dateTime for the given time zone differential. | |
LocalDateTime | Creates a LocalDateTime for the given Julian day in the local time zone. | |
LocalDateTime | @ deprecated Creates a LocalDateTime for the given Julian day in the time zone denoted by the time zone differential in tzd. | |
LocalDateTime | Copy constructor. Creates the LocalDateTime from another one. | |
~LocalDateTime | Destroys the LocalDateTime. | |
LocalDateTime & | operator= | Assigns another LocalDateTime. |
LocalDateTime & | operator= | Assigns a timestamp. |
LocalDateTime & | operator= | Assigns a Julian day in the local time zone. |
LocalDateTime & | assign | Assigns a Gregorian local date and time. |
LocalDateTime & | assign | @ deprecated Assigns a Gregorian local date and time in the time zone denoted by the time zone differential in tzd. |
LocalDateTime & | assign | @ deprecated Assigns a Julian day in the time zone denoted by the time zone differential in tzd. |
void | swap | Swaps the LocalDateTime with another one. |
int | year const inline | Returns the year. |
int | month const inline | Returns the month (1 to 12). |
int | week const inline | Returns the week number within the year. FirstDayOfWeek should be either SUNDAY (0) or MONDAY (1). The returned week number will be from 0 to 53. Week number 1 is the week containing January 4. This is in accordance to ISO 8601. |
int | day const inline | Returns the day witin the month (1 to 31). |
int | dayOfWeek const inline | Returns the weekday (0 to 6, where 0 = Sunday, 1 = Monday, ..., 6 = Saturday). |
int | dayOfYear const inline | Returns the number of the day in the year. January 1 is 1, February 1 is 32, etc. |
int | hour const inline | Returns the hour (0 to 23). |
int | hourAMPM const inline | Returns the hour (0 to 12). |
bool | isAM const inline | Returns true if hour < 12;. |
bool | isPM const inline | Returns true if hour >= 12. |
int | minute const inline | Returns the minute (0 to 59). |
int | second const inline | Returns the second (0 to 59). |
int | millisecond const inline | Returns the millisecond (0 to 999) |
int | microsecond const inline | Returns the microsecond (0 to 999) |
double | julianDay const inline | Returns the julian day for the date. |
int | tzd const inline | Returns the time zone differential. |
DateTime | utc const | Returns the UTC equivalent for the local date and time. |
Timestamp | timestamp const inline | Returns the date and time expressed as a Timestamp. |
Timestamp::UtcTimeVal | utcTime const inline | Returns the UTC equivalent for the local date and time. |
bool | operator== const | |
bool | operator!= const | |
bool | operator< const | |
bool | operator<= const | |
bool | operator> const | |
bool | operator>= const | |
LocalDateTime | operator+ const | |
LocalDateTime | operator- const | |
Timespan | operator- const | |
LocalDateTime & | operator+= | |
LocalDateTime & | operator-= |
{#localdatetime}
LocalDateTime
LocalDateTime()
Creates a LocalDateTime with the current date/time for the current time zone.
{#localdatetime}
LocalDateTime
LocalDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond)
Creates a LocalDateTime for the given Gregorian local date and time.
-
year is from 0 to 9999.
-
month is from 1 to 12.
-
day is from 1 to 31.
-
hour is from 0 to 23.
-
minute is from 0 to 59.
-
second is from 0 to 59.
-
millisecond is from 0 to 999.
-
microsecond is from 0 to 999.
{#localdatetime}
LocalDateTime
LocalDateTime(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond)
@ deprecated Creates a LocalDateTime for the given Gregorian date and time in the time zone denoted by the time zone differential in tzd.
-
tzd is in seconds.
-
year is from 0 to 9999.
-
month is from 1 to 12.
-
day is from 1 to 31.
-
hour is from 0 to 23.
-
minute is from 0 to 59.
-
second is from 0 to 59.
-
millisecond is from 0 to 999.
-
microsecond is from 0 to 999.
{#localdatetime}
LocalDateTime
LocalDateTime(const DateTime & dateTime)
Creates a LocalDateTime from the UTC time given in dateTime, using the time zone differential of the current time zone.
{#localdatetime}
LocalDateTime
LocalDateTime(int tzd, const DateTime & dateTime)
@ deprecated Creates a LocalDateTime from the UTC time given in dateTime, using the given time zone differential. Adjusts dateTime for the given time zone differential.
{#localdatetime}
LocalDateTime
LocalDateTime(int tzd, const DateTime & dateTime, bool adjust)
@ deprecated Creates a LocalDateTime from the UTC time given in dateTime, using the given time zone differential. If adjust is true, adjusts dateTime for the given time zone differential.
{#localdatetime}
LocalDateTime
LocalDateTime(double julianDay)
Creates a LocalDateTime for the given Julian day in the local time zone.
{#localdatetime}
LocalDateTime
LocalDateTime(int tzd, double julianDay)
@ deprecated Creates a LocalDateTime for the given Julian day in the time zone denoted by the time zone differential in tzd.
{#localdatetime}
LocalDateTime
LocalDateTime(const LocalDateTime & dateTime)
Copy constructor. Creates the LocalDateTime from another one.
{#localdatetime}
~LocalDateTime
~LocalDateTime()
Destroys the LocalDateTime.
{#operator}
operator=
LocalDateTime & operator=(const LocalDateTime & dateTime)
Assigns another LocalDateTime.
{#operator}
operator=
LocalDateTime & operator=(const Timestamp & timestamp)
Assigns a timestamp.
{#operator}
operator=
LocalDateTime & operator=(double julianDay)
Assigns a Julian day in the local time zone.
{#assign}
assign
LocalDateTime & assign(int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds)
Assigns a Gregorian local date and time.
-
year is from 0 to 9999.
-
month is from 1 to 12.
-
day is from 1 to 31.
-
hour is from 0 to 23.
-
minute is from 0 to 59.
-
second is from 0 to 59.
-
millisecond is from 0 to 999.
-
microsecond is from 0 to 999.
{#assign}
assign
LocalDateTime & assign(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds)
@ deprecated Assigns a Gregorian local date and time in the time zone denoted by the time zone differential in tzd.
-
tzd is in seconds.
-
year is from 0 to 9999.
-
month is from 1 to 12.
-
day is from 1 to 31.
-
hour is from 0 to 23.
-
minute is from 0 to 59.
-
second is from 0 to 59.
-
millisecond is from 0 to 999.
-
microsecond is from 0 to 999.
{#assign}
assign
LocalDateTime & assign(int tzd, double julianDay)
@ deprecated Assigns a Julian day in the time zone denoted by the time zone differential in tzd.
{#swap}
swap
void swap(LocalDateTime & dateTime)
Swaps the LocalDateTime with another one.
{#year}
year
const inline
inline int year() const
Returns the year.
{#month}
month
const inline
inline int month() const
Returns the month (1 to 12).
{#week}
week
const inline
inline int week(int firstDayOfWeek) const
Returns the week number within the year. FirstDayOfWeek should be either SUNDAY (0) or MONDAY (1). The returned week number will be from 0 to 53. Week number 1 is the week containing January 4. This is in accordance to ISO 8601.
The following example assumes that firstDayOfWeek is MONDAY. For 2005, which started on a Saturday, week 1 will be the week starting on Monday, January 3. January 1 and 2 will fall within week 0 (or the last week of the previous year).
For 2007, which starts on a Monday, week 1 will be the week startung on Monday, January 1. There will be no week 0 in 2007.
{#day}
day
const inline
inline int day() const
Returns the day witin the month (1 to 31).
{#dayofweek}
dayOfWeek
const inline
inline int dayOfWeek() const
Returns the weekday (0 to 6, where 0 = Sunday, 1 = Monday, ..., 6 = Saturday).
{#dayofyear}
dayOfYear
const inline
inline int dayOfYear() const
Returns the number of the day in the year. January 1 is 1, February 1 is 32, etc.
{#hour}
hour
const inline
inline int hour() const
Returns the hour (0 to 23).
{#hourampm}
hourAMPM
const inline
inline int hourAMPM() const
Returns the hour (0 to 12).
{#isam}
isAM
const inline
inline bool isAM() const
Returns true if hour < 12;.
{#ispm}
isPM
const inline
inline bool isPM() const
Returns true if hour >= 12.
{#minute}
minute
const inline
inline int minute() const
Returns the minute (0 to 59).
{#second}
second
const inline
inline int second() const
Returns the second (0 to 59).
{#millisecond}
millisecond
const inline
inline int millisecond() const
Returns the millisecond (0 to 999)
{#microsecond}
microsecond
const inline
inline int microsecond() const
Returns the microsecond (0 to 999)
{#julianday}
julianDay
const inline
inline double julianDay() const
Returns the julian day for the date.
{#tzd}
tzd
const inline
inline int tzd() const
Returns the time zone differential.
{#utc}
utc
const
DateTime utc() const
Returns the UTC equivalent for the local date and time.
{#timestamp}
timestamp
const inline
inline Timestamp timestamp() const
Returns the date and time expressed as a Timestamp.
{#utctime}
utcTime
const inline
inline Timestamp::UtcTimeVal utcTime() const
Returns the UTC equivalent for the local date and time.
{#operator}
operator==
const
bool operator==(const LocalDateTime & dateTime) const
{#operator}
operator!=
const
bool operator!=(const LocalDateTime & dateTime) const
{#operator}
operator<
const
bool operator<(const LocalDateTime & dateTime) const
{#operator}
operator<=
const
bool operator<=(const LocalDateTime & dateTime) const
{#operator}
operator>
const
bool operator>(const LocalDateTime & dateTime) const
{#operator}
operator>=
const
bool operator>=(const LocalDateTime & dateTime) const
{#operator}
operator+
const
LocalDateTime operator+(const Timespan & span) const
{#operator}
operator-
const
LocalDateTime operator-(const Timespan & span) const
{#operator}
operator-
const
Timespan operator-(const LocalDateTime & dateTime) const
{#operator}
operator+=
LocalDateTime & operator+=(const Timespan & span)
{#operator}
operator-=
LocalDateTime & operator-=(const Timespan & span)
Protected Methods
| Return | Name | Description |
|---|---|---|
LocalDateTime | ||
void | determineTzd | Recalculate the tzd based on the _dateTime member based on the current timezone using the Standard C runtime functions. If adjust is true, then adjustForTzd() is called after the differential is calculated. |
void | adjustForTzd inline | Adjust the _dateTime member based on the _tzd member. |
std::time_t | dstOffset const | Determine the DST offset for the current date/time. |
{#localdatetime}
LocalDateTime
LocalDateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff, int tzd)
{#determinetzd}
determineTzd
void determineTzd(bool adjust)
Recalculate the tzd based on the _dateTime member based on the current timezone using the Standard C runtime functions. If adjust is true, then adjustForTzd() is called after the differential is calculated.
{#adjustfortzd}
adjustForTzd
inline
inline void adjustForTzd()
Adjust the _dateTime member based on the _tzd member.
{#dstoffset}
dstOffset
const
std::time_t dstOffset(int & dstOffset) const
Determine the DST offset for the current date/time.
Private Attributes
| Return | Name | Description |
|---|---|---|
DateTime | _dateTime | |
int | _tzd |
{#_datetime}
_dateTime
DateTime _dateTime
{#_tzd}
_tzd
int _tzd
{#datetimeformat}
DateTimeFormat
#include <icy/datetime.h>
Definition of date/time formats and various constants used by DateTimeFormatter and DateTimeParser.
Public Static Attributes
| Return | Name | Description |
|---|---|---|
const std::string | ISO8601_FORMAT static | predefined date formats The date/time format defined in the ISO 8601 standard. |
const std::string | ISO8601_FRAC_FORMAT static | The date/time format defined in the ISO 8601 standard, with fractional seconds. |
const std::string | RFC822_FORMAT static | The date/time format defined in RFC 822 (obsoleted by RFC 1123). |
const std::string | RFC1123_FORMAT static | The date/time format defined in RFC 1123 (obsoletes RFC 822). |
const std::string | HTTP_FORMAT static | The date/time format defined in the HTTP specification (RFC 2616), which is basically a variant of RFC 1036 with a zero-padded day field. |
const std::string | RFC850_FORMAT static | The date/time format defined in RFC 850 (obsoleted by RFC 1036). |
const std::string | RFC1036_FORMAT static | The date/time format defined in RFC 1036 (obsoletes RFC 850). |
const std::string | ASCTIME_FORMAT static | The date/time format produced by the ANSI C asctime() function. |
const std::string | SORTABLE_FORMAT static | A simple, sortable date/time format. |
const std::string | WEEKDAY_NAMES static | names used by formatter and parser English names of week days (Sunday, Monday, Tuesday, ...). |
const std::string | MONTH_NAMES static | English names of months (January, February, ...). |
{#iso8601_format}
ISO8601_FORMAT
static
const std::string ISO8601_FORMAT
predefined date formats The date/time format defined in the ISO 8601 standard.
Examples: 2005-01-01T12:00:00+01:00 2005-01-01T11:00:00Z
{#iso8601_frac_format}
ISO8601_FRAC_FORMAT
static
const std::string ISO8601_FRAC_FORMAT
The date/time format defined in the ISO 8601 standard, with fractional seconds.
Examples: 2005-01-01T12:00:00.000000+01:00 2005-01-01T11:00:00.000000Z
{#rfc822_format}
RFC822_FORMAT
static
const std::string RFC822_FORMAT
The date/time format defined in RFC 822 (obsoleted by RFC 1123).
Examples: Sat, 1 Jan 05 12:00:00 +0100 Sat, 1 Jan 05 11:00:00 GMT
{#rfc1123_format}
RFC1123_FORMAT
static
const std::string RFC1123_FORMAT
The date/time format defined in RFC 1123 (obsoletes RFC 822).
Examples: Sat, 1 Jan 2005 12:00:00 +0100 Sat, 1 Jan 2005 11:00:00 GMT
{#http_format}
HTTP_FORMAT
static
const std::string HTTP_FORMAT
The date/time format defined in the HTTP specification (RFC 2616), which is basically a variant of RFC 1036 with a zero-padded day field.
Examples: Sat, 01 Jan 2005 12:00:00 +0100 Sat, 01 Jan 2005 11:00:00 GMT
{#rfc850_format}
RFC850_FORMAT
static
const std::string RFC850_FORMAT
The date/time format defined in RFC 850 (obsoleted by RFC 1036).
Examples: Saturday, 1-Jan-05 12:00:00 +0100 Saturday, 1-Jan-05 11:00:00 GMT
{#rfc1036_format}
RFC1036_FORMAT
static
const std::string RFC1036_FORMAT
The date/time format defined in RFC 1036 (obsoletes RFC 850).
Examples: Saturday, 1 Jan 05 12:00:00 +0100 Saturday, 1 Jan 05 11:00:00 GMT
{#asctime_format}
ASCTIME_FORMAT
static
const std::string ASCTIME_FORMAT
The date/time format produced by the ANSI C asctime() function.
Example: Sat Jan 1 12:00:00 2005
{#sortable_format}
SORTABLE_FORMAT
static
const std::string SORTABLE_FORMAT
A simple, sortable date/time format.
Example: 2005-01-01 12:00:00
{#weekday_names}
WEEKDAY_NAMES
static
const std::string WEEKDAY_NAMES
names used by formatter and parser English names of week days (Sunday, Monday, Tuesday, ...).
{#month_names}
MONTH_NAMES
static
const std::string MONTH_NAMES
English names of months (January, February, ...).
{#datetimeformatter}
DateTimeFormatter
#include <icy/datetime.h>
This class converts dates and times into strings, supporting a variety of standard and custom formats.
There are two kind of static member functions:
-
format* functions return a std::string containin the formatted value.
-
append* functions append the formatted value to an existing string.
Public Static Methods
| Return | Name | Description |
|---|---|---|
std::string | format static inline | Formats the given timestamp according to the given format. The format string is used as a template to format the date and is copied character by character except for the following special characters, which are replaced by the corresponding value. |
std::string | format static inline | Formats the given date and time according to the given format. See format(const Timestamp&, std::string_view, int) for more information. |
std::string | format static inline | Formats the given local date and time according to the given format. See format(const Timestamp&, std::string_view, int) for more information. |
std::string | format static inline | Formats the given timespan according to the given format. The format string is used as a template to format the date and is copied character by character except for the following special characters, which are replaced by the corresponding value. |
void | append static inline | Formats the given timestamp according to the given format and appends it to str. |
void | append static | Formats the given date and time according to the given format and appends it to str. |
void | append static | Formats the given local date and time according to the given format and appends it to str. |
void | append static | Formats the given timespan according to the given format and appends it to str. |
std::string | tzdISO static inline | Formats the given timezone differential in ISO format. If timeZoneDifferential is UTC, "Z" is returned, otherwise, +HH.MM (or -HH.MM) is returned. |
std::string | tzdRFC static inline | Formats the given timezone differential in RFC format. If timeZoneDifferential is UTC, "GMT" is returned, otherwise ++HHMM (or -HHMM) is returned. |
void | tzdISO static | Formats the given timezone differential in ISO format and appends it to the given string. If timeZoneDifferential is UTC, "Z" is returned, otherwise, +HH.MM (or -HH.MM) is returned. |
void | tzdRFC static | Formats the given timezone differential in RFC format and appends it to the given string. If timeZoneDifferential is UTC, "GMT" is returned, otherwise ++HHMM (or -HHMM) is returned. |
{#format}
format
static inline
static inline std::string format(const Timestamp & timestamp, std::string_view fmt, int timeZoneDifferential)
Formats the given timestamp according to the given format. The format string is used as a template to format the date and is copied character by character except for the following special characters, which are replaced by the corresponding value.
-
w - abbreviated weekday (Mon, Tue, ...)
-
W - full weekday (Monday, Tuesday, ...)
-
b - abbreviated month (Jan, Feb, ...)
-
B - full month (January, February, ...)
-
d - zero-padded day of month (01 .. 31)
-
e - day of month (1 .. 31)
-
f - space-padded day of month ( 1 .. 31)
-
m - zero-padded month (01 .. 12)
-
n - month (1 .. 12)
-
o - space-padded month ( 1 .. 12)
-
y - year without century (70)
-
Y - year with century (1970)
-
H - hour (00 .. 23)
-
h - hour (00 .. 12)
-
a - am/pm
-
A - AM/PM
-
M - minute (00 .. 59)
-
S - second (00 .. 59)
-
s - seconds and microseconds (equivalent to S.F)
-
i - millisecond (000 .. 999)
-
c - centisecond (0 .. 9)
-
F - fractional seconds/microseconds (000000 - 999999)
-
z - time zone differential in ISO 8601 format (Z or +NN.NN)
-
Z - time zone differential in RFC format (GMT or +NNNN)
-
%% - percent sign
Class DateTimeFormat defines format strings for various standard date/time formats.
{#format}
format
static inline
static inline std::string format(const DateTime & dateTime, std::string_view fmt, int timeZoneDifferential)
Formats the given date and time according to the given format. See format(const Timestamp&, std::string_view, int) for more information.
{#format}
format
static inline
static inline std::string format(const LocalDateTime & dateTime, std::string_view fmt)
Formats the given local date and time according to the given format. See format(const Timestamp&, std::string_view, int) for more information.
{#format}
format
static inline
static inline std::string format(const Timespan & timespan, std::string_view fmt)
Formats the given timespan according to the given format. The format string is used as a template to format the date and is copied character by character except for the following special characters, which are replaced by the corresponding value.
-
d - days
-
H - hours (00 .. 23)
-
h - total hours (0 .. n)
-
M - minutes (00 .. 59)
-
m - total minutes (0 .. n)
-
S - seconds (00 .. 59)
-
s - total seconds (0 .. n)
-
i - milliseconds (000 .. 999)
-
c - centisecond (0 .. 9)
-
F - fractional seconds/microseconds (000000 - 999999)
-
%% - percent sign
{#append}
append
static inline
static inline void append(std::string & str, const Timestamp & timestamp, std::string_view fmt, int timeZoneDifferential)
Formats the given timestamp according to the given format and appends it to str.
See format() for documentation of the formatting string.
{#append}
append
static
static void append(std::string & str, const DateTime & dateTime, std::string_view fmt, int timeZoneDifferential)
Formats the given date and time according to the given format and appends it to str.
See format() for documentation of the formatting string.
{#append}
append
static
static void append(std::string & str, const LocalDateTime & dateTime, std::string_view fmt)
Formats the given local date and time according to the given format and appends it to str.
See format() for documentation of the formatting string.
{#append}
append
static
static void append(std::string & str, const Timespan & timespan, std::string_view fmt)
Formats the given timespan according to the given format and appends it to str.
See format() for documentation of the formatting string.
{#tzdiso}
tzdISO
static inline
static inline std::string tzdISO(int timeZoneDifferential)
Formats the given timezone differential in ISO format. If timeZoneDifferential is UTC, "Z" is returned, otherwise, +HH.MM (or -HH.MM) is returned.
{#tzdrfc}
tzdRFC
static inline
static inline std::string tzdRFC(int timeZoneDifferential)
Formats the given timezone differential in RFC format. If timeZoneDifferential is UTC, "GMT" is returned, otherwise ++HHMM (or -HHMM) is returned.
{#tzdiso}
tzdISO
static
static void tzdISO(std::string & str, int timeZoneDifferential)
Formats the given timezone differential in ISO format and appends it to the given string. If timeZoneDifferential is UTC, "Z" is returned, otherwise, +HH.MM (or -HH.MM) is returned.
{#tzdrfc}
tzdRFC
static
static void tzdRFC(std::string & str, int timeZoneDifferential)
Formats the given timezone differential in RFC format and appends it to the given string. If timeZoneDifferential is UTC, "GMT" is returned, otherwise ++HHMM (or -HHMM) is returned.
Public Types
| Name | Description |
|---|---|
| `` |
{#classicy_1_1datetimeformatter_1aecc87c353df5e93ffe5ce179f14efc06}
enum
| Value | Description |
|---|---|
UTC | Special value for timeZoneDifferential denoting UTC. |
{#datetimeparser}
DateTimeParser
#include <icy/datetime.h>
This class provides a method for parsing dates and times from strings. All parsing methods do their best to parse a meaningful result, even from malformed input strings.
The returned DateTime will always contain a time in the same timezone as the time in the string. Call DateTime::makeUTC() with the timeZoneDifferential returned by parse() to convert the DateTime to UTC.
Note: When parsing a time in 12-hour (AM/PM) format, the hour (h) must be parsed before the AM/PM designator (a, A), otherwise the AM/PM designator will be ignored.
See the DateTimeFormatter class for a list of supported format specifiers. In addition to the format specifiers supported by DateTimeFormatter, an additional specifier is supported: r will parse a year given by either two or four digits. Years 69-00 are interpreted in the 20th century (1969-2000), years 01-68 in the 21th century (2001-2068).
Public Static Methods
| Return | Name | Description |
|---|---|---|
void | parse static | Parses a date and time in the given format from the given string. Throws a SyntaxException if the string cannot be successfully parsed. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats. |
DateTime | parse static | Parses a date and time in the given format from the given string. Throws a SyntaxException if the string cannot be successfully parsed. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats. |
bool | tryParse static | Parses a date and time in the given format from the given string. Returns true if the string has been successfully parsed, false otherwise. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats. |
void | parse static | Parses a date and time from the given dateTime string. Before parsing, the method examines the dateTime string for a known date/time format. Throws a SyntaxException if the string cannot be successfully parsed. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats. |
DateTime | parse static | Parses a date and time from the given dateTime string. Before parsing, the method examines the dateTime string for a known date/time format. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats. |
bool | tryParse static | Parses a date and time from the given dateTime string. Before parsing, the method examines the dateTime string for a known date/time format. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats. |
int | parseMonth static | Tries to interpret the given range as a month name. The range must be at least three characters long. Returns the month number (1 .. 12) if the month name is valid. Otherwise throws a SyntaxException. |
int | parseDayOfWeek static | Tries to interpret the given range as a weekday name. The range must be at least three characters long. Returns the weekday number (0 .. 6, where 0 = Synday, 1 = Monday, etc.) if the weekday name is valid. Otherwise throws a SyntaxException. |
{#parse}
parse
static
static void parse(std::string_view fmt, std::string_view str, DateTime & dateTime, int & timeZoneDifferential)
Parses a date and time in the given format from the given string. Throws a SyntaxException if the string cannot be successfully parsed. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats.
{#parse}
parse
static
static DateTime parse(std::string_view fmt, std::string_view str, int & timeZoneDifferential)
Parses a date and time in the given format from the given string. Throws a SyntaxException if the string cannot be successfully parsed. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats.
{#tryparse}
tryParse
static
static bool tryParse(std::string_view fmt, std::string_view str, DateTime & dateTime, int & timeZoneDifferential)
Parses a date and time in the given format from the given string. Returns true if the string has been successfully parsed, false otherwise. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats.
{#parse}
parse
static
static void parse(std::string_view str, DateTime & dateTime, int & timeZoneDifferential)
Parses a date and time from the given dateTime string. Before parsing, the method examines the dateTime string for a known date/time format. Throws a SyntaxException if the string cannot be successfully parsed. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats.
{#parse}
parse
static
static DateTime parse(std::string_view str, int & timeZoneDifferential)
Parses a date and time from the given dateTime string. Before parsing, the method examines the dateTime string for a known date/time format. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats.
{#tryparse}
tryParse
static
static bool tryParse(std::string_view str, DateTime & dateTime, int & timeZoneDifferential)
Parses a date and time from the given dateTime string. Before parsing, the method examines the dateTime string for a known date/time format. Please see DateTimeFormatter::format() for a description of the format string. Class DateTimeFormat defines format strings for various standard date/time formats.
{#parsemonth}
parseMonth
static
static int parseMonth(const char *& it, const char * end)
Tries to interpret the given range as a month name. The range must be at least three characters long. Returns the month number (1 .. 12) if the month name is valid. Otherwise throws a SyntaxException.
{#parsedayofweek}
parseDayOfWeek
static
static int parseDayOfWeek(const char *& it, const char * end)
Tries to interpret the given range as a weekday name. The range must be at least three characters long. Returns the weekday number (0 .. 6, where 0 = Synday, 1 = Monday, etc.) if the weekday name is valid. Otherwise throws a SyntaxException.
{#stopwatch}
Stopwatch
#include <icy/datetime.h>
A simple facility to measure time intervals with microsecond resolution.
The Stopwatch uses the current system time, so if the system time changes the measured time will be incorrect.
Public Methods
| Return | Name | Description |
|---|---|---|
Stopwatch | ||
void | start | Starts (or restarts) the stopwatch. |
void | stop | Stops or pauses the stopwatch. |
void | reset | Resets the stopwatch. |
void | restart | Resets and starts the stopwatch. |
Timestamp::TimeDiff | elapsed const | Returns the elapsed time in microseconds since the stopwatch started. |
int | elapsedSeconds const | Returns the number of seconds elapsed since the stopwatch started. |
int | elapsedMilliseconds const | Returns the number of milliseconds elapsed since the stopwatch started. |
{#stopwatch}
Stopwatch
Stopwatch()
{#start}
start
void start()
Starts (or restarts) the stopwatch.
{#stop}
stop
void stop()
Stops or pauses the stopwatch.
{#reset}
reset
void reset()
Resets the stopwatch.
{#restart}
restart
void restart()
Resets and starts the stopwatch.
{#elapsed}
elapsed
const
Timestamp::TimeDiff elapsed() const
Returns the elapsed time in microseconds since the stopwatch started.
{#elapsedseconds}
elapsedSeconds
const
int elapsedSeconds() const
Returns the number of seconds elapsed since the stopwatch started.
{#elapsedmilliseconds}
elapsedMilliseconds
const
int elapsedMilliseconds() const
Returns the number of milliseconds elapsed since the stopwatch started.
Public Static Methods
| Return | Name | Description |
|---|---|---|
Timestamp::TimeVal | resolution static | Returns the resolution of the stopwatch. |
{#resolution}
resolution
static
static Timestamp::TimeVal resolution()
Returns the resolution of the stopwatch.
Private Attributes
| Return | Name | Description |
|---|---|---|
Timestamp | _start | |
Timestamp::TimeDiff | _elapsed | |
bool | _running |
{#_start}
_start
Timestamp _start
{#_elapsed}
_elapsed
Timestamp::TimeDiff _elapsed
{#_running}
_running
bool _running
Private Methods
| Return | Name | Description |
|---|---|---|
Stopwatch | Deleted constructor. |
{#stopwatch}
Stopwatch
Stopwatch(const Stopwatch &) = delete
Deleted constructor.
{#threadedstreamreader}
ThreadedStreamReader
#include <icy/packetio.h>
Inherits:
PacketStreamAdapter,Startable
Threaded stream reader class.
This class can be connected to a [PacketStream](#packetstream) to read input from any class that derives from std::istream. It's most regularly used for reading input files.
Public Attributes
| Return | Name | Description |
|---|---|---|
PacketSignal | emitter |
{#emitter}
emitter
PacketSignal emitter
Public Methods
| Return | Name | Description |
|---|---|---|
ThreadedStreamReader inline | #### Parameters | |
~ThreadedStreamReader inline | Stops the reader thread and deletes the owned stream. | |
void | start virtual inline | Starts the reader thread; emits one line per iteration as a RawPacket. Emits a FlagPacket with [PacketFlags::Final](#namespaceicy_1a3d1e0d9028d45b9ec824bf4306047f18abeae421a14a34f831c113f61323d1ab3) on EOF. |
void | stop virtual inline | Cancels the reader thread. |
StreamT & | stream inline | Returns the internal stream cast to StreamT. |
std::istream & | stream inline | #### Returns |
{#threadedstreamreader}
ThreadedStreamReader
inline
inline ThreadedStreamReader(std::istream * is)
Parameters
isInput stream to read from; takes ownership.
{#threadedstreamreader}
~ThreadedStreamReader
inline
inline ~ThreadedStreamReader()
Stops the reader thread and deletes the owned stream.
{#start}
start
virtual inline
virtual inline void start()
Starts the reader thread; emits one line per iteration as a RawPacket. Emits a FlagPacket with [PacketFlags::Final](#namespaceicy_1a3d1e0d9028d45b9ec824bf4306047f18abeae421a14a34f831c113f61323d1ab3) on EOF.
{#stop}
stop
virtual inline
virtual inline void stop()
Cancels the reader thread.
{#stream}
stream
inline
template<class StreamT> inline StreamT & stream()
Returns the internal stream cast to StreamT.
Parameters
StreamTTarget stream type derived fromstd::istream.
Returns
Reference to the cast stream.
Exceptions
std::runtime_errorif the cast fails.
{#stream}
stream
inline
inline std::istream & stream()
Returns
Reference to the underlying input stream.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Thread | _runner | |
std::istream * | _istream |
{#_runner}
_runner
Thread _runner
{#_istream}
_istream
std::istream * _istream
{#streamwriter}
StreamWriter
#include <icy/packetio.h>
Inherits:
PacketProcessor
Packet stream writer class.
This class can be connected to a [PacketStream](#packetstream) to write output to any class that derives from std::ostream. It's most regularly used for writing output files.
Public Attributes
| Return | Name | Description |
|---|---|---|
PacketSignal | emitter |
{#emitter}
emitter
PacketSignal emitter
Public Methods
| Return | Name | Description |
|---|---|---|
StreamWriter inline | #### Parameters | |
~StreamWriter virtual inline | Closes any open std::ofstream and deletes the owned stream. | |
void | process virtual inline | Serializes the packet via write(), flushes it to the output stream, then forwards the packet to the next processor. |
StreamT & | stream inline | Returns the internal output stream cast to StreamT. |
void | onStreamStateChange virtual inline | Closes the output file on Closed or [Error](#error) stream state transitions. |
std::ostream & | stream inline | #### Returns |
{#streamwriter}
StreamWriter
inline
inline StreamWriter(std::ostream * stream)
Parameters
streamOutput stream to write to; takes ownership.
{#streamwriter}
~StreamWriter
virtual inline
virtual inline ~StreamWriter()
Closes any open std::ofstream and deletes the owned stream.
{#process}
process
virtual inline
virtual inline void process(IPacket & packet)
Serializes the packet via write(), flushes it to the output stream, then forwards the packet to the next processor.
Parameters
packetIncoming packet to process.
{#stream}
stream
inline
template<class StreamT> inline StreamT & stream()
Returns the internal output stream cast to StreamT.
Parameters
StreamTTarget stream type derived fromstd::ostream.
Returns
Reference to the cast stream.
Exceptions
std::runtime_errorif the cast fails.
{#onstreamstatechange}
onStreamStateChange
virtual inline
virtual inline void onStreamStateChange(const PacketStreamState & state)
Closes the output file on Closed or [Error](#error) stream state transitions.
Parameters
stateNew stream state.
{#stream}
stream
inline
inline std::ostream & stream()
Returns
Reference to the underlying output stream.
Exceptions
std::runtime_errorif the stream pointer is null.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::ostream * | _ostream |
{#_ostream}
_ostream
std::ostream * _ostream
{#state}
State
#include <icy/stateful.h>
Subclassed by:
DiagnosticState,PacketStreamState,TransactionState,EncoderState,InstallationState,ClientState,ClientState
State class for state machines.
This class defines the state for a state machine, and should be extended and passed to implementations of the [Stateful](#stateful) template.
For an example See also: PacketStreamState
Public Methods
| Return | Name | Description |
|---|---|---|
State | #### Parameters | |
State | Copy constructor. | |
State & | operator= | Copy assignment. |
ID | id const | Returns the current state ID. |
void | set | Sets the state ID. |
std::string | str virtual const | Returns a human-readable string for the given state ID. Override in derived classes to provide meaningful names. |
std::string | toString virtual const | Returns a human-readable string for the current state ID. |
bool | equals const | Returns true if the current state ID equals the given ID. |
bool | between const | Returns true if the current state ID is in the inclusive range [lid, rid]. |
bool | operator== const inline | |
bool | operator== const inline |
{#state}
State
State(ID id)
Parameters
idInitial state ID. Defaults to 0.
{#state}
State
State(const State & that)
Copy constructor.
Parameters
thatState to copy from.
{#operator}
operator=
State & operator=(const State & that)
Copy assignment.
Parameters
thatState to assign from.
{#id}
id
const
ID id() const
Returns the current state ID.
Returns
Atomic state ID value.
{#set}
set
void set(ID id)
Sets the state ID.
Parameters
idNew state ID to assign.
{#str}
str
virtual const
virtual std::string str(ID id) const
Returns a human-readable string for the given state ID. Override in derived classes to provide meaningful names.
Parameters
idState ID to convert.
Returns
String representation of the state, or "undefined" by default.
{#tostring}
toString
virtual const
virtual std::string toString() const
Returns a human-readable string for the current state ID.
Returns
Result of str(id()).
{#equals}
equals
const
bool equals(ID id) const
Returns true if the current state ID equals the given ID.
Parameters
idState ID to compare against.
Returns
True if IDs match.
{#between}
between
const
bool between(ID lid, ID rid) const
Returns true if the current state ID is in the inclusive range [lid, rid].
Parameters
-
lidLower bound state ID. -
ridUpper bound state ID.
Returns
True if lid <= id() <= rid.
{#operator}
operator==
const inline
inline bool operator==(const State & that) const
{#operator}
operator==
const inline
inline bool operator==(const State::ID & that) const
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::atomic< ID > | _id |
{#_id}
_id
std::atomic< ID > _id
Public Types
| Name | Description |
|---|---|
ID |
{#id}
ID
uint32_t ID()
{#stateful}
Stateful
#include <icy/stateful.h>
State machine implementation.
For an example See also: PacketStream
Parameters
Thederived[State](#state)type.
Public Attributes
| Return | Name | Description |
|---|---|---|
Signal< void(void *, T &, const T &)> | StateChange | Signals when the state changes. |
{#statechange}
StateChange
Signal< void(void *, T &, const T &)> StateChange
Signals when the state changes.
Public Methods
| Return | Name | Description |
|---|---|---|
Stateful inline | ||
bool | stateEquals virtual const inline | Returns true if the current state ID equals the given ID. |
bool | stateBetween virtual const inline | Returns true if the current state ID is in the inclusive range [lid, rid]. |
T & | state virtual inline | Returns a mutable reference to the current state. |
const T | state virtual const inline | Returns a copy of the current state. |
{#stateful}
Stateful
inline
inline Stateful()
{#stateequals}
stateEquals
virtual const inline
virtual inline bool stateEquals(typename T::ID id) const
Returns true if the current state ID equals the given ID.
Parameters
idState ID to compare against.
Returns
True if the current state matches.
{#statebetween}
stateBetween
virtual const inline
virtual inline bool stateBetween(typename T::ID lid, typename T::ID rid) const
Returns true if the current state ID is in the inclusive range [lid, rid].
Parameters
-
lidLower bound state ID. -
ridUpper bound state ID.
Returns
True if lid <= state.id() <= rid.
{#state}
state
virtual inline
virtual inline T & state()
Returns a mutable reference to the current state.
Returns
Reference to the internal state object.
{#state}
state
virtual const inline
virtual inline const T state() const
Returns a copy of the current state.
Returns
Current state value.
Protected Attributes
| Return | Name | Description |
|---|---|---|
T | _state |
{#_state}
_state
T _state
Protected Methods
| Return | Name | Description |
|---|---|---|
bool | beforeStateChange virtual inline | Override to handle pre state change logic. Return false to prevent state change. |
void | onStateChange virtual inline | Override to handle post state change logic. |
bool | setState virtual inline | Sets the state and sends the state signal if the state change was successful. |
bool | setState virtual inline | Sets the state and sends the state signal if the state change was successful. |
{#beforestatechange}
beforeStateChange
virtual inline
virtual inline bool beforeStateChange(const T & state)
Override to handle pre state change logic. Return false to prevent state change.
{#onstatechange}
onStateChange
virtual inline
virtual inline void onStateChange(T &, const T &)
Override to handle post state change logic.
{#setstate}
setState
virtual inline
virtual inline bool setState(void * sender, typename T::ID id)
Sets the state and sends the state signal if the state change was successful.
{#setstate}
setState
virtual inline
virtual inline bool setState(void * sender, const T & state)
Sets the state and sends the state signal if the state change was successful.
{#iregistry}
IRegistry
#include <icy/iregistry.h>
Abstract interface for object registries.
Public Attributes
| Return | Name | Description |
|---|---|---|
Signal< void(const std::string &)> | TypeRegistered | |
Signal< void(const std::string &)> | TypeUnregistered |
{#typeregistered}
TypeRegistered
Signal< void(const std::string &)> TypeRegistered
{#typeunregistered}
TypeUnregistered
Signal< void(const std::string &)> TypeUnregistered
Public Methods
| Return | Name | Description |
|---|---|---|
IRegistry | Defaulted constructor. | |
ItemT * | createInstance virtual inline | Creates and returns a new heap-allocated instance of the type registered under key s. |
void | registerType inline | Registers type T under the given key s. Emits TypeRegistered. Subsequent calls to createInstance(s) will return new T(). |
void | unregisterType virtual inline | Removes the type registered under key s. Emits TypeUnregistered. Does nothing if s is not registered. |
TypeMap | types const inline | Returns a copy of the current type map. |
{#iregistry}
IRegistry
IRegistry() = default
Defaulted constructor.
{#createinstance}
createInstance
virtual inline
virtual inline ItemT * createInstance(const std::string & s)
Creates and returns a new heap-allocated instance of the type registered under key s.
Parameters
sThe registration key (type name).
Returns
Pointer to the new instance, or nullptr if s is not registered.
{#registertype}
registerType
inline
template<typename T> inline void registerType(const std::string & s)
Registers type T under the given key s. Emits TypeRegistered. Subsequent calls to createInstance(s) will return new T().
Parameters
TConcrete type to register; must be default-constructible and derive from ItemT.
Parameters
sRegistration key (type name).
{#unregistertype}
unregisterType
virtual inline
virtual inline void unregisterType(const std::string & s)
Removes the type registered under key s. Emits TypeUnregistered. Does nothing if s is not registered.
Parameters
sRegistration key to remove.
{#types}
types
const inline
inline TypeMap types() const
Returns a copy of the current type map.
Returns
Map of registration keys to factory function pointers.
Public Types
| Name | Description |
|---|---|
TypeMap |
{#typemap}
TypeMap
std::map< std::string, ItemT *(*)()> TypeMap()
Private Attributes
| Return | Name | Description |
|---|---|---|
TypeMap | _types |
{#_types}
_types
TypeMap _types
Private Static Methods
| Return | Name | Description |
|---|---|---|
ItemT * | createT static inline |
{#createt}
createT
static inline
template<typename T> static inline ItemT * createT()
{#singleton}
Singleton
#include <icy/singleton.h>
Helper template class for managing singleton objects allocated on the heap.
Public Methods
| Return | Name | Description |
|---|---|---|
Singleton | Defaulted constructor. | |
S * | get inline | Returns a pointer to the managed singleton, instantiating it on first call. Thread-safe; protected by an internal mutex. |
S * | swap inline | Replaces the managed singleton with newPtr and returns the previous instance. The caller takes ownership of the returned pointer. Thread-safe; protected by an internal mutex. |
void | destroy inline | Destroys the managed singleton instance and resets the internal pointer to null. Thread-safe; protected by an internal mutex. |
{#singleton}
Singleton
Singleton() = default
Defaulted constructor.
{#get}
get
inline
inline S * get()
Returns a pointer to the managed singleton, instantiating it on first call. Thread-safe; protected by an internal mutex.
Returns
Pointer to the singleton instance (never null).
{#swap}
swap
inline
inline S * swap(S * newPtr)
Replaces the managed singleton with newPtr and returns the previous instance. The caller takes ownership of the returned pointer. Thread-safe; protected by an internal mutex.
Parameters
newPtrReplacement instance (may be nullptr).
Returns
Previously managed pointer (caller must delete if non-null).
{#destroy}
destroy
inline
inline void destroy()
Destroys the managed singleton instance and resets the internal pointer to null. Thread-safe; protected by an internal mutex.
Private Attributes
| Return | Name | Description |
|---|---|---|
std::unique_ptr< S, Deleter > | _ptr | |
std::mutex | _m |
{#_ptr}
_ptr
std::unique_ptr< S, Deleter > _ptr
{#_m}
_m
std::mutex _m
{#keyedstore}
KeyedStore
#include <icy/collection.h>
Subclassed by:
TimedManager< TKey, TValue >
A keyed store of unique_ptr values with optional lifecycle hooks. Not thread-safe; designed for single-threaded event loop contexts.
Subclasses can override onAdd/onRemove for lifecycle reactions, and add Signal members for external observers.
Public Methods
| Return | Name | Description |
|---|---|---|
KeyedStore | Defaulted constructor. | |
KeyedStore | Deleted constructor. | |
KeyedStore | Defaulted constructor. | |
TValue * | get const inline | Returns the item for key, or nullptr if not found. |
TValue & | add inline | Inserts a uniquely owned item. Returns a reference to the stored item. |
bool | tryAdd inline | Inserts if absent; returns false on duplicate (never throws). |
TValue & | put inline | Inserts or replaces the item under key. |
bool | erase inline | Removes and destroys the item under key. |
bool | contains const inline | |
bool | empty const inline | |
size_t | size const inline | |
void | clear inline | |
Map & | map inline | Direct map access for iteration. |
const Map & | map const inline | |
auto | begin inline | |
auto | end inline | |
auto | begin const inline | |
auto | end const inline |
{#keyedstore}
KeyedStore
KeyedStore() = default
Defaulted constructor.
{#keyedstore}
KeyedStore
KeyedStore(constKeyedStore &) = delete
Deleted constructor.
{#keyedstore}
KeyedStore
KeyedStore(KeyedStore &&) = default
Defaulted constructor.
{#get}
get
const inline
inline TValue * get(constTKey & key) const
Returns the item for key, or nullptr if not found.
{#add}
add
inline
inline TValue & add(constTKey & key, std::unique_ptr< TValue > item)
Inserts a uniquely owned item. Returns a reference to the stored item.
Exceptions
std::runtime_errorif the key already exists.
{#tryadd}
tryAdd
inline
inline bool tryAdd(constTKey & key, std::unique_ptr< TValue > item)
Inserts if absent; returns false on duplicate (never throws).
{#put}
put
inline
inline TValue & put(constTKey & key, std::unique_ptr< TValue > item)
Inserts or replaces the item under key.
{#erase}
erase
inline
inline bool erase(constTKey & key)
Removes and destroys the item under key.
Returns
true if the item existed and was removed.
{#contains}
contains
const inline
inline bool contains(constTKey & key) const
{#empty}
empty
const inline
inline bool empty() const
{#size}
size
const inline
inline size_t size() const
{#clear}
clear
inline
inline void clear()
{#map}
map
inline
inline Map & map()
Direct map access for iteration.
{#map}
map
const inline
inline const Map & map() const
{#begin}
begin
inline
inline auto begin()
{#end}
end
inline
inline auto end()
{#begin}
begin
const inline
inline auto begin() const
{#end}
end
const inline
inline auto end() const
Protected Attributes
| Return | Name | Description |
|---|---|---|
Map | _map |
{#_map}
_map
Map _map
Protected Methods
| Return | Name | Description |
|---|---|---|
void | onAdd virtual inline | Override for lifecycle reactions. |
void | onRemove virtual inline |
{#onadd}
onAdd
virtual inline
virtual inline void onAdd(constTKey &, TValue *)
Override for lifecycle reactions.
{#onremove}
onRemove
virtual inline
virtual inline void onRemove(constTKey &, TValue *)
Public Types
| Name | Description |
|---|---|
Map |
{#map}
Map
std::map< TKey, std::unique_ptr< TValue > > Map()
{#kvcollection}
KVCollection
#include <icy/collection.h>
A keyed value store (values stored by copy, not pointer).
Public Methods
| Return | Name | Description |
|---|---|---|
KVCollection | Defaulted constructor. | |
bool | add inline | Inserts a value; returns false if key already exists. |
TValue & | get inline | Returns the value or throws. |
constTValue & | get const inline | Returns the value or defaultValue. |
bool | remove inline | |
bool | has const inline | |
bool | empty const inline | |
size_t | size const inline | |
void | clear inline | |
Map & | map inline | |
const Map & | map const inline |
{#kvcollection}
KVCollection
KVCollection() = default
Defaulted constructor.
{#add}
add
inline
inline bool add(constTKey & key, constTValue & item)
Inserts a value; returns false if key already exists.
{#get}
get
inline
inline TValue & get(constTKey & key)
Returns the value or throws.
{#get}
get
const inline
inline constTValue & get(constTKey & key, constTValue & defaultValue) const
Returns the value or defaultValue.
{#remove}
remove
inline
inline bool remove(constTKey & key)
{#has}
has
const inline
inline bool has(constTKey & key) const
{#empty}
empty
const inline
inline bool empty() const
{#size}
size
const inline
inline size_t size() const
{#clear}
clear
inline
inline void clear()
{#map}
map
inline
inline Map & map()
{#map}
map
const inline
inline const Map & map() const
Protected Attributes
| Return | Name | Description |
|---|---|---|
Map | _map |
{#_map}
_map
Map _map
Public Types
| Name | Description |
|---|---|
Map |
{#map}
Map
std::map< TKey, TValue > Map()
{#nvcollection}
NVCollection
#include <icy/collection.h>
Subclassed by:
FormWriter,Message
A storage container for a name value collections. This collection can store multiple entries for each name, and it's getters are case-insensitive.
Public Methods
| Return | Name | Description |
|---|---|---|
NVCollection inline | ||
NVCollection inline | ||
NVCollection inline | ||
NVCollection & | operator= | Assigns the name-value pairs of another NVCollection to this one. |
const std::string & | operator[] const | Returns the value of the (first) name-value pair with the given name. |
void | set | Sets the value of the (first) name-value pair with the given name. |
void | add | Adds a new name-value pair with the given name and value. |
void | add | Adds a new name-value pair using move semantics. |
const std::string & | get const | Returns the value of the first name-value pair with the given name. |
const std::string & | get const | Returns the value of the first name-value pair with the given name. If no value with the given name has been found, the defaultValue is returned. |
bool | has const | Returns true if there is at least one name-value pair with the given name. |
ConstIterator | find const | Returns an iterator pointing to the first name-value pair with the given name. |
ConstIterator | begin const | Returns an iterator pointing to the begin of the name-value pair collection. |
ConstIterator | end const | Returns an iterator pointing to the end of the name-value pair collection. |
bool | empty const | Returns true iff the header does not have any content. |
int | size const | Returns the number of name-value pairs in the collection. |
void | erase | Removes all name-value pairs with the given name. |
void | clear | Removes all name-value pairs and their values. |
{#nvcollection}
NVCollection
inline
inline NVCollection()
{#nvcollection}
NVCollection
inline
inline NVCollection(const NVCollection & nvc)
{#nvcollection}
NVCollection
inline
inline NVCollection(NVCollection && nvc) noexcept
{#operator}
operator=
NVCollection & operator=(const NVCollection & nvc)
Assigns the name-value pairs of another NVCollection to this one.
{#operator}
operator[]
const
const std::string & operator[](std::string_view name) const
Returns the value of the (first) name-value pair with the given name.
Throws a NotFoundException if the name-value pair does not exist.
{#set}
set
void set(const std::string & name, const std::string & value)
Sets the value of the (first) name-value pair with the given name.
{#add}
add
void add(const std::string & name, const std::string & value)
Adds a new name-value pair with the given name and value.
{#add}
add
void add(std::string && name, std::string && value)
Adds a new name-value pair using move semantics.
{#get}
get
const
const std::string & get(std::string_view name) const
Returns the value of the first name-value pair with the given name.
Throws a NotFoundException if the name-value pair does not exist.
{#get}
get
const
const std::string & get(std::string_view name, const std::string & defaultValue) const
Returns the value of the first name-value pair with the given name. If no value with the given name has been found, the defaultValue is returned.
{#has}
has
const
bool has(std::string_view name) const
Returns true if there is at least one name-value pair with the given name.
{#find}
find
const
ConstIterator find(std::string_view name) const
Returns an iterator pointing to the first name-value pair with the given name.
{#begin}
begin
const
ConstIterator begin() const
Returns an iterator pointing to the begin of the name-value pair collection.
{#end}
end
const
ConstIterator end() const
Returns an iterator pointing to the end of the name-value pair collection.
{#empty}
empty
const
bool empty() const
Returns true iff the header does not have any content.
{#size}
size
const
int size() const
Returns the number of name-value pairs in the collection.
{#erase}
erase
void erase(std::string_view name)
Removes all name-value pairs with the given name.
{#clear}
clear
void clear()
Removes all name-value pairs and their values.
Public Types
| Name | Description |
|---|---|
Map | |
Iterator | |
ConstIterator |
{#map}
Map
std::vector< std::pair< std::string, std::string > > Map()
{#iterator}
Iterator
Map::iterator Iterator()
{#constiterator}
ConstIterator
Map::const_iterator ConstIterator()
Private Attributes
| Return | Name | Description |
|---|---|---|
Map | _map |
{#_map}
_map
Map _map
{#application}
Application
#include <icy/application.h>
Main icey application class.
This class exposes basic features required by most applications:
-
Running the event loop
-
Command line option parsing See also: OptionParser
-
Shutdown signal (Ctrl-C) handling
-
Garbage collection
Public Attributes
| Return | Name | Description |
|---|---|---|
uv::Loop * | loop | Active event loop. |
{#loop}
loop
uv::Loop * loop
Active event loop.
The event loop may be assigned on construction, otherwise the default event loop will be used.
Public Methods
| Return | Name | Description |
|---|---|---|
Application | Constructor. | |
~Application | Destructor. | |
void | run | Run the application event loop. |
void | stop | Stop the application event loop. |
void | finalize | Finalize and free any remaining pointers still held by the application event loop. |
void | waitForShutdown | Bind the shutdown signal and run the main event loop. |
void | bindShutdownSignal | Bind the shutdown signal. |
{#application}
Application
Application(uv::Loop * loop)
Constructor.
{#application}
~Application
~Application()
Destructor.
{#run}
run
void run()
Run the application event loop.
{#stop}
stop
void stop()
Stop the application event loop.
{#finalize}
finalize
void finalize()
Finalize and free any remaining pointers still held by the application event loop.
{#waitforshutdown}
waitForShutdown
void waitForShutdown(std::function< void(void *)> callback, void * opaque)
Bind the shutdown signal and run the main event loop.
{#bindshutdownsignal}
bindShutdownSignal
void bindShutdownSignal(std::function< void(void *)> callback, void * opaque)
Bind the shutdown signal.
Public Static Methods
| Return | Name | Description |
|---|---|---|
Application & | getDefault static | Returns the default Application singleton, although Application instances may be initialized individually. |
{#getdefault}
getDefault
static
static Application & getDefault()
Returns the default Application singleton, although Application instances may be initialized individually.
Protected Methods
| Return | Name | Description |
|---|---|---|
Application | Deleted constructor. | |
Application | Deleted constructor. |
{#application}
Application
Application(const Application &) = delete
Deleted constructor.
{#application}
Application
Application(Application &&) = delete
Deleted constructor.
{#syncpacketqueue}
SyncPacketQueue
#include <icy/packetqueue.h>
Inherits:
SyncQueue< IPacket >,PacketProcessor
Synchronized packet queue for event loop integration.
Public Attributes
| Return | Name | Description |
|---|---|---|
PacketSignal | emitter |
{#emitter}
emitter
PacketSignal emitter
Public Methods
| Return | Name | Description |
|---|---|---|
SyncPacketQueue inline | #### Parameters | |
SyncPacketQueue inline | Uses the default libuv event loop. | |
void | process virtual inline | Clones the incoming packet and pushes it onto the queue for synchronized dispatch. This queue is therefore an explicit PacketStream ownership boundary. Drops the packet with a warning if the queue has been cancelled. |
bool | accepts virtual inline | Returns true if the packet can be cast to type T. |
PacketRetention | retention virtual const inline | Returns how this adapter treats incoming packet lifetime. Most adapters are synchronous and therefore only borrow the packet for the current call chain. Queue-style adapters override this to advertise that they clone before deferred use. Callers may treat the first adapter reporting Cloned or Retained as the explicit ownership boundary in the stream graph. |
{#syncpacketqueue}
SyncPacketQueue
inline
inline SyncPacketQueue(uv::Loop * loop, int maxSize)
Parameters
-
loopEvent loop to synchronize dispatch onto. -
maxSizeMaximum number of queued packets before oldest are dropped.
{#syncpacketqueue}
SyncPacketQueue
inline
inline SyncPacketQueue(int maxSize)
Uses the default libuv event loop.
Parameters
maxSizeMaximum number of queued packets before oldest are dropped.
{#process}
process
virtual inline
virtual inline void process(IPacket & packet)
Clones the incoming packet and pushes it onto the queue for synchronized dispatch. This queue is therefore an explicit PacketStream ownership boundary. Drops the packet with a warning if the queue has been cancelled.
Parameters
packetIncoming packet to enqueue.
{#accepts}
accepts
virtual inline
virtual inline bool accepts(IPacket * packet)
Returns true if the packet can be cast to type T.
Parameters
packetPacket to test.
Returns
True if dynamic_cast<T*>(packet) succeeds.
{#retention}
retention
virtual const inline
virtual inline PacketRetention retention() const
Returns how this adapter treats incoming packet lifetime. Most adapters are synchronous and therefore only borrow the packet for the current call chain. Queue-style adapters override this to advertise that they clone before deferred use. Callers may treat the first adapter reporting Cloned or Retained as the explicit ownership boundary in the stream graph.
Protected Methods
| Return | Name | Description |
|---|---|---|
void | dispatch virtual inline | Emits the packet to downstream processors from the event loop thread. |
void | onStreamStateChange virtual inline | Cancels the queue on Closed or [Error](#error) stream state transitions. |
{#dispatch}
dispatch
virtual inline
virtual inline void dispatch(T & packet)
Emits the packet to downstream processors from the event loop thread.
Parameters
packetPacket to dispatch.
{#onstreamstatechange}
onStreamStateChange
virtual inline
virtual inline void onStreamStateChange(const PacketStreamState &)
Cancels the queue on Closed or [Error](#error) stream state transitions.
Parameters
stateNew stream state.
Public Types
| Name | Description |
|---|---|
Queue | |
Processor |
{#queue}
Queue
SyncQueue< T > Queue()
{#processor}
Processor
PacketProcessor Processor()
{#asyncpacketqueue}
AsyncPacketQueue
#include <icy/packetqueue.h>
Inherits:
AsyncQueue< IPacket >,PacketProcessor
Thread-based asynchronous packet dispatch queue.
Public Attributes
| Return | Name | Description |
|---|---|---|
PacketSignal | emitter |
{#emitter}
emitter
PacketSignal emitter
Public Methods
| Return | Name | Description |
|---|---|---|
AsyncPacketQueue inline | #### Parameters | |
void | close virtual inline | Flushes remaining packets, cancels the queue, and joins the dispatch thread. |
void | process virtual inline | Clones the incoming packet and pushes it onto the async queue. This queue is therefore an explicit PacketStream ownership boundary. Drops the packet with a warning if the queue has been cancelled. |
bool | accepts virtual inline | Returns true if the packet can be cast to type T. |
PacketRetention | retention virtual const inline | Returns how this adapter treats incoming packet lifetime. Most adapters are synchronous and therefore only borrow the packet for the current call chain. Queue-style adapters override this to advertise that they clone before deferred use. Callers may treat the first adapter reporting Cloned or Retained as the explicit ownership boundary in the stream graph. |
{#asyncpacketqueue}
AsyncPacketQueue
inline
inline AsyncPacketQueue(int maxSize)
Parameters
maxSizeMaximum number of queued packets before oldest are dropped.
{#close}
close
virtual inline
virtual inline void close()
Flushes remaining packets, cancels the queue, and joins the dispatch thread.
{#process}
process
virtual inline
virtual inline void process(IPacket & packet)
Clones the incoming packet and pushes it onto the async queue. This queue is therefore an explicit PacketStream ownership boundary. Drops the packet with a warning if the queue has been cancelled.
Parameters
packetIncoming packet to enqueue.
{#accepts}
accepts
virtual inline
virtual inline bool accepts(IPacket * packet)
Returns true if the packet can be cast to type T.
Parameters
packetPacket to test.
Returns
True if dynamic_cast<T*>(packet) succeeds.
{#retention}
retention
virtual const inline
virtual inline PacketRetention retention() const
Returns how this adapter treats incoming packet lifetime. Most adapters are synchronous and therefore only borrow the packet for the current call chain. Queue-style adapters override this to advertise that they clone before deferred use. Callers may treat the first adapter reporting Cloned or Retained as the explicit ownership boundary in the stream graph.
Protected Methods
| Return | Name | Description |
|---|---|---|
void | dispatch virtual inline | Emits the packet to downstream processors from the async thread. |
void | onStreamStateChange virtual inline | Closes the queue on [Error](#error) or Closed stream state transitions. |
{#dispatch}
dispatch
virtual inline
virtual inline void dispatch(T & packet)
Emits the packet to downstream processors from the async thread.
Parameters
packetPacket to dispatch.
{#onstreamstatechange}
onStreamStateChange
virtual inline
virtual inline void onStreamStateChange(const PacketStreamState &)
Closes the queue on [Error](#error) or Closed stream state transitions.
Parameters
stateNew stream state.
Public Types
| Name | Description |
|---|---|
Queue | |
Processor |
{#queue}
Queue
AsyncQueue< T > Queue()
{#processor}
Processor
PacketProcessor Processor()
{#ratelimiter}
RateLimiter
#include <icy/ratelimiter.h>
Token bucket rate limiter for throttling message send frequency.
Public Attributes
| Return | Name | Description |
|---|---|---|
double | rate | How many messages. |
double | seconds | Over how many seconds. |
double | allowance | Remaining send allowance. |
{#rate}
rate
double rate
How many messages.
{#seconds}
seconds
double seconds
Over how many seconds.
{#allowance}
allowance
double allowance
Remaining send allowance.
Public Methods
| Return | Name | Description |
|---|---|---|
RateLimiter inline | Constructs a token bucket limiter. | |
bool | canSend inline | Returns true if a message may be sent without exceeding the rate limit. Replenishes the token bucket based on elapsed time since the last check, then consumes one token. Returns false if the bucket is empty. |
{#ratelimiter}
RateLimiter
inline
inline RateLimiter(double rate, double seconds)
Constructs a token bucket limiter.
Parameters
-
rateMaximum number of messages permitted in the window. -
secondsDuration of the replenishment window in seconds.
{#cansend}
canSend
inline
inline bool canSend()
Returns true if a message may be sent without exceeding the rate limit. Replenishes the token bucket based on elapsed time since the last check, then consumes one token. Returns false if the bucket is empty.
Returns
true if sending is allowed, false if the rate limit is exceeded.
Private Attributes
| Return | Name | Description |
|---|---|---|
std::chrono::steady_clock::time_point | _lastCheck | |
bool | _started |
{#_lastcheck}
_lastCheck
std::chrono::steady_clock::time_point _lastCheck
{#_started}
_started
bool _started
{#packetstreamadapter}
PacketStreamAdapter
#include <icy/packetstream.h>
Subclassed by:
PacketProcessor,ThreadedStreamReader,ICapture,FormWriter,WebRtcTrackReceiver
This class is a wrapper for integrating external classes with the a PacketStream's data flow and state machine.
Public Methods
| Return | Name | Description |
|---|---|---|
PacketStreamAdapter | Construct the adapter, binding it to the given packet signal. | |
void | emit virtual | Emit a mutable raw buffer as a packet. |
void | emit virtual | Emit a read-only raw buffer as a packet (data is copied internally). |
void | emit virtual | Emit a string as a packet (data is copied internally). |
void | emit virtual | Emit a flag-only packet carrying no payload data. |
void | emit virtual | Emit an existing packet directly onto the outgoing signal. |
PacketSignal & | getEmitter | Returns a reference to the outgoing packet signal. |
PacketRetention | retention virtual const | Returns how this adapter treats incoming packet lifetime. Most adapters are synchronous and therefore only borrow the packet for the current call chain. Queue-style adapters override this to advertise that they clone before deferred use. Callers may treat the first adapter reporting Cloned or Retained as the explicit ownership boundary in the stream graph. |
void | onStreamStateChange virtual inline | Called by the PacketStream to notify when the internal Stream state changes. On receiving the Stopped state, it is the responsibility of the adapter to have ceased all outgoing packet transmission, especially in multi-thread scenarios. |
{#packetstreamadapter}
PacketStreamAdapter
PacketStreamAdapter(PacketSignal & emitter)
Construct the adapter, binding it to the given packet signal.
Parameters
emitterThe outgoing packet signal owned by the subclass.
{#emit}
emit
virtual
virtual void emit(char * data, size_t len, unsigned flags)
Emit a mutable raw buffer as a packet.
Parameters
-
dataPointer to the buffer (not copied; caller retains ownership). -
lenNumber of bytes in the buffer. -
flagsOptional packet flags (see PacketFlags).
{#emit}
emit
virtual
virtual void emit(const char * data, size_t len, unsigned flags)
Emit a read-only raw buffer as a packet (data is copied internally).
Parameters
-
dataPointer to the buffer. -
lenNumber of bytes in the buffer. -
flagsOptional packet flags (see PacketFlags).
{#emit}
emit
virtual
virtual void emit(const std::string & str, unsigned flags)
Emit a string as a packet (data is copied internally).
Parameters
-
strString payload. -
flagsOptional packet flags (see PacketFlags).
{#emit}
emit
virtual
virtual void emit(unsigned flags)
Emit a flag-only packet carrying no payload data.
Parameters
flagsPacket flags to embed in the emitted FlagPacket.
{#emit}
emit
virtual
virtual void emit(IPacket & packet)
Emit an existing packet directly onto the outgoing signal.
Parameters
packetThe packet to forward; must remain valid for the duration of the call.
{#getemitter}
getEmitter
PacketSignal & getEmitter()
Returns a reference to the outgoing packet signal.
{#retention}
retention
virtual const
virtual PacketRetention retention() const
Returns how this adapter treats incoming packet lifetime. Most adapters are synchronous and therefore only borrow the packet for the current call chain. Queue-style adapters override this to advertise that they clone before deferred use. Callers may treat the first adapter reporting Cloned or Retained as the explicit ownership boundary in the stream graph.
{#onstreamstatechange}
onStreamStateChange
virtual inline
virtual inline void onStreamStateChange(const PacketStreamState &)
Called by the PacketStream to notify when the internal Stream state changes. On receiving the Stopped state, it is the responsibility of the adapter to have ceased all outgoing packet transmission, especially in multi-thread scenarios.
Protected Attributes
| Return | Name | Description |
|---|---|---|
PacketSignal & | _emitter |
{#_emitter}
_emitter
PacketSignal & _emitter
Protected Methods
| Return | Name | Description |
|---|---|---|
PacketStreamAdapter | NonCopyable and NonMovable. | |
PacketStreamAdapter | Deleted constructor. |
{#packetstreamadapter}
PacketStreamAdapter
PacketStreamAdapter(const PacketStreamAdapter &) = delete
NonCopyable and NonMovable.
{#packetstreamadapter}
PacketStreamAdapter
PacketStreamAdapter(PacketStreamAdapter &&) = delete
Deleted constructor.
{#packetprocessor}
PacketProcessor
#include <icy/packetstream.h>
Inherits:
PacketStreamAdapterSubclassed by:AsyncPacketQueue< PacketT >,PlanarAudioPacket >,PlanarVideoPacket >,AsyncPacketQueue< T >,StreamWriter,SyncPacketQueue< T >,AudioPacketEncoder,FPSLimiter,MultiplexPacketEncoder,VideoPacketEncoder,ChunkedAdapter,MultipartAdapter,FrameSampler,WebRtcTrackSender
This class is a virtual interface for creating PacketStreamAdapters which process that and emit the IPacket type.
Public Methods
| Return | Name | Description |
|---|---|---|
PacketProcessor inline | ||
void | process | This method performs processing on the given packet and emits the result. |
bool | accepts virtual inline | This method ensures compatibility with the given packet type. Return false to reject the packet. |
void | operator<< virtual inline | Stream operator alias for process() |
{#packetprocessor}
PacketProcessor
inline
inline PacketProcessor(PacketSignal & emitter)
{#process}
process
void process(IPacket & packet)
This method performs processing on the given packet and emits the result.
Processors that defer work asynchronously must either clone the packet or retain an owned equivalent. See retention().
{#accepts}
accepts
virtual inline
virtual inline bool accepts(IPacket *)
This method ensures compatibility with the given packet type. Return false to reject the packet.
{#operator}
operator<<
virtual inline
virtual inline void operator<<(IPacket & packet)
Stream operator alias for process()
{#packetstream}
PacketStream
#include <icy/packetstream.h>
Inherits:
Stateful< PacketStreamState >
Processes and broadcasts IPackets through a configurable adapter graph.
A PacketStream consists of one or many PacketSources, one or many PacketProcessors, and one or many delegate receivers.
This class enables the developer to setup a processor chain in order to perform arbitrary processing on data packets using interchangeable packet adapters, and pump the output to any delegate function or even another PacketStream.
Note that PacketStream itself inherits from PacketStreamAdapter, so a PacketStream can be the source of another PacketStream.
All PacketStream methods are thread-safe, but once the stream is running you will not be able to attach or detach stream adapters.
In order to synchronize output packets with the application event loop take a look at the SyncPacketQueue class. For lengthy operations you can add an AsyncPacketQueue to the start of the stream to defer processing from the PacketSource thread.
Public Attributes
| Return | Name | Description |
|---|---|---|
PacketSignal | emitter | Signals to delegates on outgoing packets. |
ThreadSignal< void(PacketStream &, const std::exception_ptr &)> | Error | Signals that the PacketStream is in Error state. If stream output is synchronized then the Error signal will be sent from the synchronization context, otherwise it will be sent from the async processor context. See synchronizeOutput() |
ThreadSignal< void(PacketStream &)> | Close | Signals that the PacketStream is in Close state. This signal is sent immediately via the close() method, and as such will be sent from the calling thread context. |
{#emitter}
emitter
PacketSignal emitter
Signals to delegates on outgoing packets.
{#error}
Error
ThreadSignal< void(PacketStream &, const std::exception_ptr &)> Error
Signals that the PacketStream is in Error state. If stream output is synchronized then the Error signal will be sent from the synchronization context, otherwise it will be sent from the async processor context. See synchronizeOutput()
{#close}
Close
ThreadSignal< void(PacketStream &)> Close
Signals that the PacketStream is in Close state. This signal is sent immediately via the close() method, and as such will be sent from the calling thread context.
Public Methods
| Return | Name | Description |
|---|---|---|
PacketStream | Construct a named packet stream. | |
~PacketStream virtual | Destroy the stream; calls close() then reset() to release all adapters. | |
PacketStream | Deleted constructor. | |
PacketStream | Deleted constructor. | |
void | start virtual | Start the stream and synchronized sources. |
void | stop virtual | Stop the stream and synchronized sources. |
void | pause virtual | Pause the stream. |
void | resume virtual | Resume the stream. |
void | close virtual | Close the stream and transition the internal state to Closed. |
void | reset virtual | Cleanup all managed stream adapters and reset the stream state. |
bool | active virtual const | Returns true when the stream is in the Active state. |
bool | stopped virtual const | Returns true when the stream is in the Stopping or Stopped state. |
bool | closed virtual const | Returns true when the stream is in the Closed or Error state. |
bool | lock virtual | Sets the stream to locked state. In a locked state no new adapters can be added or removed from the stream until the stream is stopped. |
bool | locked virtual const | Returns true is the stream is currently locked. |
void | write virtual | Write a mutable buffer into the stream without copying. The caller must keep the buffer alive until processing crosses a Cloned/Retained boundary or, if the graph is fully synchronous, until write() returns. |
void | write virtual | Write a read-only buffer into the stream; data is copied immediately into an owning RawPacket before any adapter sees it. |
void | write virtual | Write a packet directly into the processing chain. |
void | attachSource virtual | Attach a bare packet signal as a stream source. The signal is wrapped in an unowned PacketStreamAdapter internally. Useful when the source is another PacketStream::emitter. |
void | attachSource virtual | Attach a PacketStreamAdapter as a source. Source adapters default to Borrowed retention unless overridden; they must not retain inbound packet storage asynchronously without reporting Cloned or Retained. |
void | attachSource inline | Attach a shared_ptr-managed source adapter to the stream. The stream shares ownership; the adapter is kept alive at least until teardown. Throws std::runtime_error if ptr does not derive from PacketStreamAdapter. |
bool | detachSource virtual | Detach a source by its packet signal. Disconnects the signal from the stream's process slot and removes the adapter entry. |
bool | detachSource virtual | Detach a source by its adapter pointer. Disconnects the adapter's emitter from the stream's process slot and removes the entry. |
void | attach virtual | Attach a packet processor to the stream. Processors are executed in ascending order of their order value. Pass order = -1 to append at the end of the current processor list. Valid range is -1 to 101; values outside this range throw std::invalid_argument. Borrowed processors must finish with the packet before process() returns. Queue/processors that defer work must report Cloned or Retained via retention() so upstream code has an explicit ownership boundary. |
void | attach inline | Attach a shared_ptr-managed processor to the stream. The stream shares ownership; the processor is kept alive at least until teardown. Throws std::runtime_error if ptr does not derive from PacketProcessor. |
bool | detach virtual | Detach a packet processor from the stream. The processor's delegate connections are removed; ownership is released if held. |
void | synchronizeOutput virtual | Synchronize stream output packets with a libuv event loop. Internally attaches a SyncPacketQueue at order 101 so that all packets emitted by the processor chain are dispatched from the loop thread rather than the source thread. Must be called before start(). |
void | autoStart virtual | Enable or disable auto-start behaviour (default: false). When enabled, the stream automatically transitions to Active state upon receiving the first packet while in the None or Locked state. Must be called before start(). |
void | closeOnError virtual | Enable or disable close-on-error behaviour (default: true). When enabled, an unhandled processor exception causes the stream to transition from Error to Closed state automatically. |
const std::exception_ptr & | error | Accessors for the unmanaged client data pointer. |
std::string | name const | Return the name assigned to this stream at construction. |
PacketAdapterVec | adapters const | Returns a combined list of all stream sources and processors. |
PacketAdapterVec | sources const | Returns a list of all stream sources. |
PacketAdapterVec | processors const | Returns a list of all stream processors. |
int | numSources const | Return the number of source adapters currently registered. |
int | numProcessors const | Return the number of processor adapters currently registered. |
int | numAdapters const | Return the total number of adapters (sources + processors). |
AdapterT * | getSource inline | Return the nth source of type AdapterT, or nullptr if not found. Sources are searched in their registered order; only adapters that dynamic_cast successfully to AdapterT are counted. |
AdapterT * | getProcessor inline | Return the nth processor of type AdapterT, or nullptr if not found. Processors are searched in their registered order; only adapters that dynamic_cast successfully to AdapterT are counted. |
PacketProcessor * | getProcessor inline | Return the processor registered at a specific order value. Unlike the template overload, this searches by order rather than by type and index. |
{#packetstream}
PacketStream
PacketStream(const std::string & name)
Construct a named packet stream.
Parameters
nameOptional human-readable name used in log output.
{#packetstream}
~PacketStream
virtual
virtual ~PacketStream()
Destroy the stream; calls close() then reset() to release all adapters.
{#packetstream}
PacketStream
PacketStream(const PacketStream &) = delete
Deleted constructor.
{#packetstream}
PacketStream
PacketStream(PacketStream &&) = delete
Deleted constructor.
{#start}
start
virtual
virtual void start()
Start the stream and synchronized sources.
{#stop}
stop
virtual
virtual void stop()
Stop the stream and synchronized sources.
{#pause}
pause
virtual
virtual void pause()
Pause the stream.
{#resume}
resume
virtual
virtual void resume()
Resume the stream.
{#close}
close
virtual
virtual void close()
Close the stream and transition the internal state to Closed.
{#reset}
reset
virtual
virtual void reset()
Cleanup all managed stream adapters and reset the stream state.
{#active}
active
virtual const
virtual bool active() const
Returns true when the stream is in the Active state.
{#stopped}
stopped
virtual const
virtual bool stopped() const
Returns true when the stream is in the Stopping or Stopped state.
{#closed}
closed
virtual const
virtual bool closed() const
Returns true when the stream is in the Closed or Error state.
{#lock}
lock
virtual
virtual bool lock()
Sets the stream to locked state. In a locked state no new adapters can be added or removed from the stream until the stream is stopped.
{#locked}
locked
virtual const
virtual bool locked() const
Returns true is the stream is currently locked.
{#write}
write
virtual
virtual void write(char * data, size_t len)
Write a mutable buffer into the stream without copying. The caller must keep the buffer alive until processing crosses a Cloned/Retained boundary or, if the graph is fully synchronous, until write() returns.
Parameters
-
dataPointer to the raw data buffer. -
lenNumber of bytes to process.
{#write}
write
virtual
virtual void write(const char * data, size_t len)
Write a read-only buffer into the stream; data is copied immediately into an owning RawPacket before any adapter sees it.
Parameters
-
dataPointer to the raw data buffer. -
lenNumber of bytes to process.
{#write}
write
virtual
virtual void write(IPacket && packet)
Write a packet directly into the processing chain.
Parameters
packetPacket to process; moved into the stream.
{#attachsource}
attachSource
virtual
virtual void attachSource(PacketSignal & source)
Attach a bare packet signal as a stream source. The signal is wrapped in an unowned PacketStreamAdapter internally. Useful when the source is another PacketStream::emitter.
Parameters
sourceThe packet signal to attach; must outlive the stream.
{#attachsource}
attachSource
virtual
virtual void attachSource(PacketStreamAdapter * source, bool owned, bool syncState)
Attach a PacketStreamAdapter as a source. Source adapters default to Borrowed retention unless overridden; they must not retain inbound packet storage asynchronously without reporting Cloned or Retained.
Parameters
-
sourceThe adapter to attach; must not be null. -
ownedIf true the stream takes ownership and deletes the pointer on teardown. -
syncStateIf true andsourceimplements basic::Startable, its start()/stop() will be called by startSources()/stopSources().
{#attachsource}
attachSource
inline
template<class C> inline void attachSource(std::shared_ptr< C > ptr, bool syncState)
Attach a shared_ptr-managed source adapter to the stream. The stream shares ownership; the adapter is kept alive at least until teardown. Throws std::runtime_error if ptr does not derive from PacketStreamAdapter.
Parameters
CAdapter type; must derive from PacketStreamAdapter.
Parameters
-
ptrShared pointer to the adapter instance. -
syncStateIf true andptrimplements basic::Startable, its start()/stop() will be called by startSources()/stopSources().
{#detachsource}
detachSource
virtual
virtual bool detachSource(PacketSignal & source)
Detach a source by its packet signal. Disconnects the signal from the stream's process slot and removes the adapter entry.
Parameters
sourceThe packet signal previously attached via attachSource(PacketSignal&).
Returns
true if the source was found and removed, false otherwise.
{#detachsource}
detachSource
virtual
virtual bool detachSource(PacketStreamAdapter * source)
Detach a source by its adapter pointer. Disconnects the adapter's emitter from the stream's process slot and removes the entry.
Parameters
sourcePointer to the adapter previously attached.
Returns
true if the source was found and removed, false otherwise.
{#attach}
attach
virtual
virtual void attach(PacketProcessor * proc, int order, bool owned)
Attach a packet processor to the stream. Processors are executed in ascending order of their order value. Pass order = -1 to append at the end of the current processor list. Valid range is -1 to 101; values outside this range throw std::invalid_argument. Borrowed processors must finish with the packet before process() returns. Queue/processors that defer work must report Cloned or Retained via retention() so upstream code has an explicit ownership boundary.
Parameters
-
procThe processor to attach; must not be null. -
orderPosition in the processing chain (lower runs first). -
ownedIf true the stream takes ownership and deletes the pointer on teardown.
{#attach}
attach
inline
template<class C> inline void attach(std::shared_ptr< C > ptr, int order, bool syncState)
Attach a shared_ptr-managed processor to the stream. The stream shares ownership; the processor is kept alive at least until teardown. Throws std::runtime_error if ptr does not derive from PacketProcessor.
Parameters
CProcessor type; must derive from PacketProcessor.
Parameters
-
ptrShared pointer to the processor instance. -
orderPosition in the processing chain (lower runs first). -
syncStateReserved for future use; currently unused.
{#detach}
detach
virtual
virtual bool detach(PacketProcessor * proc)
Detach a packet processor from the stream. The processor's delegate connections are removed; ownership is released if held.
Parameters
procPointer to the processor to remove.
Returns
true if the processor was found and removed, false otherwise.
{#synchronizeoutput}
synchronizeOutput
virtual
virtual void synchronizeOutput(uv::Loop * loop)
Synchronize stream output packets with a libuv event loop. Internally attaches a SyncPacketQueue at order 101 so that all packets emitted by the processor chain are dispatched from the loop thread rather than the source thread. Must be called before start().
Parameters
loopThe event loop to synchronize output onto; must not be null.
{#autostart}
autoStart
virtual
virtual void autoStart(bool flag)
Enable or disable auto-start behaviour (default: false). When enabled, the stream automatically transitions to Active state upon receiving the first packet while in the None or Locked state. Must be called before start().
Parameters
flagtrue to enable auto-start, false to disable.
{#closeonerror}
closeOnError
virtual
virtual void closeOnError(bool flag)
Enable or disable close-on-error behaviour (default: true). When enabled, an unhandled processor exception causes the stream to transition from Error to Closed state automatically.
Parameters
flagtrue to close the stream on error, false to remain in Error state.
{#error}
error
const std::exception_ptr & error()
Accessors for the unmanaged client data pointer.
Return the last captured exception, if the stream is in Error state. The pointer is null when no error has occurred.
Returns
A reference to the stored exception_ptr; empty if no error.
{#name}
name
const
std::string name() const
Return the name assigned to this stream at construction.
Returns
The stream name; empty string if none was provided.
{#adapters}
adapters
const
PacketAdapterVec adapters() const
Returns a combined list of all stream sources and processors.
{#sources}
sources
const
PacketAdapterVec sources() const
Returns a list of all stream sources.
{#processors}
processors
const
PacketAdapterVec processors() const
Returns a list of all stream processors.
{#numsources}
numSources
const
int numSources() const
Return the number of source adapters currently registered.
Returns
Source count; thread-safe.
{#numprocessors}
numProcessors
const
int numProcessors() const
Return the number of processor adapters currently registered.
Returns
Processor count; thread-safe.
{#numadapters}
numAdapters
const
int numAdapters() const
Return the total number of adapters (sources + processors).
Returns
Combined adapter count; thread-safe.
{#getsource}
getSource
inline
template<class AdapterT> inline AdapterT * getSource(int index)
Return the nth source of type AdapterT, or nullptr if not found. Sources are searched in their registered order; only adapters that dynamic_cast successfully to AdapterT are counted.
Parameters
AdapterTTarget type; must derive from PacketStreamAdapter.
Parameters
indexZero-based index among matching sources (default 0).
Returns
Pointer to the matching adapter, or nullptr.
{#getprocessor}
getProcessor
inline
template<class AdapterT> inline AdapterT * getProcessor(int index)
Return the nth processor of type AdapterT, or nullptr if not found. Processors are searched in their registered order; only adapters that dynamic_cast successfully to AdapterT are counted.
Parameters
AdapterTTarget type; must derive from PacketProcessor.
Parameters
indexZero-based index among matching processors (default 0).
Returns
Pointer to the matching processor, or nullptr.
{#getprocessor}
getProcessor
inline
inline PacketProcessor * getProcessor(int order)
Return the processor registered at a specific order value. Unlike the template overload, this searches by order rather than by type and index.
Parameters
orderThe order value to match (default 0).
Returns
Pointer to the matching processor, or nullptr if none registered at that order.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::mutex | _mutex | |
std::mutex | _procMutex | |
std::string | _name | |
PacketAdapterVec | _sources | |
PacketAdapterVec | _processors | |
std::deque< PacketStreamState > | _states | |
std::exception_ptr | _error | |
bool | _autoStart | |
bool | _closeOnError | |
bool | _wired |
{#_mutex}
_mutex
std::mutex _mutex
{#_procmutex}
_procMutex
std::mutex _procMutex
{#_name}
_name
std::string _name
{#_sources}
_sources
PacketAdapterVec _sources
{#_processors}
_processors
PacketAdapterVec _processors
{#_states}
_states
std::deque< PacketStreamState > _states
{#_error}
_error
std::exception_ptr _error
{#_autostart}
_autoStart
bool _autoStart
{#_closeonerror}
_closeOnError
bool _closeOnError
{#_wired}
_wired
bool _wired
Protected Methods
| Return | Name | Description |
|---|---|---|
void | setup | Attach the source and processor delegate chain. |
void | teardown | Detach the source and processor delegate chain. |
void | attachSource | |
void | attach | |
void | startSources | Start synchronized sources. |
void | stopSources | Stop synchronized sources. |
void | process virtual | Process incoming packets. |
void | emit | Emit the final packet to listeners. |
void | synchronizeStates | Synchronize queued states with adapters. |
void | onStateChange virtual | Override the Stateful::onStateChange method. |
void | assertCanModify | Returns true if the given state ID is queued. |
void | handleException | Handle an internal exception. |
{#setup}
setup
void setup()
Attach the source and processor delegate chain.
{#teardown}
teardown
void teardown()
Detach the source and processor delegate chain.
{#attachsource}
attachSource
void attachSource(PacketAdapterReference::Ptr ref)
{#attach}
attach
void attach(PacketAdapterReference::Ptr ref)
{#startsources}
startSources
void startSources()
Start synchronized sources.
{#stopsources}
stopSources
void stopSources()
Stop synchronized sources.
{#process}
process
virtual
virtual void process(IPacket & packet)
Process incoming packets.
{#emit}
emit
void emit(IPacket & packet)
Emit the final packet to listeners.
Synchronized signals such as Close and Error are sent from this method. See synchronizeOutput()
{#synchronizestates}
synchronizeStates
void synchronizeStates()
Synchronize queued states with adapters.
{#onstatechange}
onStateChange
virtual
virtual void onStateChange(PacketStreamState & state, const PacketStreamState & oldState)
Override the Stateful::onStateChange method.
{#assertcanmodify}
assertCanModify
void assertCanModify()
Returns true if the given state ID is queued.
Asserts that the stream can be modified, ie is not in the Locked, Stopping or Active states.
{#handleexception}
handleException
void handleException(std::exception & exc)
Handle an internal exception.
Public Types
| Name | Description |
|---|---|
Ptr |
{#ptr}
Ptr
std::shared_ptr< PacketStream > Ptr()
{#synchronizer}
Synchronizer
#include <icy/synchronizer.h>
Inherits:
Runner
Synchronizer enables any thread to communicate with the associated event loop via synchronized callbacks.
This class inherits the [Runner](#runner) interface and may be used with any implementation that's powered by an asynchronous [Runner](#runner).
Public Methods
| Return | Name | Description |
|---|---|---|
Synchronizer | Creates a synchronizer attached to the given event loop without a callback. Call [start()](#classicy_1_1Synchronizer_1a535a1605fc8902d814f9f5ab5e213a66) separately to register the callback before using [post()](#classicy_1_1Synchronizer_1a1400f8a4c294ba3d4a9d9d1887131abb). | |
Synchronizer | Creates and immediately starts a synchronizer with a single callback function. The target is invoked from the event loop context each time [post()](#classicy_1_1Synchronizer_1a1400f8a4c294ba3d4a9d9d1887131abb) is called. | |
Synchronizer inline explicit | Creates and immediately starts a synchronizer with a variadic callback. | |
~Synchronizer virtual | Destructor. | |
void | post | Send a synchronization request to the event loop. Call this each time you want the target method called synchronously. The synchronous method will be called on next iteration. This is not atomic, so do not expect a callback for every request. |
void | start inline | Starts the synchronizer with a variadic callback function. The callback is invoked from the event loop each time [post()](#classicy_1_1Synchronizer_1a1400f8a4c294ba3d4a9d9d1887131abb) is called. Throws std::logic_error if already running or if the handle is null. |
void | start virtual | Starts the synchronizer with a std::function callback. Overrides [Runner::start](#classicy_1_1Runner_1a5969e823f1ce0bdd8730d3108bf13fbd); delegates to the variadic start template. |
void | cancel virtual | Cancels the synchronizer, signalling the associated callback to stop. A subsequent [post()](#classicy_1_1Synchronizer_1a1400f8a4c294ba3d4a9d9d1887131abb) is needed to wake up the event loop so it can process the cancellation. |
void | close virtual | Cancels the synchronizer and closes the underlying uv_async_t handle. Safe to call multiple times; no-op if already closed. |
uv::Handle< uv_async_t > & | handle | Returns a reference to the underlying libuv async handle. |
{#synchronizer}
Synchronizer
Synchronizer(uv::Loop * loop)
Creates a synchronizer attached to the given event loop without a callback. Call [start()](#classicy_1_1Synchronizer_1a535a1605fc8902d814f9f5ab5e213a66) separately to register the callback before using [post()](#classicy_1_1Synchronizer_1a1400f8a4c294ba3d4a9d9d1887131abb).
Parameters
loopEvent loop to attach the async handle to.
{#synchronizer}
Synchronizer
Synchronizer(std::function< void()> target, uv::Loop * loop)
Creates and immediately starts a synchronizer with a single callback function. The target is invoked from the event loop context each time [post()](#classicy_1_1Synchronizer_1a1400f8a4c294ba3d4a9d9d1887131abb) is called.
Parameters
-
targetCallback to invoke on each event loop wakeup. -
loopEvent loop to attach the async handle to.
{#synchronizer}
Synchronizer
inline explicit
template<typename Function, typename... Args> inline explicit Synchronizer(Function && func, Args &&... args, uv::Loop * loop)
Creates and immediately starts a synchronizer with a variadic callback.
Parameters
-
FunctionCallable type. -
ArgsArgument types forwarded to the function.
Parameters
-
funcCallable to invoke on each event loop wakeup. -
argsArguments forwarded tofunc. -
loopEvent loop to attach the async handle to.
{#synchronizer}
~Synchronizer
virtual
virtual ~Synchronizer()
Destructor.
{#post}
post
void post()
Send a synchronization request to the event loop. Call this each time you want the target method called synchronously. The synchronous method will be called on next iteration. This is not atomic, so do not expect a callback for every request.
{#start}
start
inline
template<typename Function, typename... Args> inline void start(Function && func, Args &&... args)
Starts the synchronizer with a variadic callback function. The callback is invoked from the event loop each time [post()](#classicy_1_1Synchronizer_1a1400f8a4c294ba3d4a9d9d1887131abb) is called. Throws std::logic_error if already running or if the handle is null.
Parameters
-
FunctionCallable type. -
ArgsArgument types forwarded to the function.
Parameters
-
funcCallable to invoke on each event loop wakeup. -
argsArguments forwarded tofunc.
{#start}
start
virtual
virtual void start(std::function< void()> func)
Starts the synchronizer with a std::function callback. Overrides [Runner::start](#classicy_1_1Runner_1a5969e823f1ce0bdd8730d3108bf13fbd); delegates to the variadic start template.
Parameters
funcCallback invoked from the event loop on each[post()](#classicy_1_1Synchronizer_1a1400f8a4c294ba3d4a9d9d1887131abb)call.
{#cancel}
cancel
virtual
virtual void cancel()
Cancels the synchronizer, signalling the associated callback to stop. A subsequent [post()](#classicy_1_1Synchronizer_1a1400f8a4c294ba3d4a9d9d1887131abb) is needed to wake up the event loop so it can process the cancellation.
{#close}
close
virtual
virtual void close()
Cancels the synchronizer and closes the underlying uv_async_t handle. Safe to call multiple times; no-op if already closed.
{#handle}
handle
uv::Handle< uv_async_t > & handle()
Returns a reference to the underlying libuv async handle.
Returns
Reference to the [uv::Handle](uv.md#handle-2)<uv_async_t>.
Protected Attributes
| Return | Name | Description |
|---|---|---|
uv::Handle< uv_async_t > | _handle |
{#_handle}
_handle
uv::Handle< uv_async_t > _handle
Protected Methods
| Return | Name | Description |
|---|---|---|
bool | async virtual const | Returns true if the implementation is thread-based. |
{#async}
async
virtual const
virtual bool async() const
Returns true if the implementation is thread-based.
Returns
True for thread-backed runners, false for event-loop-driven runners.
{#timedmanager}
TimedManager
#include <icy/timedmanager.h>
Inherits:
KeyedStore< TKey, TValue >
Timed pointer manager
Provides timed persistent data storage for class instances. TValue must implement the clone() method.
Public Methods
| Return | Name | Description |
|---|---|---|
TimedManager inline | Constructs a TimedManager and starts the internal expiry-check timer. | |
void | add inline | Add an item which will expire (and be deleted) after the specified timeout value. If the timeout is 0 the item will be stored indefinitely. The TimedManager assumes ownership of the given pointer. |
bool | expires virtual inline | Update the item expiry timeout. |
bool | expires virtual inline | Update the item expiry timeout. |
void | clear virtual inline | Removes all items and their associated timeouts. |
{#timedmanager}
TimedManager
inline
inline TimedManager(uv::Loop * loop)
Constructs a TimedManager and starts the internal expiry-check timer.
Parameters
loopEvent loop used by the internal timer (default: process-wide default loop).
{#add}
add
inline
inline void add(constTKey & key, std::unique_ptr< TValue > item, long timeout)
Add an item which will expire (and be deleted) after the specified timeout value. If the timeout is 0 the item will be stored indefinitely. The TimedManager assumes ownership of the given pointer.
{#expires}
expires
virtual inline
virtual inline bool expires(constTKey & key, long timeout)
Update the item expiry timeout.
{#expires}
expires
virtual inline
virtual inline bool expires(TValue * item, long timeout)
Update the item expiry timeout.
{#clear}
clear
virtual inline
virtual inline void clear()
Removes all items and their associated timeouts.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::mutex | _tmutex | |
TimeoutMap | _timeouts | |
Timer | _timer |
{#_tmutex}
_tmutex
std::mutex _tmutex
{#_timeouts}
_timeouts
TimeoutMap _timeouts
{#_timer}
_timer
Timer _timer
Protected Methods
| Return | Name | Description |
|---|---|---|
bool | setTimeout virtual inline | Sets or removes the expiry timeout for a specific item pointer. If timeout > 0, starts a countdown; if timeout == 0, removes any existing timeout. |
void | onRemove virtual inline | Called when an item is removed from the collection. Erases the item's timeout entry and calls the base implementation. |
void | onTimeout virtual inline | Called when an item's timeout expires. Default implementation removes and deletes the item. |
void | onTimerUpdate inline | Internal timer callback; iterates all tracked timeouts and calls onTimeout() for any that have expired. |
{#settimeout}
setTimeout
virtual inline
virtual inline bool setTimeout(TValue * item, long timeout)
Sets or removes the expiry timeout for a specific item pointer. If timeout > 0, starts a countdown; if timeout == 0, removes any existing timeout.
Parameters
-
itemPointer to the managed item. -
timeoutDelay in milliseconds, or 0 to clear the timeout.
Returns
true on success.
Exceptions
std::logic_errorif item is nullptr.
{#onremove}
onRemove
virtual inline
virtual inline void onRemove(constTKey & key, TValue * item)
Called when an item is removed from the collection. Erases the item's timeout entry and calls the base implementation.
Parameters
-
keyKey of the removed item. -
itemPointer to the removed item.
{#ontimeout}
onTimeout
virtual inline
virtual inline void onTimeout(TValue * item)
Called when an item's timeout expires. Default implementation removes and deletes the item.
Parameters
itemPointer to the expired item.
{#ontimerupdate}
onTimerUpdate
inline
inline void onTimerUpdate()
Internal timer callback; iterates all tracked timeouts and calls onTimeout() for any that have expired.
Public Types
| Name | Description |
|---|---|
Base | |
TimeoutMap |
{#base}
Base
KeyedStore< TKey, TValue > Base()
{#timeoutmap}
TimeoutMap
std::map< TValue *, Timeout > TimeoutMap()
{#ipacketcreationstrategy}
IPacketCreationStrategy
#include <icy/packetfactory.h>
Subclassed by:
PacketCreationStrategy< PacketT >
Abstract strategy for creating typed packets from raw buffer data.
Public Methods
| Return | Name | Description |
|---|---|---|
IPacketCreationStrategy | Defaulted constructor. | |
IPacket * | create const | Attempts to create a typed packet from the given buffer. |
int | priority const | Returns the dispatch priority of this strategy (0–100; higher runs first). |
{#ipacketcreationstrategy}
IPacketCreationStrategy
IPacketCreationStrategy() = default
Defaulted constructor.
{#create}
create
const
IPacket * create(const ConstBuffer & buffer, size_t & nread) const
Attempts to create a typed packet from the given buffer.
Parameters
-
bufferRaw input data. -
nreadSet to the number of bytes consumed on success, 0 otherwise.
Returns
Newly allocated packet on success, nullptr if the buffer does not match.
{#priority}
priority
const
int priority() const
Returns the dispatch priority of this strategy (0–100; higher runs first).
{#packetfactory}
PacketFactory
#include <icy/packetfactory.h>
Priority-ordered factory that creates typed packets from raw buffers using registered strategies.
Public Methods
| Return | Name | Description |
|---|---|---|
PacketFactory | Defaulted constructor. | |
PacketFactory | Deleted constructor. | |
PacketFactory | Defaulted constructor. | |
void | registerPacketType inline | Registers a [PacketCreationStrategy](#packetcreationstrategy)<PacketT> at the given priority. Any previously registered strategy for PacketT is replaced. |
void | unregisterPacketType inline | Removes the [PacketCreationStrategy](#packetcreationstrategy)<PacketT> from the factory, if present. |
void | registerStrategy inline | Registers an arbitrary [IPacketCreationStrategy](#ipacketcreationstrategy) subclass at the given priority. Any previously registered instance of the same type is replaced. |
void | unregisterStrategy inline | Removes the StrategyT instance from the factory, if present. |
PacketCreationStrategyList & | types inline | #### Returns |
const PacketCreationStrategyList & | types const inline | #### Returns |
bool | onPacketCreated virtual inline | Called after a packet is successfully created by a strategy. Override to apply filtering; return false to reject the packet (it will be deleted). |
IPacket * | createPacket virtual inline | Iterates registered strategies in priority order and returns the first successfully created packet. |
{#packetfactory}
PacketFactory
PacketFactory() = default
Defaulted constructor.
{#packetfactory}
PacketFactory
PacketFactory(const PacketFactory &) = delete
Deleted constructor.
{#packetfactory}
PacketFactory
PacketFactory(PacketFactory &&) = default
Defaulted constructor.
{#registerpackettype}
registerPacketType
inline
template<class PacketT> inline void registerPacketType(int priority)
Registers a [PacketCreationStrategy](#packetcreationstrategy)<PacketT> at the given priority. Any previously registered strategy for PacketT is replaced.
Parameters
PacketTPacket type to register; must default-constructible with aread()method.
Parameters
priorityDispatch priority (0–100; higher runs first).
{#unregisterpackettype}
unregisterPacketType
inline
template<class PacketT> inline void unregisterPacketType()
Removes the [PacketCreationStrategy](#packetcreationstrategy)<PacketT> from the factory, if present.
Parameters
PacketTPacket type whose strategy should be removed.
{#registerstrategy}
registerStrategy
inline
template<class StrategyT> inline void registerStrategy(int priority)
Registers an arbitrary [IPacketCreationStrategy](#ipacketcreationstrategy) subclass at the given priority. Any previously registered instance of the same type is replaced.
Parameters
StrategyTStrategy type to instantiate; must accept a priority int in its constructor.
Parameters
priorityDispatch priority (0–100; higher runs first).
{#unregisterstrategy}
unregisterStrategy
inline
template<class StrategyT> inline void unregisterStrategy()
Removes the StrategyT instance from the factory, if present.
Parameters
StrategyTStrategy type to remove.
{#types}
types
inline
inline PacketCreationStrategyList & types()
Returns
Mutable reference to the ordered list of registered strategies.
{#types}
types
const inline
inline const PacketCreationStrategyList & types() const
Returns
Const reference to the ordered list of registered strategies.
{#onpacketcreated}
onPacketCreated
virtual inline
virtual inline bool onPacketCreated(IPacket * packet)
Called after a packet is successfully created by a strategy. Override to apply filtering; return false to reject the packet (it will be deleted).
Parameters
packetNewly created packet.
Returns
True to accept the packet, false to discard it and try the next strategy.
{#createpacket}
createPacket
virtual inline
virtual inline IPacket * createPacket(const ConstBuffer & buffer, size_t & nread)
Iterates registered strategies in priority order and returns the first successfully created packet.
Parameters
-
bufferRaw input data. -
nreadSet to the number of bytes consumed on success.
Returns
Newly allocated packet, or nullptr if no strategy matched.
Exceptions
std::logic_errorif no packet types have been registered.
Protected Attributes
| Return | Name | Description |
|---|---|---|
PacketCreationStrategyList | _types |
{#_types}
_types
PacketCreationStrategyList _types
Private Methods
| Return | Name | Description |
|---|---|---|
void | sortTypes inline |
{#sorttypes}
sortTypes
inline
inline void sortTypes()
{#streammanager}
StreamManager
#include <icy/streammanager.h>
Inherits:
string, PacketStream >
Manages a named collection of PacketStream instances with lifecycle callbacks.
Public Methods
| Return | Name | Description |
|---|---|---|
StreamManager | ||
bool | addStream | |
bool | addStream | |
bool | closeStream | |
void | closeAll | |
PacketStream * | getStream const | |
PacketStream * | getDefaultStream const | |
void | print const |
{#streammanager}
StreamManager
StreamManager()
{#addstream}
addStream
bool addStream(PacketStream * stream, bool whiny)
{#addstream}
addStream
bool addStream(std::unique_ptr< PacketStream > stream, bool whiny)
{#closestream}
closeStream
bool closeStream(const std::string & name, bool whiny)
{#closeall}
closeAll
void closeAll()
{#getstream}
getStream
const
PacketStream * getStream(const std::string & name, bool whiny) const
{#getdefaultstream}
getDefaultStream
const
PacketStream * getDefaultStream() const
{#print}
const
void print(std::ostream & os) const
Protected Methods
| Return | Name | Description |
|---|---|---|
void | onAdd virtual | Override for lifecycle reactions. |
void | onRemove virtual | |
void | onStreamStateChange | |
constchar * | className virtual const inline |
{#onadd}
onAdd
virtual
virtual void onAdd(const std::string &, PacketStream *)
Override for lifecycle reactions.
{#onremove}
onRemove
virtual
virtual void onRemove(const std::string &, PacketStream * stream)
{#onstreamstatechange}
onStreamStateChange
void onStreamStateChange(void * sender, PacketStreamState & state, constPacketStreamState &)
{#classname}
className
virtual const inline
virtual inline constchar * className() const
{#idiagnostic}
IDiagnostic
#include <icy/diagnosticmanager.h>
Inherits:
Stateful< DiagnosticState >Subclassed by:AsyncDiagnostic
Abstract interface for diagnostic information providers.
Public Attributes
| Return | Name | Description |
|---|---|---|
std::string | name | The name of the diagnostic. |
std::string | description | The diagnostic description. |
std::vector< std::string > | summary | The diagnostic summary, maybe including troubleshooting information on failure. |
ThreadSignal< void(const std::string &)> | SummaryUpdated | Signals when a new text item is added to the summary. |
{#name}
name
std::string name
The name of the diagnostic.
{#description}
description
std::string description
The diagnostic description.
{#summary}
summary
std::vector< std::string > summary
The diagnostic summary, maybe including troubleshooting information on failure.
{#summaryupdated}
SummaryUpdated
ThreadSignal< void(const std::string &)> SummaryUpdated
Signals when a new text item is added to the summary.
Public Methods
| Return | Name | Description |
|---|---|---|
IDiagnostic | ||
void | check virtual | Resets state to None and invokes run() to perform the diagnostic check. |
void | reset virtual | Clears the summary and resets state to None. |
bool | complete virtual const | Returns true if the diagnostic has reached a terminal state (Passed or Failed). |
bool | passed virtual const | Returns true if the diagnostic state is Passed. |
bool | failed virtual const | Returns true if the diagnostic state is Failed. |
{#idiagnostic}
IDiagnostic
IDiagnostic()
{#check}
check
virtual
virtual void check()
Resets state to None and invokes run() to perform the diagnostic check.
{#reset}
reset
virtual
virtual void reset()
Clears the summary and resets state to None.
{#complete}
complete
virtual const
virtual bool complete() const
Returns true if the diagnostic has reached a terminal state (Passed or Failed).
Returns
true if complete.
{#passed}
passed
virtual const
virtual bool passed() const
Returns true if the diagnostic state is Passed.
Returns
true if passed.
{#failed}
failed
virtual const
virtual bool failed() const
Returns true if the diagnostic state is Failed.
Returns
true if failed.
Protected Methods
| Return | Name | Description |
|---|---|---|
void | run | Override to implement diagnostic logic. |
bool | pass virtual | Transitions the state to Passed. |
bool | fail virtual | Transitions the state to Failed. |
void | addSummary virtual | Appends text to the summary list and emits SummaryUpdated. |
{#run}
run
void run()
Override to implement diagnostic logic.
The StateChange signal will dispatch diagnostic test results to delegates.
{#pass}
pass
virtual
virtual bool pass()
Transitions the state to Passed.
Returns
true if the state transition succeeded.
{#fail}
fail
virtual
virtual bool fail()
Transitions the state to Failed.
Returns
true if the state transition succeeded.
{#addsummary}
addSummary
virtual
virtual void addSummary(const std::string & text)
Appends text to the summary list and emits SummaryUpdated.
Parameters
textSummary line to append.
{#asyncdiagnostic}
AsyncDiagnostic
#include <icy/diagnosticmanager.h>
Inherits:
IDiagnostic,Runnable
Asynchronous diagnostic information collector.
Public Methods
| Return | Name | Description |
|---|---|---|
void | run | Override to implement diagnostic logic. |
void | check virtual inline | Resets the diagnostic and launches run() on a background thread. |
{#run}
run
void run()
Override to implement diagnostic logic.
The StateChange signal will dispatch diagnostic test results to delegates.
{#check}
check
virtual inline
virtual inline void check()
Resets the diagnostic and launches run() on a background thread.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Thread | _thread |
{#_thread}
_thread
Thread _thread
{#diagnosticmanager}
DiagnosticManager
#include <icy/diagnosticmanager.h>
Inherits:
string, IDiagnostic >
Registry and manager for diagnostic providers.
Public Attributes
| Return | Name | Description |
|---|---|---|
NullSignal | DiagnosticsComplete |
{#diagnosticscomplete}
DiagnosticsComplete
NullSignal DiagnosticsComplete
Public Methods
| Return | Name | Description |
|---|---|---|
DiagnosticManager | ||
bool | addDiagnostic | Adds a diagnostic, taking ownership. |
bool | freeDiagnostic | Removes and deletes the diagnostic registered under name. |
IDiagnostic * | getDiagnostic const | Returns the diagnostic or nullptr. |
void | resetAll | |
void | checkAll | |
bool | allComplete const | |
void | onDiagnosticStateChange |
{#diagnosticmanager}
DiagnosticManager
DiagnosticManager()
{#adddiagnostic}
addDiagnostic
bool addDiagnostic(std::unique_ptr< IDiagnostic > test)
Adds a diagnostic, taking ownership.
{#freediagnostic}
freeDiagnostic
bool freeDiagnostic(const std::string & name)
Removes and deletes the diagnostic registered under name.
{#getdiagnostic}
getDiagnostic
const
IDiagnostic * getDiagnostic(const std::string & name) const
Returns the diagnostic or nullptr.
{#resetall}
resetAll
void resetAll()
{#checkall}
checkAll
void checkAll()
{#allcomplete}
allComplete
const
bool allComplete() const
{#ondiagnosticstatechange}
onDiagnosticStateChange
void onDiagnosticStateChange(void *, DiagnosticState & state, constDiagnosticState &)
{#packettransaction}
PacketTransaction
#include <icy/packettransaction.h>
Inherits:
Sendable,Stateful< TransactionState >,RefCounted< PacketTransaction< PacketT > >Subclassed by:Transaction< Message >,Transaction< PacketT >
Request/response transaction with timeout and retry logic.
Lifetime is managed by IntrusivePtr via the RefCounted base class. The transaction is kept alive as long as at least one IntrusivePtr references it. The owning client holds a Ptr in its transaction list; callbacks should capture a Ptr copy to prevent premature deletion.
When a terminal state (Success or Failed) is reached, the transaction cleans up its timer but does NOT delete itself. The IntrusivePtr destructor handles deletion when the last reference is released.
Public Methods
| Return | Name | Description |
|---|---|---|
PacketTransaction inline | #### Parameters | |
PacketTransaction inline | #### Parameters | |
bool | send virtual inline | Starts the transaction timer and sends the request. Overriding classes should implement send logic here. |
void | cancel virtual inline | Cancellation means that the agent will not retransmit the request, will not treat the lack of response to be a failure, but will wait the duration of the transaction timeout for a response. Transitions the transaction to the Cancelled state. |
bool | cancelled const inline | #### Returns |
void | dispose virtual inline | Stops the timer and unregisters callbacks. Does NOT delete the object; the IntrusivePtr destructor handles deletion when the last reference is released. Safe to call multiple times. |
bool | disposed const inline | #### Returns |
bool | canResend virtual inline | #### Returns |
int | attempts const inline | #### Returns |
int | retries const inline | #### Returns |
PacketT & | request inline | #### Returns |
PacketT | request const inline | #### Returns |
PacketT & | response inline | #### Returns |
PacketT | response const inline | #### Returns |
{#packettransaction}
PacketTransaction
inline
inline PacketTransaction(long timeout, int retries, uv::Loop * loop)
Parameters
-
timeoutTransaction timeout in milliseconds before failure or retry. -
retriesMaximum number of retransmissions (0 means one attempt only). -
loopEvent loop for the timeout timer.
{#packettransaction}
PacketTransaction
inline
inline PacketTransaction(const PacketT & request, long timeout, int retries, uv::Loop * loop)
Parameters
-
requestInitial request packet to store and send. -
timeoutTransaction timeout in milliseconds before failure or retry. -
retriesMaximum number of retransmissions (0 means one attempt only). -
loopEvent loop for the timeout timer.
{#send}
send
virtual inline
virtual inline bool send()
Starts the transaction timer and sends the request. Overriding classes should implement send logic here.
{#cancel}
cancel
virtual inline
virtual inline void cancel()
Cancellation means that the agent will not retransmit the request, will not treat the lack of response to be a failure, but will wait the duration of the transaction timeout for a response. Transitions the transaction to the Cancelled state.
{#cancelled}
cancelled
const inline
inline bool cancelled() const
Returns
True if the transaction is in the Cancelled state.
{#dispose}
dispose
virtual inline
virtual inline void dispose()
Stops the timer and unregisters callbacks. Does NOT delete the object; the IntrusivePtr destructor handles deletion when the last reference is released. Safe to call multiple times.
{#disposed}
disposed
const inline
inline bool disposed() const
Returns
True if dispose() has been called.
{#canresend}
canResend
virtual inline
virtual inline bool canResend()
Returns
True if the transaction is not cancelled and has attempts remaining.
{#attempts}
attempts
const inline
inline int attempts() const
Returns
The number of times [send()](#classicy_1_1PacketTransaction_1acf7a9bbcfff95999c0c227cb36f9cfd4) has been called for this transaction.
{#retries}
retries
const inline
inline int retries() const
Returns
The configured maximum number of retransmissions.
{#request}
request
inline
inline PacketT & request()
Returns
Mutable reference to the outgoing request packet.
{#request}
request
const inline
inline PacketT request() const
Returns
Copy of the outgoing request packet.
{#response}
response
inline
inline PacketT & response()
Returns
Mutable reference to the received response packet.
{#response}
response
const inline
inline PacketT response() const
Returns
Copy of the received response packet.
Protected Attributes
| Return | Name | Description |
|---|---|---|
PacketT | _request | |
PacketT | _response | |
Timer | _timer | The request timeout callback. |
int | _retries | The maximum number of attempts before the transaction is considered failed. |
int | _attempts | The number of times the transaction has been sent. |
bool | _disposed |
{#_request}
_request
PacketT _request
{#_response}
_response
PacketT _response
{#_timer}
_timer
Timer _timer
The request timeout callback.
{#_retries}
_retries
int _retries
The maximum number of attempts before the transaction is considered failed.
{#_attempts}
_attempts
int _attempts
The number of times the transaction has been sent.
{#_disposed}
_disposed
bool _disposed = false
Protected Methods
| Return | Name | Description |
|---|---|---|
void | onStateChange virtual inline | Post state change hook. Calls dispose() on terminal states to stop the timer, but does not delete the object; IntrusivePtr handles that. |
bool | handlePotentialResponse virtual inline | Processes a potential response candidate and updates the state accordingly. |
bool | checkResponse | Checks a potential response candidate and returns true on successful match. |
void | onResponse virtual inline | Called when a successful response is received. |
void | onTimeout virtual inline | Called by the timer when the transaction timeout elapses. Retransmits if retries remain, otherwise transitions to Failed. |
{#onstatechange}
onStateChange
virtual inline
virtual inline void onStateChange(TransactionState & state, const TransactionState &)
Post state change hook. Calls dispose() on terminal states to stop the timer, but does not delete the object; IntrusivePtr handles that.
{#handlepotentialresponse}
handlePotentialResponse
virtual inline
virtual inline bool handlePotentialResponse(const PacketT & packet)
Processes a potential response candidate and updates the state accordingly.
{#checkresponse}
checkResponse
bool checkResponse(const PacketT & packet)
Checks a potential response candidate and returns true on successful match.
{#onresponse}
onResponse
virtual inline
virtual inline void onResponse()
Called when a successful response is received.
{#ontimeout}
onTimeout
virtual inline
virtual inline void onTimeout()
Called by the timer when the transaction timeout elapses. Retransmits if retries remain, otherwise transitions to Failed.
Public Types
| Name | Description |
|---|---|
Ptr |
{#ptr}
Ptr
IntrusivePtr< PacketTransaction< PacketT > > Ptr()
{#task}
Task
#include <icy/task.h>
Abstract base class for implementing asynchronous tasks.
Tasks are designed to be run by a TaskRunner.
Public Methods
| Return | Name | Description |
|---|---|---|
Task | #### Parameters | |
void | destroy virtual | Sets the task to destroyed state. |
bool | destroyed virtual const | Signals that the task should be disposed of. |
bool | repeating virtual const | Signals that the task should be called repeatedly by the TaskRunner. If this returns false the task will be cancelled. |
uint32_t | id virtual const | Unique task ID. |
Task | Deleted constructor. | |
Task | Deleted constructor. |
{#task}
Task
Task(bool repeat)
Parameters
repeatIf true, the[TaskRunner](#taskrunner)will call[run()](#classicy_1_1Task_1a27c42c43ba0ce7ea66f3210fdd27f3de)repeatedly; if false, the task is cancelled after one execution.
{#destroy}
destroy
virtual
virtual void destroy()
Sets the task to destroyed state.
{#destroyed}
destroyed
virtual const
virtual bool destroyed() const
Signals that the task should be disposed of.
{#repeating}
repeating
virtual const
virtual bool repeating() const
Signals that the task should be called repeatedly by the TaskRunner. If this returns false the task will be cancelled.
{#id}
id
virtual const
virtual uint32_t id() const
Unique task ID.
{#task}
Task
Task(const Task & task) = delete
Deleted constructor.
{#task}
Task
Task(Task &&) = delete
Deleted constructor.
Protected Attributes
| Return | Name | Description |
|---|---|---|
uint32_t | _id | |
bool | _repeating | |
bool | _destroyed |
{#_id}
_id
uint32_t _id
{#_repeating}
_repeating
bool _repeating
{#_destroyed}
_destroyed
bool _destroyed
Protected Methods
| Return | Name | Description |
|---|---|---|
void | run | Called by the TaskRunner to run the task. Override this method to implement task action. Returning true means the task should be called again, and false will cause the task to be destroyed. The task will similarly be destroyed if destroy() was called during the current task iteration. |
{#run}
run
void run()
Called by the TaskRunner to run the task. Override this method to implement task action. Returning true means the task should be called again, and false will cause the task to be destroyed. The task will similarly be destroyed if destroy() was called during the current task iteration.
{#taskrunner}
TaskRunner
#include <icy/task.h>
Runner for tasks that inherit the [Task](#task) interface.
The [TaskRunner](#taskrunner) continually loops through each task in the task list calling the task's [run()](#classicy_1_1TaskRunner_1a99cef8fc7be815ddd9c151dd4d6985d2) method.
The [TaskRunner](#taskrunner) is powered by an abstract [Runner](#runner) instance, which means that tasks can be executed in a thread or event loop context.
Public Attributes
| Return | Name | Description |
|---|---|---|
NullSignal | Idle | Fires after completing an iteration of all tasks. |
NullSignal | Shutdown | Signals when the [TaskRunner](#taskrunner) is shutting down. |
{#idle}
Idle
NullSignal Idle
Fires after completing an iteration of all tasks.
{#shutdown}
Shutdown
NullSignal Shutdown
Signals when the [TaskRunner](#taskrunner) is shutting down.
Public Methods
| Return | Name | Description |
|---|---|---|
TaskRunner | #### Parameters | |
TaskRunner | Deleted constructor. | |
TaskRunner | Deleted constructor. | |
bool | start virtual | Starts a task, adding it if it doesn't exist. |
bool | cancel virtual | Cancels a task. |
bool | destroy virtual | Queues a task for destruction. |
bool | exists virtual const | Returns whether a task exists. |
Task * | get virtual const | Returns the task pointer matching the given ID, or nullptr if no task exists. |
void | setRunner virtual | Set the asynchronous context for packet processing. This may be a Thread or another derivative of Async. Must be set before the stream is activated. |
const char * | className virtual const inline |
{#taskrunner}
TaskRunner
TaskRunner(std::shared_ptr< Runner > runner)
Parameters
runnerAsync runner to drive task execution; defaults to a new[Thread](#thread).
{#taskrunner}
TaskRunner
TaskRunner(const TaskRunner &) = delete
Deleted constructor.
{#taskrunner}
TaskRunner
TaskRunner(TaskRunner &&) = delete
Deleted constructor.
{#start}
start
virtual
virtual bool start(Task * task)
Starts a task, adding it if it doesn't exist.
{#cancel}
cancel
virtual
virtual bool cancel(Task * task)
Cancels a task.
The task reference will be managed by the TaskRunner until the task is destroyed.
{#destroy}
destroy
virtual
virtual bool destroy(Task * task)
Queues a task for destruction.
{#exists}
exists
virtual const
virtual bool exists(Task * task) const
Returns whether a task exists.
{#get}
get
virtual const
virtual Task * get(uint32_t id) const
Returns the task pointer matching the given ID, or nullptr if no task exists.
{#setrunner}
setRunner
virtual
virtual void setRunner(std::shared_ptr< Runner > runner)
Set the asynchronous context for packet processing. This may be a Thread or another derivative of Async. Must be set before the stream is activated.
{#classname}
className
virtual const inline
virtual inline const char * className() const
Public Static Methods
| Return | Name | Description |
|---|---|---|
TaskRunner & | getDefault static | Returns the default [TaskRunner](#taskrunner) singleton, although TaskRunner instances may be initialized individually. The default runner should be kept for short running tasks such as timers in order to maintain performance. |
{#getdefault}
getDefault
static
static TaskRunner & getDefault()
Returns the default [TaskRunner](#taskrunner) singleton, although TaskRunner instances may be initialized individually. The default runner should be kept for short running tasks such as timers in order to maintain performance.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::mutex | _mutex | |
std::shared_ptr< Runner > | _runner | |
TaskList | _tasks |
{#_mutex}
_mutex
std::mutex _mutex
{#_runner}
_runner
std::shared_ptr< Runner > _runner
{#_tasks}
_tasks
TaskList _tasks
Protected Methods
| Return | Name | Description |
|---|---|---|
void | run virtual | Called by the async context to run the next task. |
bool | add virtual | Adds a task to the runner. |
bool | remove virtual | Removes a task from the runner. |
Task * | next virtual const | Returns the next task to be run. |
void | clear virtual | Destroys and clears all manages tasks. |
void | onAdd virtual | Called after a task is added. |
void | onStart virtual | Called after a task is started. |
void | onCancel virtual | Called after a task is cancelled. |
void | onRemove virtual | Called after a task is removed. |
void | onRun virtual | Called after a task has run. |
{#run}
run
virtual
virtual void run()
Called by the async context to run the next task.
{#add}
add
virtual
virtual bool add(Task * task)
Adds a task to the runner.
{#remove}
remove
virtual
virtual bool remove(Task * task)
Removes a task from the runner.
{#next}
next
virtual const
virtual Task * next() const
Returns the next task to be run.
{#clear}
clear
virtual
virtual void clear()
Destroys and clears all manages tasks.
{#onadd}
onAdd
virtual
virtual void onAdd(Task * task)
Called after a task is added.
{#onstart}
onStart
virtual
virtual void onStart(Task * task)
Called after a task is started.
{#oncancel}
onCancel
virtual
virtual void onCancel(Task * task)
Called after a task is cancelled.
{#onremove}
onRemove
virtual
virtual void onRemove(Task * task)
Called after a task is removed.
{#onrun}
onRun
virtual
virtual void onRun(Task * task)
Called after a task has run.
{#ipacket}
IPacket
#include <icy/packet.h>
Subclassed by:
FlagPacket,RawPacket,Message,Message
The basic packet type which is passed around the icey system. IPacket can be extended for each protocol to enable polymorphic processing and callbacks using PacketStream and friends.
Public Attributes
| Return | Name | Description |
|---|---|---|
std::any | opaque | Optional type-safe context data. Use std::any_cast to retrieve. Lifetime of the stored value is tied to the packet's lifetime. |
std::unique_ptr< IPacketInfo > | info | Optional extra information about the packet. |
Bitwise | flags | Provides basic information about the packet. |
{#opaque}
opaque
std::any opaque
Optional type-safe context data. Use std::any_cast to retrieve. Lifetime of the stored value is tied to the packet's lifetime.
{#info}
info
std::unique_ptr< IPacketInfo > info
Optional extra information about the packet.
{#flags}
flags
Bitwise flags
Provides basic information about the packet.
Public Methods
| Return | Name | Description |
|---|---|---|
IPacket inline | #### Parameters | |
IPacket inline | Copy constructor; clones the info object if present. | |
IPacket & | operator= inline | Copy assignment; clones the info object if present. |
std::unique_ptr< IPacket > | clone const | Returns a heap-allocated deep copy of this packet. |
ssize_t | read | Read/parse to the packet from the given input buffer. The number of bytes read is returned. |
void | write const | Copy/generate to the packet given output buffer. The number of bytes written can be obtained from the buffer. |
size_t | size virtual const inline | The size of the packet in bytes. |
bool | hasData virtual const inline | Returns true if the packet has a non-null data pointer. |
char * | data virtual const inline | The packet data pointer for buffered packets. |
const void * | constData virtual const inline | The const packet data pointer for buffered packets. |
const char * | className const | Returns the class name of this packet type for logging and diagnostics. |
void | print virtual const inline | Prints a human-readable representation to the given stream. |
{#ipacket}
IPacket
inline
inline IPacket(std::unique_ptr< IPacketInfo > info, unsigned flags)
Parameters
-
infoOptional packet info; ownership transferred. -
flagsInitial bitwise flags.
{#ipacket}
IPacket
inline
inline IPacket(const IPacket & r)
Copy constructor; clones the info object if present.
Parameters
rSource packet.
{#operator}
operator=
inline
inline IPacket & operator=(const IPacket & r)
Copy assignment; clones the info object if present.
Parameters
rSource packet.
Returns
Reference to this packet.
{#clone}
clone
const
std::unique_ptr< IPacket > clone() const
Returns a heap-allocated deep copy of this packet.
Returns
Owning pointer to the cloned packet.
{#read}
read
ssize_t read(const ConstBuffer &)
Read/parse to the packet from the given input buffer. The number of bytes read is returned.
{#write}
write
const
void write(Buffer &) const
Copy/generate to the packet given output buffer. The number of bytes written can be obtained from the buffer.
Todo: It may be preferable to use our pod types here instead of buffer input, but the current codebase requires that the buffer be dynamically resizable for some protocols...
{#size}
size
virtual const inline
virtual inline size_t size() const
The size of the packet in bytes.
This is the number of bytes that will be written on a call to write(), but may not be the number of bytes that will be consumed by read().
{#hasdata}
hasData
virtual const inline
virtual inline bool hasData() const
Returns true if the packet has a non-null data pointer.
{#data}
data
virtual const inline
virtual inline char * data() const
The packet data pointer for buffered packets.
{#constdata}
constData
virtual const inline
virtual inline const void * constData() const
The const packet data pointer for buffered packets.
{#classname}
className
const
const char * className() const
Returns the class name of this packet type for logging and diagnostics.
{#print}
virtual const inline
virtual inline void print(std::ostream & os) const
Prints a human-readable representation to the given stream.
Parameters
osOutput stream.
{#flagpacket}
FlagPacket
#include <icy/packet.h>
Inherits:
IPacket
Packet for sending bitwise flags along the packet stream.
Public Methods
| Return | Name | Description |
|---|---|---|
FlagPacket inline | #### Parameters | |
std::unique_ptr< IPacket > | clone virtual const inline | #### Returns |
FlagPacket inline | #### Parameters | |
ssize_t | read virtual inline | No-op read; FlagPacket carries no payload data. |
void | write virtual const inline | No-op write; FlagPacket carries no payload data. |
const char * | className virtual const inline | Returns the class name of this packet type for logging and diagnostics. |
{#flagpacket}
FlagPacket
inline
inline FlagPacket(unsigned flags)
Parameters
flagsBitwise flags to carry in this packet.
{#clone}
clone
virtual const inline
virtual inline std::unique_ptr< IPacket > clone() const
Returns
Owning pointer to a deep copy of this packet.
{#flagpacket}
FlagPacket
inline
inline FlagPacket(const FlagPacket & that)
Parameters
thatSource packet to copy from.
{#read}
read
virtual inline
virtual inline ssize_t read(const ConstBuffer &)
No-op read; FlagPacket carries no payload data.
Returns
Always returns true (1).
{#write}
write
virtual const inline
virtual inline void write(Buffer &) const
No-op write; FlagPacket carries no payload data.
{#classname}
className
virtual const inline
virtual inline const char * className() const
Returns the class name of this packet type for logging and diagnostics.
{#rawpacket}
RawPacket
#include <icy/packet.h>
Inherits:
IPacketSubclassed by:MediaPacket,SocketPacket
RawPacket is the default data packet type which consists of an optionally managed char pointer and a size value.
Public Methods
| Return | Name | Description |
|---|---|---|
RawPacket inline | Construct with borrowed (non-owning) buffer. | |
RawPacket inline | Construct with const data (copied, owning). | |
RawPacket inline | Copy constructor (always copies data). | |
std::unique_ptr< IPacket > | clone virtual const inline | #### Returns |
void | copyData virtual inline | Copies data into an internally owned buffer, replacing any prior content. |
ssize_t | read virtual inline | Reads from the buffer by copying its contents into an owned buffer. |
void | write virtual const inline | Appends the packet data to the given output buffer. |
char * | data virtual const inline | #### Returns |
size_t | size virtual const inline | #### Returns |
const char * | className virtual const inline | Returns the class name of this packet type for logging and diagnostics. |
bool | ownsBuffer const inline | #### Returns |
{#rawpacket}
RawPacket
inline
inline RawPacket(char * data, size_t size, unsigned flags, std::unique_ptr< IPacketInfo > info)
Construct with borrowed (non-owning) buffer.
{#rawpacket}
RawPacket
inline
inline RawPacket(const char * data, size_t size, unsigned flags, std::unique_ptr< IPacketInfo > info)
Construct with const data (copied, owning).
{#rawpacket}
RawPacket
inline
inline RawPacket(const RawPacket & that)
Copy constructor (always copies data).
{#clone}
clone
virtual const inline
virtual inline std::unique_ptr< IPacket > clone() const
Returns
Owning pointer to a deep copy of this packet (always copies data).
{#copydata}
copyData
virtual inline
virtual inline void copyData(const void * data, size_t size)
Copies data into an internally owned buffer, replacing any prior content.
Parameters
-
dataSource data pointer. -
sizeNumber of bytes to copy.
{#read}
read
virtual inline
virtual inline ssize_t read(const ConstBuffer & buf)
Reads from the buffer by copying its contents into an owned buffer.
Parameters
bufInput buffer to read from.
Returns
Number of bytes consumed (equal to buf.size()).
{#write}
write
virtual const inline
virtual inline void write(Buffer & buf) const
Appends the packet data to the given output buffer.
Parameters
bufBuffer to write into.
{#data}
data
virtual const inline
virtual inline char * data() const
Returns
Mutable pointer to the raw packet data, or nullptr if empty.
{#size}
size
virtual const inline
virtual inline size_t size() const
Returns
Size of the packet data in bytes.
{#classname}
className
virtual const inline
virtual inline const char * className() const
Returns the class name of this packet type for logging and diagnostics.
{#ownsbuffer}
ownsBuffer
const inline
inline bool ownsBuffer() const
Returns
True if this packet owns (manages) its data buffer.
Protected Attributes
| Return | Name | Description |
|---|---|---|
char * | _data | |
size_t | _size | |
std::unique_ptr< char[]> | _owned |
{#_data}
_data
char * _data
{#_size}
_size
size_t _size
{#_owned}
_owned
std::unique_ptr< char[]> _owned
{#configuration}
Configuration
#include <icy/configuration.h>
Subclassed by:
Configuration
Configuration is an abstract base class for managing different kinds of configuration storage back ends such as JSON, XML, or database.
Subclasses must override the getRaw() and setRaw() and methods.
This class is safe for multithreaded use.
Public Attributes
| Return | Name | Description |
|---|---|---|
ThreadSignal< void(const std::string &, const std::string &)> | PropertyChanged | The Key and Value of the changed configuration property. |
{#propertychanged}
PropertyChanged
ThreadSignal< void(const std::string &, const std::string &)> PropertyChanged
The Key and Value of the changed configuration property.
Public Methods
| Return | Name | Description |
|---|---|---|
Configuration | Creates the Configuration. | |
~Configuration virtual | Destroys the Configuration. | |
bool | exists const | Returns true if the property with the given key exists. |
std::string | getString const | Returns the string value of the property with the given name. Throws a NotFoundException if the key does not exist. |
std::string | getString const | If a property with the given key exists, returns the property's string value, otherwise returns the given default value. |
std::string | getRawString const | Returns the raw string value of the property with the given name. Throws a NotFoundException if the key does not exist. References to other properties are not expanded. |
std::string | getRawString const | If a property with the given key exists, returns the property's raw string value, otherwise returns the given default value. References to other properties are not expanded. |
int | getInt const | Returns the int value of the property with the given name. Throws a NotFoundException if the key does not exist. Throws a SyntaxException if the property can not be converted to an int. Numbers starting with 0x are treated as hexadecimal. |
int | getInt const | If a property with the given key exists, returns the property's int value, otherwise returns the given default value. Throws a SyntaxException if the property can not be converted to an int. Numbers starting with 0x are treated as hexadecimal. |
std::int64_t | getLargeInt const | Returns the int value of the property with the given name. Throws a NotFoundException if the key does not exist. Throws a SyntaxException if the property can not be converted to an int. Numbers starting with 0x are treated as hexadecimal. |
std::int64_t | getLargeInt const | If a property with the given key exists, returns the property's int value, otherwise returns the given default value. Throws a SyntaxException if the property can not be converted to an int. Numbers starting with 0x are treated as hexadecimal. |
double | getDouble const | Returns the double value of the property with the given name. Throws a NotFoundException if the key does not exist. Throws a SyntaxException if the property can not be converted to a double. |
double | getDouble const | If a property with the given key exists, returns the property's double value, otherwise returns the given default value. Throws a SyntaxException if the property can not be converted to an double. |
bool | getBool const | Returns the double value of the property with the given name. Throws a NotFoundException if the key does not exist. Throws a SyntaxException if the property can not be converted to a double. |
bool | getBool const | If a property with the given key exists, returns the property's bool value, otherwise returns the given default value. Throws a SyntaxException if the property can not be converted to a boolean. The following string values can be converted into a boolean: |
void | setString | Sets the property with the given key to the given value. An already existing value for the key is overwritten. |
void | setInt | Sets the property with the given key to the given value. An already existing value for the key is overwritten. |
void | setLargeInt | Sets the property with the given key to the given value. An already existing value for the key is overwritten. |
void | setDouble | Sets the property with the given key to the given value. An already existing value for the key is overwritten. |
void | setBool | Sets the property with the given key to the given value. An already existing value for the key is overwritten. |
{#configuration}
Configuration
Configuration()
Creates the Configuration.
{#configuration}
~Configuration
virtual
virtual ~Configuration()
Destroys the Configuration.
{#exists}
exists
const
bool exists(const std::string & key) const
Returns true if the property with the given key exists.
{#getstring}
getString
const
std::string getString(const std::string & key) const
Returns the string value of the property with the given name. Throws a NotFoundException if the key does not exist.
{#getstring}
getString
const
std::string getString(const std::string & key, const std::string & defaultValue) const
If a property with the given key exists, returns the property's string value, otherwise returns the given default value.
{#getrawstring}
getRawString
const
std::string getRawString(const std::string & key) const
Returns the raw string value of the property with the given name. Throws a NotFoundException if the key does not exist. References to other properties are not expanded.
{#getrawstring}
getRawString
const
std::string getRawString(const std::string & key, const std::string & defaultValue) const
If a property with the given key exists, returns the property's raw string value, otherwise returns the given default value. References to other properties are not expanded.
{#getint}
getInt
const
int getInt(const std::string & key) const
Returns the int value of the property with the given name. Throws a NotFoundException if the key does not exist. Throws a SyntaxException if the property can not be converted to an int. Numbers starting with 0x are treated as hexadecimal.
{#getint}
getInt
const
int getInt(const std::string & key, int defaultValue) const
If a property with the given key exists, returns the property's int value, otherwise returns the given default value. Throws a SyntaxException if the property can not be converted to an int. Numbers starting with 0x are treated as hexadecimal.
{#getlargeint}
getLargeInt
const
std::int64_t getLargeInt(const std::string & key) const
Returns the int value of the property with the given name. Throws a NotFoundException if the key does not exist. Throws a SyntaxException if the property can not be converted to an int. Numbers starting with 0x are treated as hexadecimal.
{#getlargeint}
getLargeInt
const
std::int64_t getLargeInt(const std::string & key, std::int64_t defaultValue) const
If a property with the given key exists, returns the property's int value, otherwise returns the given default value. Throws a SyntaxException if the property can not be converted to an int. Numbers starting with 0x are treated as hexadecimal.
{#getdouble}
getDouble
const
double getDouble(const std::string & key) const
Returns the double value of the property with the given name. Throws a NotFoundException if the key does not exist. Throws a SyntaxException if the property can not be converted to a double.
{#getdouble}
getDouble
const
double getDouble(const std::string & key, double defaultValue) const
If a property with the given key exists, returns the property's double value, otherwise returns the given default value. Throws a SyntaxException if the property can not be converted to an double.
{#getbool}
getBool
const
bool getBool(const std::string & key) const
Returns the double value of the property with the given name. Throws a NotFoundException if the key does not exist. Throws a SyntaxException if the property can not be converted to a double.
{#getbool}
getBool
const
bool getBool(const std::string & key, bool defaultValue) const
If a property with the given key exists, returns the property's bool value, otherwise returns the given default value. Throws a SyntaxException if the property can not be converted to a boolean. The following string values can be converted into a boolean:
-
numerical values: non zero becomes true, zero becomes false
-
strings: true, yes, on become true, false, no, off become false Case does not matter.
{#setstring}
setString
void setString(const std::string & key, const std::string & value)
Sets the property with the given key to the given value. An already existing value for the key is overwritten.
{#setint}
setInt
void setInt(const std::string & key, int value)
Sets the property with the given key to the given value. An already existing value for the key is overwritten.
{#setlargeint}
setLargeInt
void setLargeInt(const std::string & key, std::int64_t value)
Sets the property with the given key to the given value. An already existing value for the key is overwritten.
{#setdouble}
setDouble
void setDouble(const std::string & key, double value)
Sets the property with the given key to the given value. An already existing value for the key is overwritten.
{#setbool}
setBool
void setBool(const std::string & key, bool value)
Sets the property with the given key to the given value. An already existing value for the key is overwritten.
Protected Methods
| Return | Name | Description |
|---|---|---|
bool | getRaw const | If the property with the given key exists, stores the property's value in value and returns true. Otherwise, returns false. |
void | setRaw | Sets the property with the given key to the given value. An already existing value for the key is overwritten. |
Configuration | Deleted constructor. | |
Configuration | Deleted constructor. |
{#getraw}
getRaw
const
bool getRaw(const std::string & key, std::string & value) const
If the property with the given key exists, stores the property's value in value and returns true. Otherwise, returns false.
Must be overridden by subclasses.
{#setraw}
setRaw
void setRaw(const std::string & key, const std::string & value)
Sets the property with the given key to the given value. An already existing value for the key is overwritten.
The implementation is responsible for emitting the PropertyChanged signal.
{#configuration}
Configuration
Configuration(const Configuration &) = delete
Deleted constructor.
{#configuration}
Configuration
Configuration(Configuration &&) = delete
Deleted constructor.
Private Attributes
| Return | Name | Description |
|---|---|---|
std::mutex | _mutex |
{#_mutex}
_mutex
std::mutex _mutex
{#scopedconfiguration}
ScopedConfiguration
#include <icy/configuration.h>
ScopedConfiguration provides multiple levels of configuration for a module. Multiple levels means that there is a module level scope, and a default scope. When a property is accessed, the module scope value will be used if available, otherwise the default scope value will be used.
Example scoping: Module: channels.[name].modes.[name].[value] Default: modes.[name].[value]
Public Attributes
| Return | Name | Description |
|---|---|---|
Configuration & | config | |
std::string | currentScope | |
std::string | defaultScope |
{#config}
config
Configuration & config
{#currentscope}
currentScope
std::string currentScope
{#defaultscope}
defaultScope
std::string defaultScope
Public Methods
| Return | Name | Description |
|---|---|---|
ScopedConfiguration | #### Parameters | |
ScopedConfiguration | ||
std::string | getString const | Returns the string value, trying currentScope first then defaultScope. |
int | getInt const | Returns the int value, trying currentScope first then defaultScope. |
double | getDouble const | Returns the double value, trying currentScope first then defaultScope. |
bool | getBool const | Returns the bool value, trying currentScope first then defaultScope. |
void | setString | Writes a string value under the scoped key. |
void | setInt | Writes an int value under the scoped key. |
void | setDouble | Writes a double value under the scoped key. |
void | setBool | Writes a bool value under the scoped key. |
std::string | getCurrentScope const | #### Parameters |
std::string | getDafaultKey const | #### Parameters |
std::string | getScopedKey const | #### Parameters |
{#scopedconfiguration}
ScopedConfiguration
ScopedConfiguration(Configuration & config, const std::string & currentScope, const std::string & defaultScope)
Parameters
-
configBacking configuration store. -
currentScopeKey prefix for the module-level scope. -
defaultScopeKey prefix for the default/fallback scope.
{#scopedconfiguration}
ScopedConfiguration
ScopedConfiguration(const ScopedConfiguration & that)
{#getstring}
getString
const
std::string getString(const std::string & key, const std::string & defaultValue, bool forceDefaultScope) const
Returns the string value, trying currentScope first then defaultScope.
Parameters
-
keyProperty key (without scope prefix). -
defaultValueFallback when neither scope has the key. -
forceDefaultScopeIf true, skipscurrentScopeand reads fromdefaultScopeonly.
Returns
Property value or defaultValue.
{#getint}
getInt
const
int getInt(const std::string & key, int defaultValue, bool forceDefaultScope) const
Returns the int value, trying currentScope first then defaultScope.
Parameters
-
keyProperty key (without scope prefix). -
defaultValueFallback when neither scope has the key. -
forceDefaultScopeIf true, reads fromdefaultScopeonly.
Returns
Property value or defaultValue.
{#getdouble}
getDouble
const
double getDouble(const std::string & key, double defaultValue, bool forceDefaultScope) const
Returns the double value, trying currentScope first then defaultScope.
Parameters
-
keyProperty key (without scope prefix). -
defaultValueFallback when neither scope has the key. -
forceDefaultScopeIf true, reads fromdefaultScopeonly.
Returns
Property value or defaultValue.
{#getbool}
getBool
const
bool getBool(const std::string & key, bool defaultValue, bool forceDefaultScope) const
Returns the bool value, trying currentScope first then defaultScope.
Parameters
-
keyProperty key (without scope prefix). -
defaultValueFallback when neither scope has the key. -
forceDefaultScopeIf true, reads fromdefaultScopeonly.
Returns
Property value or defaultValue.
{#setstring}
setString
void setString(const std::string & key, const std::string & value, bool defaultScope)
Writes a string value under the scoped key.
Parameters
-
keyProperty key (without scope prefix). -
valueValue to store. -
defaultScopeIf true, writes todefaultScope; otherwise tocurrentScope.
{#setint}
setInt
void setInt(const std::string & key, int value, bool defaultScope)
Writes an int value under the scoped key.
Parameters
-
keyProperty key (without scope prefix). -
valueValue to store. -
defaultScopeIf true, writes todefaultScope; otherwise tocurrentScope.
{#setdouble}
setDouble
void setDouble(const std::string & key, double value, bool defaultScope)
Writes a double value under the scoped key.
Parameters
-
keyProperty key (without scope prefix). -
valueValue to store. -
defaultScopeIf true, writes todefaultScope; otherwise tocurrentScope.
{#setbool}
setBool
void setBool(const std::string & key, bool value, bool defaultScope)
Writes a bool value under the scoped key.
Parameters
-
keyProperty key (without scope prefix). -
valueValue to store. -
defaultScopeIf true, writes todefaultScope; otherwise tocurrentScope.
{#getcurrentscope}
getCurrentScope
const
std::string getCurrentScope(const std::string & key) const
Parameters
keyProperty key (without scope prefix).
Returns
Fully qualified key in currentScope.
{#getdafaultkey}
getDafaultKey
const
std::string getDafaultKey(const std::string & key) const
Parameters
keyProperty key (without scope prefix).
Returns
Fully qualified key in defaultScope.
{#getscopedkey}
getScopedKey
const
std::string getScopedKey(const std::string & key, bool defaultScope) const
Parameters
-
keyProperty key (without scope prefix). -
defaultScopeIf true, returns thedefaultScopekey; otherwisecurrentScopekey.
Returns
Fully qualified scoped key string.
{#error}
Error
#include <icy/error.h>
Basic error type.
Errors contain an error code, message, and exception pointer.
Public Attributes
| Return | Name | Description |
|---|---|---|
int | err | |
std::string | message | |
std::exception_ptr | exception |
{#err}
err
int err
{#message}
message
std::string message
{#exception}
exception
std::exception_ptr exception
Public Methods
| Return | Name | Description |
|---|---|---|
Error inline | Default constructor; initializes all fields to a no-error state. | |
Error inline | Constructs an error with the given message string. | |
Error inline | Constructs an error with the given C string message. | |
bool | any const inline | Returns true if any error condition is set (non-zero code, non-empty message, or exception). |
void | reset inline | Clears all error fields, resetting to a no-error state. |
void | rethrow inline | Re-throws the stored exception pointer if one is set. Has no effect if exception is null. |
{#error}
Error
inline
inline Error()
Default constructor; initializes all fields to a no-error state.
{#error}
Error
inline
inline Error(const std::string & msg)
Constructs an error with the given message string.
Parameters
msgHuman-readable error description.
{#error}
Error
inline
inline Error(const char * msg)
Constructs an error with the given C string message.
Parameters
msgHuman-readable error description.
{#any}
any
const inline
inline bool any() const
Returns true if any error condition is set (non-zero code, non-empty message, or exception).
Returns
True if an error is present.
{#reset}
reset
inline
inline void reset()
Clears all error fields, resetting to a no-error state.
{#rethrow}
rethrow
inline
inline void rethrow()
Re-throws the stored exception pointer if one is set. Has no effect if exception is null.
{#logstream}
LogStream
#include <icy/logger.h>
No-op log record used when logging is compiled out.
Public Methods
| Return | Name | Description |
|---|---|---|
LogStream inline | ||
LogStream inline | ||
void | write inline | |
LogStream & | operator<< inline | |
LogStream & | operator<< inline |
{#logstream}
LogStream
inline
inline LogStream(Level level, std::string realm, int line, const char * channel)
{#logstream}
LogStream
inline
inline LogStream(const LogStream & that)
{#write}
write
inline
template<typename... Args> inline void write(Args... args)
{#operator}
operator<<
inline
template<typename T> inline LogStream & operator<<(const T &)
{#operator}
operator<<
inline
inline LogStream & operator<<(std::ostream &(*)(std::ostream &) f)
{#nullsharedmutex}
NullSharedMutex
#include <icy/signal.h>
No-op mutex for single-threaded signal usage. When all signal operations occur on a single libuv event loop thread, the shared_mutex is unnecessary overhead.
Public Methods
| Return | Name | Description |
|---|---|---|
void | lock inline | |
void | unlock inline | |
void | lock_shared inline | |
void | unlock_shared inline |
{#lock}
lock
inline
inline void lock()
{#unlock}
unlock
inline
inline void unlock()
{#lock_shared}
lock_shared
inline
inline void lock_shared()
{#unlock_shared}
unlock_shared
inline
inline void unlock_shared()
{#bitwise}
Bitwise
#include <icy/bitwise.h>
Container for smart management of bitwise integer flags.
Public Attributes
| Return | Name | Description |
|---|---|---|
unsigned | data | Backing storage for the flag bits. |
{#data}
data
unsigned data
Backing storage for the flag bits.
Public Methods
| Return | Name | Description |
|---|---|---|
Bitwise inline | Constructs a Bitwise with optional initial flags. | |
void | reset virtual inline | Clears all flags (sets data to 0). |
void | set virtual inline | Sets the given flag only if it is not already set. |
void | add virtual inline | Unconditionally sets (OR) the given flag bits. |
void | remove virtual inline | Clears the given flag bits. |
void | toggle virtual inline | Toggles (XOR) the given flag bits. |
bool | has virtual const inline | Returns true if all bits in flag are set. |
{#bitwise}
Bitwise
inline
inline Bitwise(unsigned flags)
Constructs a Bitwise with optional initial flags.
Parameters
flagsInitial flag value (default: 0).
{#reset}
reset
virtual inline
virtual inline void reset()
Clears all flags (sets data to 0).
{#set}
set
virtual inline
virtual inline void set(unsigned flag)
Sets the given flag only if it is not already set.
Parameters
flagThe flag bit(s) to set.
{#add}
add
virtual inline
virtual inline void add(unsigned flag)
Unconditionally sets (OR) the given flag bits.
Parameters
flagThe flag bit(s) to add.
{#remove}
remove
virtual inline
virtual inline void remove(unsigned flag)
Clears the given flag bits.
Parameters
flagThe flag bit(s) to remove.
{#toggle}
toggle
virtual inline
virtual inline void toggle(unsigned flag)
Toggles (XOR) the given flag bits.
Parameters
flagThe flag bit(s) to toggle.
{#has}
has
virtual const inline
virtual inline bool has(unsigned flag) const
Returns true if all bits in flag are set.
Parameters
flagThe flag bit(s) to test.
Returns
true if every bit in flag is present in data.
{#abstractdelegate}
AbstractDelegate
#include <icy/delegate.h>
Abstract delegate interface.
The Delegate class contains a pointer to a function. This wrapper class is used instead of std::function since it is interchangable with fast delegates and also provides an equality operator for comparing the underlying function where supported.
Public Methods
| Return | Name | Description |
|---|---|---|
RT | operator() const | Invokes the underlying callable with the supplied arguments. |
bool | operator== const | Compares two delegates for equality (same target function and instance). |
{#operator}
operator()
const
RT operator()(Args... args) const
Invokes the underlying callable with the supplied arguments.
Parameters
argsArguments forwarded to the wrapped function.
Returns
Result of the wrapped function call.
{#operator}
operator==
const
bool operator==(const AbstractDelegate< RT, Args... > & that) const
Compares two delegates for equality (same target function and instance).
Parameters
thatOther delegate to compare against.
Returns
True if both delegates refer to the same callable target.
{#functiondelegate}
FunctionDelegate
#include <icy/delegate.h>
Inherits:
AbstractDelegate< RT, Args... >
The [FunctionDelegate](#functiondelegate) contains a std::function.
Public Attributes
| Return | Name | Description |
|---|---|---|
std::function< RT(Args...)> | func |
{#func}
func
std::function< RT(Args...)> func
Public Methods
| Return | Name | Description |
|---|---|---|
FunctionDelegate inline | #### Parameters | |
RT | operator() virtual const inline | Calls the wrapped std::function. |
bool | operator== virtual const inline | Always returns false; std::function targets cannot be compared for equality. |
{#functiondelegate}
FunctionDelegate
inline
inline FunctionDelegate(std::function< RT(Args...)> func)
Parameters
funcstd::functionto wrap.
{#operator}
operator()
virtual const inline
virtual inline RT operator()(Args... args) const
Calls the wrapped std::function.
Parameters
argsArguments forwarded to the function.
Returns
Function result.
{#operator}
operator==
virtual const inline
virtual inline bool operator==(const AbstractDelegate< RT, Args... > &) const
Always returns false; std::function targets cannot be compared for equality.
{#classdelegate}
ClassDelegate
#include <icy/delegate.h>
Inherits:
AbstractDelegate< RT, Args... >
The [ClassDelegate](#classdelegate) contains a pointer to a class member.
This class implements fast delegates and function comparison.
Public Attributes
| Return | Name | Description |
|---|---|---|
Class * | instance | |
RT(Class::* | method |
{#instance}
instance
Class * instance
{#method}
method
RT(Class::* method
Public Methods
| Return | Name | Description |
|---|---|---|
ClassDelegate inline | #### Parameters | |
RT | operator() virtual const inline | Calls the member function on instance. |
bool | operator== virtual const inline | #### Parameters |
{#classdelegate}
ClassDelegate
inline
inline ClassDelegate(Class * instance, RT(Class::*)(Args...) method)
Parameters
-
instanceObject on which to invoke the member function. -
methodPointer to the member function to wrap.
{#operator}
operator()
virtual const inline
virtual inline RT operator()(Args... args) const
Calls the member function on instance.
Parameters
argsArguments forwarded to the method.
Returns
Method result.
{#operator}
operator==
virtual const inline
virtual inline bool operator==(const AbstractDelegate< RT, Args... > & that) const
Parameters
thatOther delegate to compare.
Returns
True if both delegates wrap the same instance/method pair.
{#constclassdelegate}
ConstClassDelegate
#include <icy/delegate.h>
Inherits:
AbstractDelegate< RT, Args... >
The [ConstClassDelegate](#constclassdelegate) contains a pointer to a const class member.
This class implements fast delegates and function comparison.
Public Attributes
| Return | Name | Description |
|---|---|---|
Class * | instance | |
RT(Class::* | method |
{#instance}
instance
Class * instance
{#method}
method
RT(Class::* method
Public Methods
| Return | Name | Description |
|---|---|---|
ConstClassDelegate inline | #### Parameters | |
RT | operator() virtual const inline | Calls the const member function on instance. |
bool | operator== virtual const inline | #### Parameters |
{#constclassdelegate}
ConstClassDelegate
inline
inline ConstClassDelegate(Class * instance, RT(Class::*)(Args...) const method)
Parameters
-
instanceObject on which to invoke the const member function. -
methodPointer to the const member function to wrap.
{#operator}
operator()
virtual const inline
virtual inline RT operator()(Args... args) const
Calls the const member function on instance.
Parameters
argsArguments forwarded to the method.
Returns
Method result.
{#operator}
operator==
virtual const inline
virtual inline bool operator==(const AbstractDelegate< RT, Args... > & that) const
Parameters
thatOther delegate to compare.
Returns
True if both delegates wrap the same instance/method pair.
{#polymorphicdelegate}
PolymorphicDelegate
#include <icy/delegate.h>
Inherits:
AbstractDelegate< RT, IT & >
Polymorphic function delegate.
Theis class contains a pointer to a class member that receices a derived subclass (PT) of the base type specified by the IT param.
Public Attributes
| Return | Name | Description |
|---|---|---|
Class * | instance | |
RT(Class::* | method |
{#instance}
instance
Class * instance
{#method}
method
RT(Class::* method
Public Methods
| Return | Name | Description |
|---|---|---|
PolymorphicDelegate inline | #### Parameters | |
RT | operator() virtual const inline | Attempts to cast object to PT; invokes the method if successful. Returns a default-constructed RT if the cast fails (packet type mismatch). |
bool | operator== virtual const inline | #### Parameters |
{#polymorphicdelegate}
PolymorphicDelegate
inline
inline PolymorphicDelegate(Class * instance, RT(Class::*)(PT &) method)
Parameters
-
instanceObject on which to invoke the member function. -
methodPointer to the member function accepting a derivedPT&.
{#operator}
operator()
virtual const inline
virtual inline RT operator()(IT & object) const
Attempts to cast object to PT; invokes the method if successful. Returns a default-constructed RT if the cast fails (packet type mismatch).
Parameters
objectBase-type reference; cast toPTbefore dispatch.
Returns
Method result, or default RT on cast failure.
{#operator}
operator==
virtual const inline
virtual inline bool operator==(const AbstractDelegate< RT, IT & > & that) const
Parameters
thatOther delegate to compare.
Returns
True if both delegates wrap the same instance/method pair.
{#optionparser}
OptionParser
#include <icy/application.h>
Command-line option parser.
Public Attributes
| Return | Name | Description |
|---|---|---|
std::string | exepath | |
OptionMap | args |
{#exepath}
exepath
std::string exepath
{#args}
args
OptionMap args
Public Methods
| Return | Name | Description |
|---|---|---|
OptionParser | Parses command-line arguments from argc/argv. | |
bool | has inline | Returns true if the given option key was present on the command line. |
std::string | get inline | Returns the string value associated with the given option key. Returns an empty string if the key was not found. |
NumericType | get inline | Returns the value associated with the given option key, converted to a numeric type. |
{#optionparser}
OptionParser
OptionParser(int argc, char * argv, const char * delim)
Parses command-line arguments from argc/argv.
Parameters
-
argcArgument count frommain(). -
argvArgument vector frommain(). -
delimPrefix string that identifies an option key (e.g. "--").
{#has}
has
inline
inline bool has(const char * key)
Returns true if the given option key was present on the command line.
Parameters
keyOption key to look up (without delimiter prefix).
Returns
True if the key exists in the parsed argument map.
{#get}
get
inline
inline std::string get(const char * key)
Returns the string value associated with the given option key. Returns an empty string if the key was not found.
Parameters
keyOption key to look up.
Returns
Value string, or empty string if not present.
{#get}
get
inline
template<typename NumericType> inline NumericType get(const char * key)
Returns the value associated with the given option key, converted to a numeric type.
Parameters
NumericTypeIntegral or floating-point type to convert the value to.
Parameters
keyOption key to look up.
Returns
Converted numeric value.
{#shutdowncmd}
ShutdownCmd
#include <icy/application.h>
Shutdown command packet for signalling process termination.
Public Attributes
| Return | Name | Description |
|---|---|---|
void * | opaque | |
std::function< void(void *)> | callback |
{#opaque}
opaque
void * opaque
{#callback}
callback
std::function< void(void *)> callback
{#packetadapterreference}
PacketAdapterReference
#include <icy/packetstream.h>
Provides a reference to a PacketStreamAdapter with optional ownership.
Public Attributes
| Return | Name | Description |
|---|---|---|
PacketStreamAdapter * | ptr | |
std::shared_ptr< void > | _prevent_deletion | |
int | order | |
bool | syncState |
{#ptr}
ptr
PacketStreamAdapter * ptr
{#_prevent_deletion}
_prevent_deletion
std::shared_ptr< void > _prevent_deletion
{#order}
order
int order
{#syncstate}
syncState
bool syncState
Public Methods
| Return | Name | Description |
|---|---|---|
PacketAdapterReference inline | Construct with raw pointer (non-owning). | |
PacketAdapterReference inline | Construct with shared_ptr ownership. |
{#packetadapterreference}
PacketAdapterReference
inline
inline PacketAdapterReference(PacketStreamAdapter * ptr, int order, bool syncState)
Construct with raw pointer (non-owning).
{#packetadapterreference}
PacketAdapterReference
inline
template<class C> inline PacketAdapterReference(std::shared_ptr< C > owned, int order, bool syncState)
Construct with shared_ptr ownership.
Public Static Methods
| Return | Name | Description |
|---|---|---|
bool | compareOrder static inline | Comparator for sorting references by ascending order value. |
{#compareorder}
compareOrder
static inline
static inline bool compareOrder(const PacketAdapterReference::Ptr & l, const PacketAdapterReference::Ptr & r)
Comparator for sorting references by ascending order value.
Parameters
-
lLeft-hand reference. -
rRight-hand reference.
Returns
true if l should appear before r in the processor chain.
Public Types
| Name | Description |
|---|---|
Ptr |
{#ptr}
Ptr
std::shared_ptr< PacketAdapterReference > Ptr()
{#packetstreamstate}
PacketStreamState
#include <icy/packetstream.h>
Inherits:
State
State machine states for PacketStream.
Public Methods
| Return | Name | Description |
|---|---|---|
std::string | str const inline |
{#str}
str
const inline
inline std::string str(unsigned int id) const
Public Static Attributes
| Return | Name | Description |
|---|---|---|
constexpr unsigned int | None static | |
constexpr unsigned int | Locked static | |
constexpr unsigned int | Active static | |
constexpr unsigned int | Paused static | |
constexpr unsigned int | Stopping static | |
constexpr unsigned int | Stopped static | |
constexpr unsigned int | Closed static | |
constexpr unsigned int | Error static |
{#none}
None
static
constexpr unsigned int None = static_cast<unsigned int>(Type::None)
{#locked}
Locked
static
constexpr unsigned int Locked = static_cast<unsigned int>(Type::Locked)
{#active}
Active
static
constexpr unsigned int Active = static_cast<unsigned int>(Type::Active)
{#paused}
Paused
static
constexpr unsigned int Paused = static_cast<unsigned int>(Type::Paused)
{#stopping}
Stopping
static
constexpr unsigned int Stopping = static_cast<unsigned int>(Type::Stopping)
{#stopped}
Stopped
static
constexpr unsigned int Stopped = static_cast<unsigned int>(Type::Stopped)
{#closed}
Closed
static
constexpr unsigned int Closed = static_cast<unsigned int>(Type::Closed)
{#error}
Error
static
constexpr unsigned int Error = static_cast<unsigned int>(Type::Error)
Public Types
| Name | Description |
|---|---|
Type |
{#type}
Type
enum Type
| Value | Description |
|---|---|
None | |
Locked | |
Active | |
Paused | |
Stopping | |
Stopped | |
Closed | |
Error |
{#packetcreationstrategy}
PacketCreationStrategy
#include <icy/packetfactory.h>
Inherits:
IPacketCreationStrategy
This template class implements an adapter that sits between an SignalBase and an object receiving notifications from it.
Public Methods
| Return | Name | Description |
|---|---|---|
PacketCreationStrategy inline | #### Parameters | |
IPacket * | create virtual const inline | Attempts to default-construct a PacketT, calling its read() method. |
int | priority virtual const inline | #### Returns |
{#packetcreationstrategy}
PacketCreationStrategy
inline
inline PacketCreationStrategy(int priority)
Parameters
priorityDispatch priority in the range 0–100.
Exceptions
std::logic_errorif priority exceeds 100.
{#create}
create
virtual const inline
virtual inline IPacket * create(const ConstBuffer & buffer, size_t & nread) const
Attempts to default-construct a PacketT, calling its read() method.
Parameters
-
bufferRaw input data. -
nreadSet to the number of bytes consumed when read() succeeds.
Returns
Newly allocated PacketT on success, nullptr if read() returns 0.
{#priority}
priority
virtual const inline
virtual inline int priority() const
Returns
The priority value assigned at construction.
Protected Attributes
| Return | Name | Description |
|---|---|---|
int | _priority |
{#_priority}
_priority
int _priority
{#sharedlibrary}
SharedLibrary
#include <icy/sharedlibrary.h>
Loads a shared library at runtime and resolves exported symbols.
Public Methods
| Return | Name | Description |
|---|---|---|
bool | open inline | Opens a shared library. The filename is in utf-8. Returns true on success and false on error. Call [SharedLibrary::error()](#structicy_1_1SharedLibrary_1a884ec111fdba82e16e31feaaf65bd4fd) to get the error message. |
void | close inline | Closes the shared library. |
bool | sym inline | Retrieves a data pointer from a dynamic library. It is legal for a symbol to map to nullptr. Returns 0 on success and -1 if the symbol was not found. |
void | setError inline | Reads the last libuv dynamic-linker error, stores it in _error, and throws a std::runtime_error with the combined prefix and error message. |
std::string | error const inline | Returns the last error message recorded by setError(). Empty if no error has occurred. |
{#open}
open
inline
inline bool open(const std::string & path)
Opens a shared library. The filename is in utf-8. Returns true on success and false on error. Call [SharedLibrary::error()](#structicy_1_1SharedLibrary_1a884ec111fdba82e16e31feaaf65bd4fd) to get the error message.
{#close}
close
inline
inline void close()
Closes the shared library.
{#sym}
sym
inline
inline bool sym(const char * name, void ** ptr)
Retrieves a data pointer from a dynamic library. It is legal for a symbol to map to nullptr. Returns 0 on success and -1 if the symbol was not found.
{#seterror}
setError
inline
inline void setError(const std::string & prefix)
Reads the last libuv dynamic-linker error, stores it in _error, and throws a std::runtime_error with the combined prefix and error message.
Parameters
prefixHuman-readable context string prepended to the error detail.
Exceptions
std::runtime_erroralways.
{#error}
error
const inline
inline std::string error() const
Returns the last error message recorded by setError(). Empty if no error has occurred.
Returns
Last error string.
Protected Attributes
| Return | Name | Description |
|---|---|---|
uv_lib_t | _lib | |
std::string | _error |
{#_lib}
_lib
uv_lib_t _lib
{#_error}
_error
std::string _error
{#diagnosticstate}
DiagnosticState
#include <icy/diagnosticmanager.h>
Inherits:
State
State definitions for diagnostic providers.
Public Methods
| Return | Name | Description |
|---|---|---|
std::string | str const inline | Returns a human-readable string for the given state ID. |
{#str}
str
const inline
inline std::string str(unsigned int id) const
Returns a human-readable string for the given state ID.
Parameters
idA DiagnosticState::Type value.
Returns
State name string.
Exceptions
std::logic_errorfor unknown IDs.
Public Types
| Name | Description |
|---|---|
Type |
{#type}
Type
enum Type
| Value | Description |
|---|---|
None | |
Checking | |
Passed | |
Failed |
{#transactionstate}
TransactionState
#include <icy/packettransaction.h>
Inherits:
State
State machine states for PacketTransaction.
Public Methods
| Return | Name | Description |
|---|---|---|
std::string | str const inline | #### Parameters |
{#str}
str
const inline
inline std::string str(unsigned int id) const
Parameters
idA[TransactionState::Type](#structicy_1_1TransactionState_1a3389dd308d8acd3cab977d1826298434)value.
Returns
Human-readable name of the state.
Public Types
| Name | Description |
|---|---|
Type |
{#type}
Type
enum Type
| Value | Description |
|---|---|
Waiting | |
Running | |
Success | |
Cancelled | |
Failed |
{#ipacketinfo}
IPacketInfo
#include <icy/packet.h>
Subclassed by:
PacketInfo
An abstract interface for packet sources to provide extra information about packets.
Public Methods
| Return | Name | Description |
|---|---|---|
IPacketInfo | Defaulted constructor. | |
std::unique_ptr< IPacketInfo > | clone const | Returns a heap-allocated deep copy of this info object. |
{#ipacketinfo}
IPacketInfo
IPacketInfo() = default
Defaulted constructor.
{#clone}
clone
const
std::unique_ptr< IPacketInfo > clone() const
Returns a heap-allocated deep copy of this info object.
Returns
Owning pointer to the cloned instance.