Overview / Data & formats

compression

Compression, decompression and the checksums of the containers. The format is a value (<code>Compress</code>, <code>Decompress</code>, <code>CompressBound</code>), with format detection from the start of the stream.

Always compiled: part of the core build.Include #include <ethereal/cpp/compression/compression_inc.hpp>C layer

compression_inc.hpp

#include <ethereal/cpp/compression/compression_inc.hpp>

checksum.hpp

#include <ethereal/cpp/compression/checksum.hpp>

Checksums of the Compression module.

CRC32 (IEEE), CRC32C (Castagnoli), Adler-32, XXH64 and XXH32, one shot and incremental. The zlib, gzip and LZ4 envelopes need them, so the module spec lists them under Compression.

There are two CRC32 implementations in the tree, on purpose. Section 10 of the conventions says to reuse what exists, and section 2 forbids a module including another module's header to get functionality. The one in 'cryptography/crc.hpp' works byte by byte with a 256 entry table. This one uses slicing and is much faster. The suite checks one against the other.

The spec asks for "CRC32 (IEEE) using the SSE4.2 CRC32 instruction". That does not work: the x86 instruction computes the Castagnoli polynomial, and no register trick turns one into the other. Castagnoli uses the instruction. IEEE uses the slicing table, the fastest option without carry-less multiplication. The measured numbers are in the module README.

function

Crc32

Ethereal::Compression#
std::uint32_t Crc32( std::span< const std::uint8_t > Data ) noexcept;

Computes the CRC32 (IEEE) of a block.

Does not allocate. Thread safety: full.

Data
The bytes.
The checksum.
function

Crc32Update

Ethereal::Compression#
std::uint32_t Crc32Update( std::uint32_t uPrevious, std::span< const std::uint8_t > Data ) noexcept;

Continues a CRC32 (IEEE) already started.

For callers that work in chunks. The initial value of a new sequence is zero, not 0xFFFFFFFF: the input and output inversions happen inside the function, so continuing is just passing the previous value. Getting this wrong is the most common mistake with CRC. Does not allocate. Thread safety: full.

uPrevious
The value returned by the previous call, or zero.
Data
The next bytes.
The accumulated checksum.
function

Crc32c

Ethereal::Compression#
std::uint32_t Crc32c( std::span< const std::uint8_t > Data ) noexcept;

Computes the CRC32C (Castagnoli) of a block.

Uses the processor instruction when there is one, and falls back to a slicing table otherwise. The suite checks the two paths against each other. Does not allocate. Thread safety: full.

Data
The bytes.
The checksum.
function

Crc32cUpdate

Ethereal::Compression#
std::uint32_t Crc32cUpdate( std::uint32_t uPrevious, std::span< const std::uint8_t > Data ) noexcept;

Continues a CRC32C already started.

uPrevious
The value returned by the previous call, or zero.
Data
The next bytes.
The accumulated checksum.
function

Crc32cUsesHardware

Ethereal::Compression#
bool Crc32cUsesHardware() noexcept;

Tells whether the CRC32C is using the processor instruction.

This query is what makes both paths measurable. Without it, on a machine with SSE4.2 the table path would never run, and would ship to the client without anyone ever going through it. Thread safety: full.

true when the instruction is in use.
function

Adler32

Ethereal::Compression#
std::uint32_t Adler32( std::span< const std::uint8_t > Data ) noexcept;

Computes the Adler-32 of a block.

The checksum of the zlib envelope. Weaker than CRC at detecting errors and much cheaper, which is why zlib chose it. Does not allocate. Thread safety: full.

Data
The bytes.
The checksum.
function

Adler32Update

Ethereal::Compression#
std::uint32_t Adler32Update( std::uint32_t uPrevious, std::span< const std::uint8_t > Data ) noexcept;

Continues an Adler-32 already started.

uPrevious
The previous value. The initial value of a new sequence is one, not zero: RFC 1950 says so, and starting from zero gives a wrong value that looks right.
Data
The next bytes.
The accumulated checksum.
function

XxHash64

Ethereal::Compression#
std::uint64_t XxHash64( std::span< const std::uint8_t > Data, std::uint64_t uSeed = 0 ) noexcept;

Computes the XXH64 of a block.

Not cryptographic: it does not resist someone forging a collision. It detects corruption and does not authenticate. Does not allocate. Thread safety: full.

Data
The bytes.
uSeed
The seed. The LZ4 frame uses zero.
The checksum.
struct

SXxHash32State

Ethereal::Compression#
C++
struct   SXxHash32State   final
{
    /// @brief  The four accumulators of the long path.
    std::uint32_t aAcc[ 4 ] = {};

    /// @brief  What was left of a chunk, waiting to complete sixteen bytes.
    std::uint8_t aRemainder[ 16 ] = {};

    /// @brief  Number of bytes in aRemainder.
    std::uint32_t uRemainder = 0;

    /// @brief  Number of bytes seen in total.
    std::uint64_t uTotal = 0;

    /// @brief  The seed it started with.
    std::uint32_t uSeed = 0;
};

State of an XXH32 that has not finished yet.

function

XxHash32Begin

Ethereal::Compression#
void XxHash32Begin( SXxHash32State & State, std::uint32_t uSeed = 0 ) noexcept;

Starts an incremental XXH32.

Does not allocate. Thread safety: full.

State
The state to start.
uSeed
The seed. The LZ4 frame uses zero.
function

XxHash32Update

Ethereal::Compression#
void XxHash32Update( SXxHash32State & State, std::span< const std::uint8_t > Data ) noexcept;

Feeds one more chunk.

How the input is split does not change the result. The suite checks this with chunks of 1, 3, 17 and 4096 bytes against the one shot function. Does not allocate. Thread safety: full.

State
The state.
Data
The next bytes.
function

XxHash32End

Ethereal::Compression#
std::uint32_t XxHash32End( const SXxHash32State & State ) noexcept;

Finishes and returns the checksum.

Does not change the state: calling it twice returns the same number, and feeding more data afterwards continues where it stopped. Does not allocate. Thread safety: full.

State
The state.
The checksum.
function

XxHash32

Ethereal::Compression#
std::uint32_t XxHash32( std::span< const std::uint8_t > Data, std::uint32_t uSeed = 0 ) noexcept;

Computes the XXH32 of a block.

This is not XXH64 cut in half. They are different functions, with different constants and a different final mix. Mixing them up gives a plausible number that matches nobody.

It is the checksum the LZ4 frame uses: in the header, in each block and over the whole content. Not cryptographic. Does not allocate. Thread safety: full.

Data
The bytes.
uSeed
The seed. The LZ4 frame uses zero.
The checksum.

compress.hpp

#include <ethereal/cpp/compression/compress.hpp>

Entry point of the Compression module.

Before this layer, using the module meant knowing the function of each format. A program that stores a configuration option ("compress with gzip") does not want a 'switch' over seven functions, and every such 'switch' is a place where a new format gets forgotten. Here the format is a value of EAlgorithm.

Nothing here is faster or slower than calling the format function directly. It is dispatch, not a second implementation.

function

CompressBound

Ethereal::Compression#
std::size_t CompressBound( EAlgorithm eAlgorithm, std::size_t uBytes ) noexcept;

Largest size the compressed output can have for this format.

eAlgorithm
The format.
uBytes
Size of the input.
The bound, or zero when the format is not compiled into this library.
Does not allocate. Thread safety: full.
function

Compress

Ethereal::Compression#
ECompressionError Compress( EAlgorithm eAlgorithm, std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, ELevel eLevel = ELevel::Default ) noexcept;

Compresses in the given format.

Dispatches to the format function and keeps its guarantees: none of them allocate, and all are safe to call from several threads at once.

The level does not apply to every format. RLE, Store and the LZ4 frame have nothing to tune, and for them the parameter is ignored.

eAlgorithm
The format.
In
The bytes.
Out
Where to write. Needs CompressBound bytes.
uWrittenOut
Receives the number of bytes written. Zero on failure.
eLevel
How much effort, where that means something.
ECompressionError::eOk, eBufferTooSmall or eUnsupportedAlgorithm. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
Does not allocate. Thread safety: full.
function

Decompress

Ethereal::Compression#
ECompressionError Decompress( EAlgorithm eAlgorithm, std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, SDecompressLimits Limits = SDecompressLimits{} ) noexcept;

Decompresses the given format.

The caller says the format, it is not guessed. Guessing from the content is what DetectAlgorithm does, and it says clearly when it does not know.

eAlgorithm
The format.
In
The stream.
Out
Where to write.
uWrittenOut
Receives the number of bytes written. Zero on failure.
Limits
Output ceiling. On by default.
The result of the decompression.
Does not allocate. Thread safety: full.
function

DetectAlgorithm

Ethereal::Compression#
bool DetectAlgorithm( std::span< const std::uint8_t > In, EAlgorithm & eAlgorithmOut ) noexcept;

Guesses the format from the start of the stream.

Only three formats identify themselves, by their own design:

gzip starts with 1F 8B and method eight. zlib has method eight and a check number that closes on 31. LZ4 frame starts with the magic number 04 22 4D 18.

Raw deflate, the LZ4 block and RLE cannot be recognized: they start with data, and any data is a valid start. For them the answer is false, and the caller has to know some other way.

A raw stream can look like zlib by chance. The zlib header is two bytes with a five bit check, so one in 1024 arbitrary sequences passes it. The format allows this, which is why the function guesses and the name says so.

In
Start of the stream. Three bytes are enough.
eAlgorithmOut
Receives the format, when there is one.
true when recognized, false when the format does not identify itself.
Does not allocate. Thread safety: full.
function

CompressorMemoryUsage

Ethereal::Compression#
std::size_t CompressorMemoryUsage( EAlgorithm eAlgorithm, ELevel eLevel ) noexcept;

Bytes a compressor takes, not counting the stack.

Zero for the algorithms this module does not compress as a stream.

eAlgorithm
The format.
eLevel
The effort. It does not change the number today. The parameter stays because the spec asks for it and because a level with match chains would change it.
Size in bytes.
Does not allocate. Thread safety: full.
function

DecompressorMemoryUsage

Ethereal::Compression#
std::size_t DecompressorMemoryUsage( EAlgorithm eAlgorithm, std::size_t uWindowLog ) noexcept;

Bytes a decompressor takes, not counting the stack.

eAlgorithm
The format.
uWindowLog
Exponent of the requested window. Ignored for the deflate family, whose window is fixed at 32 KiB by the format. Another value would not shrink anything.
Size in bytes.
Does not allocate. Thread safety: full.
function

CompressorStackUsage

Ethereal::Compression#
std::size_t CompressorStackUsage( EAlgorithm eAlgorithm, ELevel eLevel ) noexcept;

Stack the operation uses, in bytes, besides the object.

Not in the spec. It is here because without it the two numbers above are misleading. See the section note above.

eAlgorithm
The format.
eLevel
The effort.
Size in bytes.
Does not allocate. Thread safety: full.

compression_common.hpp

#include <ethereal/cpp/compression/compression_common.hpp>

Shared types of the Compression module.

Error codes, algorithms, compression levels and the limits that protect decompression against bombs.

enum

ECompressionError

Ethereal::Compression#
C++
enum class   ECompressionError : ETL_INT32
{
    /// @brief  The operation finished as requested.
    eOk = 0,

    /// @brief  The result does not fit in the space the caller gave.
    eBufferTooSmall,

    /// @brief  The stream is malformed.
    ///
    /// @details  Untrusted input ends up here. No decoder in this module
    ///            trusts a size, an offset or a code that came from outside:
    ///            everything is checked against the window before any copy.
    eCorruptStream,

    /// @brief  The stream ended in the middle of something.
    eTruncatedStream,

    /// @brief  The output would go past the limit the caller set.
    ///
    /// @details  This is the shield against decompression bombs, and it is on
    ///            by default. A few kilobytes of input can become gigabytes of
    ///            output, and a server that decompresses what the client sent
    ///            without a limit runs out of memory with no bug in its code.
    eOutputLimitExceeded,

    /// @brief  An argument has no usable value.
    eInvalidArgument,

    /// @brief  The requested algorithm is not compiled into this library.
    eUnsupportedAlgorithm,

    /// @brief  The working memory could not be reserved.
    ///
    /// @details  Only happens in Init. After it, nothing in this module allocates.
    eOutOfMemory,

    /// @brief  The call does not fit the current state of the object.
    eInvalidState,

    /// @brief  Refused: no license was accepted and the evaluation of this machine has
    ///          ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed
};

Portable cause of a compression or decompression failure.

function

CompressionErrorName

Ethereal::Compression#
const ETL_CHAR * CompressionErrorName( ECompressionError eError ) noexcept;

Readable name of an ECompressionError.

eError
The cause to name.
Static null terminated string. Never null.
Thread safety: full.
enum

EAlgorithm

Ethereal::Compression#
C++
enum class   EAlgorithm : ETL_UINT8
{
    /// @brief  No compression: copies the bytes and nothing else.
    ///
    /// @details  Already compressed content grows with any algorithm, and a
    ///            path that only stores avoids that waste.
    Store = 0,

    /// @brief  Run length encoding. Cheap, for sparse data.
    Rle = 1,

    /// @brief  Raw deflate, without envelope (RFC 1951).
    Deflate = 2,

    /// @brief  Deflate in the zlib envelope (RFC 1950).
    Zlib = 3,

    /// @brief  Deflate in the gzip envelope (RFC 1952).
    Gzip = 4,

    /// @brief  LZ4, block format.
    Lz4Block = 5,

    /// @brief  LZ4, frame format.
    Lz4Frame = 6,

    /// @brief  Zstd.
    ///
    /// @warning  Not implemented. The package spec explicitly allows shipping
    ///            complete Deflate and LZ4 and leaving Zstd for later, instead
    ///            of shipping half a Zstd. Asking for this value returns
    ///            ECompressionError::eUnsupportedAlgorithm.
    Zstd = 7
};

Which format.

enum

ELevel

Ethereal::Compression#
C++
enum class   ELevel : ETL_UINT8
{
    /// @brief  The fastest. Compresses little.
    Fastest = 0,

    /// @brief  Fast.
    Fast = 1,

    /// @brief  The usual balance.
    Default = 2,

    /// @brief  Compresses more, costs more.
    Better = 3,

    /// @brief  The most the format allows.
    Best = 4
};

How much effort to spend compressing.

Does not affect decompression: any level produces a stream that any decompressor of the same format reads.

function

AlgorithmName

Ethereal::Compression#
const ETL_CHAR * AlgorithmName( EAlgorithm eAlgorithm ) noexcept;

Readable name of an EAlgorithm.

struct

SDecompressLimits

Ethereal::Compression#
C++
struct   SDecompressLimits   final
{
    /// @brief  Absolute ceiling of output bytes. Zero means no ceiling.
    ///
    /// @details  The 64 MiB default is generous for common data and small
    ///            enough not to bring a server down. Whoever needs more says how
    ///            much.
    std::size_t uMaxOutputBytes = 64u * 1024u * 1024u;

    /// @brief  Maximum ratio between output and input. Zero means no limit.
    ///
    /// @details  Catches the bomb the absolute ceiling would let through: a
    ///            10 MiB request that becomes 60 MiB fits the ceiling, but a
    ///            ratio of a thousand to one shows what it is.
    ///
    /// @warning  It does not protect LZ4. Measured.
    ///
    ///            The LZ4 block format limits expansion to about 255 times by
    ///            construction: each extended length byte adds 255 to the output
    ///            and costs one byte of input. No valid LZ4 stream reaches 1024,
    ///            so for this format uMaxOutputBytes is what protects.
    ///
    ///            Lowering the default to near 255 is not the answer: five
    ///            thousand zeros compress to twenty bytes, already a ratio of 250,
    ///            and refusing that would refuse legitimate data.
    ///
    ///            The value is still useful for formats that expand more. Deflate
    ///            reaches 1032 times, and there the ratio bites.
    std::uint32_t uMaxExpansionRatio = 1024u;
};

What the caller allows the decompression to produce.

The shield is on by default, on purpose. A stream of a few kilobytes can expand to gigabytes. Whoever decompresses what came from outside (a network server, a reader of user uploads) runs out of memory with no bug in its own code. That is why the limit is not optional nor partly off. Whoever really wants no limit writes so.

datachunk.hpp

#include <ethereal/cpp/compression/datachunk.hpp>
class

CDataChunk

Ethereal::DataChunk#

Class responsible for managing data/memory blocks (Data Chunk).

class CDataChunk final

There is no guarantee that it is thread-safe. Synchronization is the responsibility of the caller. It must not be directly inherited by any structure, class, or object.

constructor

CDataChunk

#
CDataChunk() noexcept;

Default constructor.

constructor

CDataChunk

#
CDataChunk( CDataChunk && other ) noexcept;

Move constructor.

operator

operator=

#
CDataChunk & operator=( const CDataChunk & other );

Copy assignment operator.

operator

operator=

#
CDataChunk & operator=( CDataChunk && other ) noexcept;

Move assignment operator.

function

CleanupDataAndMemory

#
void CleanupDataAndMemory( void );

Resets and clears all current data chunk memory.

function

CleanupBackupDataAndMemory

#
void CleanupBackupDataAndMemory( void );

Resets and clears all backup data chunk memory.

function

CleanupDataChunk

#
void CleanupDataChunk( void );

Resets and releases all memory, data, and structures of the data chunk.

function

GetDataPtr

#
ETL_CPTR GetDataPtr( void ) const

Retrieves the pointer to the current data allocation.

Constant pointer to the current data.
function

GetBackupDataPtr

#
ETL_CPTR GetBackupDataPtr( void ) const

Retrieves the pointer to the backup data allocation.

Constant pointer to the backup data.
function

GetDataSize

#
std::size_t GetDataSize( void ) const

Retrieves the size (in bytes) of the current data allocation.

Size of the current data.
function

GetBackupDataSize

#
std::size_t GetBackupDataSize( void ) const

Retrieves the size (in bytes) of the current backup data allocation.

Size of the backup data.
function

Initialize

#
ETL_INT32 Initialize( void * DataBufferPtr, const std::size_t SizeInBytes, const bool bIsBackupDataRegion = false );

Initializes the selected chunk region with a specific size (in bytes). This function is a wrapper for Reserve(), applying the requested size to the specified region (current or backup). If the region already has a block with a size greater than or equal to the requested size, no changes will be made (Reserve() returns 1).

DataBufferPtr
Data buffer or pointer to data to be copied into the chunk after reserving space.
SizeInBytes
Desired size (in bytes) for the target region after the operation.
bIsBackupDataRegion
Indicates the target region: true = backup region; false = current region.
0 if the operation was successful. 1 data chunk already initialized previously. 2 error during space reservation (Reserve); check the log if enabled. 3 reservation or generic error; the chunk cannot store all requested data. 4 memory copy error from the provided pointer or buffer to the target chunk memory.
If an invalid pointer is passed to @param DataBufferPtr, the operation will only reserve space in the chunk. To store data later, the memory copy function must be used MANUALLY on the target chunk memory. Copying data or buffers into improperly initialized chunk memory will result in undefined behavior. Ensure that the target memory and allocated byte size are sufficient when performing MANUAL copy operations.
'void *' instead of 'LPVOID': this is a public header and cannot require <windows.h> from whoever includes it. Both are the same type on Windows.
function

Backup

#
ETL_INT32 Backup( const bool bCleanupCurrentData = false );

Backs up the current chunk memory to its backup region. Allows restoring the data later. If desired, the original memory can be cleaned after the backup.

bCleanupCurrentData
If true, cleans and releases the current memory after saving the backup.
0 if the operation was successful. 1 if there was no valid data to back up. 2 if backup allocation failed. 3 if memory copy failed.
function

Restore

#
ETL_INT32 Restore( const bool bCleanupBackupData = true );

Restores data from the backup region to the active chunk memory. If desired, the backup memory can be cleaned after restoration.

bCleanupBackupData
If true, cleans and releases the backup memory after restoration.
0 if the operation was successful. 1 if there was no valid backup to restore. 2 if allocation for active data failed. 3 if memory copy failed.
function

ToString

#
std::string ToString( const bool bIsBackupDataRegion = false ) const;

Converts the raw chunk contents into a @std::string. Reads the bytes from the specified region (current or backup) and constructs a std::string with exactly the allocated size (may contain '\0'). If the target region does not have valid memory, returns a descriptive error string.

bIsBackupDataRegion
Indicates the read region: true = backup region; false = current region.
A @std::string containing the bytes from the requested region. In case of an invalid pointer, returns a textual error message.
The returned string may contain null bytes and is not guaranteed to be valid text/UTF-8. Interpretation of the content is the caller's responsibility.
function

ToCAString

#
String::CAString ToCAString( const bool bIsBackupDataRegion = false ) const;

Converts the raw chunk contents into a @CAString. Reads the bytes from the specified region (current or backup) and constructs a CAString with exactly the allocated size (may contain '\0'). If the target region does not have valid memory, returns a descriptive error string.

bIsBackupDataRegion
Indicates the read region: true = backup region; false = current region.
A @CAString containing the bytes from the requested region. In case of an invalid pointer, returns a textual error message.
The returned string may contain null bytes and is not guaranteed to be valid text/UTF-8. Interpretation of the content is the caller's responsibility.
const

alignof

#
static constexpr std::size_t uDataAlignment = alignof( std::max_align_t );

Default alignment for chunk allocations.

function

LoadFileMemoryToChunk

Ethereal::DataChunk#
ETL_INT32 LoadFileMemoryToChunk( const wchar_t * wFileName, DataChunk::CDataChunk * DataChunkPtrOut, const bool bPreferChunkBackupMemory = false );

Loads the contents of a file into a @DataChunk. Opens the specified file, retrieves its size in bytes, initializes the @DataChunk with the required capacity, and copies the entire file content into the chunk memory. The read operation can target either the “primary” or the “backup” buffer, as preferred.

wFileName
Path of the file (wide) to be read.
DataChunkPtrOut
Pointer to the destination DataChunk that will receive the data.
bPreferChunkBackupMemory
If true, uses the chunk’s backup buffer; otherwise, uses the default buffer.
Operation result code: 0: Success, data loaded into the DataChunk. 1: Failed to open the file (CreateFileW). 2: Failed to retrieve the file size (GetFileSizeEx). 3: Failed to initialize the DataChunk (Initialize). 4: Invalid target chunk memory (null/invalid pointer). 5: Invalid or non-positive chunk size. 6: Chunk size greater than 4GB (not currently supported). 7: Failed to read the file (ReadFile returned FALSE). 8: Number of bytes read differs from the expected amount.
function

WriteChunkDataToFile

Ethereal::DataChunk#
ETL_INT32 WriteChunkDataToFile( const wchar_t * wFileName, const DataChunk::CDataChunk * DataChunkPtr, const std::size_t sBytesToWrite = 0, const bool bPreferChunkBackupMemory = false, const bool bAppendToFile = false );

Writes data from a @DataChunk to a file. Selects the @DataChunk buffer (primary or backup) and writes it to the target file, supporting create/overwrite or append mode. Allows limiting the number of bytes to write (sBytesToWrite), when only part of the chunk should be written.

wFileName
Destination file path (wide).
DataChunkPtr
Pointer to the source DataChunk.
sBytesToWrite
Number of bytes to write (0 to write the full chunk size).
bPreferChunkBackupMemory
If true, writes from the backup buffer; otherwise, from the default buffer.
bAppendToFile
If true, opens/creates the file and seeks to the end (append); otherwise, recreates it from scratch.
Operation result code: 0: Success, data written to the file. 1: Invalid chunk memory (null/invalid pointer). 2: Invalid or non-positive total chunk size. 3: Inconsistent sBytesToWrite (greater than the chunk size). 4: Chunk size greater than 4GB (not currently supported). 5: Failed to open/create the file (CreateFileW). 6: Write failure (WriteFile returned FALSE). 7: Number of bytes written differs from the expected amount.
function

WriteStringDataToFile

Ethereal::DataChunk#
ETL_INT32 WriteStringDataToFile( const wchar_t * wFileName, const std::string * StringPtr, const bool bAppendToFile = false );

Writes a std::string to a file using a temporary DataChunk. Initializes a DataChunk with the string bytes, performs the write operation to the target file (optionally in append mode), and cleans up the temporary chunk with error logging.

wFileName
Destination file path (wide).
StringPtr
Pointer to the string to be written.
bAppendToFile
If true, writes in append mode; otherwise, recreates the file from scratch.
Operation result code: 0: Success, string written to the file. 1: Failed to initialize the temporary DataChunk (Initialize). 2: Failed to write the DataChunk to the target file (WriteChunkDataToFile).
function

WriteCAStringDataToFile

Ethereal::DataChunk#
ETL_INT32 WriteCAStringDataToFile( const wchar_t * wFileName, const String::CAString * StringPtr, const bool bAppendToFile = false );

Writes a CAString to a file using a temporary @DataChunk. Initializes a @DataChunk with the string bytes, performs the write operation to the target file (optionally in append mode), and cleans up the temporary chunk with error logging.

wFileName
Destination file path (wide).
StringPtr
Pointer to the string to be written.
bAppendToFile
If true, writes in append mode; otherwise, recreates the file from scratch.
Operation result code: 0: Success, string written to the file. 1: Failed to initialize the temporary DataChunk (Initialize). 2: Failed to write the DataChunk to the target file (WriteChunkDataToFile).
function

WriteCWStringDataToFile

Ethereal::DataChunk#
ETL_INT32 WriteCWStringDataToFile( const wchar_t * wFileName, const String::CWString * StringPtr, const bool bAppendToFile = false );

Writes a CWString to a file using a temporary DataChunk. Initializes a DataChunk with the string bytes, performs the write operation to the target file (optionally in append mode), and cleans up the temporary chunk with error logging.

wFileName
Destination file path (wide).
StringPtr
Pointer to the string to be written.
bAppendToFile
If true, writes in append mode; otherwise, recreates the file from scratch.
Operation result code: 0: Success, string written to the file. 1: Failed to initialize the temporary DataChunk (Initialize). 2: Failed to write the DataChunk to the target file (WriteChunkDataToFile).

deflate.hpp

#include <ethereal/cpp/compression/deflate.hpp>

DEFLATE (RFC 1951) and its zlib and gzip envelopes.

The stream is a sequence of blocks, and bits are read from the least significant to the most significant inside each byte. Each block starts with:

1 bit -> is it the last block? 2 bits -> type: 00 stored, 01 fixed Huffman, 10 dynamic Huffman

Stored aligns to the byte and carries the length in two bytes, followed by its complement, which exists to be checked.

Fixed uses a table the RFC spells out. Dynamic carries its own table, encoded by a third table that comes in shuffled order. Three levels, and most of the work lives there.

Inside a block, symbols 0 to 255 are literals, 256 ends the block, and 257 to 285 are match lengths, each with its own number of extra bits. The distance comes from a separate alphabet of 30 symbols with up to 13 extra bits, reaching 32768.

The 32 KiB window is not allocated. It is the caller's output buffer, as in LZ4. That keeps the promise that nothing in this module allocates, and the distance is checked against what was already written instead of a circular window whose content before the start is undefined. The price is that streaming decompression (output in chunks) needs another path. Noted.

function

DeflateBound

Ethereal::Compression#
std::size_t DeflateBound( std::size_t uBytes ) noexcept;

Largest size the compressed output can have.

The bound of the stored path, because that is where the compressor falls back when the content does not compress: five bytes every 65535 and nothing more. Sizing with less makes the compression fail exactly on the content it does not help.

uBytes
Size of the input.
The bound.
Does not allocate. Thread safety: full.
function

Deflate

Ethereal::Compression#
ECompressionError Deflate( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, ELevel eLevel = ELevel::Default ) noexcept;

Compresses to raw deflate (RFC 1951), without envelope.

Fixed Huffman, as a stated choice. The dynamic code yields more and costs a statistics pass plus a table written in the stream. This produces legitimate deflate that any decompressor reads. What it lacks is ratio, not correctness, and the README says how much.

When it does not compress, it stores. Incompressible content grows under fixed Huffman, because literals from 144 on cost nine bits. In that case the result goes out in stored blocks, five bytes per block and nothing more. The choice is made by measuring both.

The working table lives on the stack.

In
The bytes.
Out
Where to write. Needs DeflateBound bytes.
uWrittenOut
Receives the number of bytes written. Zero on failure.
eLevel
How much effort. Up to ELevel::Fast the table only gets the start of each match. Above that it gets everything the match covers, which yields more and costs more.
ECompressionError::eOk or eBufferTooSmall. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
Does not allocate. Thread safety: full.
function

ZlibCompress

Ethereal::Compression#
ECompressionError ZlibCompress( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, ELevel eLevel = ELevel::Default ) noexcept;

Compresses in the zlib envelope (RFC 1950).

Two header bytes, the deflate, and the Adler32 of the original content in four bytes, high byte first.

In
The bytes.
Out
Where to write.
uWrittenOut
Receives the number of bytes written. Zero on failure.
eLevel
How much effort.
The result of the compression.
Does not allocate. Thread safety: full.
function

GzipCompress

Ethereal::Compression#
ECompressionError GzipCompress( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, ELevel eLevel = ELevel::Default ) noexcept;

Compresses in the gzip envelope (RFC 1952).

The time stays at zero, which the RFC defines as "no time available". Writing the current time would make the output change on every run, and output that changes by itself cannot be compared with a baseline or checked by a checksum.

In
The bytes.
Out
Where to write.
uWrittenOut
Receives the number of bytes written. Zero on failure.
eLevel
How much effort.
The result of the compression.
Does not allocate. Thread safety: full.
const

DEFLATE_DICTIONARY_SIZE

Ethereal::Compression#
inline constexpr std::size_t DEFLATE_DICTIONARY_SIZE = 32768u;

Size of a prepared dictionary, in bytes.

Not a magic number. The real type (the hash table) lives in the private core, and this header is public. The number is checked by a static_assert inside the .cpp: if the table changes size, the build breaks.

struct

SPreparedDictionary

Ethereal::Compression#
C++
struct   SPreparedDictionary   final
{
    /// @brief  The built table. Opaque here on purpose.
    std::uint8_t aOpaque[ DEFLATE_DICTIONARY_SIZE ] = {};

    /// @brief  Size of the dictionary that built this table.
    std::size_t uDictBytes = 0;

    /// @brief  false until PrepareDictionary runs.
    bool bReady = false;

    /// @brief  Explicit padding.
    ///
    /// @details  Without it the implicit padding stays uninitialized, and two
    ///            dictionaries prepared from the same dictionary come out with
    ///            different bytes when saved, because the garbage between the
    ///            fields is not the same.
    ///
    ///            That breaks exactly what the spec asks of this type: *"persist
    ///            and reload a prepared dictionary state"*. Whoever saves writes
    ///            sizeof bytes, and the padding goes along.
    ///
    ///            The suite caught it by accident: the check that two objects are
    ///            identical passed while both were born next to each other on the
    ///            stack, and failed when another change moved one of them.
    std::uint8_t aPadding[ sizeof( std::size_t ) - 1u ] = {};
};

A dictionary with its hash table already built.

Nothing here allocates: it is a POD, and whoever creates it decides where it lives. It fits in a static, a member or a vector.

It is bound to the dictionary that prepared it. Saving to disk and reloading is legitimate (it is flat memory) as long as the dictionary is the same.

function

PrepareDictionary

Ethereal::Compression#
ECompressionError PrepareDictionary( std::span< const std::uint8_t > Dict, SPreparedDictionary & Out ) noexcept;

Builds the hash table of a dictionary, once.

Dict
The dictionary. May be larger than the window. Only the last 32 KiB are reachable, and the rest is ignored without error.
Out
Receives the built table.
ECompressionError::eOk, or eInvalidArgument when the dictionary is too short to hold a minimum match. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
Does not allocate. Thread safety: full.
function

DeflateWithPreparedDictionary

Ethereal::Compression#
ECompressionError DeflateWithPreparedDictionary( const SPreparedDictionary & Dic, std::span< const std::uint8_t > DictAndIn, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, ELevel eLevel = ELevel::Default ) noexcept;

Compresses to raw deflate reusing a prepared dictionary.

The output is identical to DeflateWithDictionary with the same dictionary. Only the time changes. The suite checks this equality, because it is the only way to know the shortcut did not change the result.

Dic
The prepared dictionary.
DictAndIn
The same dictionary followed by the data, in one buffer.
Out
Where to write.
uWrittenOut
Receives the number of bytes written. Zero on failure.
eLevel
How much effort.
ECompressionError::eInvalidArgument when the preparation did not run or the dictionary size does not match the prepared one. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
Does not allocate. Thread safety: full.
function

ZlibCompressWithPreparedDictionary

Ethereal::Compression#
ECompressionError ZlibCompressWithPreparedDictionary( const SPreparedDictionary & Dic, std::span< const std::uint8_t > DictAndIn, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, ELevel eLevel = ELevel::Default ) noexcept;

Compresses to zlib reusing a prepared dictionary.

The envelope carries the DICTID, as in ZlibCompressWithDictionary.

Dic
The prepared dictionary.
DictAndIn
The same dictionary followed by the data, in one buffer.
Out
Where to write.
uWrittenOut
Receives the number of bytes written. Zero on failure.
eLevel
How much effort.
The result of the compression.
Does not allocate. Thread safety: full.
function

DeflateWithDictionary

Ethereal::Compression#
ECompressionError DeflateWithDictionary( std::span< const std::uint8_t > DictAndIn, std::size_t uDictBytes, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, ELevel eLevel = ELevel::Default ) noexcept;

Compresses to raw deflate, with a dictionary.

DictAndIn
The dictionary followed by the data, in one buffer.
uDictBytes
How many bytes at the start are dictionary.
Out
Where to write. DeflateBound of the data size.
uWrittenOut
Receives the number of bytes written. Zero on failure.
eLevel
How much effort.
The result of the compression.
Does not allocate. Thread safety: full.
function

InflateWithDictionary

Ethereal::Compression#
ECompressionError InflateWithDictionary( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t uDictBytes, std::size_t & uWrittenOut, SDecompressLimits Limits = SDecompressLimits{} ) noexcept;

Decompresses raw deflate, with a dictionary.

In
The stream.
Out
The whole buffer. The first uDictBytes already hold the dictionary.
uDictBytes
How many bytes at the start of Out are dictionary.
uWrittenOut
Receives the number of bytes this call wrote, not counting the dictionary. Zero on failure.
Limits
Output ceiling. On by default.
The result of the decompression.
Does not allocate. Thread safety: full.
function

ZlibCompressWithDictionary

Ethereal::Compression#
ECompressionError ZlibCompressWithDictionary( std::span< const std::uint8_t > DictAndIn, std::size_t uDictBytes, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, ELevel eLevel = ELevel::Default ) noexcept;

Compresses in the zlib envelope, with a dictionary.

The header carries the dictionary bit and the DICTID, which is the Adler32 of the dictionary. A decompression without the right dictionary is refused by that number instead of producing garbage.

DictAndIn
The dictionary followed by the data, in one buffer.
uDictBytes
How many bytes at the start are dictionary.
Out
Where to write.
uWrittenOut
Receives the number of bytes written. Zero on failure.
eLevel
How much effort.
The result of the compression.
Does not allocate. Thread safety: full.
function

ZlibDecompressWithDictionary

Ethereal::Compression#
ECompressionError ZlibDecompressWithDictionary( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t uDictBytes, std::size_t & uWrittenOut, SDecompressLimits Limits = SDecompressLimits{} ) noexcept;

Decompresses the zlib envelope, with a dictionary.

The DICTID is checked. A stream that asks for another dictionary returns ECompressionError::eInvalidArgument, not a plausible and wrong output.

A stream that does not ask for a dictionary also works here: the given dictionary is ignored, and uDictBytes is still where the output starts.

In
The stream.
Out
The whole buffer. The first uDictBytes already hold the dictionary.
uDictBytes
How many bytes at the start of Out are dictionary.
uWrittenOut
Receives the number of bytes written. Zero on failure.
Limits
Output ceiling. On by default.
The result of the decompression.
Does not allocate. Thread safety: full.
function

Inflate

Ethereal::Compression#
ECompressionError Inflate( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, std::size_t & uConsumedOut, SDecompressLimits Limits = SDecompressLimits{} ) noexcept;

Decompresses a raw deflate stream (RFC 1951), without envelope.

Trusts nothing in the input. Every Huffman code is checked for completeness when built: a set of lengths with codes left over or missing is refused, not used. Every distance is checked against what was already written. Every length is checked against the space left. The complement of a stored block is checked.

In
The stream.
Out
Where to write. Also serves as the window.
uWrittenOut
Receives the number of bytes written. Zero on failure.
uConsumedOut
Receives the number of input bytes read. The envelopes need this to find the trailer.
Limits
Output ceiling. On by default.
ECompressionError::eOk, eBufferTooSmall, eCorruptStream, eTruncatedStream or eOutputLimitExceeded.
Does not allocate. Thread safety: full.
function

Inflate

Ethereal::Compression#
ECompressionError Inflate( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, SDecompressLimits Limits = SDecompressLimits{} ) noexcept;

Same as above, for callers that do not care how much input was read.

function

ZlibDecompress

Ethereal::Compression#
ECompressionError ZlibDecompress( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, SDecompressLimits Limits = SDecompressLimits{} ) noexcept;
function

GzipDecompress

Ethereal::Compression#
ECompressionError GzipDecompress( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, SDecompressLimits Limits = SDecompressLimits{} ) noexcept;

Decompresses a stream in the gzip envelope (RFC 1952).

Ten header bytes, optional fields of variable size, and eight trailer bytes: the Crc32 of the content and its size in 32 bits.

Both are checked. The trailer size is compared with the output modulo four billion, as the RFC says. Files larger than that exist, and refusing them would invent a rule the RFC does not have.

Several concatenated members are all read. 'cat a.gz b.gz' produces a legitimate gzip file, and pigz produces that naturally. Each member has its own header, CRC and size, each checked on its own.

The ceiling of SDecompressLimits applies to the total, not per member. Otherwise a thousand members of one megabyte would pass a one megabyte ceiling, which is the bomb the ceiling exists to stop.

What is left at the end without the magic number is ignored, as gzip itself does: files padded with zeros are common, and ignoring is safer than trying to interpret. This function does not say how much input it consumed, so whoever needs that has to look at the input.

In
The stream.
Out
Where to write.
uWrittenOut
Receives the number of bytes written. Zero on failure.
Limits
Output ceiling. On by default.
The result of the decompression.
Does not allocate. Thread safety: full.

deflate_tables.hpp

#include <ethereal/cpp/compression/deflate_tables.hpp>

The tables RFC 1951 spells out.

The compressor and the decompressor need the same tables, and a copy on each side is a divergence waiting to happen: a wrong number in one of them produces a stream its own pair reads back without complaint, and only an outside library notices. So there is one source. If it is wrong, it is wrong on both sides, the round trip still closes, and the comparison against zlib breaks at once. That is the arrangement that makes the defect show.

lz4.hpp

#include <ethereal/cpp/compression/lz4.hpp>

LZ4 block format.

The stream is a sequence of groups. Each group starts with a token byte:

high nibble -> how many literals follow low nibble -> how much matches what was already written, minus four

When a nibble is 15, the value continues in the next bytes: each 255 means add and keep reading, and the first byte below 255 ends it.

After the literals comes the offset, two bytes low first, counted backwards from the current output position. The last group of the stream has only literals and no offset.

The match copy overlaps, and that is the trick. An offset of 1 with length 100 means "repeat the last byte a hundred times". The copy has to go byte by byte, forward: 'memcpy' there gives a wrong result, because it does not promise to read what it just wrote. It is the most common mistake in an LZ decompressor, and it does not show with common content, only with short repeats.

function

Lz4CompressBound

Ethereal::Compression#
std::size_t Lz4CompressBound( std::size_t uBytes ) noexcept;
function

Lz4Compress

Ethereal::Compression#
ECompressionError Lz4Compress( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut ) noexcept;

Compresses a block.

Fast compressor: a hash table with one entry per position, no chain and no lazy search. It is what the spec calls the fastest path. The working table lives on the stack.

In
The bytes.
Out
Where to write. Needs Lz4CompressBound bytes.
uWrittenOut
Receives the number of bytes written. Zero on failure.
ECompressionError::eOk or eBufferTooSmall. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
Does not allocate. Thread safety: full.
function

Lz4Decompress

Ethereal::Compression#
ECompressionError Lz4Decompress( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, SDecompressLimits Limits = SDecompressLimits{} ) noexcept;

Decompresses a block.

Trusts nothing in the input. Every length and every offset is checked against what is left of the input and against what was already written, before any copy. An offset pointing before the start of the output, a length past the end, a sum that overflows: all of it is refused, not read.

Network data comes in through here. A decompressor that trusts an offset reads memory that is not its own, which is a security flaw and not a wrong result.

In
The compressed block.
Out
Where to write.
uWrittenOut
Receives the number of bytes written. Zero on failure.
Limits
Output ceiling. On by default.
ECompressionError::eOk, eBufferTooSmall, eCorruptStream, eTruncatedStream or eOutputLimitExceeded.
Does not allocate. Thread safety: full.
The space between the end of the output and the end of Out may be touched. To avoid a function call every few bytes, the copy uses blocks of constant size when there is slack, and only after checking that the slack exists inside Out. What goes past the logical end is scribble, never a write outside. Nothing is written outside Out, under any circumstance, hostile streams included. A caller that gives exactly the needed space sees no scribble, because then there is no slack and the narrow path takes over. The reference library asks more than this: it requires the caller to size with slack and writes in that slack without checking.
function

Lz4CompressWithDictionary

Ethereal::Compression#
ECompressionError Lz4CompressWithDictionary( std::span< const std::uint8_t > DictAndIn, std::size_t uDictBytes, std::span< std::uint8_t > Out, std::size_t & uWrittenOut ) noexcept;

Compresses a block with a dictionary.

Same shape as deflate: the dictionary comes right before the data, in the same buffer. See the section note in deflate.hpp. On the other side, the decompressor uses Lz4DecompressWithPrefix with the dictionary at the start of the output buffer.

Only the last 64 KiB of the dictionary are reachable, because that is the window of the format.

DictAndIn
The dictionary followed by the data, in one buffer.
uDictBytes
How many bytes at the start are dictionary.
Out
Where to write. Lz4CompressBound of the data size.
uWrittenOut
Receives the number of bytes written. Zero on failure.
The result of the compression.
Does not allocate. Thread safety: full.
function

Lz4DecompressWithPrefix

Ethereal::Compression#
ECompressionError Lz4DecompressWithPrefix( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t uPrefix, std::size_t & uWrittenOut, SDecompressLimits Limits = SDecompressLimits{} ) noexcept;

Decompresses a block that may look behind where it starts writing.

The LZ4 frame allows linked blocks, where a match can point into the previous block. It is the default of the reference compressor, so it is the common case.

Here it comes for free, because the window was never a circular buffer. It is the caller's own buffer, and it is enough to say how much of it is already written.

The offset check is the same and still holds: it compares against everything already written, prefix included, and refuses what points before the start of Out.

In
The compressed block.
Out
The whole buffer. The first uPrefix bytes are already valid.
uPrefix
How many bytes of Out are already written.
uWrittenOut
Receives the number of bytes this call wrote. Zero on failure.
Limits
Output ceiling. On by default.
The result of the decompression.
Does not allocate. Thread safety: full.

lz4_frame.hpp

#include <ethereal/cpp/compression/lz4_frame.hpp>

LZ4 frame format.

The block format carries nothing besides the data: its reader has to know from outside the original size and whether the content arrived whole. It serves whoever already has an envelope.

The frame is the file format: magic number, descriptor, blocks of limited size, end mark and checksums. It is what the 'lz4' program writes and what any other implementation expects.

MagicNb 4 bytes, 0x184D2204 FLG 1 byte: version, block independence, checksums, size, dictionary BD 1 byte: maximum block size [size] 8 bytes, if the descriptor says it is there [dictID] 4 bytes, same HC 1 byte: bits 8 to 15 of the XXH32 of the descriptor blocks... each with a 4 byte size. The high bit means "not compressed" EndMark 4 zero bytes [checksum] 4 bytes of XXH32 of the original content, if the descriptor asks

Linked blocks are the reference default, not a rare case. With linked blocks a match can point into the previous block. The reference 'LZ4F_compressFrame' produces them unless told otherwise, so a reader that only understands independent blocks fails on the most common case. Here both work at no cost: the window was never a circular buffer, it is the caller's own buffer. See Lz4DecompressWithPrefix.

function

Lz4FrameCompressBound

Ethereal::Compression#
std::size_t Lz4FrameCompressBound( std::size_t uBytes ) noexcept;

Largest size a frame can have.

uBytes
Size of the input.
The bound, header and trailer included.
Does not allocate. Thread safety: full.
function

Lz4FrameCompress

Ethereal::Compression#
ECompressionError Lz4FrameCompress( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut ) noexcept;

Compresses into a complete LZ4 frame.

Writes independent blocks of up to 64 KiB, with the content size and the content checksum in the descriptor.

A block that does not compress goes raw. The format has a bit for that, and using it avoids the growth LZ4 suffers with incompressible content.

In
The bytes.
Out
Where to write. Needs Lz4FrameCompressBound bytes.
uWrittenOut
Receives the number of bytes written. Zero on failure.
ECompressionError::eOk or eBufferTooSmall. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
Does not allocate. Thread safety: full.
function

Lz4FrameDecompress

Ethereal::Compression#
ECompressionError Lz4FrameDecompress( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, SDecompressLimits Limits = SDecompressLimits{} ) noexcept;

Decompresses an LZ4 frame.

Trusts nothing in the input. The magic number, the version, the reserved bits, the header checksum, the size of each block against the declared maximum, the end mark, the announced content size and the content checksum are all checked. A frame that lies in any of them is refused.

Accepts linked and independent blocks, with or without block checksums, with or without declared size.

A preset dictionary is not supported: when the descriptor carries a dictionary id, the answer is ECompressionError::eUnsupportedAlgorithm, not a silence that would produce garbage.

Concatenated frames: reads the first one and stops. The format allows it, and this is noted.

In
The frame.
Out
Where to write. Also serves as the window.
uWrittenOut
Receives the number of bytes written. Zero on failure.
Limits
Output ceiling. On by default.
ECompressionError::eOk, eBufferTooSmall, eCorruptStream, eTruncatedStream, eUnsupportedAlgorithm or eOutputLimitExceeded.
Does not allocate. Thread safety: full.

rle.hpp

#include <ethereal/cpp/compression/rle.hpp>

Run length encoding.

A control byte opens each group:

bit 7 set -> repeat. Count = (control & 0x7F) + 1, from 1 to 128. One byte follows, repeated that many times.

bit 7 clear -> literals. Count = control + 1, from 1 to 128. That many bytes follow, copied as they are.

It is the PackBits scheme, with the count shifted by one so the empty group does not exist: a group that carries nothing would let the stream grow without limit and never end.

It pays off on sparse data: bitmaps, zeroed fields, images without noise. On common content it grows, which is why RleCompressBound returns more than the input. Whoever does not know what will be compressed should use EAlgorithm::Store as the fallback, not this.

function

RleCompressBound

Ethereal::Compression#
std::size_t RleCompressBound( std::size_t uBytes ) noexcept;

Largest size the output can have.

The worst case is input with no repetition at all: every 128 bytes become 129, plus the rest. It returns more than the input on purpose: asking for the same space as the input is the mistake that makes compression fail exactly on the content it does not help.

uBytes
Size of the input.
The bound.
Does not allocate. Thread safety: full.
function

RleCompress

Ethereal::Compression#
ECompressionError RleCompress( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut ) noexcept;

Compresses by repetition.

In
The bytes.
Out
Where to write. Needs RleCompressBound bytes.
uWrittenOut
Receives the number of bytes written. Zero on failure.
ECompressionError::eOk or eBufferTooSmall. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
Does not allocate. Thread safety: full.
function

RleDecompress

Ethereal::Compression#
ECompressionError RleDecompress( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, SDecompressLimits Limits = SDecompressLimits{} ) noexcept;

Decompresses.

Does not trust the input. Each count is checked against what is left of the input and of the output space before any copy.

In
The compressed stream.
Out
Where to write.
uWrittenOut
Receives the number of bytes written. Zero on failure.
Limits
Output ceiling. On by default.
ECompressionError::eOk, eBufferTooSmall, eTruncatedStream or eOutputLimitExceeded.
Does not allocate. Thread safety: full.

stream.hpp

#include <ethereal/cpp/compression/stream.hpp>

Streaming compressors and decompressors.

The one shot functions need the whole input in memory and an output buffer that fits the whole result. That is enough for a configuration file and not for anything that comes from the network or a large disk, where bytes arrive in chunks of whatever size the system gives. Here the input goes in by chunks, the output comes out by chunks, and the state survives between calls.

Two interfaces, while the spec has one. The package spec describes a single ICompressor with Init, Update, Finish and Reset. Section 10 of the conventions says to report divergences, and this is one: there are two interfaces here with the same shape. Compressing and decompressing have different contracts where it matters most. The decompressor takes untrusted input and needs SDecompressLimits. The compressor takes data and needs ELevel. A single interface would have half its fields ignored in each use, and an ignored field is where tomorrow's bug lives.

The virtual seam is crossed once per chunk, never per byte. The spec requires it, and it holds by construction: inside Update the loop is direct, with no virtual call.

Nothing here allocates, not even in Init. The spec allows one allocation in Init. The concrete classes of this module do not need it: the window and the tables are members, and whoever creates the object decides where it lives. A deflate decompressor takes about 40 KiB and fits on the stack, in a static or in a vector.

struct

SStreamParams

Ethereal::Compression#
C++
struct   SStreamParams   final
{
    /// @brief  Which format.
    EAlgorithm eAlgorithm = EAlgorithm::Deflate;

    /// @brief  How much effort. Only used when compressing.
    ELevel eLevel = ELevel::Default;

    /// @brief  Output ceiling. Only used when decompressing, and on by default.
    SDecompressLimits Limits{};
};

What to tell Init.

struct

IDecompressor

Ethereal::Compression#
C++
struct   IDecompressor
{
    ///
    /// Init
    ///
    /// @brief  Prepares the object. Can be called again to switch format.
    ///
    /// @param Params    The format and the limits.
    ///
    /// @return  ECompressionError::eOk or eUnsupportedAlgorithm.
    ///
    virtual ECompressionError Init( const SStreamParams & Params ) ETL_NOEXCEPT = 0;

    ///
    /// Update
    ///
    /// @brief  Eats a chunk of input and produces what it can of the output.
    ///
    /// @details  Not everything is consumed and not everything is produced, and
    ///            that is normal, not an error: the function stops when the input
    ///            runs out or the output space fills, whichever comes first. The
    ///            caller looks at both counters and comes back with the rest.
    ///
    ///            Calling with empty input is legitimate, and it is how what was
    ///            left pending when the output filled gets drained.
    ///
    /// @param In            The chunk that arrived. May be empty.
    /// @param Out            Where to write.
    /// @param pConsumed    Receives how many bytes of In were eaten.
    /// @param pWritten        Receives how many bytes were written to Out.
    ///
    /// @return  ECompressionError::eOk while there is a way forward, or the cause
    ///              of the refusal. After a refusal the object is only good for Reset.
    ///
    virtual ECompressionError Update( std::span< const std::uint8_t > In,
                                      std::span< std::uint8_t > Out,
                                      std::size_t * pConsumed,
                                      std::size_t * pWritten ) ETL_NOEXCEPT = 0;

    ///
    /// Finish
    ///
    /// @brief  Says the input ended and drains what is left.
    ///
    /// @details  It may need to be called more than once: if the output space
    ///            fills, it returns eOk with something still pending. The caller
    ///            repeats until Done answers true.
    ///
    ///            Ending the input in the middle of a stream is an error, and it
    ///            says so.
    ///
    /// @param Out            Where to write.
    /// @param pWritten        Receives how many bytes were written to Out.
    ///
    /// @return  ECompressionError::eOk, or the cause of the refusal.
    ///
    virtual ECompressionError Finish( std::span< std::uint8_t > Out,
                                      std::size_t * pWritten ) ETL_NOEXCEPT = 0;

    /// @brief  The stream ended and nothing is pending.
    ///
    virtual bool Done() const ETL_NOEXCEPT = 0;

    /// @brief  Goes back to the just initialized state, without freeing or
    ///             reallocating anything.
    ///
    virtual ECompressionError Reset() ETL_NOEXCEPT = 0;

    /// @brief  Virtual destructor.
    ///
    virtual ~IDecompressor() = default;
};

Streaming decompressor.

const

DEFLATE_WINDOW

Ethereal::Compression#
inline constexpr std::size_t DEFLATE_WINDOW = 32768u;

How much window deflate needs to keep.

const

INFLATE_CODE_SIZE

Ethereal::Compression#
inline constexpr std::size_t INFLATE_CODE_SIZE = 1664u;

Size of a built Huffman code, in bytes.

Not a magic number. The real type lives in the private inflate core, and this header is public, so it cannot see it. The number is checked by a static_assert inside the .cpp, so it cannot drift in silence: if the type grows, the build breaks.

Same arrangement as the rest of the module: what cannot be seen is asserted.

const

DEFLATE_BACKLOG

Ethereal::Compression#
inline constexpr std::size_t DEFLATE_BACKLOG = 1024u;

How much input the streaming decompressor keeps on hold.

One unit of the format (the table of a dynamic block) reaches about 560 bytes, and it cannot be decoded halfway. When the chunk that arrived ends in the middle of one, what was already read has to stay available for the next call.

1024 bytes cover the largest unit with wide slack.

class

CInflateStream

Ethereal::Compression#

Decompresses deflate, zlib or gzip in chunks.

class CInflateStream final : public IDecompressor

Allocates nothing, not even in Init: the window and the tables are members. The object takes about 40 KiB and lives wherever its creator wants.

The output is byte for byte equal to the one shot function. This is checked with chunks of 1, 3, 17 and 4096 bytes, which is the acceptance criterion the spec writes.

The padding of this type is intended (alignment). See 'ETL_BEGIN_INTENDED_PADDING'.

constructor

CInflateStream

#
CInflateStream() noexcept;

Default constructor. Builds the two Huffman codes in the opaque memory.

function

Init

#
ECompressionError Init( const SStreamParams & Params ) noexcept override;

See IDecompressor::Init.

function

Update

#
ECompressionError Update( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t * pConsumed, std::size_t * pWritten ) noexcept override;

See IDecompressor::Update.

function

Finish

#
ECompressionError Finish( std::span< std::uint8_t > Out, std::size_t * pWritten ) noexcept override;

See IDecompressor::Finish.

function

Done

#
bool Done() const noexcept override;

See IDecompressor::Done.

function

Reset

#
ECompressionError Reset() noexcept override;

See IDecompressor::Reset.

function

TotalProduced

#
std::size_t TotalProduced() const noexcept

How many bytes the stream has produced in total.

function

PeakPendingAtStep

#
std::size_t PeakPendingAtStep() const noexcept

Largest number of undelivered bytes a step has seen when starting.

Instrumentation, not a usage contract. It exists because three guards inside the state machine survived a mutation sweep, and reading the code showed why: they are unreachable.

Update drains before each step, and when the output fills it breaks the loop instead of taking the step. So a step always starts with an empty window, and the "no space" guards never fire.

Arguments age, numbers do not. This counter turns the argument into a measurement, and the suite requires it to be zero after the whole battery. If someone changes the Update loop, it stops being zero and the test says those guards became a live path, and a live path needs its own test.

function

PeakPending

#
std::size_t PeakPending() const noexcept

Largest number of undelivered bytes the object has seen, anywhere.

This number exists to prove the other one. A measurement that has to be zero cannot be told apart from a broken one that is always zero: the instrument would pass its own test without ever measuring anything.

Both readings come from the same function, RecordPeak, taken at two points: this one at the top of the Update loop, where the pending bytes are large, and the other when a step starts, where they have to be zero. Breaking the mechanism brings both down, and the suite requires this one to pass 258, the longest match of the format.

const

LZ4_STREAM_BLOCK

Ethereal::Compression#
inline constexpr std::size_t LZ4_STREAM_BLOCK = 64u * 1024u;
class

CLz4FrameStream

Ethereal::Compression#

Decompresses an LZ4 frame in chunks.

class CLz4FrameStream final : public IDecompressor

Allocates nothing, not even in Init. The object takes over 190 KiB: the 64 KiB window linked blocks need, plus the current decoded block, plus the compressed block waiting.

Linked blocks are the reference default, and they are why the window exists: a match points into the previous block.

function

Init

#
ECompressionError Init( const SStreamParams & Params ) noexcept override;

See IDecompressor::Init.

function

Update

#
ECompressionError Update( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t * pConsumed, std::size_t * pWritten ) noexcept override;

See IDecompressor::Update.

function

Finish

#
ECompressionError Finish( std::span< std::uint8_t > Out, std::size_t * pWritten ) noexcept override;

See IDecompressor::Finish.

function

Done

#
bool Done() const noexcept override;

See IDecompressor::Done.

function

Reset

#
ECompressionError Reset() noexcept override;

See IDecompressor::Reset.

function

TotalProduced

#
std::size_t TotalProduced() const noexcept

How many bytes the frame has produced.

function

BlocksRead

#
std::size_t BlocksRead() const noexcept

How many blocks the frame has closed.

Instrumentation. A single block frame exercises neither the window between blocks nor the chaining, and a test that does not look at this number cannot tell whether it did.

function

MaxPrefix

#
std::size_t MaxPrefix() const noexcept

Largest prefix a block got to see.

This and MinPrefix come from the same record and have to give opposite answers: the smallest is zero, because the first block has no past, and the largest goes above zero as soon as there is a second block.

Without the pair, a blinded instrument would return the expected constant and pass. That happened with the deflate compressor.

function

MinPrefix

#
std::size_t MinPrefix() const noexcept

Smallest prefix a block got to see. See MaxPrefix.

struct

ICompressor

Ethereal::Compression#
C++
struct   ICompressor
{
    ///
    /// Init
    ///
    /// @brief  Prepares the object. Can be called again to switch format.
    ///
    /// @param Params    The format and the level.
    ///
    /// @return  ECompressionError::eOk or eUnsupportedAlgorithm.
    ///          Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
    ///
    virtual ECompressionError Init( const SStreamParams & Params ) ETL_NOEXCEPT = 0;

    ///
    /// Update
    ///
    /// @brief  Eats a chunk of input and produces what it can of the output.
    ///
    /// @param In            The chunk that arrived. May be empty.
    /// @param Out            Where to write.
    /// @param pConsumed    Receives how many bytes of In were eaten.
    /// @param pWritten        Receives how many bytes were written to Out.
    ///
    /// @return  ECompressionError::eOk, or the cause of the refusal.
    ///
    virtual ECompressionError Update( std::span< const std::uint8_t > In,
                                      std::span< std::uint8_t > Out,
                                      std::size_t * pConsumed,
                                      std::size_t * pWritten ) ETL_NOEXCEPT = 0;

    ///
    /// Finish
    ///
    /// @brief  Says the input ended, closes the last block and drains.
    ///
    /// @details  Repeat until Done, as with the decompressor.
    ///
    /// @param Out            Where to write.
    /// @param pWritten        Receives how many bytes were written to Out.
    ///
    /// @return  ECompressionError::eOk, or the cause of the refusal.
    ///
    virtual ECompressionError Finish( std::span< std::uint8_t > Out,
                                      std::size_t * pWritten ) ETL_NOEXCEPT = 0;

    /// @brief  The stream ended and nothing is pending.
    ///
    virtual bool Done() const ETL_NOEXCEPT = 0;

    /// @brief  Goes back to the just initialized state, without freeing or
    ///             reallocating anything.
    ///
    virtual ECompressionError Reset() ETL_NOEXCEPT = 0;

    /// @brief  Virtual destructor.
    ///
    virtual ~ICompressor() = default;
};

Streaming compressor.

Same shape as IDecompressor, with the same contracts: Update stops when the input runs out or the output fills, and Finish may need more than one round.

The real difference is in the parameters: here ELevel applies and SDecompressLimits does not. Compressing takes data from whoever sends it, decompressing takes untrusted input. That is why there are two interfaces. See the note at the top of this file.

const

DEFLATE_BLOCK

Ethereal::Compression#
inline constexpr std::size_t DEFLATE_BLOCK = 32768u;

How much new data goes into each block of the stream.

A trade off, not a magic number. Each block pays a reinsertion of the 32 KiB of history into the hash table: with 32 KiB blocks that doubles the hashing work, larger blocks dilute it. In exchange, a larger block delays the first output byte more and grows the object.

const

DEFLATE_STAGE

Ethereal::Compression#
inline constexpr std::size_t DEFLATE_STAGE = DEFLATE_BLOCK + 1024u;

Where a compressed block waits to be delivered.

Incompressible content becomes a stored block, which is the worst case: the data size plus five bytes per 65535 byte piece, plus the alignment and the envelope slack. The static_assert that checks this sum is in the .cpp, next to the code that knows it.

class

CDeflateStream

Ethereal::Compression#

Compresses to deflate, zlib or gzip in chunks.

class CDeflateStream final : public ICompressor

Allocates nothing, not even in Init. The object takes about 100 KiB: twice the block, to keep history and new data side by side, plus the output stage. That is too large for the stack of a small thread, and whoever creates it decides where it lives.

The output is a single stream, not several glued together. Deflate blocks are not byte aligned: the bit accumulator crosses the boundary between them, and only the last one carries the end bit.

function

Init

#
ECompressionError Init( const SStreamParams & Params ) noexcept override;

See ICompressor::Init.

function

Update

#
ECompressionError Update( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t * pConsumed, std::size_t * pWritten ) noexcept override;

See ICompressor::Update.

function

Finish

#
ECompressionError Finish( std::span< std::uint8_t > Out, std::size_t * pWritten ) noexcept override;

See ICompressor::Finish.

function

Done

#
bool Done() const noexcept override;

See ICompressor::Done.

function

Reset

#
ECompressionError Reset() noexcept override;

See ICompressor::Reset.

function

TotalConsumed

#
std::size_t TotalConsumed() const noexcept

How many input bytes the stream has eaten.

function

BlocksClosed

#
std::size_t BlocksClosed() const noexcept

How many blocks the stream has closed.

Instrumentation, not a contract. A stream that fits in a single block never exercises the "not the last" bit, and a test that does not look at this number cannot tell whether it did. See the note in the suite.

function

MaxHistory

#
std::size_t MaxHistory() const noexcept

Largest history a block had when it was emitted.

It exists because of a defect no output test catches. If the history stops crossing the boundary between blocks, the stream stays perfectly valid, it just gets larger, because the matches that would point into the previous block no longer exist. The round trip passes, zlib accepts it, and nobody complains.

It is the third time this module produced a defect of this family, and the answer is always the same: the code declares the property. The suite requires this number to reach DEFLATE_WINDOW.

A previous version of this note said the instrument could not be blinded ("a dead instrument returns zero, and zero fails"). Wrong, and measured: the mutant does not return zero, it returns the constant the suite expects, and the check accepts it. That is why there is MinHistory, which comes from the same record and has to give the opposite.
function

MinHistory

#
std::size_t MinHistory() const noexcept

Smallest history a block had when it was emitted.

Has to be zero: the first block of a stream has no past.

Both readings come from the same record, from the same argument. Replacing that argument with a constant (the mutant that passed) gets one right and the other wrong.

The limit is stated: mutating both lines inside the record at once would still pass. The pair makes the fraud more expensive, it does not make it impossible, and promising that it does was the mistake of the previous note.

function

StageOverall

#
std::size_t StageOverall() const noexcept

Largest stage seen at the start of a loop round.

Proves the instrument below measures. See StageAtEmit.

function

StageAtEmit

#
std::size_t StageAtEmit() const noexcept

Largest stage seen at the start of an Emit.

Has to be zero, and that is what makes a guard unnecessary. Update drains before each round and breaks the loop when the output fills, so a block is only emitted with an empty stage.

Three guards said that, one in Update and two in Finish. The mutation sweep killed none of them: none is reachable. The three became this declaration.

Both readings come from the same function, and the one above has to give the opposite of this one. Breaking the mechanism brings both down.

const

RLE_STREAM_GATHER

Ethereal::Compression#
inline constexpr std::size_t RLE_STREAM_GATHER = 4096u;

How much the RLE compressor gathers before flushing.

It has to fit a whole group (128 bytes) with wide slack, so the end of what was gathered almost never falls inside a group being formed.

class

CRleCompressor

Ethereal::Compression#

Compresses to RLE in chunks.

class CRleCompressor final : public ICompressor

Allocates nothing. The object takes a few kilobytes.

The output is the same as the one shot function, as a requirement: both use the same minimum run, and a group only closes when it closes by itself or when Finish says nothing more comes.

function

Init

#
ECompressionError Init( const SStreamParams & Params ) noexcept override;

See ICompressor::Init.

function

Update

#
ECompressionError Update( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t * pConsumed, std::size_t * pWritten ) noexcept override;

See ICompressor::Update.

function

Finish

#
ECompressionError Finish( std::span< std::uint8_t > Out, std::size_t * pWritten ) noexcept override;

See ICompressor::Finish.

function

Done

#
bool Done() const noexcept override;

See ICompressor::Done.

function

Reset

#
ECompressionError Reset() noexcept override;

See ICompressor::Reset.

function

Groups

#
std::size_t Groups() const noexcept

How many groups went out.

function

Runs

#
std::size_t Runs() const noexcept

How many of them were runs, not literals.

Instrumentation. A stream that only emits literals goes back to the original exactly like one that uses the runs. Only the size changes, and size does not fail a test. The suite requires this number to be above zero.

class

CRleStream

Ethereal::Compression#

Decompresses RLE in chunks.

class CRleStream final : public IDecompressor

RLE has a real bomb: two input bytes become 128 output bytes. The expansion ratio matters here more than in any other format of this module.

There is no end mark in the format: a stream ended when the input ends on a complete group. Finish is what states that it ended.

function

Init

#
ECompressionError Init( const SStreamParams & Params ) noexcept override;

See IDecompressor::Init.

function

Update

#
ECompressionError Update( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t * pConsumed, std::size_t * pWritten ) noexcept override;

See IDecompressor::Update.

function

Finish

#
ECompressionError Finish( std::span< std::uint8_t > Out, std::size_t * pWritten ) noexcept override;

See IDecompressor::Finish.

function

Done

#
bool Done() const noexcept override;

See IDecompressor::Done.

function

Reset

#
ECompressionError Reset() noexcept override;

See IDecompressor::Reset.

function

TotalProduced

#
std::size_t TotalProduced() const noexcept

How many bytes the stream has produced.

class

CLz4FrameCompressor

Ethereal::Compression#

Compresses to the LZ4 frame in chunks.

class CLz4FrameCompressor final : public ICompressor

Allocates nothing, not even in Init. The object takes over 130 KiB: the input block being gathered and the compressed block waiting for output.

The blocks are independent, which simplifies this side a lot. A linked block would need the window of the previous one. An independent one needs no past, so there is no prefix to slide.

It is the same choice the one shot function already made, and it trades ratio for simplicity: an independent block does not use what came before it. The reader understands both modes.

function

Init

#
ECompressionError Init( const SStreamParams & Params ) noexcept override;

See ICompressor::Init.

function

Update

#
ECompressionError Update( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t * pConsumed, std::size_t * pWritten ) noexcept override;

See ICompressor::Update.

function

Finish

#
ECompressionError Finish( std::span< std::uint8_t > Out, std::size_t * pWritten ) noexcept override;

See ICompressor::Finish.

function

Done

#
bool Done() const noexcept override;

See ICompressor::Done.

function

Reset

#
ECompressionError Reset() noexcept override;

See ICompressor::Reset.

function

BlocksWritten

#
std::size_t BlocksWritten() const noexcept

How many blocks the frame has closed.

function

RawBlocks

#
std::size_t RawBlocks() const noexcept

How many of them went out raw, because they did not compress.

Instrumentation. The raw block branch is what keeps the frame from growing with incompressible content, and it cannot be told apart by the output: a frame with a raw block and one without are both valid and both go back to the original. Only the size changes, and size does not fail a test.

The suite requires this number to be above zero, to know the branch ran.