base

May 10, 2026 · View on GitHub

{#basemodule}

base

The base module contains reusable cross platform tools and utilities.

Namespaces

NameDescription
hexHexadecimal encoding and decoding helpers.
ipcClasses for inter-process communication.
testModern unit testing framework.
timeClasses and functions for handling time.
base64Base64 encoding and decoding helpers.
deleterDeleter helpers for objects managed through custom destruction routines.
numericInteger parsing and formatting helpers.
basicInterface classes.
fsCross-platform filesystem path and file helpers.
utilMiscellaneous string, parsing, and version utilities.

Classes

NameDescription
PipeNamed pipe / stdio stream built on uv_pipe_t.
IdlerAsynchronous type that triggers callbacks when the event loop is idle.
QueueThread-safe queue container.
RunnableQueueQueue of runnable tasks for sequential execution.
SyncQueueSyncQueue 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.
AsyncQueueAsyncQueue is a thread-based queue which receives packets from any thread source and dispatches them asynchronously.
TimerAsynchronous event based timer.
MutableBufferThe 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.
ConstBufferThe 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.
BitReaderClass for reading binary streams.
BitWriterClass for reading/writing binary streams.
DynamicBitWriterClass for reading/writing dynamically resizable binary streams.
LogWriterLog output stream writer.
AsyncLogWriterThread based log output stream writer.
LoggerLogger class.
LogChannelNamed log output channel with configurable severity level and formatting.
ConsoleChannelLog channel that writes formatted messages to standard output.
FileChannelLog channel that writes formatted messages to a file.
RotatingFileChannelLog channel that writes to time-rotated log files.
RefCountedBase class for intrusive reference counting.
IntrusivePtrIntrusive smart pointer for RefCounted objects.
RandomRandom implements a pseudo random number generator (PRNG) using the Mersenne Twister algorithm (std::mt19937).
RunnerRunner 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.
StreamBasic stream type for sockets and pipes.
ThreadPlatform-independent wrapper around an operating system thread.
ProcessSpawns and manages a child process with stdin/stdout/stderr pipes.
TimeoutTimeout counter which expires after a given delay. Delay is specified in milliseconds.
TimedTokenToken that expires after the specified duration.
TimestampA Timestamp stores a monotonic* time value with (theoretical) microseconds resolution. Timestamps can be compared with each other and simple arithmetics are supported.
TimespanA class that represents time spans up to microsecond resolution.
DateTimeThis 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.
TimezoneThis class provides information about the current timezone.
LocalDateTimeThis 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.
DateTimeFormatDefinition of date/time formats and various constants used by DateTimeFormatter and DateTimeParser.
DateTimeFormatterThis class converts dates and times into strings, supporting a variety of standard and custom formats.
DateTimeParserThis 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.
StopwatchA simple facility to measure time intervals with microsecond resolution.
ThreadedStreamReaderThreaded stream reader class.
StreamWriterPacket stream writer class.
StateState class for state machines.
StatefulState machine implementation.
IRegistryAbstract interface for object registries.
SingletonHelper template class for managing singleton objects allocated on the heap.
KeyedStoreA keyed store of unique_ptr values with optional lifecycle hooks. Not thread-safe; designed for single-threaded event loop contexts.
KVCollectionA keyed value store (values stored by copy, not pointer).
NVCollectionA storage container for a name value collections. This collection can store multiple entries for each name, and it's getters are case-insensitive.
ApplicationMain icey application class.
SyncPacketQueueSynchronized packet queue for event loop integration.
AsyncPacketQueueThread-based asynchronous packet dispatch queue.
RateLimiterToken bucket rate limiter for throttling message send frequency.
PacketStreamAdapterThis class is a wrapper for integrating external classes with the a PacketStream's data flow and state machine.
PacketProcessorThis class is a virtual interface for creating PacketStreamAdapters which process that and emit the IPacket type.
PacketStreamProcesses and broadcasts IPackets through a configurable adapter graph.
SynchronizerSynchronizer enables any thread to communicate with the associated event loop via synchronized callbacks.
TimedManagerTimed pointer manager
IPacketCreationStrategyAbstract strategy for creating typed packets from raw buffer data.
PacketFactoryPriority-ordered factory that creates typed packets from raw buffers using registered strategies.
StreamManagerManages a named collection of PacketStream instances with lifecycle callbacks.
IDiagnosticAbstract interface for diagnostic information providers.
AsyncDiagnosticAsynchronous diagnostic information collector.
DiagnosticManagerRegistry and manager for diagnostic providers.
PacketTransactionRequest/response transaction with timeout and retry logic.
TaskAbstract base class for implementing asynchronous tasks.
TaskRunnerRunner for tasks that inherit the [Task](#task) interface.
IPacketThe 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.
FlagPacketPacket for sending bitwise flags along the packet stream.
RawPacketRawPacket is the default data packet type which consists of an optionally managed char pointer and a size value.
ConfigurationConfiguration is an abstract base class for managing different kinds of configuration storage back ends such as JSON, XML, or database.
ScopedConfigurationScopedConfiguration 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.
ErrorBasic error type.
LogStreamNo-op log record used when logging is compiled out.
NullSharedMutexNo-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.
BitwiseContainer for smart management of bitwise integer flags.
AbstractDelegateAbstract delegate interface.
FunctionDelegateThe [FunctionDelegate](#functiondelegate) contains a std::function.
ClassDelegateThe [ClassDelegate](#classdelegate) contains a pointer to a class member.
ConstClassDelegateThe [ConstClassDelegate](#constclassdelegate) contains a pointer to a const class member.
PolymorphicDelegatePolymorphic function delegate.
OptionParserCommand-line option parser.
ShutdownCmdShutdown command packet for signalling process termination.
PacketAdapterReferenceProvides a reference to a PacketStreamAdapter with optional ownership.
PacketStreamStateState machine states for PacketStream.
PacketCreationStrategyThis template class implements an adapter that sits between an SignalBase and an object receiving notifications from it.
SharedLibraryLoads a shared library at runtime and resolves exported symbols.
DiagnosticStateState definitions for diagnostic providers.
TransactionStateState machine states for PacketTransaction.
IPacketInfoAn abstract interface for packet sources to provide extra information about packets.

Enumerations

NameDescription
LevelLogging severity levels used by Logger and LogChannel.
ByteOrderByte-order policy used when reading or writing multi-byte integers.
PacketRetentionDescribes how an adapter treats incoming packet lifetime beyond the current synchronous call chain.
PacketFlagsFlags which determine how the packet is handled by the PacketStream.

{#level}

Level

enum Level

Logging severity levels used by Logger and LogChannel.

ValueDescription
TraceMost verbose diagnostic output.
DebugDebug-only diagnostic output.
InfoNormal informational output.
WarnWarning output for recoverable problems.
ErrorError output for failed operations.
FatalFatal output immediately before termination.

{#byteorder}

ByteOrder

enum ByteOrder

Byte-order policy used when reading or writing multi-byte integers.

ValueDescription
NetworkDefault, use network byte order (big endian).
HostUse 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.

ValueDescription
BorrowedPacket is only used synchronously during the current emit/process call.
ClonedAdapter makes its own copy before deferred or asynchronous use.
RetainedAdapter 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.

ValueDescription
NoModifyThe packet should not be modified by processors.
FinalThe final packet in the stream.

Typedefs

ReturnNameDescription
std::vector< char >BufferCore buffer type.
LogChannelNullChannelNull log channel.
Signal< void()>NullSignalZero-argument signal alias used for simple local event notifications.
Signal< RT, std::shared_mutex >ThreadSignalCross-thread signal variant.
Signal< RT, NullSharedMutex >LocalSignalCompatibility alias for the single-threaded fast path.
uv_process_options_tProcessOptionsRaw libuv process spawn options passed through to uv_spawn.
std::map< std::string, std::string >StringMapGeneric string-to-string map used for headers, options, and environment-style metadata.
std::vector< std::string >StringVecGeneric string vector used for argument lists and ordered string collections.
std::map< std::string, std::string >OptionMapCommand Line Option Parser.
Signal< void(IPacket &)>PacketSignalSignal that broadcasts [IPacket](#ipacket) types.
PacketStreamAdapterPacketSourceFor 0.8.x compatibility.
PacketProcessorIPacketizerCompatibility alias for a packet processor that packetizes stream output.
PacketProcessorIDepacketizerFor 0.8.x compatibility.
std::vector< PacketAdapterReference::Ptr >PacketAdapterVecOrdered list of packet adapter references used for sources and processors.
std::vector< PacketStream * >PacketStreamVecNon-owning list of packet stream pointers used for graph traversal helpers.
std::vector< PacketStream::Ptr >PacketStreamPtrVecOwning list of packet stream handles retained across stream graphs.
std::unique_ptr< IPacketCreationStrategy >PacketCreationStrategyPtrOwning handle for one packet creation strategy.
std::vector< PacketCreationStrategyPtr >PacketCreationStrategyListOrdered 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

ReturnNameDescription
voidrunOnceSchedules 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::stringformatError inlineFormats 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.
voidthrowError inlineThrows a std::runtime_error with a formatted error message.
MutableBuffermutableBuffer inlineCreates a [MutableBuffer](#mutablebuffer) from an arbitrary pointer and size.
MutableBuffermutableBuffer inlineCreates a [MutableBuffer](#mutablebuffer) from a std::string.
MutableBuffermutableBuffer inlineCreates a [MutableBuffer](#mutablebuffer) from a const std::string. Casts away constness; use with care.
MutableBuffermutableBuffer inlineCreates a [MutableBuffer](#mutablebuffer) from a const std::vector. Casts away constness; use with care.
MutableBuffermutableBuffer inlineCreates a [MutableBuffer](#mutablebuffer) from a Buffer.
MutableBuffermutableBuffer inlineCreates a [MutableBuffer](#mutablebuffer) from a const Buffer. Casts away constness; use with care.
ConstBufferconstBuffer inlineCreates a [ConstBuffer](#constbuffer) from an arbitrary pointer and size.
ConstBufferconstBuffer inlineCreates a [ConstBuffer](#constbuffer) from a std::string.
ConstBufferconstBuffer inlineCreates a [ConstBuffer](#constbuffer) from a std::vector.
constexpr ConstBufferconstBuffer inlineCreates a [ConstBuffer](#constbuffer) from a [MutableBuffer](#mutablebuffer).
ConstBufferconstBuffer inlineCreates a [ConstBuffer](#constbuffer) from a Buffer.
ConstBufferconstBuffer inlineCreates a [ConstBuffer](#constbuffer) from a const Buffer. Casts away constness internally; use with care.
constexpr PointerToPodTypebufferCast inlineCasts a [MutableBuffer](#mutablebuffer) to a specified pointer-to-POD type.
constexpr PointerToPodTypebufferCast inlineCasts a [ConstBuffer](#constbuffer) to a specified pointer-to-POD type.
LevelgetLevelFromString inlineConverts a log level string to its corresponding Level enum value. Unrecognized strings default to [Level::Trace](#namespaceicy_1aad3e81b3cd2daab89338dae9b5323f6badd4ec0ac4e58f7c32a01244ae91150b1).
const char *getStringFromLevel inlineConverts a Level enum value to its lowercase string representation.
voidlogArgsWrite a single logging argument into the destination stream.
voidlogArgsWrite multiple logging arguments into the destination stream in order.
constexpr const char *str_endReturn a pointer to the null terminator of a C string.
constexpr boolstr_slantReturn true if the C string contains a forward or back slash.
constexpr const char *r_slantWalk backward to the character after the last path separator.
constexpr const char *_fileNameReturn the filename portion of a compile-time path string.
std::string_methodName inlineExtract the class-qualified method name from a compiler pretty-function string.
voiddeleteLater inlineSchedules 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 >makeIntrusiveCreates an IntrusivePtr managing a newly heap-allocated T. Equivalent to std::make_shared.
std::shared_ptr< internal::Slot< RT, Args... > >slotCreates a slot that binds a non-const class member function to an instance.
std::shared_ptr< internal::Slot< RT, Args... > >slotCreates a slot that wraps a free (static) function pointer.
voidswap inlineExchange two DateTime values.
voidswap inlineExchange two LocalDateTime values.
voidswap inlineExchange two Timestamp values.
voidswap inlineExchange two Timespan values.
std::stringgetExePathCross-platform utilities.
std::stringgetCwdReturn the current working directory.
uint64_tgetFreeMemoryReturns the current amount of free memory.
uint64_tgetTotalMemoryReturns the current amount of used memory.
intnumCpuCoresReturns the number of CPU cores.
voidsleepPause the current thread for the given ms duration.
voidpausePause the current thread until enter is pressed.
std::stringgetHostnameReturn the system hostname.
std::stringgetEnvReturn an environment variable or the default value.
boolgetEnvBoolReturn an environment variable boolean or the default value. The variable must be 1 or true for this function to return true.
voidset8 inlineWrites a single byte at the given offset in memory.
uint8_tget8 inlineReads a single byte at the given offset from memory.
voidsetBE16 inlineWrites a 16-bit value to memory in big-endian byte order.
voidsetBE32 inlineWrites a 32-bit value to memory in big-endian byte order.
voidsetBE64 inlineWrites a 64-bit value to memory in big-endian byte order.
uint16_tgetBE16 inlineReads a 16-bit big-endian value from memory.
uint32_tgetBE32 inlineReads a 32-bit big-endian value from memory.
uint64_tgetBE64 inlineReads a 64-bit big-endian value from memory.
voidsetLE16 inlineWrites a 16-bit value to memory in little-endian byte order.
voidsetLE32 inlineWrites a 32-bit value to memory in little-endian byte order.
voidsetLE64 inlineWrites a 64-bit value to memory in little-endian byte order.
uint16_tgetLE16 inlineReads a 16-bit little-endian value from memory.
uint32_tgetLE32 inlineReads a 32-bit little-endian value from memory.
uint64_tgetLE64 inlineReads a 64-bit little-endian value from memory.
boolisBigEndian inlineReturns true if the host CPU is big-endian.
uint16_thostToNetwork16 inlineConverts a 16-bit value from host byte order to network (big-endian) byte order.
uint32_thostToNetwork32 inlineConverts a 32-bit value from host byte order to network (big-endian) byte order.
uint64_thostToNetwork64 inlineConverts a 64-bit value from host byte order to network (big-endian) byte order.
uint16_tnetworkToHost16 inlineConverts a 16-bit value from network (big-endian) byte order to host byte order.
uint32_tnetworkToHost32 inlineConverts a 32-bit value from network (big-endian) byte order to host byte order.
uint64_tnetworkToHost64 inlineConverts a 64-bit value from network (big-endian) byte order to host byte order.
voidonShutdownSignal inlineInstalls a SIGINT handler on the given event loop. When the signal fires, callback is invoked with opaque and the signal handle is closed.
voidwaitForShutdown inlineInstalls 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 & > >packetSlotCreates a signal slot that filters by packet subtype PT before invoking method.
constexpr unsigned[`operator`](#operator-9)
RawPacketrawPacket inlineConstructs a non-owning RawPacket from a mutable buffer (borrowed pointer).
RawPacketrawPacket inlineConstructs an owning RawPacket from a const buffer (data is copied).
RawPacketrawPacket inlineConstructs a non-owning RawPacket from a raw mutable pointer (borrowed).
RawPacketrawPacket inlineConstructs 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

  • loop Event loop on which to schedule the callback.

  • func Callable to invoke on the next loop tick.

  • args Arguments 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

  • message Descriptive context for the error.

  • err libuv error code (e.g. from a failed uv_* call). Defaults to UV_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

  • message Descriptive context for the error.

  • err libuv error code to append. Defaults to UV_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

  • T Pointer type; must be implicitly castable to void*.

Parameters

  • data Pointer to the start of the memory region.

  • size Number 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

  • str Source 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

  • str Source 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

  • T Element type of the vector.

Parameters

  • vec Source 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

  • buf Source 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

  • buf Source 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

  • T Pointer type; must be implicitly castable to const void*.

Parameters

  • data Pointer to the start of the memory region.

  • size Number 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

  • str Source 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

  • T Element type of the vector.

Parameters

  • vec Source 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

  • buf Source 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

  • T Unused; kept for overload symmetry.

Parameters

  • buf Source 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

  • T Unused; kept for overload symmetry.

Parameters

  • buf Source 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

  • PointerToPodType Target pointer type (e.g. char*, uint8_t*).

Parameters

  • b Source 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

  • PointerToPodType Target pointer type (e.g. const char*, const uint8_t*).

Parameters

  • b Source 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

  • level Lowercase 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

  • level The 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

  • o Destination stream.

  • t Argument 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

  • o Destination stream.

  • t First argument to append.

  • args Remaining 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

  • T Type of the object to delete.

Parameters

  • ptr Object to delete. Does nothing if nullptr.

  • loop Event 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

  • T Type to construct; must inherit from RefCounted.

Parameters

  • args Arguments forwarded to T's constructor.

Returns

IntrusivePtr owning the new object.


{#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

  • Class The class that owns the member function.

  • RT Return type of the member function.

  • Args Parameter types of the member function.

Parameters

  • instance Pointer to the object on which method will be called.

  • method Pointer to the non-const member function to bind.

  • id Explicit slot ID to assign; pass -1 to auto-assign.

  • priority Higher values are called first; pass -1 for 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

  • RT Return type of the function.

  • Args Parameter types of the function.

Parameters

  • method Pointer to the free function to bind.

  • id Explicit slot ID to assign; pass -1 to auto-assign.

  • priority Higher values are called first; pass -1 for 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

  • memory Pointer to the destination buffer.

  • offset Byte offset within the buffer.

  • v Value 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

  • memory Pointer to the source buffer.

  • offset Byte 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

  • memory Pointer to the destination buffer (must be at least 2 bytes).

  • v Value 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

  • memory Pointer to the destination buffer (must be at least 4 bytes).

  • v Value 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

  • memory Pointer to the destination buffer (must be at least 8 bytes).

  • v Value to write.


{#getbe16}

getBE16

inline

inline uint16_t getBE16(const void * memory)

Reads a 16-bit big-endian value from memory.

Parameters

  • memory Pointer 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

  • memory Pointer 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

  • memory Pointer 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

  • memory Pointer to the destination buffer (must be at least 2 bytes).

  • v Value 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

  • memory Pointer to the destination buffer (must be at least 4 bytes).

  • v Value 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

  • memory Pointer to the destination buffer (must be at least 8 bytes).

  • v Value to write.


{#getle16}

getLE16

inline

inline uint16_t getLE16(const void * memory)

Reads a 16-bit little-endian value from memory.

Parameters

  • memory Pointer 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

  • memory Pointer 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

  • memory Pointer 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

  • n Value 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

  • n Value 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

  • n Value 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

  • n Value 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

  • n Value 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

  • n Value 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

  • callback Optional function called on SIGINT.

  • opaque Optional user data pointer passed to the callback.

  • loop Event 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

  • callback Optional function called on SIGINT before the loop exits.

  • opaque Optional user data pointer passed to the callback.

  • loop Event 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

  • Class Listener class type.

  • RT Return type of the listener method.

  • PT Derived packet type the listener expects (must derive from IT).

  • IT Base packet interface type; defaults to [IPacket](#ipacket).

Parameters

  • instance Pointer to the listener object.

  • method Member function pointer on Class accepting a PT&.

  • id Optional slot identifier; -1 for automatic assignment.

  • priority Optional 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

NameDescription
DecoderHex decoder.
EncoderHex encoder.

Functions

ReturnNameDescription
std::stringencode inlineConverts 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

ReturnNameDescription
charlastbyte

{#lastbyte}

lastbyte

char lastbyte

Public Methods

ReturnNameDescription
Decoder inline
ssize_tdecode virtual inlineDecodes hex-encoded input to binary. Whitespace in the input is ignored. A trailing unpaired nibble is buffered and prepended on the next call.
ssize_tfinalize virtual inlineNo-op finalizer; hex decoding has no pending output state.
boolreadnext inlineReads the next non-whitespace character from inbuf, prepending any buffered lastbyte before consuming from the stream.
intnybble inlineConverts an ASCII hex character to its 4-bit integer value.
booliswspace inlineReturns 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

  • inbuf Hex-encoded input buffer.

  • nread Number of bytes to read from inbuf.

  • outbuf Destination 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

  • inbuf Input buffer.

  • nread Total bytes in inbuf.

  • rpos Current read position; advanced on each consumed byte.

  • c Output: 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

  • n ASCII character ('0'-'9', 'a'-'f', 'A'-'F').

Returns

Integer value in the range [0, 15].

Exceptions

  • std::runtime_error if 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

  • c Character to test.

Returns

true if c is whitespace.

{#encoder-1}

Encoder

#include <icy/hex.h>

Inherits: Encoder

Hex encoder.

Public Attributes

ReturnNameDescription
int_linePos
int_lineLength
int_uppercase

{#_linepos}

_linePos

int _linePos

{#_linelength}

_lineLength

int _lineLength

{#_uppercase}

_uppercase

int _uppercase

Public Methods

ReturnNameDescription
Encoder inline
ssize_tencode virtual inlineEncodes binary input as lowercase hex characters, optionally inserting newlines every _lineLength output characters.
ssize_tfinalize virtual inlineNo-op finalizer; hex encoding has no pending state.
voidsetUppercase inlineControls whether encoded output uses uppercase hex digits (A-F) or lowercase (a-f).
voidsetLineLength inlineSets 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

  • inbuf Input buffer to encode.

  • nread Number of bytes to read from inbuf.

  • outbuf Destination 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

  • flag true 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

  • lineLength Characters per line.

{#ipc}

ipc

Classes for inter-process communication.

Classes

NameDescription
QueueIPC queue is for safely passing templated actions between threads and processes.
SyncQueueIPC synchronization queue is for passing templated actions between threads and the event loop we are synchronizing with.
ActionDefault action type for executing synchronized callbacks.

Typedefs

ReturnNameDescription
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

ReturnNameDescription
Queue inline
voidpush virtual inlinePushes 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 inlineRemoves and returns the next action from the front of the queue. The caller takes ownership of the returned pointer. Thread-safe.
voidrunSync virtual inlineDrains the queue by invoking and deleting every pending action in order. Must be called from the thread that owns the event loop.
voidclose virtual inlineCloses the underlying notification handle. No-op in the base implementation.
voidpost virtual inlineSignals the event loop that new actions are available. No-op in the base implementation.
voidwaitForSync inlineBlocks 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

  • action Heap-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

  • timeout Maximum time to wait (default: 5000 ms).

Protected Attributes

ReturnNameDescription
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

ReturnNameDescription
SyncQueue inlineConstructs a SyncQueue bound to the given libuv event loop.
voidclose virtual inlineCloses the underlying Synchronizer handle and stops loop wakeups.
voidpost virtual inlineWakes up the event loop so pending actions are dispatched via runSync().
Synchronizer &sync virtual inlineReturns 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

  • loop Event 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

ReturnNameDescription
Synchronizer_sync

{#_sync}

_sync

Synchronizer _sync

{#action}

Action

#include <icy/ipc.h>

Default action type for executing synchronized callbacks.

Public Attributes

ReturnNameDescription
CallbacktargetThe callable to invoke when the action is dispatched.
void *argOptional opaque pointer passed to the callback.
std::stringdataOptional 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

ReturnNameDescription
Action inlineConstructs 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

  • target Callback to invoke on dispatch.

  • arg Opaque pointer passed to the callback (default: nullptr).

  • data String payload passed to the callback (default: empty).

Public Types

NameDescription
Callback

{#callback-1}

Callback

std::function< void(const Action &)> Callback()

{#test}

test

Modern unit testing framework.

Classes

NameDescription
FunctionTestTest wrapper for standalone test functions.
TestTest wrapper class.
TestRunnerTest manager queue.

Typedefs

ReturnNameDescription
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

ReturnNameDescription
voidinitInitialize the test environment.
intfinalizeFinalize the test environment.
voidrunAllRun all tests.
voiddescribeDescribe a test environment implemented by the given lambda function.
voiddescribeDescribe a test environment implemented by the given test instance.
voidexpectImplExpect asserts that a condition is true (use expect() as defined below).
boolwaitForRun 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

ReturnNameDescription
std::function< void()>target

{#target-1}

target

std::function< void()> target

Public Methods

ReturnNameDescription
FunctionTest inline#### Parameters

{#functiontest-1}

FunctionTest

inline

inline FunctionTest(std::function< void()> target, const std::string & name)

Parameters

  • target Lambda or function to execute as the test body.

  • name Human-readable test name.

Protected Methods

ReturnNameDescription
voidrun virtual inlineCalled 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

ReturnNameDescription
std::stringnameThe name of the test.
SErroristerrorsA list of test errors.
doubledurationThe 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

ReturnNameDescription
Test#### Parameters
~Test virtualShould remain protected.
voidrunCalled by the TestRunner to run the test.
boolpassedReturn true when the test passed without errors.

{#test-2}

Test

Test(const std::string & name)

Parameters

  • name Human-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

ReturnNameDescription
TestDeleted 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

ReturnNameDescription
TestRunner
voidaddAdds a test to the runner and prints its name to stdout.
Test *get constReturn a pointer to the test matching the given name, or nullptr if no matching test exists.
voidrunRuns all registered tests sequentially, printing results to stdout.
voidclearDestroy and clears all managed tests.
Test *current constReturn the currently active Test or nullptr.
TestListtests constReturn the list of tests.
ErrorMaperrors constReturn a map of tests and errors.
boolpassed constReturn 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

  • test Non-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

  • name Test 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

ReturnNameDescription
TestRunner &getDefault staticReturn 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

ReturnNameDescription
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

ReturnNameDescription
std::time_tnowReturns the current wall-clock time as a UTC time_t (seconds since epoch).
doubleclockSecsReturns the elapsed process time in decimal seconds using a monotonic clock.
std::stringprintFormats a broken-down time value using the given strftime format string.
std::stringprintLocalFormats the current local time using the given strftime format string.
std::stringprintUTCFormats the current UTC time using the given strftime format string.
std::tmtoLocalConverts a time_t value to a broken-down local time structure. Uses thread-safe native functions (localtime_r / localtime_s).
std::tmtoUTCConverts a time_t value to a broken-down UTC time structure. Uses thread-safe native functions (gmtime_r / gmtime_s).
std::stringgetLocalReturns the current local time as an ISO8601 formatted string.
std::stringgetUTCReturns the current UTC time as an ISO8601 formatted string.
uint64_thrtimeReturns 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}

print

std::string print(const std::tm & dt, const char * fmt)

Formats a broken-down time value using the given strftime format string.

Parameters

  • dt Broken-down time to format.

  • fmt strftime 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

  • fmt strftime 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

  • fmt strftime 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

  • time UTC 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

  • time UTC 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

ReturnNameDescription
const int64_tkNumMillisecsPerSec staticConstants for calculating time.
const int64_tkNumMicrosecsPerSec static
const int64_tkNumNanosecsPerSec static
const int64_tkNumMicrosecsPerMillisec static
const int64_tkNumNanosecsPerMillisec static
const int64_tkNumNanosecsPerMicrosec static
const char *ISO8601Format staticThe 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

NameDescription
DecoderBase64 decoder.
EncoderBase64 encoder.

Functions

ReturnNameDescription
size_tencodedBufferCapacity inlineReturns 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::stringencode inlineEncodes an STL byte container to a Base64 string.
std::stringdecode inlineDecodes 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

  • T Container type with a size() method and contiguous operator[].

Parameters

  • bytes Input data container.

  • lineLength Characters 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

  • T Container type with a size() method and contiguous operator[].

Parameters

  • bytes Input Base64 data container.

Returns

Decoded binary string.

Variables

ReturnNameDescription
constexpr intBUFFER_SIZE
constexpr intLINE_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

ReturnNameDescription
internal::decodestate_state
int_buffersize

{#_state}

_state

internal::decodestate _state

{#_buffersize}

_buffersize

int _buffersize

Public Methods

ReturnNameDescription
Decoder inline#### Parameters
ssize_tdecode inlineDecodes a single Base64 character to its 6-bit value.
ssize_tdecode virtual inlineDecodes a raw Base64 buffer into binary data.
voiddecode inlineDecodes 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

  • buffersize Internal 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_in Base64 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

  • inbuf Input Base64 characters.

  • nread Number of characters to decode.

  • outbuf Output buffer; must be at least nread * 3 / 4 bytes.

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

  • istrm Source stream of Base64 data.

  • ostrm Destination stream for decoded binary output.

{#encoder-3}

Encoder

#include <icy/base64.h>

Inherits: Encoder

Base64 encoder.

Public Attributes

ReturnNameDescription
internal::encodestate_state
int_buffersize

{#_state-1}

_state

internal::encodestate _state

{#_buffersize-1}

_buffersize

int _buffersize

Public Methods

ReturnNameDescription
Encoder inline#### Parameters
voidencode inlineEncodes the entire input stream and writes Base64 output to ostrm. Resets the encoder state after completion.
voidencode inlineEncodes a string to Base64 and appends the result to out. Resets the encoder state after completion.
ssize_tencode virtual inlineEncodes a raw buffer, writing Base64 characters to outbuf. May be called multiple times before calling [finalize()](#finalize-3).
ssize_tfinalize virtual inlineWrites any pending padding and resets the encoder state. Must be called once after all [encode()](#encode-17) calls to flush the final block.
voidsetLineLength inlineSets the line wrap length for encoded output (0 disables line wrapping).

{#encoder-4}

Encoder

inline

inline Encoder(int buffersize)

Parameters

  • buffersize Internal 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

  • istrm Source stream to encode.

  • ostrm Destination 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

  • in Input string.

  • out Output 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

  • inbuf Input binary data.

  • nread Number of bytes to encode.

  • outbuf Output buffer; must be at least nread * 4 / 3 + 4 bytes.

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

  • outbuf Output 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

  • lineLength Characters per line; use 0 to disable.

{#deleter-2}

deleter

Deleter helpers for objects managed through custom destruction routines.

Classes

NameDescription
ArrayDeleter functor for array pointers. Calls delete[] on the pointer.
DisposeDeleter 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

ReturnNameDescription
voidoperator() inlineCalls delete[] on ptr if non-null.

{#operator-10}

operator()

inline

inline void operator()(T * ptr)

Calls delete[] on ptr if non-null.

Parameters

  • ptr Array 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

ReturnNameDescription
voidoperator() inlineCalls 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

  • ptr Pointer to dispose; may be nullptr.

{#numeric}

numeric

Integer parsing and formatting helpers.

Functions

ReturnNameDescription
voidformatFormats an integer value in decimal notation.
voidformatFormats an integer value in decimal notation, right justified in a field having at least the specified width.
voidformat0Formats an integer value in decimal notation, right justified and zero-padded in a field having at least the specified width.
voidformatHexFormats an int value in hexadecimal notation. The value is treated as unsigned.
voidformatHexFormats 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.
voidformatFormats an unsigned int value in decimal notation.
voidformatFormats an unsigned int value in decimal notation, right justified in a field having at least the specified width.
voidformat0Formats an unsigned int value in decimal notation, right justified and zero-padded in a field having at least the specified width.
voidformatHexFormats an unsigned int value in hexadecimal notation.
voidformatHexFormats an unsigned int value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width.
voidformatFormats a long value in decimal notation.
voidformatFormats a long value in decimal notation, right justified in a field having at least the specified width.
voidformat0Formats a long value in decimal notation, right justified and zero-padded in a field having at least the specified width.
voidformatHexFormats a long value in hexadecimal notation. The value is treated as unsigned.
voidformatHexFormats 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.
voidformatFormats an unsigned long value in decimal notation.
voidformatFormats an unsigned long value in decimal notation, right justified in a field having at least the specified width.
voidformat0Formats an unsigned long value in decimal notation, right justified and zero-padded in a field having at least the specified width.
voidformatHexFormats an unsigned long value in hexadecimal notation.
voidformatHexFormats an unsigned long value in hexadecimal notation, right justified and zero-padded in a field having at least the specified width.
voidformatFormats a 64-bit integer value in decimal notation.
voidformatFormats a 64-bit integer value in decimal notation, right justified in a field having at least the specified width.
voidformat0Formats a 64-bit integer value in decimal notation, right justified and zero-padded in a field having at least the specified width.
voidformatHexFormats a 64-bit integer value in hexadecimal notation. The value is treated as unsigned.
voidformatHexFormats 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.
voidformatFormats an unsigned 64-bit integer value in decimal notation.
voidformatFormats an unsigned 64-bit integer value in decimal notation, right justified in a field having at least the specified width.
voidformat0Formats an unsigned 64-bit integer value in decimal notation, right justified and zero-padded in a field having at least the specified width.
voidformatHexFormats an unsigned 64-bit integer value in hexadecimal notation.
voidformatHexFormats 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum 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

  • str Output string to append to.

  • value Value 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

  • str Output string to append to.

  • value Value to format.

  • width Minimum field width; padded with zeros on the left.

{#basic}

basic

Interface classes.

Classes

NameDescription
DecoderAbstract interface for stream decoders.
EncoderAbstract interface for stream encoders.
RunnableAbstract interface for classes that can be run and cancelled.
SendableAbstract interface for classes that can be sent and cancelled.
StartableAbstract interface for a classes that can be started and stopped.

{#decoder-4}

Decoder

#include <icy/interface.h>

Subclassed by: Decoder, Decoder

Abstract interface for stream decoders.

Public Methods

ReturnNameDescription
DecoderDefaulted constructor.
ssize_tdecodeDecodes nread bytes from inbuf and writes decoded output to outbuf.
ssize_tfinalize virtual inlineFlushes 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

  • inbuf Encoded input buffer.

  • nread Number of bytes to decode from inbuf.

  • outbuf Destination 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

  • outbuf Destination buffer for any remaining output.

Returns

Number of bytes written, or 0 if nothing to flush.

{#encoder-5}

Encoder

#include <icy/interface.h>

Subclassed by: Encoder, Encoder

Abstract interface for stream encoders.

Public Methods

ReturnNameDescription
EncoderDefaulted constructor.
ssize_tencodeEncodes nread bytes from inbuf and writes encoded output to outbuf.
ssize_tfinalize virtual inlineFlushes 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

  • inbuf Raw input buffer to encode.

  • nread Number of bytes to encode from inbuf.

  • outbuf Destination 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

  • outbuf Destination 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

ReturnNameDescription
Runnable inline
voidrunThe run method will be called by the asynchronous context.
voidcancel virtual inlineCancel the current task. The run() method should return ASAP.
boolcancelled virtual const inlineReturns 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

ReturnNameDescription
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

ReturnNameDescription
boolsendInitiates the send operation.
voidcancelCancels 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

ReturnNameDescription
voidstartStarts the object (e.g. begins processing or listening).
voidstopStops 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

ReturnNameDescription
std::stringfilenameReturns the file name and extension part of the given path.
std::stringbasenameReturns the file name without its extension.
std::stringdirnameReturns the directory part of the path.
std::stringextnameReturns the file extension part of the path.
boolexistsReturns true if the file or directory exists.
boolisdirReturns true if the path refers to a directory.
std::int64_tfilesizeReturns the size in bytes of the given file.
voidreaddirPopulates res with the names of all entries in the given directory.
voidmkdirCreates a single directory.
voidmkdirrCreates a directory and all missing parent directories.
voidrmdirRemoves an empty directory.
voidunlinkDeletes a file.
voidrenameRenames or moves the given file to the target path.
voidaddsepAppends the platform-specific path separator to path if not already present.
voidaddnodeAppends a path node to path, inserting a separator if necessary.
std::stringmakePathJoins a base path and a node component into a single path string.
std::stringnormalizeNormalizes a path by resolving . and .. segments and converting separators to the native platform style.
std::stringtranscodeTranscodes 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.
boolsavefileWrites 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

  • path Filesystem 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

  • path Filesystem 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

  • path Filesystem 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

  • path Filesystem path to parse.

  • includeDot If 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

  • path Path 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

  • path Path 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

  • path Path 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

  • path Path to the directory to read.

  • res Vector to receive the list of entry names.


{#mkdir}

mkdir

void mkdir(std::string_view path, int mode)

Creates a single directory.

Parameters

  • path Path of the directory to create.

  • mode Permission 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

  • path Path of the directory hierarchy to create.

  • mode Permission bits (default: 0755). Ignored on Windows.


{#rmdir}

rmdir

void rmdir(std::string_view path)

Removes an empty directory.

Parameters

  • path Path of the directory to remove.

{#unlink}

void unlink(std::string_view path)

Deletes a file.

Parameters

  • path Path 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

  • path Source file path.

  • target Destination file path.


{#addsep}

addsep

void addsep(std::string & path)

Appends the platform-specific path separator to path if not already present.

Parameters

  • path Path 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

  • path Base path string to modify in place.

  • node Directory 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

  • base Base directory path.

  • node Directory 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

  • path Path 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

  • path Path 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

  • path Destination file path. Parent directories must already exist.

  • data Pointer to the data to write.

  • size Number of bytes to write.

  • whiny If true, throws a std::runtime_error on failure instead of returning false.

Returns

True on success, false on failure (when whiny is false).

Variables

ReturnNameDescription
const char *separatorThe platform specific path separator string: "/" on unix and "\" on windows.
const chardelimiterThe 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

NameDescription
VersionSemantic version number with major, minor, and patch fields.

Functions

ReturnNameDescription
std::stringformatPrintf-style string formatting for POD types.
voidtoUnderscoreReplaces all non-alphanumeric characters in str with underscores and converts to lowercase.
boolisNumberReturns true if str consists entirely of digit characters.
boolendsWithReturns true if str ends with the given suffix.
voidremoveSpecialCharactersReplaces non-alphanumeric characters. Removes all non-alphanumeric characters from str in place.
voidreplaceSpecialCharactersReplaces all non-alphanumeric characters in str with with in place.
booltryParseHexAttempts to parse a hex string into an unsigned integer.
unsignedparseHexParses a hex string into an unsigned integer.
std::stringdumpbinFormats the binary contents of data as a hex+ASCII dump string.
boolcompareVersionCompares two dot-separated version strings.
boolmatchNodesChecks whether node matches xnode by splitting both on delim and comparing element-wise.
boolmatchNodesChecks whether params matches xparams element-wise.
std::stringmemAddressReturns the memory address of ptr as a hex string (e.g. "0x7f3a2b10c0").
std::stringitostrConverts an integer (or any stream-insertable type) to its string representation.
TstrtoiParses a string into integer type T using std::istringstream. Returns 0 if parsing fails. Ensure T has sufficient range for the value.
uint32_trandomNumberGenerates a 31-bit pseudo random number using the internal Random instance.
std::stringrandomStringGenerates a random alphanumeric string of the given length.
std::stringrandomBinaryStringGenerates a random binary string of the given byte length.
voidsplitSplits str on the delimiter string and appends tokens to elems.
std::vector< std::string >splitSplits str on the delimiter string and returns the tokens as a vector.
voidsplitSplits str on the delimiter character and appends tokens to elems.
std::vector< std::string >splitSplits str on the delimiter character and returns the tokens as a vector.
S &replaceInPlaceReplace all occurrences of from in str with to, starting at position start. Modifies and returns str in place. from must not be empty.
S &replaceInPlaceReplace all occurrences of from in str with to, starting at position start. C-string overload. Modifies and returns str in place.
SreplaceReplace all occurences of from (which must not be the empty string) in str with to, starting at position start.
SreplaceReturns a copy of str with all occurrences of from replaced by to (C-string overload).
StrimLeftReturns a copy of str with all leading whitespace removed.
S &trimLeftInPlaceRemoves all leading whitespace in str.
StrimRightReturns a copy of str with all trailing whitespace removed.
S &trimRightInPlaceRemoves all trailing whitespace in str.
StrimReturns a copy of str with all leading and trailing whitespace removed.
S &trimInPlaceRemoves all leading and trailing whitespace in str.
StoUpperReturns a copy of str containing all upper-case characters.
S &toUpperInPlaceReplaces all characters in str with their upper-case counterparts.
StoLowerReturns a copy of str containing all lower-case characters.
S &toLowerInPlaceReplaces all characters in str with their lower-case counterparts.
inticompare inlineCase-insensitive string comparison (locale-independent, ASCII only).
std::streamsizecopyStreamUnbufferedCopies all bytes from istr to ostr one byte at a time (no internal buffer).
std::streamsizecopyStreamCopies all bytes from istr to ostr using an internal buffer.
std::streamsizecopyToStringReads all bytes from istr and appends them to str.
voidclearList inlineDelete all elements from a list of pointers.
voidclearDeque inlineDelete all elements from a deque of pointers.
voidclearVector inlineDelete all elements from a vector of pointers.
voidclearMap inlineDelete 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

  • fmt printf 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

  • str String to transform in place.

{#isnumber}

isNumber

bool isNumber(std::string_view str)

Returns true if str consists entirely of digit characters.

Parameters

  • str String 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

  • str String to test.

  • suffix Suffix 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

  • str String to modify.

  • allowSpaces If 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

  • str String to modify.

  • with Replacement character (default: '_').

  • allowSpaces If 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

  • s Hex string (with or without 0x prefix).

  • value Output: 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

  • s Hex string (with or without 0x prefix).

Returns

Parsed value.

Exceptions

  • std::invalid_argument if 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

  • data Pointer to the buffer to dump.

  • len Number 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

  • l Left (local) version string.

  • r Right (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

  • node Node list string to test.

  • xnode Expected node list pattern.

  • delim Delimiter 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

  • params Parameter list to test.

  • xparams Expected 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

  • ptr Pointer 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

  • T Type to convert; must support operator<< on std::ostream.

Parameters

  • t Value 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

  • T Target integer type.

Parameters

  • s String 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

  • size Number 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

  • size Number of random bytes to generate.

  • doBase64 If 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

  • str String to split.

  • delim Delimiter string.

  • elems Output vector; tokens are appended to it.

  • limit Maximum 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

  • str String to split.

  • delim Delimiter string.

  • limit Maximum 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

  • str String to split.

  • delim Delimiter character.

  • elems Output vector; tokens are appended to it.

  • limit Maximum 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

  • str String to split.

  • delim Delimiter character.

  • limit Maximum 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

  • str Source string.

  • from Substring to search for; must not be empty.

  • to Replacement string.

  • start Position 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

  • a First string.

  • b Second 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

  • istr Source stream.

  • ostr Destination 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

  • istr Source stream.

  • ostr Destination stream.

  • bufferSize Internal 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

  • istr Source stream.

  • str Output string to append data to.

  • bufferSize Internal 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

ReturnNameDescription
intmajor
intminor
intrevision
intbuild

{#major}

major

int major

{#minor}

minor

int minor

{#revision}

revision

int revision

{#build}

build

int build

Public Methods

ReturnNameDescription
Version inlineParses 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".
booloperator< inlineReturns true if this version is strictly less than other. Compares fields in major, minor, revision, build order.
booloperator== const inlineReturns 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

  • version Dot-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

  • other Version 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

  • other Version 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

ReturnNameDescription
PipeConstruct a [Pipe](#pipe) bound to loop without initializing the libuv handle.
~Pipe virtualDestroy the pipe, stopping reads and closing the handle.
voidinit virtualInitialize the underlying uv_pipe_t handle.
boolreadStart virtualStart 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

  • loop Event 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

  • ipc Set to true to 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

ReturnNameDescription
IdlerCreate the idler bound to loop without starting it.
Idler inline explicitCreate and immediately start the idler on the default loop.
Idler inline explicitCreate and immediately start the idler on the given loop.
voidstart inlineStart the idler, invoking func (with args) on every idle iteration.
voidstart virtualStart 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

  • loop Event 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

  • func Callable invoked on every idle iteration.

  • args Arguments forwarded to func.


{#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

  • loop Event loop to associate with.

  • func Callable invoked on every idle iteration.

  • args Arguments forwarded to func.


{#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

  • func Callable invoked each time the event loop is idle.

  • args Arguments forwarded to func on 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

  • func Callback 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

ReturnNameDescription
uv::Handle< uv_idle_t >_handle

{#_handle}

_handle

uv::Handle< uv_idle_t > _handle

Protected Methods

ReturnNameDescription
voidinit virtualInitialize the underlying uv_idle_t handle and unref it from the loop.
boolasync 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

ReturnNameDescription
voidpush inlineAppends an item to the back of the queue (thread-safe).
voidpush inlineAppends an item to the back of the queue by move (thread-safe).
boolempty const inline#### Returns
Tfront const inline#### Returns
Tback const inline#### Returns
voidpop inlineRemoves the front item from the queue (thread-safe).
voidsort inlineSorts all queued items using the given comparator (thread-safe).
size_tsize 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

  • data Item to enqueue.

{#push}

push

inline

inline void push(T && data)

Appends an item to the back of the queue by move (thread-safe).

Parameters

  • data Item 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

  • Compare Comparator type compatible with std::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

ReturnNameDescription
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 * >, Runnable Subclassed by: AsyncQueue< IPacket >, AsyncQueue< PacketT >, PlanarAudioPacket >, PlanarVideoPacket >, SyncQueue< IPacket >, AsyncQueue< T >, SyncQueue< T >

Queue of runnable tasks for sequential execution.

Public Attributes

ReturnNameDescription
std::function< void(T &)>ondispatchThe 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

ReturnNameDescription
RunnableQueue inline#### Parameters
voidpush virtual inlinePush an item onto the queue. The queue takes ownership of the item pointer.
voidflush virtual inlineFlush all outgoing items.
voidclear inline
voidrun virtual inlineCalled asynchronously to dispatch queued items. If not timeout is set this method blocks until cancel() is called, otherwise runTimeout() will be called.
voidrunTimeout virtual inlineCalled asynchronously to dispatch queued items until the queue is empty or the timeout expires. Pseudo protected for std::bind compatability.
voiddispatch virtual inlineDispatch a single item to listeners.
inttimeout inline#### Returns
voidsetTimeout inlineSets the dispatch timeout. Must only be called when the queue is empty.
size_tdropped const inline#### Returns

{#runnablequeue}

RunnableQueue

inline

inline RunnableQueue(int limit, int timeout)

Parameters

  • limit Maximum number of queued items; oldest are purged when exceeded (0 = unlimited).

  • timeout Dispatch 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

  • milliseconds New timeout in milliseconds.

Exceptions

  • std::logic_error if 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

ReturnNameDescription
int_limit
int_timeout
size_t_dropped

{#_limit}

_limit

int _limit

{#_timeout}

_timeout

int _timeout

{#_dropped}

_dropped

size_t _dropped = 0

Protected Methods

ReturnNameDescription
RunnableQueueDeleted constructor.
RunnableQueueDeleted constructor.
T *popNext virtual inlinePops the next waiting item.
booldispatchNext virtual inlinePops 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

ReturnNameDescription
SyncQueue inline#### Parameters
~SyncQueue virtual inlineDestruction is deferred to allow enough time for all callbacks to return.
voidpush virtual inlinePushes an item onto the queue and wakes the event loop for dispatch. Ownership of item is transferred to the queue.
voidcancel virtual inlineCancels the queue and its underlying synchronizer.
Synchronizer &sync inline#### Returns

{#syncqueue}

SyncQueue

inline

inline SyncQueue(uv::Loop * loop, int limit, int timeout)

Parameters

  • loop Event loop used by the internal [Synchronizer](#synchronizer).

  • limit Maximum queued items; oldest are dropped when exceeded.

  • timeout Dispatch 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

  • item Heap-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

  • flag True to cancel, false to un-cancel.

{#sync}

sync

inline

inline Synchronizer & sync()

Returns

Reference to the underlying [Synchronizer](#synchronizer) handle.

Protected Attributes

ReturnNameDescription
Synchronizer_sync

{#_sync}

_sync

Synchronizer _sync

Public Types

NameDescription
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

ReturnNameDescription
AsyncQueue inline#### Parameters
voidcancel virtual inlineCancels the queue and joins the dispatch thread.

{#asyncqueue}

AsyncQueue

inline

inline AsyncQueue(int limit)

Parameters

  • limit Maximum 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

  • flag True to cancel, false to un-cancel.

Protected Attributes

ReturnNameDescription
Thread_thread

{#_thread}

_thread

Thread _thread

Public Types

NameDescription
Queue

{#queue}

Queue

RunnableQueue< T > Queue()

{#timer}

Timer

#include <icy/timer.h>

Inherits: Runner

Asynchronous event based timer.

Public Attributes

ReturnNameDescription
NullSignalTimeoutSignal that gets triggered on timeout.

{#timeout}

Timeout

NullSignal Timeout

Signal that gets triggered on timeout.

Public Methods

ReturnNameDescription
TimerCreate a timer without a timeout or interval; values must be set before [start()](#classicy_1_1Timer_1a59e3275d17107212520b362cbf0cb3d5).
TimerCreate a one-shot timer that fires after timeout milliseconds.
TimerCreate a repeating timer with an initial delay and a repeat period.
~Timer virtualDestructor.
voidstartStart the timer using the previously configured timeout and interval.
voidstart virtualConnect func to the [Timeout](#timeout) signal and start the timer.
voidstopStop the timer. Resets the fire count to zero.
voidrestartRestart the timer.
voidagainReset the countdown without stopping and restarting the timer.
voidsetTimeoutSet the initial delay before the first timeout event.
voidsetIntervalSet the repeat interval (calls uv_timer_set_repeat).
boolactive const#### Returns
std::int64_ttimeout const#### Returns
std::int64_tinterval const#### Returns
std::int64_tcount#### Returns
uv::Handle< uv_timer_t > &handle#### Returns
boolasync 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

  • loop Event 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

  • timeout Delay in milliseconds before the first (and only) fire.

  • loop Event loop to associate with.

  • func Optional 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

  • timeout Initial delay in milliseconds.

  • interval Repeat period in milliseconds.

  • loop Event loop to associate with.

  • func Optional 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

  • func Callback 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

  • timeout Delay 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

  • interval Repeat 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

ReturnNameDescription
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

ReturnNameDescription
TimerDeleted constructor.
TimerDeleted constructor.
voidinit

{#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

ReturnNameDescription
constexprMutableBuffer inlineConstruct an empty buffer.
constexprMutableBuffer inlineConstruct a buffer to represent the given memory range.
constexpr void *data const inline
constexpr size_tsize const inline
char *cstr const inlineCast the buffer as a char pointer.
std::stringstr const inlineReturns 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

ReturnNameDescription
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

ReturnNameDescription
constexprConstBuffer inlineConstruct an empty buffer.
constexprConstBuffer inlineConstruct a buffer to represent the given memory range.
constexprConstBuffer inlineConstruct a non-modifiable buffer from a modifiable one.
constexpr const void *data const inline
constexpr size_tsize const inline
const char *cstr const inlineCast the buffer as a const char pointer.
std::stringstr const inlineReturns 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

ReturnNameDescription
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

ReturnNameDescription
BitReaderConstructs a [BitReader](#bitreader) over a raw byte array.
BitReaderConstructs a [BitReader](#bitreader) over a Buffer.
BitReaderConstructs a [BitReader](#bitreader) over a [ConstBuffer](#constbuffer).
voidgetReads 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.
voidgetReads len bytes and appends them to val. Throws std::out_of_range if insufficient data remains.
voidgetU8Reads an unsigned 8-bit integer. Throws std::out_of_range if insufficient data remains.
voidgetU16Reads an unsigned 16-bit integer, applying byte-order conversion. Throws std::out_of_range if insufficient data remains.
voidgetU24Reads an unsigned 24-bit integer into a 32-bit variable, applying byte-order conversion. Throws std::out_of_range if insufficient data remains.
voidgetU32Reads an unsigned 32-bit integer, applying byte-order conversion. Throws std::out_of_range if insufficient data remains.
voidgetU64Reads an unsigned 64-bit integer, applying byte-order conversion. Throws std::out_of_range if insufficient data remains.
charpeekPeeks at the current byte without advancing the position.
uint8_tpeekU8Peeks at the current byte as a uint8_t without advancing the position.
uint16_tpeekU16Peeks at the next two bytes as a uint16_t without advancing the position.
uint32_tpeekU24Peeks at the next three bytes as a uint32_t without advancing the position.
uint32_tpeekU32Peeks at the next four bytes as a uint32_t without advancing the position.
uint64_tpeekU64Peeks data from the BitReader. -1 is returned if reading past boundary.
size_tskipToCharAdvances the position until the given character is found, stopping before it.
size_tskipWhitespaceAdvances the position past any leading space characters.
size_tskipToNextLineAdvances the position past the end of the current line (past the newline).
size_tskipNextWordAdvances the position past the next whitespace-delimited word.
size_treadNextWordReads the next whitespace-delimited word into val.
size_treadNextNumberReads the next whitespace-delimited decimal number into val.
size_treadLineReads bytes up to (but not including) the next newline into val.
size_treadToNextReads bytes up to (but not including) the next occurrence of c into val.
voidseekSet position pointer to absolute position. Throws a std::out_of_range exception if the value exceeds the limit.
voidskipSet position pointer to relative position. Throws a std::out_of_range exception if the value exceeds the limit.
size_tlimit constReturns the read limit.
size_tposition const inlineReturns the current read position.
size_tavailable constReturns the number of elements between the current position and the limit.
const char *begin const inlineReturns a pointer to the start of the buffer.
const char *current const inlineReturns a pointer to the current read position.
ByteOrderorder const inlineReturns the byte order used for multi-byte integer reads.
std::stringtoStringReturns 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

  • bytes Pointer to the start of the data. Must remain valid for the lifetime of the reader.

  • size Number of bytes available for reading.

  • order Byte order used when reading multi-byte integer types.


{#bitreader}

BitReader

BitReader(const Buffer & buf, ByteOrder order)

Constructs a [BitReader](#bitreader) over a Buffer.

Parameters

  • buf Source buffer. Must remain valid for the lifetime of the reader.

  • order Byte 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

  • pod Source const buffer. Must remain valid for the lifetime of the reader.

  • order Byte 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

  • val Destination buffer; must have capacity of at least len bytes.

  • len Number 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

  • val String to append the read bytes to.

  • len Number 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

  • val Output 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

  • val Output 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

  • val Output 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

  • val Output 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

  • val Output 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

  • c Character 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

  • val String 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

  • val Output 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

  • val String 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

  • val String to receive the read bytes.

  • c Delimiter 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

ReturnNameDescription
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

ReturnNameDescription
voidinit

{#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

ReturnNameDescription
BitWriterConstructs a [BitWriter](#bitwriter) over a raw byte array with a fixed capacity.
BitWriterConstructs a [BitWriter](#bitwriter) backed by a Buffer. Writes are bounded by the buffer's capacity; use [DynamicBitWriter](#dynamicbitwriter) for auto-resize.
BitWriterConstructs a [BitWriter](#bitwriter) over a [MutableBuffer](#mutablebuffer) with a fixed capacity.
voidput virtualAppend bytes to the buffer. Throws a std::out_of_range exception if reading past the limit.
voidputAppends the contents of a string. Throws std::out_of_range if capacity is exceeded.
voidputU8Appends an unsigned 8-bit integer. Throws std::out_of_range if capacity is exceeded.
voidputU16Appends an unsigned 16-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded.
voidputU24Appends the low 24 bits of a 32-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded.
voidputU32Appends an unsigned 32-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded.
voidputU64Appends an unsigned 64-bit integer with byte-order conversion. Throws std::out_of_range if capacity is exceeded.
boolupdate virtualUpdate a byte range. Throws a std::out_of_range exception if reading past the limit.
boolupdateOverwrites a previously written string at the given absolute position.
boolupdateU8Overwrites a uint8_t at the given absolute position.
boolupdateU16Overwrites a uint16_t at the given absolute position, with byte-order conversion.
boolupdateU24Overwrites 3 bytes (low 24 bits of val) at the given absolute position, with byte-order conversion.
boolupdateU32Overwrites a uint32_t at the given absolute position, with byte-order conversion.
boolupdateU64Overwrites a uint64_t at the given absolute position, with byte-order conversion.
voidseekSet position pointer to absolute position. Throws a std::out_of_range exception if the value exceeds the limit.
voidskipSet position pointer to relative position. Throws a std::out_of_range exception if the value exceeds the limit.
size_tlimit constReturns the write limit.
size_tposition const inlineReturns the current write position.
size_tavailable constReturns the number of elements between the current write position and the limit.
char *begin inlineReturns a pointer to the start of the write buffer.
char *current inlineReturns a pointer to the current write position.
const char *begin const inlineReturns a const pointer to the start of the write buffer.
const char *current const inlineReturns a const pointer to the current write position.
ByteOrderorder const inlineReturns the byte order used for multi-byte integer writes.
std::stringtoStringReturns 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

  • bytes Pointer to the writable buffer. Must remain valid for the writer's lifetime.

  • size Capacity of the buffer in bytes.

  • order Byte 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

  • buf Source buffer. Must remain valid for the writer's lifetime.

  • order Byte 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

  • pod Source mutable buffer. Must remain valid for the writer's lifetime.

  • order Byte 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

  • val String 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

  • val Value 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

  • val Value 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

  • val Value 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

  • val Value 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

  • val Value 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

  • val String to write.

  • pos Absolute 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

  • val Value to write.

  • pos Absolute 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

  • val Value to write.

  • pos Absolute 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

  • val Value to write.

  • pos Absolute 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

  • val Value to write.

  • pos Absolute 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

  • val Value to write.

  • pos Absolute 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

ReturnNameDescription
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

ReturnNameDescription
voidinit 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

ReturnNameDescription
DynamicBitWriterConstructs a [DynamicBitWriter](#dynamicbitwriter) backed by a dynamically resizable Buffer. The buffer is expanded automatically as data is written.
DynamicBitWriterConstructs a [DynamicBitWriter](#dynamicbitwriter) that inserts data starting at a specific iterator position.
voidput virtualAppend bytes to the buffer. Throws a std::out_of_range exception if reading past the limit.
boolupdate virtualUpdate 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

  • buf Buffer to write into; expanded as needed.

  • order Byte 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

  • buf Buffer to write into; expanded as needed.

  • offset Iterator into buf indicating the insertion start point.

  • order Byte 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

ReturnNameDescription
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

ReturnNameDescription
LogWriter
voidwrite virtualWrites 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>

Inherits: LogWriter, Runnable

Thread based log output stream writer.

Public Methods

ReturnNameDescription
AsyncLogWriter
voidwrite virtualQueues the given log message stream.
voidflushFlushes queued messages.
voidrun virtualWrites queued messages asynchronously.
voidclearClears 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

ReturnNameDescription
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

ReturnNameDescription
boolwriteNext

{#writenext}

writeNext

bool writeNext()

{#logger}

Logger

#include <icy/logger.h>

Logger class.

Public Methods

ReturnNameDescription
Logger
voidaddAdds the given log channel. Takes ownership.
voidremoveRemoves the given log channel by name.
LogChannel *get constReturns the specified log channel. Throws an exception if the channel doesn't exist.
voidsetDefaultSets the default log to the specified log channel.
voidsetWriterSets the log writer instance. Takes ownership.
LogChannel *getDefault constReturns the default log channel, or the nullptr channel if no default channel has been set.
voidwriteWrites the given message to the default log channel. The message will be copied.
voidwriteWrites 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

ReturnNameDescription
Logger &instance staticReturns the default logger singleton. Logger instances may be created separately as needed.
voidsetInstance staticSets the default logger singleton instance.
voiddestroy staticDestroys 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

ReturnNameDescription
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

ReturnNameDescription
LoggerNonCopyable and NonMovable.
LoggerDeleted 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

ReturnNameDescription
LogChannel#### Parameters
voidwrite virtualWrites a log stream entry to this channel.
voidwrite virtualWrites a plain message to this channel.
voidformat virtualFormats a log stream entry into the given output stream.
std::stringname const inlineReturns the channel name.
Levellevel const inlineReturns the minimum severity level.
std::stringtimeFormat const inlineReturns the timestamp format string.
voidsetLevel inlineSets the minimum severity level.
voidsetTimeFormat inlineSets the timestamp format string.
voidsetFilter inlineSets a realm filter; only messages whose realm matches are written.

{#logchannel}

LogChannel

LogChannel(std::string name, Level level, std::string timeFormat)

Parameters

  • name Unique channel name.

  • level Minimum severity level; messages below this level are dropped.

  • timeFormat strftime-compatible format string for timestamps.


{#write}

write

virtual

virtual void write(const LogStream & stream)

Writes a log stream entry to this channel.

Parameters

  • stream The 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

  • message Log message text.

  • level Severity level for the message.

  • realm Optional 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

  • stream The log stream to format.

  • ost The 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

  • level Messages below this level are dropped.

{#settimeformat}

setTimeFormat

inline

inline void setTimeFormat(std::string format)

Sets the timestamp format string.

Parameters

  • format strftime-compatible format string.

{#setfilter}

setFilter

inline

inline void setFilter(std::string filter)

Sets a realm filter; only messages whose realm matches are written.

Parameters

  • filter Realm substring or pattern to match against.

Protected Attributes

ReturnNameDescription
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

ReturnNameDescription
ConsoleChannel#### Parameters
voidwrite virtualFormats 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

  • name Unique channel name.

  • level Minimum severity level; messages below this level are dropped.

  • timeFormat strftime-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

  • stream The log stream to write.

{#filechannel}

FileChannel

#include <icy/logger.h>

Inherits: LogChannel

Log channel that writes formatted messages to a file.

Public Methods

ReturnNameDescription
FileChannel#### Parameters
voidwrite virtualFormats and writes the log stream entry to the file. Opens the file on first write if not already open.
voidsetPathSets the file path and reopens the file stream.
std::stringpath constReturns the current log file path.

{#filechannel}

FileChannel

FileChannel(std::string name, std::string path, Level level, std::string timeFormat)

Parameters

  • name Unique channel name.

  • path Path to the output log file. Directories are created if needed.

  • level Minimum severity level; messages below this level are dropped.

  • timeFormat strftime-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

  • stream The log stream to write.

{#setpath}

setPath

void setPath(const std::string & path)

Sets the file path and reopens the file stream.

Parameters

  • path Path 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

ReturnNameDescription
std::ofstream_fstream
std::string_path

{#_fstream}

_fstream

std::ofstream _fstream

{#_path}

_path

std::string _path

Protected Methods

ReturnNameDescription
voidopen virtual
voidclose 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

ReturnNameDescription
RotatingFileChannel#### Parameters
voidwrite virtualFormats and writes the log stream entry to the current log file. Rotates the file if the rotation interval has elapsed.
voidrotate virtualCloses the current log file and opens a new one with a timestamped filename.
std::stringdir const inlineReturns the directory where log files are written.
std::stringfilename const inlineReturns the filename of the currently open log file.
introtationInterval const inlineReturns the rotation interval in seconds.
voidsetDir inlineSets the output directory for rotated log files.
voidsetExtension inlineSets the file extension for rotated log files.
voidsetRotationInterval inlineSets the rotation interval.

{#rotatingfilechannel}

RotatingFileChannel

RotatingFileChannel(std::string name, std::string dir, Level level, std::string extension, int rotationInterval, std::string timeFormat)

Parameters

  • name Unique channel name.

  • dir Directory in which rotated log files are written.

  • level Minimum severity level; messages below this level are dropped.

  • extension File extension for log files (without leading dot).

  • rotationInterval Seconds between log rotations (default: 12 hours).

  • timeFormat strftime-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

  • stream The 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

  • dir Target directory path.

{#setextension}

setExtension

inline

inline void setExtension(std::string ext)

Sets the file extension for rotated log files.

Parameters

  • ext Extension without leading dot (e.g. "log").

{#setrotationinterval}

setRotationInterval

inline

inline void setRotationInterval(int interval)

Sets the rotation interval.

Parameters

  • interval Number of seconds between rotations.

Protected Attributes

ReturnNameDescription
std::unique_ptr< std::ofstream >_fstream
std::string_dir
std::string_filename
std::string_extension
int_rotationIntervalThe log rotation interval in seconds.
time_t_rotatedAtThe 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, then use IntrusivePtr instead of std::shared_ptr.

Public Methods

ReturnNameDescription
RefCountedDefaulted constructor.
RefCounted inline
voidaddRef const inlineIncrements the reference count. Called by IntrusivePtr on acquisition.
boolreleaseRef const inlineDecrements the reference count.
intrefCount const inlineReturns 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

ReturnNameDescription
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

ReturnNameDescription
IntrusivePtr inline
IntrusivePtr inline
IntrusivePtr inline explicit
IntrusivePtr inline
IntrusivePtr inline
IntrusivePtr inline
IntrusivePtr inline
voidreset inlineReleases ownership of the current pointer, decrementing its refcount. The pointer is set to null.
voidreset inlineReleases the current pointer and takes ownership of p, incrementing its refcount.
T *get const inlineReturns the raw pointer without transferring ownership.
T &operator* const inlineDereferences the managed pointer.
T *operator-> const inlineMember access on the managed pointer.
operator bool const inline explicitReturns true if the pointer is non-null.
voidswap inlineSwaps the managed pointer with another IntrusivePtr.
voiddetach inlineRelease ownership without decrementing refcount. Used internally for move construction across types.
booloperator== const inline
booloperator!= const inline
booloperator== const inline
booloperator!= const inline
booloperator< 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

  • p New 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


{#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

ReturnNameDescription
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

ReturnNameDescription
RandomCreates and initializes the PRNG. The stateSize parameter is accepted for API compatibility but is ignored; the engine always uses mt19937's fixed state size.
~RandomDestroys the PRNG.
voidseedSeeds the pseudo random generator with the given seed.
voidseedSeeds the pseudo random generator with entropy from std::random_device.
uint32_tnextReturns the next pseudo random number from the mt19937 engine.
uint32_tnextReturns the next pseudo random number in the range [0, n).
charnextCharReturns the next pseudo random byte as a char.
boolnextBoolReturns the next pseudo random boolean value.
floatnextFloatReturns the next pseudo random float in [0.0, 1.0].
doublenextDoubleReturns 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

  • stateSize Ignored; 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

  • seed 32-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

  • n Upper 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

ReturnNameDescription
voidgetSeed staticFills 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

  • seed Buffer to fill.

  • length Number of bytes to write into seed.

Private Attributes

ReturnNameDescription
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

ReturnNameDescription
Runner
voidstartStarts the asynchronous context with the given callback. The callback must remain valid for the lifetime of the [Runner](#runner).
boolrunning constReturns true if the async context is currently running.
voidcancelSignals the async context to stop at the earliest opportunity.
boolcancelled constReturns true if the context has been cancelled. The implementation is responsible for exiting as soon as possible after cancellation.
boolrepeating constReturns true if the runner is in repeating mode.
voidsetRepeatingEnables 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).
boolasync constReturns true if the implementation is thread-based.
std::thread::idtid constReturns the native thread ID of the thread running the async context.
boolwaitForExitBlocks 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

  • target Callable 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

  • flag True 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

  • timeout Maximum 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

ReturnNameDescription
std::shared_ptr< Context >_contextShared pointer to the internal Context.

{#_context}

_context

std::shared_ptr< Context > _context

Shared pointer to the internal Context.

Protected Methods

ReturnNameDescription
RunnerNonCopyable and NonMovable.
RunnerDeleted 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

ReturnNameDescription
intattach const inlineConnects a lambda or std::function to the signal.
intattach const inlineConnects a pre-constructed SlotPtr to the signal.
booldetach const inlineDetaches the slot with the given ID.
booldetach const inlineDetaches all slots associated with the given instance pointer.
booldetach const inlineDetaches the slot whose delegate compares equal to other->delegate.
voiddetachAll const inlineDetaches and destroys all currently attached slots.
RTemit virtual inlineEmits the signal, invoking all live attached slots in priority order.
std::vector< SlotPtr >slots const inlineReturns a snapshot copy of the current slot list.
size_tnslots const inlineReturns the number of slots currently registered with this signal.
intoperator+= inlineAttaches a function; equivalent to attach(func).
intoperator+= inlineAttaches a pre-constructed slot; equivalent to attach(slot).
booloperator-= inlineDetaches the slot with the given ID; equivalent to detach(id).
booloperator-= inlineDetaches all slots for the given instance; equivalent to detach(instance).
booloperator-= inlineDetaches the slot matching slot's delegate; equivalent to detach(slot).
SignalDefaulted constructor.
Signal inlineCopy constructor; copies the slot list and last-assigned ID from r.
Signal &operator= inlineCopy 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

  • func The callable to invoke when the signal is emitted.

  • instance Optional owner pointer used for instance-based detach; pass nullptr if not applicable.

  • id Explicit slot ID to assign; pass -1 to auto-assign.

  • priority Higher values are called first; pass -1 for 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

  • slot The 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_error if slot->id is 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

  • id The 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

  • instance The 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

  • other A 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

  • args Arguments 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

  • r The 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

  • r The signal to copy from.

Returns

Reference to this signal.

Public Types

NameDescription
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

ReturnNameDescription
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

ReturnNameDescription
size_tkillMatchingLocked const inline
size_temitDepthLocked const inline
voidbeginEmitLocked const inline
boolendEmitLocked const inline
voidrequestSweepLocked const inline
boolconsumeSweepRequest const inline
voidsweepLocked const inline
voidfinishEmit inline
voidresetEmitState 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

ReturnNameDescription
Signal< void(const char *, const int &)>ReadEmitted 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

ReturnNameDescription
Stream inlineConstruct the stream bound to loop with a 64 KiB read buffer.
~Stream virtual inlineDestroy the stream, stopping reads and freeing pooled write requests.
voidclose virtual inlineCloses and resets the stream handle. This will close the active socket/pipe and destroy the handle.
boolshutdown inlineSend a TCP/pipe shutdown request to the connected peer.
boolwrite inlineWrite len bytes from data to the stream.
boolwriteOwned inlineWrite an owned payload buffer to the stream.
voidsetHighWaterMark inlineSet the high water mark for the write queue (default 16MB). When the write queue exceeds this size, write() returns false.
boolwrite inlineWrite len bytes from data together with a stream handle over an IPC pipe (uses uv_write2).
uv_stream_t *stream inlineReturn 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

  • loop Event 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

  • data Pointer to the bytes to send. Must remain valid until the write completion callback fires.

  • len Number 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

  • buffer Payload 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

  • data Bytes to send alongside the handle.

  • len Number of bytes to send.

  • send Stream 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

ReturnNameDescription
Buffer_buffer
bool_started
size_t_highWaterMark16MB default write queue limit
std::vector< uv_write_t * >_writeReqFreeFreelist for write requests.
std::vector< OwnedWriteReq * >_ownedWriteReqFreeFreelist 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

ReturnNameDescription
boolreadStart virtual inlineBegin reading from the stream by registering libuv read callbacks.
boolreadStop virtual inlineStop reading from the stream.
voidonRead virtual inlineCalled by handleRead when len bytes of data arrive.
uv_write_t *allocWriteReq inlineReturn a uv_write_t from the freelist, or allocate a new one if the pool is empty.
voidfreeWriteReq inlineReturn req to the freelist, or delete it if the pool is at capacity.
OwnedWriteReq *allocOwnedWriteReq inline
voidfreeOwnedWriteReq inline
boolcanQueueWrite 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

  • data Pointer into the read buffer; valid only for this call.

  • len Number of valid bytes in data.


{#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

  • req Write 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

NameDescription
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

ReturnNameDescription
ThreadDefault constructor.
Thread inline explicitConstructs a [Thread](#thread) and immediately starts it with the given function and arguments.
~Thread virtualDestructor.
voidstart inlineStarts the thread with a variadic function and arguments. The thread is started immediately; the previous thread must have exited before calling again.
voidstart virtualStarts the thread with a std::function callback. Overrides [Runner::start](#classicy_1_1Runner_1a5969e823f1ce0bdd8730d3108bf13fbd); delegates to the variadic start template.
voidjoinWait until the thread exits.
std::thread::idid constReturn 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

  • Function Callable type.

  • Args Argument types forwarded to the function.

Parameters

  • func Callable to execute on the new thread.

  • args Arguments forwarded to func.


{#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

  • Function Callable type.

  • Args Argument types forwarded to the function.

Parameters

  • func Callable to execute on the new thread.

  • args Arguments forwarded to func.


{#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

  • func Callable 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

ReturnNameDescription
const std::thread::idmainID staticAccessor for the main thread ID.

{#mainid}

mainID

static

const std::thread::id mainID

Accessor for the main thread ID.

Public Static Methods

ReturnNameDescription
std::thread::idcurrentID staticReturn 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

ReturnNameDescription
std::thread_thread

{#_thread}

_thread

std::thread _thread

Protected Methods

ReturnNameDescription
ThreadNonCopyable and NonMovable.
ThreadDeleted constructor.
boolasync virtual constReturns 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

NameDescription
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

ReturnNameDescription
std::stringfilePath to the program to execute. Convenience proxy for options.file. Must be set before [spawn()](#classicy_1_1Process_1a1d4f466c7f2713460ee35954dc6663bc)
std::stringcwdSet the current working directory. Convenience proxy for options.cwd. Must be set before [spawn()](#classicy_1_1Process_1a1d4f466c7f2713460ee35954dc6663bc)
std::vector< std::string >argsCommand 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 >envEnvironment 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)>onstdoutStdout callback. Called when a line has been output from the process.
std::function< void(std::string)>onstderrStderr callback. Called when a line has been output on stderr.
std::function< void(std::int64_t)>onexitExit callback. Called with process exit status code.
ProcessOptionsoptionsLibUV 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

ReturnNameDescription
ProcessConstructs a [Process](#process) attached to the given event loop.
ProcessConstructs a [Process](#process) with initial command-line arguments.
~ProcessDestructor.
ProcessDeleted constructor.
ProcessDeleted constructor.
voidspawnSpawns the process. Options must be properly set. Throws an exception on error.
boolkillSends a signal to the process.
intpid constReturns the process PID, or 0 if not spawned.
Pipe &inReturns the stdin pipe.
Pipe &outReturns the stdout pipe.
Pipe &errReturns the stderr pipe.

{#process}

Process

Process(uv::Loop * loop)

Constructs a [Process](#process) attached to the given event loop.

Parameters

  • loop Event 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

  • args Initializer list of argument strings. The first element is typically the executable path.

  • loop Event 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

  • signum Signal 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

ReturnNameDescription
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

ReturnNameDescription
voidinit

{#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

ReturnNameDescription
TimeoutConstructs a Timeout with the given delay.
TimeoutCopy constructor.
TimeoutDefaulted constructor.
boolrunning constReturns true if the timer is currently running.
voidstartStarts (or restarts) the timer, recording the current time as the start point.
voidstopStops the timer without resetting it. expired() will return false after this call.
voidresetRestarts the timer from now, equivalent to calling start().
longremaining constReturns the number of milliseconds remaining before expiry. Returns 0 if already expired, or the full delay if not running.
boolexpired constReturns true if the timer is running and the delay has fully elapsed.
voidsetDelay inlineSets the expiry delay without restarting the timer.
longdelay const inlineReturns 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

  • delay Expiry duration in milliseconds (default: 0).

  • autoStart If true, starts the timer immediately on construction.


{#timeout}

Timeout

Timeout(const Timeout & src)

Copy constructor.

Parameters

  • src Source 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

  • delay New 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

  • src Source Timeout to copy state from.

Protected Attributes

ReturnNameDescription
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

ReturnNameDescription
TimedToken explicitConstructs a TimedToken with a randomly generated 32-character ID, started immediately with the given duration.
TimedToken explicitConstructs a TimedToken with an explicit ID, started immediately.
std::stringid const inlineReturns the token's identifier string.
booloperator== const inlineCompares two tokens by ID.
booloperator== const inlineCompares 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

  • duration Lifetime 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

  • id Token identifier.

  • duration Lifetime 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

ReturnNameDescription
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

ReturnNameDescription
TimestampCreates a timestamp with the current time.
TimestampCreates a timestamp from the given time value.
TimestampCopy constructor.
~TimestampDestroys the timestamp.
voidswapSwaps the Timestamp with another one.
voidupdateUpdates the Timestamp with the current time.
booloperator== const inline
booloperator!= const inline
booloperator> const inline
booloperator>= const inline
booloperator< const inline
booloperator<= const inline
Timestampoperator+ const inline
Timestampoperator- const inline
TimeDiffoperator- const inline
Timestamp &operator+= inline
Timestamp &operator-= inline
std::time_tepochTime const inlineReturns the timestamp expressed in time_t. time_t base time is midnight, January 1, 1970. Resolution is one second.
UtcTimeValutcTime const inlineReturns the timestamp expressed in UTC-based time. UTC base time is midnight, October 15, 1582. Resolution is 100 nanoseconds.
TimeValepochMicroseconds const inlineReturns the timestamp expressed in microseconds since the Unix epoch, midnight, January 1, 1970.
TimeDiffelapsed const inlineReturns the time elapsed since the time denoted by the timestamp. Equivalent to Timestamp() - *this.
boolisElapsed const inlineReturns 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

ReturnNameDescription
TimestampfromEpochTime staticCreates a timestamp from a std::time_t.
TimestampfromUtcTime staticCreates a timestamp from a UTC time value.
TimeValresolution static inlineReturns 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

NameDescription
TimeValmonotonic UTC time value in microsecond resolution
UtcTimeValmonotonic UTC time value in 100 nanosecond resolution
TimeDiffdifference 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

ReturnNameDescription
TimeVal_ts

{#_ts}

_ts

TimeVal _ts

{#timespan}

Timespan

#include <icy/datetime.h>

A class that represents time spans up to microsecond resolution.

Public Methods

ReturnNameDescription
TimespanCreates a zero Timespan.
TimespanCreates a Timespan.
TimespanCreates a Timespan. Useful for creating a Timespan from a struct timeval.
TimespanCreates a Timespan.
TimespanCreates a Timespan from another one.
~TimespanDestroys the Timespan.
Timespan &operator=Assignment operator.
Timespan &operator=Assignment operator.
Timespan &assignAssigns a new span.
Timespan &assignAssigns a new span. Useful for assigning from a struct timeval.
voidswapSwaps the Timespan with another one.
booloperator== const inline
booloperator!= const inline
booloperator> const inline
booloperator>= const inline
booloperator< const inline
booloperator<= const inline
booloperator== const inline
booloperator!= const inline
booloperator> const inline
booloperator>= const inline
booloperator< const inline
booloperator<= const inline
Timespanoperator+ const
Timespanoperator- const
Timespan &operator+=
Timespan &operator-=
Timespanoperator+ const
Timespanoperator- const
Timespan &operator+=
Timespan &operator-=
intdays const inlineReturns the number of days.
inthours const inlineReturns the number of hours (0 to 23).
inttotalHours const inlineReturns the total number of hours.
intminutes const inlineReturns the number of minutes (0 to 59).
inttotalMinutes const inlineReturns the total number of minutes.
intseconds const inlineReturns the number of seconds (0 to 59).
inttotalSeconds const inlineReturns the total number of seconds.
intmilliseconds const inlineReturns the number of milliseconds (0 to 999).
TimeDifftotalMilliseconds const inlineReturns the total number of milliseconds.
intmicroseconds const inlineReturns the fractions of a millisecond in microseconds (0 to 999).
intuseconds const inlineReturns the fractions of a second in microseconds (0 to 999999).
TimeDifftotalMicroseconds const inlineReturns 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

ReturnNameDescription
const TimeDiffMILLISECONDS staticThe number of microseconds in a millisecond.
const TimeDiffSECONDS staticThe number of microseconds in a second.
const TimeDiffMINUTES staticThe number of microseconds in a minute.
const TimeDiffHOURS staticThe number of microseconds in a hour.
const TimeDiffDAYS staticThe 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

NameDescription
TimeDiff

{#timediff}

TimeDiff

Timestamp::TimeDiff TimeDiff()

Private Attributes

ReturnNameDescription
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

ReturnNameDescription
DateTimeCreates a DateTime for the current date and time.
DateTimeCreates a DateTime for the date and time given in a Timestamp.
DateTimeCreates a DateTime for the given Gregorian date and time.
DateTimeCreates a DateTime for the given Julian day.
DateTimeCreates a DateTime from an UtcTimeVal and a TimeDiff.
DateTimeCopy constructor. Creates the DateTime from another one.
~DateTimeDestroys the DateTime.
DateTime &operator=Assigns another DateTime.
DateTime &operator=Assigns a Timestamp.
DateTime &operator=Assigns a Julian day.
DateTime &assignAssigns a Gregorian date and time.
voidswapSwaps the DateTime with another one.
intyear const inlineReturns the year.
intmonth const inlineReturns the month (1 to 12).
intweek constReturns 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.
intday const inlineReturns the day witin the month (1 to 31).
intdayOfWeek constReturns the weekday (0 to 6, where 0 = Sunday, 1 = Monday, ..., 6 = Saturday).
intdayOfYear constReturns the number of the day in the year. January 1 is 1, February 1 is 32, etc.
inthour const inlineReturns the hour (0 to 23).
inthourAMPM const inlineReturns the hour (0 to 12).
boolisAM const inlineReturns true if hour < 12;.
boolisPM const inlineReturns true if hour >= 12.
intminute const inlineReturns the minute (0 to 59).
intsecond const inlineReturns the second (0 to 59).
intmillisecond const inlineReturns the millisecond (0 to 999)
intmicrosecond const inlineReturns the microsecond (0 to 999)
doublejulianDay constReturns the julian day for the date and time.
Timestamptimestamp const inlineReturns the date and time expressed as a Timestamp.
Timestamp::UtcTimeValutcTime const inlineReturns the date and time expressed in UTC-based time. UTC base time is midnight, October 15, 1582. Resolution is 100 nanoseconds.
booloperator== const inline
booloperator!= const inline
booloperator< const inline
booloperator<= const inline
booloperator> const inline
booloperator>= const inline
DateTimeoperator+ const
DateTimeoperator- const
Timespanoperator- const
DateTime &operator+=
DateTime &operator-=
voidmakeUTCConverts a local time into UTC, by applying the given time zone differential.
voidmakeLocalConverts 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

ReturnNameDescription
boolisLeapYear static inlineReturns true if the given year is a leap year; false otherwise.
intdaysOfMonth staticReturns the number of days in the given month and year. Month is from 1 to 12.
boolisValid staticChecks 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

ReturnNameDescription
voidcomputeGregorianComputes the Gregorian date for the given Julian day. See http://vsg.cape.com/~pbaum/date/injdimp.htm, section 3.3.1 for the algorithm.
voidcomputeDaytimeExtracts 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

NameDescription
MonthsSymbolic names for month numbers (1 to 12).
DaysOfWeekSymbolic names for week day numbers (0 to 6).

{#months}

Months

enum Months

Symbolic names for month numbers (1 to 12).

ValueDescription
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).

ValueDescription
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

Private Attributes

ReturnNameDescription
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

ReturnNameDescription
voidcheckLimitUtility functions used to correct the overflow in computeGregorian.
voidnormalize

{#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

ReturnNameDescription
intutcOffset staticReturns the offset of local time to UTC, in seconds. local time = UTC + utcOffset() + dst().
intdst staticReturns the daylight saving time offset in seconds if daylight saving time is in use. local time = UTC + utcOffset() + dst().
boolisDst staticReturns 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.
inttzd staticReturns the time zone differential for the current timezone. The timezone differential is computed as utcOffset() + dst() /// and is expressed in seconds.
std::stringname staticReturns the timezone name currently in effect.
std::stringstandardName staticReturns the timezone name if not daylight saving time is in effect.
std::stringdstName staticReturns 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

ReturnNameDescription
LocalDateTimeCreates a LocalDateTime with the current date/time for the current time zone.
LocalDateTimeCreates 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.
LocalDateTimeCreates 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.
LocalDateTimeCreates 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.
LocalDateTimeCopy constructor. Creates the LocalDateTime from another one.
~LocalDateTimeDestroys the LocalDateTime.
LocalDateTime &operator=Assigns another LocalDateTime.
LocalDateTime &operator=Assigns a timestamp.
LocalDateTime &operator=Assigns a Julian day in the local time zone.
LocalDateTime &assignAssigns 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.
voidswapSwaps the LocalDateTime with another one.
intyear const inlineReturns the year.
intmonth const inlineReturns the month (1 to 12).
intweek const inlineReturns 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.
intday const inlineReturns the day witin the month (1 to 31).
intdayOfWeek const inlineReturns the weekday (0 to 6, where 0 = Sunday, 1 = Monday, ..., 6 = Saturday).
intdayOfYear const inlineReturns the number of the day in the year. January 1 is 1, February 1 is 32, etc.
inthour const inlineReturns the hour (0 to 23).
inthourAMPM const inlineReturns the hour (0 to 12).
boolisAM const inlineReturns true if hour < 12;.
boolisPM const inlineReturns true if hour >= 12.
intminute const inlineReturns the minute (0 to 59).
intsecond const inlineReturns the second (0 to 59).
intmillisecond const inlineReturns the millisecond (0 to 999)
intmicrosecond const inlineReturns the microsecond (0 to 999)
doublejulianDay const inlineReturns the julian day for the date.
inttzd const inlineReturns the time zone differential.
DateTimeutc constReturns the UTC equivalent for the local date and time.
Timestamptimestamp const inlineReturns the date and time expressed as a Timestamp.
Timestamp::UtcTimeValutcTime const inlineReturns the UTC equivalent for the local date and time.
booloperator== const
booloperator!= const
booloperator< const
booloperator<= const
booloperator> const
booloperator>= const
LocalDateTimeoperator+ const
LocalDateTimeoperator- const
Timespanoperator- 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

ReturnNameDescription
LocalDateTime
voiddetermineTzdRecalculate 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.
voidadjustForTzd inlineAdjust the _dateTime member based on the _tzd member.
std::time_tdstOffset constDetermine 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

ReturnNameDescription
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

ReturnNameDescription
const std::stringISO8601_FORMAT staticpredefined date formats The date/time format defined in the ISO 8601 standard.
const std::stringISO8601_FRAC_FORMAT staticThe date/time format defined in the ISO 8601 standard, with fractional seconds.
const std::stringRFC822_FORMAT staticThe date/time format defined in RFC 822 (obsoleted by RFC 1123).
const std::stringRFC1123_FORMAT staticThe date/time format defined in RFC 1123 (obsoletes RFC 822).
const std::stringHTTP_FORMAT staticThe 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::stringRFC850_FORMAT staticThe date/time format defined in RFC 850 (obsoleted by RFC 1036).
const std::stringRFC1036_FORMAT staticThe date/time format defined in RFC 1036 (obsoletes RFC 850).
const std::stringASCTIME_FORMAT staticThe date/time format produced by the ANSI C asctime() function.
const std::stringSORTABLE_FORMAT staticA simple, sortable date/time format.
const std::stringWEEKDAY_NAMES staticnames used by formatter and parser English names of week days (Sunday, Monday, Tuesday, ...).
const std::stringMONTH_NAMES staticEnglish 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

ReturnNameDescription
std::stringformat static inlineFormats 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::stringformat static inlineFormats the given date and time according to the given format. See format(const Timestamp&, std::string_view, int) for more information.
std::stringformat static inlineFormats the given local date and time according to the given format. See format(const Timestamp&, std::string_view, int) for more information.
std::stringformat static inlineFormats 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.
voidappend static inlineFormats the given timestamp according to the given format and appends it to str.
voidappend staticFormats the given date and time according to the given format and appends it to str.
voidappend staticFormats the given local date and time according to the given format and appends it to str.
voidappend staticFormats the given timespan according to the given format and appends it to str.
std::stringtzdISO static inlineFormats the given timezone differential in ISO format. If timeZoneDifferential is UTC, "Z" is returned, otherwise, +HH.MM (or -HH.MM) is returned.
std::stringtzdRFC static inlineFormats the given timezone differential in RFC format. If timeZoneDifferential is UTC, "GMT" is returned, otherwise ++HHMM (or -HHMM) is returned.
voidtzdISO staticFormats 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.
voidtzdRFC staticFormats 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

NameDescription
``

{#classicy_1_1datetimeformatter_1aecc87c353df5e93ffe5ce179f14efc06}

enum 
ValueDescription
UTCSpecial 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

ReturnNameDescription
voidparse staticParses 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.
DateTimeparse staticParses 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.
booltryParse staticParses 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.
voidparse staticParses 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.
DateTimeparse staticParses 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.
booltryParse staticParses 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.
intparseMonth staticTries 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.
intparseDayOfWeek staticTries 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

ReturnNameDescription
Stopwatch
voidstartStarts (or restarts) the stopwatch.
voidstopStops or pauses the stopwatch.
voidresetResets the stopwatch.
voidrestartResets and starts the stopwatch.
Timestamp::TimeDiffelapsed constReturns the elapsed time in microseconds since the stopwatch started.
intelapsedSeconds constReturns the number of seconds elapsed since the stopwatch started.
intelapsedMilliseconds constReturns 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

ReturnNameDescription
Timestamp::TimeValresolution staticReturns the resolution of the stopwatch.

{#resolution}

resolution

static

static Timestamp::TimeVal resolution()

Returns the resolution of the stopwatch.

Private Attributes

ReturnNameDescription
Timestamp_start
Timestamp::TimeDiff_elapsed
bool_running

{#_start}

_start

Timestamp _start

{#_elapsed}

_elapsed

Timestamp::TimeDiff _elapsed

{#_running}

_running

bool _running

Private Methods

ReturnNameDescription
StopwatchDeleted 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

ReturnNameDescription
PacketSignalemitter

{#emitter}

emitter

PacketSignal emitter

Public Methods

ReturnNameDescription
ThreadedStreamReader inline#### Parameters
~ThreadedStreamReader inlineStops the reader thread and deletes the owned stream.
voidstart virtual inlineStarts the reader thread; emits one line per iteration as a RawPacket. Emits a FlagPacket with [PacketFlags::Final](#namespaceicy_1a3d1e0d9028d45b9ec824bf4306047f18abeae421a14a34f831c113f61323d1ab3) on EOF.
voidstop virtual inlineCancels the reader thread.
StreamT &stream inlineReturns the internal stream cast to StreamT.
std::istream &stream inline#### Returns

{#threadedstreamreader}

ThreadedStreamReader

inline

inline ThreadedStreamReader(std::istream * is)

Parameters

  • is Input 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

  • StreamT Target stream type derived from std::istream.

Returns

Reference to the cast stream.

Exceptions

  • std::runtime_error if the cast fails.

{#stream}

stream

inline

inline std::istream & stream()

Returns

Reference to the underlying input stream.

Protected Attributes

ReturnNameDescription
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

ReturnNameDescription
PacketSignalemitter

{#emitter}

emitter

PacketSignal emitter

Public Methods

ReturnNameDescription
StreamWriter inline#### Parameters
~StreamWriter virtual inlineCloses any open std::ofstream and deletes the owned stream.
voidprocess virtual inlineSerializes the packet via write(), flushes it to the output stream, then forwards the packet to the next processor.
StreamT &stream inlineReturns the internal output stream cast to StreamT.
voidonStreamStateChange virtual inlineCloses 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

  • stream Output 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

  • packet Incoming packet to process.

{#stream}

stream

inline

template<class StreamT> inline StreamT & stream()

Returns the internal output stream cast to StreamT.

Parameters

  • StreamT Target stream type derived from std::ostream.

Returns

Reference to the cast stream.

Exceptions

  • std::runtime_error if 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

  • state New stream state.

{#stream}

stream

inline

inline std::ostream & stream()

Returns

Reference to the underlying output stream.

Exceptions

  • std::runtime_error if the stream pointer is null.

Protected Attributes

ReturnNameDescription
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

ReturnNameDescription
State#### Parameters
StateCopy constructor.
State &operator=Copy assignment.
IDid constReturns the current state ID.
voidsetSets the state ID.
std::stringstr virtual constReturns a human-readable string for the given state ID. Override in derived classes to provide meaningful names.
std::stringtoString virtual constReturns a human-readable string for the current state ID.
boolequals constReturns true if the current state ID equals the given ID.
boolbetween constReturns true if the current state ID is in the inclusive range [lid, rid].
booloperator== const inline
booloperator== const inline

{#state}

State

State(ID id)

Parameters

  • id Initial state ID. Defaults to 0.

{#state}

State

State(const State & that)

Copy constructor.

Parameters

  • that State to copy from.

{#operator}

operator=

State & operator=(const State & that)

Copy assignment.

Parameters

  • that State 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

  • id New 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

  • id State 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

  • id State 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

  • lid Lower bound state ID.

  • rid Upper 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

ReturnNameDescription
std::atomic< ID >_id

{#_id}

_id

std::atomic< ID > _id

Public Types

NameDescription
ID

{#id}

ID

uint32_t ID()

{#stateful}

Stateful

#include <icy/stateful.h>

State machine implementation.

For an example See also: PacketStream

Parameters

  • The derived [State](#state) type.

Public Attributes

ReturnNameDescription
Signal< void(void *, T &, const T &)>StateChangeSignals when the state changes.

{#statechange}

StateChange

Signal< void(void *, T &, const T &)> StateChange

Signals when the state changes.

Public Methods

ReturnNameDescription
Stateful inline
boolstateEquals virtual const inlineReturns true if the current state ID equals the given ID.
boolstateBetween virtual const inlineReturns true if the current state ID is in the inclusive range [lid, rid].
T &state virtual inlineReturns a mutable reference to the current state.
const Tstate virtual const inlineReturns 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

  • id State 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

  • lid Lower bound state ID.

  • rid Upper 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

ReturnNameDescription
T_state

{#_state}

_state

T _state

Protected Methods

ReturnNameDescription
boolbeforeStateChange virtual inlineOverride to handle pre state change logic. Return false to prevent state change.
voidonStateChange virtual inlineOverride to handle post state change logic.
boolsetState virtual inlineSets the state and sends the state signal if the state change was successful.
boolsetState virtual inlineSets 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

ReturnNameDescription
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

ReturnNameDescription
IRegistryDefaulted constructor.
ItemT *createInstance virtual inlineCreates and returns a new heap-allocated instance of the type registered under key s.
voidregisterType inlineRegisters type T under the given key s. Emits TypeRegistered. Subsequent calls to createInstance(s) will return new T().
voidunregisterType virtual inlineRemoves the type registered under key s. Emits TypeUnregistered. Does nothing if s is not registered.
TypeMaptypes const inlineReturns 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

  • s The 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

  • T Concrete type to register; must be default-constructible and derive from ItemT.

Parameters

  • s Registration 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

  • s Registration 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

NameDescription
TypeMap

{#typemap}

TypeMap

std::map< std::string, ItemT *(*)()> TypeMap()

Private Attributes

ReturnNameDescription
TypeMap_types

{#_types}

_types

TypeMap _types

Private Static Methods

ReturnNameDescription
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

ReturnNameDescription
SingletonDefaulted constructor.
S *get inlineReturns a pointer to the managed singleton, instantiating it on first call. Thread-safe; protected by an internal mutex.
S *swap inlineReplaces 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.
voiddestroy inlineDestroys 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

  • newPtr Replacement 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

ReturnNameDescription
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

ReturnNameDescription
KeyedStoreDefaulted constructor.
KeyedStoreDeleted constructor.
KeyedStoreDefaulted constructor.
TValue *get const inlineReturns the item for key, or nullptr if not found.
TValue &add inlineInserts a uniquely owned item. Returns a reference to the stored item.
booltryAdd inlineInserts if absent; returns false on duplicate (never throws).
TValue &put inlineInserts or replaces the item under key.
boolerase inlineRemoves and destroys the item under key.
boolcontains const inline
boolempty const inline
size_tsize const inline
voidclear inline
Map &map inlineDirect map access for iteration.
const Map &map const inline
autobegin inline
autoend inline
autobegin const inline
autoend 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_error if 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

ReturnNameDescription
Map_map

{#_map}

_map

Map _map

Protected Methods

ReturnNameDescription
voidonAdd virtual inlineOverride for lifecycle reactions.
voidonRemove 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

NameDescription
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

ReturnNameDescription
KVCollectionDefaulted constructor.
booladd inlineInserts a value; returns false if key already exists.
TValue &get inlineReturns the value or throws.
constTValue &get const inlineReturns the value or defaultValue.
boolremove inline
boolhas const inline
boolempty const inline
size_tsize const inline
voidclear 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

ReturnNameDescription
Map_map

{#_map}

_map

Map _map

Public Types

NameDescription
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

ReturnNameDescription
NVCollection inline
NVCollection inline
NVCollection inline
NVCollection &operator=Assigns the name-value pairs of another NVCollection to this one.
const std::string &operator[] constReturns the value of the (first) name-value pair with the given name.
voidsetSets the value of the (first) name-value pair with the given name.
voidaddAdds a new name-value pair with the given name and value.
voidaddAdds a new name-value pair using move semantics.
const std::string &get constReturns the value of the first name-value pair with the given name.
const std::string &get constReturns 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.
boolhas constReturns true if there is at least one name-value pair with the given name.
ConstIteratorfind constReturns an iterator pointing to the first name-value pair with the given name.
ConstIteratorbegin constReturns an iterator pointing to the begin of the name-value pair collection.
ConstIteratorend constReturns an iterator pointing to the end of the name-value pair collection.
boolempty constReturns true iff the header does not have any content.
intsize constReturns the number of name-value pairs in the collection.
voideraseRemoves all name-value pairs with the given name.
voidclearRemoves 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

NameDescription
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

ReturnNameDescription
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

ReturnNameDescription
uv::Loop *loopActive 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

ReturnNameDescription
ApplicationConstructor.
~ApplicationDestructor.
voidrunRun the application event loop.
voidstopStop the application event loop.
voidfinalizeFinalize and free any remaining pointers still held by the application event loop.
voidwaitForShutdownBind the shutdown signal and run the main event loop.
voidbindShutdownSignalBind 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

ReturnNameDescription
Application &getDefault staticReturns 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

ReturnNameDescription
ApplicationDeleted constructor.
ApplicationDeleted 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

ReturnNameDescription
PacketSignalemitter

{#emitter}

emitter

PacketSignal emitter

Public Methods

ReturnNameDescription
SyncPacketQueue inline#### Parameters
SyncPacketQueue inlineUses the default libuv event loop.
voidprocess virtual inlineClones 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.
boolaccepts virtual inlineReturns true if the packet can be cast to type T.
PacketRetentionretention virtual const inlineReturns 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

  • loop Event loop to synchronize dispatch onto.

  • maxSize Maximum number of queued packets before oldest are dropped.


{#syncpacketqueue}

SyncPacketQueue

inline

inline SyncPacketQueue(int maxSize)

Uses the default libuv event loop.

Parameters

  • maxSize Maximum 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

  • packet Incoming 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

  • packet Packet 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

ReturnNameDescription
voiddispatch virtual inlineEmits the packet to downstream processors from the event loop thread.
voidonStreamStateChange virtual inlineCancels 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

  • packet Packet to dispatch.

{#onstreamstatechange}

onStreamStateChange

virtual inline

virtual inline void onStreamStateChange(const PacketStreamState &)

Cancels the queue on Closed or [Error](#error) stream state transitions.

Parameters

  • state New stream state.

Public Types

NameDescription
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

ReturnNameDescription
PacketSignalemitter

{#emitter}

emitter

PacketSignal emitter

Public Methods

ReturnNameDescription
AsyncPacketQueue inline#### Parameters
voidclose virtual inlineFlushes remaining packets, cancels the queue, and joins the dispatch thread.
voidprocess virtual inlineClones 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.
boolaccepts virtual inlineReturns true if the packet can be cast to type T.
PacketRetentionretention virtual const inlineReturns 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

  • maxSize Maximum 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

  • packet Incoming 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

  • packet Packet 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

ReturnNameDescription
voiddispatch virtual inlineEmits the packet to downstream processors from the async thread.
voidonStreamStateChange virtual inlineCloses 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

  • packet Packet to dispatch.

{#onstreamstatechange}

onStreamStateChange

virtual inline

virtual inline void onStreamStateChange(const PacketStreamState &)

Closes the queue on [Error](#error) or Closed stream state transitions.

Parameters

  • state New stream state.

Public Types

NameDescription
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

ReturnNameDescription
doublerateHow many messages.
doublesecondsOver how many seconds.
doubleallowanceRemaining 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

ReturnNameDescription
RateLimiter inlineConstructs a token bucket limiter.
boolcanSend inlineReturns 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

  • rate Maximum number of messages permitted in the window.

  • seconds Duration 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

ReturnNameDescription
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

ReturnNameDescription
PacketStreamAdapterConstruct the adapter, binding it to the given packet signal.
voidemit virtualEmit a mutable raw buffer as a packet.
voidemit virtualEmit a read-only raw buffer as a packet (data is copied internally).
voidemit virtualEmit a string as a packet (data is copied internally).
voidemit virtualEmit a flag-only packet carrying no payload data.
voidemit virtualEmit an existing packet directly onto the outgoing signal.
PacketSignal &getEmitterReturns a reference to the outgoing packet signal.
PacketRetentionretention virtual constReturns 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.
voidonStreamStateChange virtual inlineCalled 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

  • emitter The 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

  • data Pointer to the buffer (not copied; caller retains ownership).

  • len Number of bytes in the buffer.

  • flags Optional 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

  • data Pointer to the buffer.

  • len Number of bytes in the buffer.

  • flags Optional 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

  • str String payload.

  • flags Optional packet flags (see PacketFlags).


{#emit}

emit

virtual

virtual void emit(unsigned flags)

Emit a flag-only packet carrying no payload data.

Parameters

  • flags Packet 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

  • packet The 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

ReturnNameDescription
PacketSignal &_emitter

{#_emitter}

_emitter

PacketSignal & _emitter

Protected Methods

ReturnNameDescription
PacketStreamAdapterNonCopyable and NonMovable.
PacketStreamAdapterDeleted constructor.

{#packetstreamadapter}

PacketStreamAdapter

PacketStreamAdapter(const PacketStreamAdapter &) = delete

NonCopyable and NonMovable.


{#packetstreamadapter}

PacketStreamAdapter

PacketStreamAdapter(PacketStreamAdapter &&) = delete

Deleted constructor.

{#packetprocessor}

PacketProcessor

#include <icy/packetstream.h>

Inherits: PacketStreamAdapter Subclassed 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

ReturnNameDescription
PacketProcessor inline
voidprocessThis method performs processing on the given packet and emits the result.
boolaccepts virtual inlineThis method ensures compatibility with the given packet type. Return false to reject the packet.
voidoperator<< virtual inlineStream 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

ReturnNameDescription
PacketSignalemitterSignals to delegates on outgoing packets.
ThreadSignal< void(PacketStream &, const std::exception_ptr &)>ErrorSignals 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 &)>CloseSignals 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

ReturnNameDescription
PacketStreamConstruct a named packet stream.
~PacketStream virtualDestroy the stream; calls close() then reset() to release all adapters.
PacketStreamDeleted constructor.
PacketStreamDeleted constructor.
voidstart virtualStart the stream and synchronized sources.
voidstop virtualStop the stream and synchronized sources.
voidpause virtualPause the stream.
voidresume virtualResume the stream.
voidclose virtualClose the stream and transition the internal state to Closed.
voidreset virtualCleanup all managed stream adapters and reset the stream state.
boolactive virtual constReturns true when the stream is in the Active state.
boolstopped virtual constReturns true when the stream is in the Stopping or Stopped state.
boolclosed virtual constReturns true when the stream is in the Closed or Error state.
boollock virtualSets 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.
boollocked virtual constReturns true is the stream is currently locked.
voidwrite virtualWrite 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.
voidwrite virtualWrite a read-only buffer into the stream; data is copied immediately into an owning RawPacket before any adapter sees it.
voidwrite virtualWrite a packet directly into the processing chain.
voidattachSource virtualAttach 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.
voidattachSource virtualAttach 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.
voidattachSource inlineAttach 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.
booldetachSource virtualDetach a source by its packet signal. Disconnects the signal from the stream's process slot and removes the adapter entry.
booldetachSource virtualDetach a source by its adapter pointer. Disconnects the adapter's emitter from the stream's process slot and removes the entry.
voidattach virtualAttach 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.
voidattach inlineAttach 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.
booldetach virtualDetach a packet processor from the stream. The processor's delegate connections are removed; ownership is released if held.
voidsynchronizeOutput virtualSynchronize 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().
voidautoStart virtualEnable 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().
voidcloseOnError virtualEnable 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 &errorAccessors for the unmanaged client data pointer.
std::stringname constReturn the name assigned to this stream at construction.
PacketAdapterVecadapters constReturns a combined list of all stream sources and processors.
PacketAdapterVecsources constReturns a list of all stream sources.
PacketAdapterVecprocessors constReturns a list of all stream processors.
intnumSources constReturn the number of source adapters currently registered.
intnumProcessors constReturn the number of processor adapters currently registered.
intnumAdapters constReturn the total number of adapters (sources + processors).
AdapterT *getSource inlineReturn 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 inlineReturn 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 inlineReturn 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

  • name Optional 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

  • data Pointer to the raw data buffer.

  • len Number 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

  • data Pointer to the raw data buffer.

  • len Number of bytes to process.


{#write}

write

virtual

virtual void write(IPacket && packet)

Write a packet directly into the processing chain.

Parameters

  • packet Packet 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

  • source The 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

  • source The adapter to attach; must not be null.

  • owned If true the stream takes ownership and deletes the pointer on teardown.

  • syncState If true and source implements 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

Parameters


{#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

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

  • source Pointer 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

  • proc The processor to attach; must not be null.

  • order Position in the processing chain (lower runs first).

  • owned If 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

Parameters

  • ptr Shared pointer to the processor instance.

  • order Position in the processing chain (lower runs first).

  • syncState Reserved 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

  • proc Pointer 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

  • loop The 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

  • flag true 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

  • flag true 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

Parameters

  • index Zero-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

Parameters

  • index Zero-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

  • order The order value to match (default 0).

Returns

Pointer to the matching processor, or nullptr if none registered at that order.

Protected Attributes

ReturnNameDescription
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

ReturnNameDescription
voidsetupAttach the source and processor delegate chain.
voidteardownDetach the source and processor delegate chain.
voidattachSource
voidattach
voidstartSourcesStart synchronized sources.
voidstopSourcesStop synchronized sources.
voidprocess virtualProcess incoming packets.
voidemitEmit the final packet to listeners.
voidsynchronizeStatesSynchronize queued states with adapters.
voidonStateChange virtualOverride the Stateful::onStateChange method.
voidassertCanModifyReturns true if the given state ID is queued.
voidhandleExceptionHandle 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

NameDescription
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

ReturnNameDescription
SynchronizerCreates 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).
SynchronizerCreates 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 explicitCreates and immediately starts a synchronizer with a variadic callback.
~Synchronizer virtualDestructor.
voidpostSend 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.
voidstart inlineStarts 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.
voidstart virtualStarts the synchronizer with a std::function callback. Overrides [Runner::start](#classicy_1_1Runner_1a5969e823f1ce0bdd8730d3108bf13fbd); delegates to the variadic start template.
voidcancel virtualCancels 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.
voidclose virtualCancels 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 > &handleReturns 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

  • loop Event 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

  • target Callback to invoke on each event loop wakeup.

  • loop Event 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

  • Function Callable type.

  • Args Argument types forwarded to the function.

Parameters

  • func Callable to invoke on each event loop wakeup.

  • args Arguments forwarded to func.

  • loop Event 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

  • Function Callable type.

  • Args Argument types forwarded to the function.

Parameters

  • func Callable to invoke on each event loop wakeup.

  • args Arguments forwarded to func.


{#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

  • func Callback 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

ReturnNameDescription
uv::Handle< uv_async_t >_handle

{#_handle}

_handle

uv::Handle< uv_async_t > _handle

Protected Methods

ReturnNameDescription
boolasync virtual constReturns 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

ReturnNameDescription
TimedManager inlineConstructs a TimedManager and starts the internal expiry-check timer.
voidadd inlineAdd 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.
boolexpires virtual inlineUpdate the item expiry timeout.
boolexpires virtual inlineUpdate the item expiry timeout.
voidclear virtual inlineRemoves 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

  • loop Event 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

ReturnNameDescription
std::mutex_tmutex
TimeoutMap_timeouts
Timer_timer

{#_tmutex}

_tmutex

std::mutex _tmutex

{#_timeouts}

_timeouts

TimeoutMap _timeouts

{#_timer}

_timer

Timer _timer

Protected Methods

ReturnNameDescription
boolsetTimeout virtual inlineSets or removes the expiry timeout for a specific item pointer. If timeout > 0, starts a countdown; if timeout == 0, removes any existing timeout.
voidonRemove virtual inlineCalled when an item is removed from the collection. Erases the item's timeout entry and calls the base implementation.
voidonTimeout virtual inlineCalled when an item's timeout expires. Default implementation removes and deletes the item.
voidonTimerUpdate inlineInternal 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

  • item Pointer to the managed item.

  • timeout Delay in milliseconds, or 0 to clear the timeout.

Returns

true on success.

Exceptions

  • std::logic_error if 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

  • key Key of the removed item.

  • item Pointer 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

  • item Pointer 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

NameDescription
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

ReturnNameDescription
IPacketCreationStrategyDefaulted constructor.
IPacket *create constAttempts to create a typed packet from the given buffer.
intpriority constReturns 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

  • buffer Raw input data.

  • nread Set 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

ReturnNameDescription
PacketFactoryDefaulted constructor.
PacketFactoryDeleted constructor.
PacketFactoryDefaulted constructor.
voidregisterPacketType inlineRegisters a [PacketCreationStrategy](#packetcreationstrategy)<PacketT> at the given priority. Any previously registered strategy for PacketT is replaced.
voidunregisterPacketType inlineRemoves the [PacketCreationStrategy](#packetcreationstrategy)<PacketT> from the factory, if present.
voidregisterStrategy inlineRegisters an arbitrary [IPacketCreationStrategy](#ipacketcreationstrategy) subclass at the given priority. Any previously registered instance of the same type is replaced.
voidunregisterStrategy inlineRemoves the StrategyT instance from the factory, if present.
PacketCreationStrategyList &types inline#### Returns
const PacketCreationStrategyList &types const inline#### Returns
boolonPacketCreated virtual inlineCalled 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 inlineIterates 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

  • PacketT Packet type to register; must default-constructible with a read() method.

Parameters

  • priority Dispatch 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

  • PacketT Packet 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

  • StrategyT Strategy type to instantiate; must accept a priority int in its constructor.

Parameters

  • priority Dispatch 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

  • StrategyT Strategy 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

  • packet Newly 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

  • buffer Raw input data.

  • nread Set to the number of bytes consumed on success.

Returns

Newly allocated packet, or nullptr if no strategy matched.

Exceptions

  • std::logic_error if no packet types have been registered.

Protected Attributes

ReturnNameDescription
PacketCreationStrategyList_types

{#_types}

_types

PacketCreationStrategyList _types

Private Methods

ReturnNameDescription
voidsortTypes 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

ReturnNameDescription
StreamManager
booladdStream
booladdStream
boolcloseStream
voidcloseAll
PacketStream *getStream const
PacketStream *getDefaultStream const
voidprint 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

ReturnNameDescription
voidonAdd virtualOverride for lifecycle reactions.
voidonRemove virtual
voidonStreamStateChange
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

ReturnNameDescription
std::stringnameThe name of the diagnostic.
std::stringdescriptionThe diagnostic description.
std::vector< std::string >summaryThe diagnostic summary, maybe including troubleshooting information on failure.
ThreadSignal< void(const std::string &)>SummaryUpdatedSignals 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

ReturnNameDescription
IDiagnostic
voidcheck virtualResets state to None and invokes run() to perform the diagnostic check.
voidreset virtualClears the summary and resets state to None.
boolcomplete virtual constReturns true if the diagnostic has reached a terminal state (Passed or Failed).
boolpassed virtual constReturns true if the diagnostic state is Passed.
boolfailed virtual constReturns 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

ReturnNameDescription
voidrunOverride to implement diagnostic logic.
boolpass virtualTransitions the state to Passed.
boolfail virtualTransitions the state to Failed.
voidaddSummary virtualAppends 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

  • text Summary line to append.

{#asyncdiagnostic}

AsyncDiagnostic

#include <icy/diagnosticmanager.h>

Inherits: IDiagnostic, Runnable

Asynchronous diagnostic information collector.

Public Methods

ReturnNameDescription
voidrunOverride to implement diagnostic logic.
voidcheck virtual inlineResets 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

ReturnNameDescription
Thread_thread

{#_thread}

_thread

Thread _thread

{#diagnosticmanager}

DiagnosticManager

#include <icy/diagnosticmanager.h>

Inherits: string, IDiagnostic >

Registry and manager for diagnostic providers.

Public Attributes

ReturnNameDescription
NullSignalDiagnosticsComplete

{#diagnosticscomplete}

DiagnosticsComplete

NullSignal DiagnosticsComplete

Public Methods

ReturnNameDescription
DiagnosticManager
booladdDiagnosticAdds a diagnostic, taking ownership.
boolfreeDiagnosticRemoves and deletes the diagnostic registered under name.
IDiagnostic *getDiagnostic constReturns the diagnostic or nullptr.
voidresetAll
voidcheckAll
boolallComplete const
voidonDiagnosticStateChange

{#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

ReturnNameDescription
PacketTransaction inline#### Parameters
PacketTransaction inline#### Parameters
boolsend virtual inlineStarts the transaction timer and sends the request. Overriding classes should implement send logic here.
voidcancel virtual inlineCancellation 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.
boolcancelled const inline#### Returns
voiddispose virtual inlineStops 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.
booldisposed const inline#### Returns
boolcanResend virtual inline#### Returns
intattempts const inline#### Returns
intretries const inline#### Returns
PacketT &request inline#### Returns
PacketTrequest const inline#### Returns
PacketT &response inline#### Returns
PacketTresponse const inline#### Returns

{#packettransaction}

PacketTransaction

inline

inline PacketTransaction(long timeout, int retries, uv::Loop * loop)

Parameters

  • timeout Transaction timeout in milliseconds before failure or retry.

  • retries Maximum number of retransmissions (0 means one attempt only).

  • loop Event loop for the timeout timer.


{#packettransaction}

PacketTransaction

inline

inline PacketTransaction(const PacketT & request, long timeout, int retries, uv::Loop * loop)

Parameters

  • request Initial request packet to store and send.

  • timeout Transaction timeout in milliseconds before failure or retry.

  • retries Maximum number of retransmissions (0 means one attempt only).

  • loop Event 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

ReturnNameDescription
PacketT_request
PacketT_response
Timer_timerThe request timeout callback.
int_retriesThe maximum number of attempts before the transaction is considered failed.
int_attemptsThe 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

ReturnNameDescription
voidonStateChange virtual inlinePost state change hook. Calls dispose() on terminal states to stop the timer, but does not delete the object; IntrusivePtr handles that.
boolhandlePotentialResponse virtual inlineProcesses a potential response candidate and updates the state accordingly.
boolcheckResponseChecks a potential response candidate and returns true on successful match.
voidonResponse virtual inlineCalled when a successful response is received.
voidonTimeout virtual inlineCalled 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

NameDescription
Ptr

{#ptr}

Ptr

IntrusivePtr< PacketTransaction< PacketT > > Ptr()

{#task}

Task

#include <icy/task.h>

Inherits: Runnable Subclassed by: Task

Abstract base class for implementing asynchronous tasks.

Tasks are designed to be run by a TaskRunner.

Public Methods

ReturnNameDescription
Task#### Parameters
voiddestroy virtualSets the task to destroyed state.
booldestroyed virtual constSignals that the task should be disposed of.
boolrepeating virtual constSignals that the task should be called repeatedly by the TaskRunner. If this returns false the task will be cancelled.
uint32_tid virtual constUnique task ID.
TaskDeleted constructor.
TaskDeleted constructor.

{#task}

Task

Task(bool repeat)

Parameters

  • repeat If 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

ReturnNameDescription
uint32_t_id
bool_repeating
bool_destroyed

{#_id}

_id

uint32_t _id

{#_repeating}

_repeating

bool _repeating

{#_destroyed}

_destroyed

bool _destroyed

Protected Methods

ReturnNameDescription
voidrunCalled 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>

Inherits: Runnable Subclassed by: Scheduler

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

ReturnNameDescription
NullSignalIdleFires after completing an iteration of all tasks.
NullSignalShutdownSignals 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

ReturnNameDescription
TaskRunner#### Parameters
TaskRunnerDeleted constructor.
TaskRunnerDeleted constructor.
boolstart virtualStarts a task, adding it if it doesn't exist.
boolcancel virtualCancels a task.
booldestroy virtualQueues a task for destruction.
boolexists virtual constReturns whether a task exists.
Task *get virtual constReturns the task pointer matching the given ID, or nullptr if no task exists.
voidsetRunner virtualSet 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

  • runner Async 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

ReturnNameDescription
TaskRunner &getDefault staticReturns 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

ReturnNameDescription
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

ReturnNameDescription
voidrun virtualCalled by the async context to run the next task.
booladd virtualAdds a task to the runner.
boolremove virtualRemoves a task from the runner.
Task *next virtual constReturns the next task to be run.
voidclear virtualDestroys and clears all manages tasks.
voidonAdd virtualCalled after a task is added.
voidonStart virtualCalled after a task is started.
voidonCancel virtualCalled after a task is cancelled.
voidonRemove virtualCalled after a task is removed.
voidonRun virtualCalled 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

ReturnNameDescription
std::anyopaqueOptional 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 >infoOptional extra information about the packet.
BitwiseflagsProvides 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

ReturnNameDescription
IPacket inline#### Parameters
IPacket inlineCopy constructor; clones the info object if present.
IPacket &operator= inlineCopy assignment; clones the info object if present.
std::unique_ptr< IPacket >clone constReturns a heap-allocated deep copy of this packet.
ssize_treadRead/parse to the packet from the given input buffer. The number of bytes read is returned.
voidwrite constCopy/generate to the packet given output buffer. The number of bytes written can be obtained from the buffer.
size_tsize virtual const inlineThe size of the packet in bytes.
boolhasData virtual const inlineReturns true if the packet has a non-null data pointer.
char *data virtual const inlineThe packet data pointer for buffered packets.
const void *constData virtual const inlineThe const packet data pointer for buffered packets.
const char *className constReturns the class name of this packet type for logging and diagnostics.
voidprint virtual const inlinePrints a human-readable representation to the given stream.

{#ipacket}

IPacket

inline

inline IPacket(std::unique_ptr< IPacketInfo > info, unsigned flags)

Parameters

  • info Optional packet info; ownership transferred.

  • flags Initial bitwise flags.


{#ipacket}

IPacket

inline

inline IPacket(const IPacket & r)

Copy constructor; clones the info object if present.

Parameters

  • r Source packet.

{#operator}

operator=

inline

inline IPacket & operator=(const IPacket & r)

Copy assignment; clones the info object if present.

Parameters

  • r Source 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

  • os Output stream.

{#flagpacket}

FlagPacket

#include <icy/packet.h>

Inherits: IPacket

Packet for sending bitwise flags along the packet stream.

Public Methods

ReturnNameDescription
FlagPacket inline#### Parameters
std::unique_ptr< IPacket >clone virtual const inline#### Returns
FlagPacket inline#### Parameters
ssize_tread virtual inlineNo-op read; FlagPacket carries no payload data.
voidwrite virtual const inlineNo-op write; FlagPacket carries no payload data.
const char *className virtual const inlineReturns the class name of this packet type for logging and diagnostics.

{#flagpacket}

FlagPacket

inline

inline FlagPacket(unsigned flags)

Parameters

  • flags Bitwise 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

  • that Source 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: IPacket Subclassed by: MediaPacket, SocketPacket

RawPacket is the default data packet type which consists of an optionally managed char pointer and a size value.

Public Methods

ReturnNameDescription
RawPacket inlineConstruct with borrowed (non-owning) buffer.
RawPacket inlineConstruct with const data (copied, owning).
RawPacket inlineCopy constructor (always copies data).
std::unique_ptr< IPacket >clone virtual const inline#### Returns
voidcopyData virtual inlineCopies data into an internally owned buffer, replacing any prior content.
ssize_tread virtual inlineReads from the buffer by copying its contents into an owned buffer.
voidwrite virtual const inlineAppends the packet data to the given output buffer.
char *data virtual const inline#### Returns
size_tsize virtual const inline#### Returns
const char *className virtual const inlineReturns the class name of this packet type for logging and diagnostics.
boolownsBuffer 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

  • data Source data pointer.

  • size Number 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

  • buf Input 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

  • buf Buffer 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

ReturnNameDescription
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

ReturnNameDescription
ThreadSignal< void(const std::string &, const std::string &)>PropertyChangedThe 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

ReturnNameDescription
ConfigurationCreates the Configuration.
~Configuration virtualDestroys the Configuration.
boolexists constReturns true if the property with the given key exists.
std::stringgetString constReturns the string value of the property with the given name. Throws a NotFoundException if the key does not exist.
std::stringgetString constIf a property with the given key exists, returns the property's string value, otherwise returns the given default value.
std::stringgetRawString constReturns 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::stringgetRawString constIf 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.
intgetInt constReturns 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.
intgetInt constIf 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_tgetLargeInt constReturns 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_tgetLargeInt constIf 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.
doublegetDouble constReturns 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.
doublegetDouble constIf 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.
boolgetBool constReturns 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.
boolgetBool constIf 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:
voidsetStringSets the property with the given key to the given value. An already existing value for the key is overwritten.
voidsetIntSets the property with the given key to the given value. An already existing value for the key is overwritten.
voidsetLargeIntSets the property with the given key to the given value. An already existing value for the key is overwritten.
voidsetDoubleSets the property with the given key to the given value. An already existing value for the key is overwritten.
voidsetBoolSets 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

ReturnNameDescription
boolgetRaw constIf the property with the given key exists, stores the property's value in value and returns true. Otherwise, returns false.
voidsetRawSets the property with the given key to the given value. An already existing value for the key is overwritten.
ConfigurationDeleted constructor.
ConfigurationDeleted 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

ReturnNameDescription
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

ReturnNameDescription
Configuration &config
std::stringcurrentScope
std::stringdefaultScope

{#config}

config

Configuration & config

{#currentscope}

currentScope

std::string currentScope

{#defaultscope}

defaultScope

std::string defaultScope

Public Methods

ReturnNameDescription
ScopedConfiguration#### Parameters
ScopedConfiguration
std::stringgetString constReturns the string value, trying currentScope first then defaultScope.
intgetInt constReturns the int value, trying currentScope first then defaultScope.
doublegetDouble constReturns the double value, trying currentScope first then defaultScope.
boolgetBool constReturns the bool value, trying currentScope first then defaultScope.
voidsetStringWrites a string value under the scoped key.
voidsetIntWrites an int value under the scoped key.
voidsetDoubleWrites a double value under the scoped key.
voidsetBoolWrites a bool value under the scoped key.
std::stringgetCurrentScope const#### Parameters
std::stringgetDafaultKey const#### Parameters
std::stringgetScopedKey const#### Parameters

{#scopedconfiguration}

ScopedConfiguration

ScopedConfiguration(Configuration & config, const std::string & currentScope, const std::string & defaultScope)

Parameters

  • config Backing configuration store.

  • currentScope Key prefix for the module-level scope.

  • defaultScope Key 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

  • key Property key (without scope prefix).

  • defaultValue Fallback when neither scope has the key.

  • forceDefaultScope If true, skips currentScope and reads from defaultScope only.

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

  • key Property key (without scope prefix).

  • defaultValue Fallback when neither scope has the key.

  • forceDefaultScope If true, reads from defaultScope only.

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

  • key Property key (without scope prefix).

  • defaultValue Fallback when neither scope has the key.

  • forceDefaultScope If true, reads from defaultScope only.

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

  • key Property key (without scope prefix).

  • defaultValue Fallback when neither scope has the key.

  • forceDefaultScope If true, reads from defaultScope only.

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

  • key Property key (without scope prefix).

  • value Value to store.

  • defaultScope If true, writes to defaultScope; otherwise to currentScope.


{#setint}

setInt

void setInt(const std::string & key, int value, bool defaultScope)

Writes an int value under the scoped key.

Parameters

  • key Property key (without scope prefix).

  • value Value to store.

  • defaultScope If true, writes to defaultScope; otherwise to currentScope.


{#setdouble}

setDouble

void setDouble(const std::string & key, double value, bool defaultScope)

Writes a double value under the scoped key.

Parameters

  • key Property key (without scope prefix).

  • value Value to store.

  • defaultScope If true, writes to defaultScope; otherwise to currentScope.


{#setbool}

setBool

void setBool(const std::string & key, bool value, bool defaultScope)

Writes a bool value under the scoped key.

Parameters

  • key Property key (without scope prefix).

  • value Value to store.

  • defaultScope If true, writes to defaultScope; otherwise to currentScope.


{#getcurrentscope}

getCurrentScope

const

std::string getCurrentScope(const std::string & key) const

Parameters

  • key Property key (without scope prefix).

Returns

Fully qualified key in currentScope.


{#getdafaultkey}

getDafaultKey

const

std::string getDafaultKey(const std::string & key) const

Parameters

  • key Property key (without scope prefix).

Returns

Fully qualified key in defaultScope.


{#getscopedkey}

getScopedKey

const

std::string getScopedKey(const std::string & key, bool defaultScope) const

Parameters

  • key Property key (without scope prefix).

  • defaultScope If true, returns the defaultScope key; otherwise currentScope key.

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

ReturnNameDescription
interr
std::stringmessage
std::exception_ptrexception

{#err}

err

int err

{#message}

message

std::string message

{#exception}

exception

std::exception_ptr exception

Public Methods

ReturnNameDescription
Error inlineDefault constructor; initializes all fields to a no-error state.
Error inlineConstructs an error with the given message string.
Error inlineConstructs an error with the given C string message.
boolany const inlineReturns true if any error condition is set (non-zero code, non-empty message, or exception).
voidreset inlineClears all error fields, resetting to a no-error state.
voidrethrow inlineRe-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

  • msg Human-readable error description.

{#error}

Error

inline

inline Error(const char * msg)

Constructs an error with the given C string message.

Parameters

  • msg Human-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

ReturnNameDescription
LogStream inline
LogStream inline
voidwrite 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

ReturnNameDescription
voidlock inline
voidunlock inline
voidlock_shared inline
voidunlock_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

ReturnNameDescription
unsigneddataBacking storage for the flag bits.

{#data}

data

unsigned data

Backing storage for the flag bits.

Public Methods

ReturnNameDescription
Bitwise inlineConstructs a Bitwise with optional initial flags.
voidreset virtual inlineClears all flags (sets data to 0).
voidset virtual inlineSets the given flag only if it is not already set.
voidadd virtual inlineUnconditionally sets (OR) the given flag bits.
voidremove virtual inlineClears the given flag bits.
voidtoggle virtual inlineToggles (XOR) the given flag bits.
boolhas virtual const inlineReturns true if all bits in flag are set.

{#bitwise}

Bitwise

inline

inline Bitwise(unsigned flags)

Constructs a Bitwise with optional initial flags.

Parameters

  • flags Initial 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

  • flag The flag bit(s) to set.

{#add}

add

virtual inline

virtual inline void add(unsigned flag)

Unconditionally sets (OR) the given flag bits.

Parameters

  • flag The flag bit(s) to add.

{#remove}

remove

virtual inline

virtual inline void remove(unsigned flag)

Clears the given flag bits.

Parameters

  • flag The flag bit(s) to remove.

{#toggle}

toggle

virtual inline

virtual inline void toggle(unsigned flag)

Toggles (XOR) the given flag bits.

Parameters

  • flag The 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

  • flag The 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

ReturnNameDescription
RToperator() constInvokes the underlying callable with the supplied arguments.
booloperator== constCompares 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

  • args Arguments 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

  • that Other 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

ReturnNameDescription
std::function< RT(Args...)>func

{#func}

func

std::function< RT(Args...)> func

Public Methods

ReturnNameDescription
FunctionDelegate inline#### Parameters
RToperator() virtual const inlineCalls the wrapped std::function.
booloperator== virtual const inlineAlways returns false; std::function targets cannot be compared for equality.

{#functiondelegate}

FunctionDelegate

inline

inline FunctionDelegate(std::function< RT(Args...)> func)

Parameters

  • func std::function to wrap.

{#operator}

operator()

virtual const inline

virtual inline RT operator()(Args... args) const

Calls the wrapped std::function.

Parameters

  • args Arguments 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

ReturnNameDescription
Class *instance
RT(Class::*method

{#instance}

instance

Class * instance

{#method}

method

RT(Class::* method

Public Methods

ReturnNameDescription
ClassDelegate inline#### Parameters
RToperator() virtual const inlineCalls the member function on instance.
booloperator== virtual const inline#### Parameters

{#classdelegate}

ClassDelegate

inline

inline ClassDelegate(Class * instance, RT(Class::*)(Args...) method)

Parameters

  • instance Object on which to invoke the member function.

  • method Pointer 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

  • args Arguments forwarded to the method.

Returns

Method result.


{#operator}

operator==

virtual const inline

virtual inline bool operator==(const AbstractDelegate< RT, Args... > & that) const

Parameters

  • that Other 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

ReturnNameDescription
Class *instance
RT(Class::*method

{#instance}

instance

Class * instance

{#method}

method

RT(Class::* method

Public Methods

ReturnNameDescription
ConstClassDelegate inline#### Parameters
RToperator() virtual const inlineCalls the const member function on instance.
booloperator== virtual const inline#### Parameters

{#constclassdelegate}

ConstClassDelegate

inline

inline ConstClassDelegate(Class * instance, RT(Class::*)(Args...) const method)

Parameters

  • instance Object on which to invoke the const member function.

  • method Pointer 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

  • args Arguments forwarded to the method.

Returns

Method result.


{#operator}

operator==

virtual const inline

virtual inline bool operator==(const AbstractDelegate< RT, Args... > & that) const

Parameters

  • that Other 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

ReturnNameDescription
Class *instance
RT(Class::*method

{#instance}

instance

Class * instance

{#method}

method

RT(Class::* method

Public Methods

ReturnNameDescription
PolymorphicDelegate inline#### Parameters
RToperator() virtual const inlineAttempts to cast object to PT; invokes the method if successful. Returns a default-constructed RT if the cast fails (packet type mismatch).
booloperator== virtual const inline#### Parameters

{#polymorphicdelegate}

PolymorphicDelegate

inline

inline PolymorphicDelegate(Class * instance, RT(Class::*)(PT &) method)

Parameters

  • instance Object on which to invoke the member function.

  • method Pointer to the member function accepting a derived PT&.


{#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

  • object Base-type reference; cast to PT before 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

  • that Other 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

ReturnNameDescription
std::stringexepath
OptionMapargs

{#exepath}

exepath

std::string exepath

{#args}

args

OptionMap args

Public Methods

ReturnNameDescription
OptionParserParses command-line arguments from argc/argv.
boolhas inlineReturns true if the given option key was present on the command line.
std::stringget inlineReturns the string value associated with the given option key. Returns an empty string if the key was not found.
NumericTypeget inlineReturns 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

  • argc Argument count from main().

  • argv Argument vector from main().

  • delim Prefix 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

  • key Option 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

  • key Option 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

  • NumericType Integral or floating-point type to convert the value to.

Parameters

  • key Option key to look up.

Returns

Converted numeric value.

{#shutdowncmd}

ShutdownCmd

#include <icy/application.h>

Shutdown command packet for signalling process termination.

Public Attributes

ReturnNameDescription
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

ReturnNameDescription
PacketStreamAdapter *ptr
std::shared_ptr< void >_prevent_deletion
intorder
boolsyncState

{#ptr}

ptr

PacketStreamAdapter * ptr

{#_prevent_deletion}

_prevent_deletion

std::shared_ptr< void > _prevent_deletion

{#order}

order

int order

{#syncstate}

syncState

bool syncState

Public Methods

ReturnNameDescription
PacketAdapterReference inlineConstruct with raw pointer (non-owning).
PacketAdapterReference inlineConstruct 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

ReturnNameDescription
boolcompareOrder static inlineComparator 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

  • l Left-hand reference.

  • r Right-hand reference.

Returns

true if l should appear before r in the processor chain.

Public Types

NameDescription
Ptr

{#ptr}

Ptr

std::shared_ptr< PacketAdapterReference > Ptr()

{#packetstreamstate}

PacketStreamState

#include <icy/packetstream.h>

Inherits: State

State machine states for PacketStream.

Public Methods

ReturnNameDescription
std::stringstr const inline

{#str}

str

const inline

inline std::string str(unsigned int id) const

Public Static Attributes

ReturnNameDescription
constexpr unsigned intNone static
constexpr unsigned intLocked static
constexpr unsigned intActive static
constexpr unsigned intPaused static
constexpr unsigned intStopping static
constexpr unsigned intStopped static
constexpr unsigned intClosed static
constexpr unsigned intError 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

NameDescription
Type

{#type}

Type

enum Type
ValueDescription
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

ReturnNameDescription
PacketCreationStrategy inline#### Parameters
IPacket *create virtual const inlineAttempts to default-construct a PacketT, calling its read() method.
intpriority virtual const inline#### Returns

{#packetcreationstrategy}

PacketCreationStrategy

inline

inline PacketCreationStrategy(int priority)

Parameters

  • priority Dispatch priority in the range 0–100.

Exceptions

  • std::logic_error if 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

  • buffer Raw input data.

  • nread Set 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

ReturnNameDescription
int_priority

{#_priority}

_priority

int _priority

{#sharedlibrary}

SharedLibrary

#include <icy/sharedlibrary.h>

Loads a shared library at runtime and resolves exported symbols.

Public Methods

ReturnNameDescription
boolopen inlineOpens 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.
voidclose inlineCloses the shared library.
boolsym inlineRetrieves 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.
voidsetError inlineReads the last libuv dynamic-linker error, stores it in _error, and throws a std::runtime_error with the combined prefix and error message.
std::stringerror const inlineReturns 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

  • prefix Human-readable context string prepended to the error detail.

Exceptions

  • std::runtime_error always.

{#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

ReturnNameDescription
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

ReturnNameDescription
std::stringstr const inlineReturns 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

Returns

State name string.

Exceptions

  • std::logic_error for unknown IDs.

Public Types

NameDescription
Type

{#type}

Type

enum Type
ValueDescription
None
Checking
Passed
Failed

{#transactionstate}

TransactionState

#include <icy/packettransaction.h>

Inherits: State

State machine states for PacketTransaction.

Public Methods

ReturnNameDescription
std::stringstr const inline#### Parameters

{#str}

str

const inline

inline std::string str(unsigned int id) const

Parameters

  • id A [TransactionState::Type](#structicy_1_1TransactionState_1a3389dd308d8acd3cab977d1826298434) value.

Returns

Human-readable name of the state.

Public Types

NameDescription
Type

{#type}

Type

enum Type
ValueDescription
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

ReturnNameDescription
IPacketInfoDefaulted constructor.
std::unique_ptr< IPacketInfo >clone constReturns 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.