Overview / Data & formats

encoding

Converts bytes to text and back: hex, base64, base32, percent-encoding, quoted-printable and Unicode transcoding. A leaf module with no dependency on any other module.

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

encoding_inc.hpp

#include <ethereal/cpp/encoding/encoding_inc.hpp>

base32.hpp

#include <ethereal/cpp/encoding/base32.hpp>

Base32 (RFC 4648 and Crockford) for the Encoding module.

Base32 takes 60% more space than base64: five bytes become eight characters, where base64 turns three into four. It is still used because its alphabet has only upper case letters and digits. No '+', no '/', no '=' in the middle, and reading ignores case.

That makes it the format for what a person has to read aloud or type by hand: two factor authentication keys, hidden service names, recovery codes. A base64 string dictated over the phone breaks at the first lower case 'l' against '1'.

Two alphabets:

  • RFC 4648: A-Z and 2-7. The standard. Pads with '=' up to a multiple of eight.
  • Crockford: 0-9 and A-Z without I, L, O and U. It drops the letters that look like digits and maps the mistakes on reading: 'I' or 'l' become '1', 'O' becomes '0'. The 'U' is dropped to make an offensive word less likely.

Reading ignores case in both. The format exists to be typed by hand, and requiring upper case would reject that use.

enum

EBase32Alphabet

Ethereal::Encoding#
C++
enum class   EBase32Alphabet : ETL_UINT8
{
    /// @brief  `A-Z` and `2-7`. The RFC 4648 standard.
    eRfc4648 = 0,

    /// @brief  `0-9` and `A-Z` without `I`, `L`, `O` and `U`. Maps the ambiguous
    ///             letters on reading.
    eCrockford
};

Which base32 alphabet.

struct

SBase32Options

Ethereal::Encoding#
C++
ETL_BEGIN_INTENDED_PADDING
/// @brief  Options of the base32 conversion.
///
struct   ETL_STRUCT_ALIGN   SBase32Options   final
{
    /// @brief  Which alphabet.
    EBase32Alphabet        eAlphabet = EBase32Alphabet::eRfc4648;

    /// @brief  Writes `=` up to a multiple of eight characters.
    ///
    /// @details  RFC 4648 asks for it and Crockford does not. The caller sets it
    ///            for the alphabet in use.
    bool                bPadding = true;

    /// @brief  Writes in lower case. Reading accepts both cases anyway.
    bool                bLowercase = false;

    /// @brief  On reading, rejects the leftover bits of the last group when they
    ///             are not zero.
    ///
    /// @details  See EEncodingError::eNonCanonical. Two forms of the same content
    ///            become different identifiers, which matters when the text is
    ///            compared, signed or used as a key.
    bool                bRejectNonCanonical = true;

    /// @brief  On Crockford reading, accepts and skips `-` as a visual separator.
    ///
    /// @details  This allows `ABCD-EFGH-IJKL` on a recovery card.
    bool                bIgnoreDashes = true;
};

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

function

Base32EncodedSize

Ethereal::Encoding#
std::size_t Base32EncodedSize( std::size_t uBytes, const SBase32Options & Options ) noexcept;
function

Base32DecodedSizeMax

Ethereal::Encoding#
std::size_t Base32DecodedSizeMax( std::size_t uChars ) noexcept;

Maximum number of bytes that uChars characters can give.

uChars
Number of input characters.
Five bits per character, rounded down to whole bytes.
function

Base32Encode

Ethereal::Encoding#
EEncodingError Base32Encode( std::span< const std::uint8_t > In, std::span< char > Out, std::size_t & uWrittenOut, const SBase32Options & Options = {} ) noexcept;

Converts bytes to base32.

In
The bytes to convert.
Out
Where to write. Needs Base32EncodedSize characters.
uWrittenOut
Receives the number of characters written. Zero on failure.
Options
Options.
eOk, or eBufferTooSmall.
Does not allocate. Thread safety: full.
function

Base32Decode

Ethereal::Encoding#
EEncodingError Base32Decode( std::string_view In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, const SBase32Options & Options = {} ) noexcept;

Converts base32 to bytes.

In
The text.
Out
Where to write. Needs Base32DecodedSizeMax bytes.
uWrittenOut
Receives the number of bytes written. Zero on failure.
Options
Options.
eOk, eBufferTooSmall, eInvalidCharacter, eInvalidLength, eInvalidPadding or eNonCanonical.
function

Base32DecodeAt

Ethereal::Encoding#
EEncodingError Base32DecodeAt( std::string_view In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, std::size_t & uErrorOffsetOut, const SBase32Options & Options = {} ) noexcept;

Same as Base32Decode, and tells where the first invalid character is.

Config and Http need this to produce useful error messages. A message that says "invalid character" without saying where makes the reader search by hand.

In
The text.
Out
Where to write.
uWrittenOut
Receives the number of bytes written.
uErrorOffsetOut
Receives the offset, or NO_ERROR_OFFSET.
Options
Options.
The same as Base32Decode.

base64.hpp

#include <ethereal/cpp/encoding/base64.hpp>

Base64 (RFC 4648) for the Encoding module.

The core functions write into the space the caller gives and never allocate. The old surface (ToBase64, FromBase64) returns std::string and std::vector, so it allocates. It still exists, as a thin layer over the core: there is one implementation.

enum

EBase64Alphabet

Ethereal::Encoding#
C++
enum class   EBase64Alphabet : ETL_UINT8
{
    /// @brief  RFC 4648, section 4: ends with '+' and '/'.
    Standard = 0,

    /// @brief  RFC 4648, section 5: ends with '-' and '_'.
    ///
    /// @details  Exists because '+' and '/' have their own meaning in a network
    ///            address and in a file name, and would need escaping.
    UrlSafe = 1
};

Which 64 character alphabet.

enum

EBase64Padding

Ethereal::Encoding#
C++
enum class   EBase64Padding : ETL_UINT8
{
    /// @brief  Encoding writes it. Decoding requires it to be correct.
    Required = 0,

    /// @brief  Encoding does not write it. Decoding rejects it when present.
    Omitted = 1,

    /// @brief  Decoding only: accepts it with or without.
    ///
    /// @details  Encoding treats it as Required, because writing it "sometimes"
    ///            is not a useful choice.
    Optional = 2
};

What to do with the '=' padding at the end.

struct

SBase64Options

Ethereal::Encoding#
C++
struct   SBase64Options   final
{
    /// @brief  Which alphabet.
    EBase64Alphabet eAlphabet = EBase64Alphabet::Standard;

    /// @brief  What to do with the padding.
    EBase64Padding ePadding = EBase64Padding::Required;

    /// @brief  On decoding, skips space, tab and line breaks.
    ///
    /// @details  Off by default, because it costs a check per character in the
    ///            hottest loop of the module. Whoever reads a MIME style message
    ///            body turns it on.
    bool bSkipWhitespace = false;

    /// @brief  On decoding, accepts non zero leftover bits in the last group.
    ///
    /// @details  Off by default. With it off, each byte sequence has a single
    ///            encoded form. That matters when the text is compared, signed or
    ///            used as a key, because two forms of the same content would become
    ///            different identifiers.
    ///
    ///           Turn it on only to read what another program wrote wrong.
    bool bLenient = false;
};

Options of the base64 conversion.

Small POD. Passed by value.
function

Base64EncodedSize

Ethereal::Encoding#
std::size_t Base64EncodedSize( std::size_t uBytes, SBase64Options Options = SBase64Options{} ) noexcept;

Number of characters the encoding of uBytes bytes takes.

uBytes
Number of input bytes.
Options
Options. Only ePadding changes the count.
The exact size.
Does not allocate. Thread safety: full.
function

Base64DecodedSizeMax

Ethereal::Encoding#
std::size_t Base64DecodedSizeMax( std::size_t uChars ) noexcept;

Maximum number of bytes the decoding of uChars characters can give.

An upper bound. Padding and whitespace do not become bytes, so the real value is usually smaller: read uWrittenOut afterwards.

uChars
Number of input characters.
Three bytes per group of four characters, rounded up.
Does not allocate. Thread safety: full.
function

Base64EncodePath

Ethereal::Encoding#
Ethereal::Cpu::ESimdLevel Base64EncodePath( std::size_t uBytes ) noexcept;

Instruction set Base64Encode would use for this input.

uBytes
Input size.
The level used for the largest part of the work.
Does not allocate. Thread safety: full.
function

Base64DecodePath

Ethereal::Encoding#
Ethereal::Cpu::ESimdLevel Base64DecodePath( std::size_t uChars, std::size_t uOutCap, SBase64Options Options = SBase64Options{} ) noexcept;

Instruction set Base64Decode would use for this input.

uChars
Text size.
uOutCap
Output space available.
Options
The options.
The level used for the largest part of the work.
Does not allocate. Thread safety: full.
function

Base64Encode

Ethereal::Encoding#
EEncodingError Base64Encode( std::span< const std::uint8_t > In, std::span< ETL_CHAR > Out, std::size_t & uWrittenOut, SBase64Options Options = SBase64Options{} ) noexcept;

Writes the base64 form of a buffer into the space the caller gives.

Does not allocate. The space is checked before any write.

In
The bytes to convert.
Out
Where to write. Needs Base64EncodedSize characters.
uWrittenOut
Receives the number of characters written. Zero on failure.
Options
Options.
eOk, or eBufferTooSmall.
Does not allocate. Thread safety: full.
function

Base64Decode

Ethereal::Encoding#
EEncodingError Base64Decode( std::string_view In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, SBase64Options Options = SBase64Options{} ) noexcept;

Reads base64 text into the space the caller gives.

Does not allocate, and validates while reading, in a single pass.

In
The text.
Out
Where to write. Needs Base64DecodedSizeMax bytes.
uWrittenOut
Receives the number of bytes written. Zero on failure.
Options
Options.
eOk, eBufferTooSmall, eInvalidCharacter, eInvalidLength, eInvalidPadding or eNonCanonical.
Does not allocate. Thread safety: full.
function

Base64DecodeAt

Ethereal::Encoding#
EEncodingError Base64DecodeAt( std::string_view In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, std::size_t & uErrorOffsetOut, SBase64Options Options = SBase64Options{} ) noexcept;

Same as Base64Decode, and also tells where the text is invalid.

In
The text.
Out
Where to write.
uWrittenOut
Receives the number of bytes written.
uErrorOffsetOut
Receives the position of the first rejected character, or NO_ERROR_OFFSET when the failure has no position.
Options
Options.
The same as Base64Decode.
Does not allocate. Thread safety: full.
function

ToBase64

Ethereal::Encoding#
std::string ToBase64( std::span< const std::uint8_t > Data );

Encodes a binary buffer in base64.

Standard RFC 4648 alphabet (A-Z, a-z, 0-9, +, /), padded with =. This is not the URL safe alphabet: + and / need escaping if the result goes into a query string.

The output has no line breaks. When the target needs MIME with 76 column lines, the caller breaks them.

Data
Binary input buffer. An empty buffer returns an empty string.
The base64 text.
function

ToBase64

Ethereal::Encoding#
std::string ToBase64( const char * Str );

Encodes a string in base64, without the null terminator.

Str
Input string. A null pointer returns an empty string.
The base64 text.
function

FromBase64

Ethereal::Encoding#
bool FromBase64( std::string_view Text, std::vector< std::uint8_t > & OutData );

Decodes base64 text back to bytes.

Rejects the input instead of guessing: any character outside the alphabet, a length that is not a multiple of 4 and misplaced padding fail. Spaces and line breaks are skipped, because the text often arrives broken into lines.

On failure OutData is emptied, not left half filled.

Text
The base64 text.
OutData
Receives the decoded bytes.
true on success.

encoding_common.hpp

#include <ethereal/cpp/encoding/encoding_common.hpp>

Shared types of the Encoding module.

The failure cause returned by every codec of the module and the value that marks a failure without a position.

enum

EEncodingError

Ethereal::Encoding#
C++
enum class   EEncodingError : ETL_INT32
{
    /// @brief  The conversion finished as requested.
    eOk = 0,

    /// @brief  The result does not fit in the space the caller gave.
    ///
    /// @details  Nothing was written outside the space. The functions check the
    ///            size before they start, and the *EncodedSize and
    ///            *DecodedSizeMax companions exist so the caller never has to guess.
    eBufferTooSmall,

    /// @brief  The input has a character the alphabet does not accept.
    eInvalidCharacter,

    /// @brief  The input length is not possible for this format.
    ///
    /// @details  In hexadecimal, an odd number of digits. In base64, a group of a
    ///            single character, which does not carry a whole byte.
    eInvalidLength,

    /// @brief  The padding is missing, extra or in the wrong place.
    eInvalidPadding,

    /// @brief  The leftover bits of the last group are not zero.
    ///
    /// @details  The same bytes would have more than one representation, and one
    ///            of them is not the canonical one. This matters when the encoded
    ///            text is compared, signed or used as a key: two forms of the same
    ///            content become different identifiers.
    ///
    ///           Rejecting is the default. There is a lenient mode to read what
    ///            another program wrote wrong.
    eNonCanonical,

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

    /// @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 conversion failure.

Narrow POD enum, in the same format the other modules use. eOk is zero and the value travels in the return register while the result goes out through a parameter.

function

EncodingErrorName

Ethereal::Encoding#
const ETL_CHAR * EncodingErrorName( EEncodingError eError ) noexcept;

Readable name of an EEncodingError, for logs and diagnostics.

eError
The cause to name.
Static null terminated string. Never null, not even for an unknown value.
Thread safety: full. Touches no state.
const

NO_ERROR_OFFSET

Ethereal::Encoding#
inline constexpr std::size_t NO_ERROR_OFFSET = static_cast< std::size_t >( -1 );

Value written to uErrorOffsetOut when the failure has no position.

A buffer that is too small, for example, does not happen at a character: it is checked before the reading starts. Returning zero there would point at the first character, which is not to blame.

hex.hpp

#include <ethereal/cpp/encoding/hex.hpp>

Hexadecimal (base 16) for the Encoding module.

The core functions write into the space the caller gives and never allocate. The old surface (ToHex, FromHex) returns std::string and std::vector, so it allocates. It still exists because it is handy and code uses it, but it is now a thin layer over the core.

There is one implementation. Two would drift apart, and on the day they differ nobody knows which one is right.

Also here: the functions that report which instruction set the codec used, and constant time variants for cryptography.

struct

SHexOptions

Ethereal::Encoding#
C++
struct   SHexOptions   final
{
    /// @brief  On encoding, uses 'A'..'F' instead of 'a'..'f'.
    bool bUpperCase = false;

    /// @brief  On decoding, skips space, tab and line breaks.
    ///
    /// @details  On by default because the old surface always did it, and turning
    ///            it off would change the behaviour for existing callers. Whoever
    ///            wants the fastest path turns it off.
    bool bSkipWhitespace = true;
};

Options of the hexadecimal conversion.

POD, eight bytes at most. Passed by value.
function

HexEncodedSize

Ethereal::Encoding#
std::size_t HexEncodedSize( std::size_t uBytes ) noexcept;

Number of characters the encoding of uBytes bytes takes.

uBytes
Number of input bytes.
Exactly twice as many. Hexadecimal has no padding.
Does not allocate. Thread safety: full.
function

HexDecodedSizeMax

Ethereal::Encoding#
std::size_t HexDecodedSizeMax( std::size_t uChars ) noexcept;

Maximum number of bytes the decoding of uChars characters can give.

An upper bound, not the exact value: with bSkipWhitespace on, the text may have spaces that become no byte. Use this number to size the space, and read uWrittenOut afterwards for the real size.

uChars
Number of input characters.
Half, rounded down.
Does not allocate. Thread safety: full.
function

HexEncode

Ethereal::Encoding#
EEncodingError HexEncode( std::span< const std::uint8_t > In, std::span< ETL_CHAR > Out, std::size_t & uWrittenOut, SHexOptions Options = SHexOptions{} ) noexcept;

Writes the hexadecimal form of a buffer into the space the caller gives.

Does not allocate. The space is checked before any write, so an output that is too small fails without touching anything.

In
The bytes to convert.
Out
Where to write. Needs HexEncodedSize characters.
uWrittenOut
Receives the number of characters written. Zero on failure.
Options
Options. Only bUpperCase matters here.
eOk, or eBufferTooSmall.
Does not allocate. Thread safety: full.
function

HexDecode

Ethereal::Encoding#
EEncodingError HexDecode( std::string_view In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, SHexOptions Options = SHexOptions{} ) noexcept;

Reads hexadecimal text into the space the caller gives.

Does not allocate. Validation happens while reading, in a single pass, with no validation scan before.

Accepts both cases. With bSkipWhitespace, skips space, tab, carriage return and newline anywhere, even in the middle of a pair.

In
The text.
Out
Where to write. Needs HexDecodedSizeMax bytes.
uWrittenOut
Receives the number of bytes written. Zero on failure.
Options
Options. Only bSkipWhitespace matters here.
eOk, eBufferTooSmall, eInvalidCharacter, or eInvalidLength when half a byte is left over.
Does not allocate. Thread safety: full.
function

HexDecodeAt

Ethereal::Encoding#
EEncodingError HexDecodeAt( std::string_view In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, std::size_t & uErrorOffsetOut, SHexOptions Options = SHexOptions{} ) noexcept;

Same as HexDecode, and also tells where the text is invalid.

Whoever reads a configuration file or a network header needs to tell the position to the user. Without it, the only possible message would be "the text is wrong", which helps nobody.

In
The text.
Out
Where to write.
uWrittenOut
Receives the number of bytes written.
uErrorOffsetOut
Receives the position of the first rejected character, or NO_ERROR_OFFSET when the failure has no position.
Options
Options.
The same as HexDecode.
Does not allocate. Thread safety: full.
function

HexEncodePath

Ethereal::Encoding#
Ethereal::Cpu::ESimdLevel HexEncodePath( std::size_t uBytes ) noexcept;

Instruction set HexEncode would use for this input.

Pure function: touches nothing, it only repeats the decision. The real dispatch calls this same function, so the two never differ.

uBytes
Input size.
The level used for the largest part of the work.
Does not allocate. Thread safety: full.
function

HexDecodePath

Ethereal::Encoding#
Ethereal::Cpu::ESimdLevel HexDecodePath( std::size_t uChars, std::size_t uOutCap, SHexOptions Options = SHexOptions{} ) noexcept;

Instruction set HexDecode would use for this input.

With bSkipWhitespace on, the answer is always scalar: a space in the middle shifts all following pairs and the fixed size block no longer applies.

uChars
Text size.
uOutCap
Output space available. It counts because the vector path only runs when a whole block fits.
Options
The options.
The level used for the largest part of the work.
Does not allocate. Thread safety: full.
function

HexEncodeConstantTime

Ethereal::Encoding#
EEncodingError HexEncodeConstantTime( std::span< const std::uint8_t > In, std::span< ETL_CHAR > Out, std::size_t & uWrittenOut, SHexOptions Options = SHexOptions{} ) noexcept;

Encodes in hexadecimal with no branch that depends on the byte values.

Slower on purpose. It exists for the cryptography module.

The common version picks the digit with a branch, so its running time depends on the content. When the content is a key or a signature, that leaks information to whoever can measure the time. Here the choice is made with branchless arithmetic.

Using this function and the common one on the same secret does not help: one value dependent path is enough for the leak to exist.

In
The bytes to convert.
Out
Where to write. Needs HexEncodedSize characters.
uWrittenOut
Receives the number of characters written.
Options
Options. Only bUpperCase matters here.
eOk, or eBufferTooSmall.
Does not allocate. Thread safety: full.
function

HexDecodeConstantTime

Ethereal::Encoding#
EEncodingError HexDecodeConstantTime( std::string_view In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut ) noexcept;

Reads hexadecimal with no branch that depends on the digit values.

Slower on purpose, and stricter: it does not skip spaces and does not report an error position. Both would need a branch that depends on the content, which is what this variant exists to avoid.

It walks the whole input even after an invalid character, and only reports at the end.

In
The text. The length must be even.
Out
Where to write. Needs In.size()/2 bytes.
uWrittenOut
Receives the number of bytes written. Zero on failure.
eOk, eBufferTooSmall, eInvalidLength, or eInvalidCharacter.
Does not allocate. Thread safety: full.
function

ToHex

Ethereal::Encoding#
std::string ToHex( std::span< const std::uint8_t > Data, const bool bUpperCase = false );

Converts a binary buffer to hexadecimal text.

Two characters per byte, most significant first, with no prefix and no separator. An empty buffer gives empty text.

Data
Binary input buffer.
bUpperCase
When true uses A-F. The default is a-f.
The hexadecimal text.
function

ToHex

Ethereal::Encoding#
void ToHex( std::span< const std::uint8_t > Data, std::string & StrOut, const bool bUpperCase = false );

Converts a binary buffer to hexadecimal text, writing into the given output.

Same conversion as ToHex, without allocating a return value: the output string is cleared, sized exactly and filled.

Data
Binary input buffer.
StrOut
Output string.
bUpperCase
When true uses A-F. The default is a-f.
function

FromHex

Ethereal::Encoding#
bool FromHex( std::string_view Text, std::vector< std::uint8_t > & OutData );

Converts hexadecimal text back to bytes.

Accepts upper and lower case, even mixed, and skips spaces, tabs and line breaks. Hexadecimal often arrives formatted in columns or in separated pairs.

Rejects instead of guessing: any character outside 0-9a-fA-F and an odd number of digits fail. Does not accept the 0x prefix, which is literal notation and not content.

On failure OutData is emptied, not left half filled.

Text
The hexadecimal text.
OutData
Receives the decoded bytes.
true on success.

percent.hpp

#include <ethereal/cpp/encoding/percent.hpp>

Percent encoding (RFC 3986) for the Encoding module.

There is no single "URL encode". There are eight, and picking the wrong one is a bug. What is safe in one part of a URI is not safe in another, which is why the spec asks for precomputed 256 bit allowed character maps, one per URI component.

  • A '/' in the path separates segments and passes as is. Inside one segment it must be encoded, or the segment splits in two and the request goes somewhere else.
  • A '&' or a '=' in the query are separators. Inside a parameter value they must be encoded, or a value with a '&' invents a parameter nobody sent. That is a classic way to fool a server.
  • A '@' or a ':' make sense in userinfo and not in the host.

A map that is too permissive is a security hole. One that is too strict is only ugly: the URI fills with '%2F' where it was not needed, and still means the same. When in doubt, pick the strictest.

The map is a set of 256 bits, not a table of 256 bytes. Thirty two bytes fit in half a cache line, the byte table takes four lines. In a loop over a whole URI, that is the difference between the map staying in the L1 cache and being evicted by every input block that goes by.

struct

SPercentMap

Ethereal::Encoding#
C++
struct   ETL_STRUCT_ALIGN   SPercentMap   final
{
    /// @brief  One bit per byte value, 64 per word.
    std::uint64_t    uBits[ 4 ] = { 0u, 0u, 0u, 0u };


    ///
    /// Passes
    ///
    /// @brief  Tells whether the byte passes without being encoded.
    ///
    /// @param b    The byte.
    ///
    /// @return  true when the bit of the byte is set.
    ///
    ETL_API_NOIGN    ETL_INL_CEXPR bool Passes( const std::uint8_t b ) const ETL_NOEXCEPT
    {
        return ( uBits[ b >> 6 ] & ( 1ull << ( b & 63u ) ) ) != 0u;
    }

    ///
    /// Allow
    ///
    /// @brief  Lets the byte pass.
    ///
    /// @param b    The byte.
    ///
    ETL_INL_CEXPR void Allow( const std::uint8_t b ) ETL_NOEXCEPT
    {
        uBits[ b >> 6 ] |= ( 1ull << ( b & 63u ) );
    }

    ///
    /// Deny
    ///
    /// @brief  Makes the byte be encoded.
    ///
    /// @param b    The byte.
    ///
    ETL_INL_CEXPR void Deny( const std::uint8_t b ) ETL_NOEXCEPT
    {
        uBits[ b >> 6 ] &= ~( 1ull << ( b & 63u ) );
    }
};

A set of 256 bits: which bytes pass without being encoded.

enum

EUriComponent

Ethereal::Encoding#
C++
enum class   EUriComponent : ETL_UINT8
{
    /// @brief  Only `A-Z a-z 0-9 - . _ ~`. The unreserved set of RFC 3986.
    ///
    /// @details  The strictest one, and the right one when unsure.
    eUnreserved = 0,

    /// @brief  `http`, `https`. Letters, digits, `+`, `-` and `.`.
    eScheme,

    /// @brief  What comes before the `@`. Lets `:` and the sub delimiters pass.
    eUserInfo,

    /// @brief  The host. Lets `[`, `]` and `:` pass for IPv6 addresses.
    eHost,

    /// @brief  The whole path. Lets `/` pass, which is a separator there.
    ePath,

    /// @brief  One path segment. Does not let `/` pass.
    ePathSegment,

    /// @brief  The whole query. Lets `&`, `=` and `/` pass.
    eQuery,

    /// @brief  A parameter name or value. Does not let `&` or `=` pass.
    eQueryParam,

    /// @brief  The fragment, after the `#`.
    eFragment
};

Which part of the URI is being encoded.

function

PercentMapFor

Ethereal::Encoding#
const SPercentMap & PercentMapFor( EUriComponent eComponent ) noexcept;

The map of a component. Built at compile time.

eComponent
The URI component.
The map. Unknown values get the unreserved map.
struct

SPercentOptions

Ethereal::Encoding#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SPercentOptions   final
{
    /// @brief  Which URI component.
    EUriComponent        eComponent = EUriComponent::eUnreserved;

    /// @brief  Uses this map instead of the component one. Null uses the component one.
    const SPercentMap *    pCustomMap = nullptr;

    /// @brief  Writes `%2F` instead of `%2f`.
    bool                bUppercase = true;

    /// @brief  On decoding, `+` becomes a space. False by default, as the spec asks.
    ///
    /// @details  This is not percent encoding. It is a rule of HTML forms
    ///            (`application/x-www-form-urlencoded`) that stuck to the rest by
    ///            habit. In a URI path a `+` is a `+`. Turning it on by default
    ///            would make `/a+b` become `/a b`, which is another file.
    bool                bPlusIsSpace = false;

    /// @brief  On decoding, lets a malformed `%` pass instead of rejecting it.
    ///
    /// @details  False by default. A `%zz` or a `%` at the end of the text is
    ///            garbage, and accepting it silently is how a malformed URI gets
    ///            through a filter and reaches whatever comes next intact.
    bool                bLenient = false;
};

Options of the percent conversion.

function

PercentEncodedSize

Ethereal::Encoding#
std::size_t PercentEncodedSize( std::span< const std::uint8_t > In, const SPercentOptions & Options ) noexcept;
function

PercentDecodedSizeMax

Ethereal::Encoding#
inline constexpr std::size_t PercentDecodedSizeMax( const std::size_t uChars ) noexcept

Maximum number of bytes that uChars characters can give.

uChars
Number of input characters.
uChars. A character never becomes more than one byte.
function

PercentEncode

Ethereal::Encoding#
EEncodingError PercentEncode( std::span< const std::uint8_t > In, std::span< char > Out, std::size_t & uWrittenOut, const SPercentOptions & Options = {} ) noexcept;

Converts bytes to percent encoded text.

In
The bytes to convert.
Out
Where to write. Needs PercentEncodedSize characters.
uWrittenOut
Receives the number of characters written. Zero on failure.
Options
Options.
eOk, or eBufferTooSmall.
function

PercentDecode

Ethereal::Encoding#
EEncodingError PercentDecode( std::string_view In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, const SPercentOptions & Options = {} ) noexcept;

Converts percent encoded text to bytes.

In
The text.
Out
Where to write. Needs PercentDecodedSizeMax bytes.
uWrittenOut
Receives the number of bytes written. Zero on failure.
Options
Options.
eOk, eBufferTooSmall, or eInvalidCharacter for a malformed escape.
function

PercentDecodeAt

Ethereal::Encoding#
EEncodingError PercentDecodeAt( std::string_view In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, std::size_t & uErrorOffsetOut, const SPercentOptions & Options = {} ) noexcept;

Same as PercentDecode, and tells where the first invalid escape is.

In
The text.
Out
Where to write.
uWrittenOut
Receives the number of bytes written.
uErrorOffsetOut
Receives the offset, or NO_ERROR_OFFSET.
Options
Options.
The same as PercentDecode.

stream.hpp

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

Quoted-printable and the streaming codecs of the Encoding module.

Quoted-printable was made for mail going through servers that only handled seven bits and short lines. It keeps text that is almost all ASCII readable, unlike base64, and escapes only what it must:

  • a byte that passes goes out as is;
  • the rest goes out as '=' and two upper case hex digits;
  • no line goes past 76 characters. When it would, a '=' followed by a line end is written: the soft line break, which the reader drops.

A space at the end of a line must be escaped, and this is the rule most homemade implementations forget: mail servers trim spaces at the end of lines, and a space left there vanishes in transit. Written as '=20' it survives.

The streaming codecs are for input that arrives in chunks and cannot be buffered whole. Base64 works in groups of three bytes, base32 in groups of five and hex in groups of one, so between two calls at most a few bytes are left over. The whole state fits well under the 64 bytes the spec allows, and there is nothing to allocate or destroy. Both promises are enforced by static_assert at the end of this file.

struct

SQuotedPrintableOptions

Ethereal::Encoding#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SQuotedPrintableOptions   final
{
    /// @brief  Where the line breaks. 76 is what the standard says.
    std::size_t        uColumns = 76u;

    /// @brief  Also escapes the characters that only matter in mail headers.
    bool            bEscapeAllNonPrintable = false;
};

Options of the quoted-printable conversion.

function

QuotedPrintableEncodedSize

Ethereal::Encoding#
std::size_t QuotedPrintableEncodedSize( std::span< const std::uint8_t > In, const SQuotedPrintableOptions & Options ) noexcept;
function

QuotedPrintableEncode

Ethereal::Encoding#
EEncodingError QuotedPrintableEncode( std::span< const std::uint8_t > In, std::span< char > Out, std::size_t & uWrittenOut, const SQuotedPrintableOptions & Options = {} ) noexcept;

Converts bytes to quoted-printable.

In
The bytes to convert.
Out
Where to write.
uWrittenOut
Receives the number of characters written. Zero on failure.
Options
Options.
eOk, eBufferTooSmall, or eInvalidLength when the line width is under 4.
function

QuotedPrintableDecode

Ethereal::Encoding#
EEncodingError QuotedPrintableDecode( std::string_view In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, std::size_t & uErrorOffsetOut ) noexcept;

Converts quoted-printable to bytes. Soft line breaks are dropped.

In
The text.
Out
Where to write.
uWrittenOut
Receives the number of bytes written. Zero on failure.
uErrorOffsetOut
Receives the offset of the bad escape, or NO_ERROR_OFFSET.
eOk, eBufferTooSmall, eInvalidLength or eInvalidCharacter.
enum

ECodec

Ethereal::Encoding#
C++
enum class   ECodec : ETL_UINT8
{
    /// @brief  Base64, standard alphabet.
    eBase64 = 0,

    /// @brief  Base32, RFC 4648 alphabet.
    eBase32,

    /// @brief  Hexadecimal.
    eHex
};

Which codec a stream uses.

class

CEncoderStream

Ethereal::Encoding#

Encodes in chunks. Does not allocate and has no destructor.

class CEncoderStream final
constructor

CEncoderStream

#
CEncoderStream() = default;

Default constructor. Call Init before use.

function

Init

#
EEncodingError Init( ECodec eCodec ) noexcept;

Starts a new stream with the given codec.

eCodec
The codec.
eOk, or eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

Update

#
EEncodingError Update( std::span< const std::uint8_t > In, std::span< char > Out, std::size_t & uWrittenOut ) noexcept;

Gives more input and receives what can already be written.

In
The next chunk of bytes.
Out
Where to write.
uWrittenOut
Receives the number of characters written.
eOk, eBufferTooSmall, or eInvalidLength when the stream was not started or is already finished.
function

Finish

#
EEncodingError Finish( std::span< char > Out, std::size_t & uWrittenOut ) noexcept;

Closes the stream: writes the incomplete group and the padding.

Without this the output is truncated. It is the most common mistake with a streaming codec: the last one or two bytes live in the internal state until someone says the input is over.

Out
Where to write.
uWrittenOut
Receives the number of characters written.
eOk, eBufferTooSmall, or eInvalidLength when the stream was not started or is already finished.
function

TotalWritten

#
std::size_t TotalWritten() const noexcept

Total number of characters written since Init.

class

CDecoderStream

Ethereal::Encoding#
class CDecoderStream final
constructor

CDecoderStream

#
CDecoderStream() = default;

Default constructor. Call Init before use.

function

Init

#
EEncodingError Init( ECodec eCodec ) noexcept;

Starts a new stream with the given codec.

eCodec
The codec.
eOk, or eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

Update

#
EEncodingError Update( std::string_view In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut ) noexcept;

Gives more text and receives the bytes that can already be decoded.

The last complete group is always held back for Finish, because it is the only one that may carry padding.

In
The next chunk of text.
Out
Where to write.
uWrittenOut
Receives the number of bytes written.
eOk, a decoding error, or eInvalidLength when the stream was not started or is already finished.
function

Finish

#
EEncodingError Finish( std::span< std::uint8_t > Out, std::size_t & uWrittenOut ) noexcept;

Closes the stream and decodes the group held back.

Out
Where to write.
uWrittenOut
Receives the number of bytes written.
eOk, a decoding error, or eInvalidLength when the stream was not started or is already finished.
function

TotalWritten

#
std::size_t TotalWritten() const noexcept

Total number of bytes written since Init.

unicode.hpp

#include <ethereal/cpp/encoding/unicode.hpp>

Unicode formats, single byte encodings and line endings for the Encoding module.

Accepting bytes that are "almost" UTF-8 is not tolerance: it is a known class of security hole. A validator must reject three forms, and each one has been exploited: 1. Overlong sequences. '/' is 0x2F and fits in one byte, but 0xC0 0xAF also decodes to 0x2F if the validator does not check, and so does 0xE0 0x80 0xAF. A filter that looks for '/' finds neither, and the next layer decodes them and gets a slash. For years this let attackers out of folders that should have been closed. 2. Surrogates. U+D800 to U+DFFF exist only as halves of a UTF-16 pair and are not characters. UTF-8 carrying them produces invalid UTF-16 when converted, and by the third conversion nobody knows where the garbage came from. 3. Above U+10FFFF. UTF-16 cannot represent them, so Unicode declared them nonexistent. A five or six byte sequence in the style of the original UTF-8 is not UTF-8.

Validation is done while decoding, in the same pass, and never in a separate pass. Validating and then converting reads the input twice and opens a window in which it can change between the two reads.

enum

EUnicodeFormat

Ethereal::Encoding#
C++
enum class   EUnicodeFormat : ETL_UINT8
{
    /// @brief  UTF-8.
    eUtf8 = 0,

    /// @brief  UTF-16, little endian.
    eUtf16Le,

    /// @brief  UTF-16, big endian.
    eUtf16Be,

    /// @brief  UTF-32, little endian.
    eUtf32Le,

    /// @brief  UTF-32, big endian.
    eUtf32Be
};

The five Unicode encoding forms.

enum

EInvalidPolicy

Ethereal::Encoding#
C++
enum class   EInvalidPolicy : ETL_UINT8
{
    /// @brief  Stops and tells where. This is the default, and should be.
    eStrict = 0,

    /// @brief  Writes U+FFFD and goes on.
    ///
    /// @details  Use it only when the text will be shown to a person. In a
    ///            comparison, a signature or a key, silent replacement makes two
    ///            different inputs become the same, which is what an attacker wants.
    eReplace
};

What to do when the input is invalid.

struct

SUnicodeOptions

Ethereal::Encoding#
C++
ETL_BEGIN_INTENDED_PADDING
/// @brief  Options of the Unicode conversions.
///
struct   ETL_STRUCT_ALIGN   SUnicodeOptions   final
{
    /// @brief  What to do with invalid input.
    EInvalidPolicy        ePolicy = EInvalidPolicy::eStrict;

    /// @brief  Writes the byte order mark at the start of the output.
    bool                bWriteBom = false;

    /// @brief  On reading, drops the byte order mark when present.
    ///
    /// @details  True by default. A BOM that survives the conversion becomes a
    ///            U+FEFF in the middle of the text. That is an invisible zero width
    ///            space, and it breaks a comparison without leaving a trace on screen.
    bool                bSkipBom = true;
};

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

function

IsAscii

Ethereal::Encoding#
bool IsAscii( std::span< const std::uint8_t > In ) noexcept;
function

IsValidUtf8At

Ethereal::Encoding#
bool IsValidUtf8At( std::span< const std::uint8_t > In, std::size_t & uErrorOffsetOut ) noexcept;

Tells whether the input is valid UTF-8. See the file notes on what is rejected.

From 64 bytes on, a vector kernel (SSE4.1 or AVX2 on x86, NEON on AArch64) validates whole blocks of 64 bytes, and the scalar path reads the tail and finds the exact offset of an error. The result and the offset are those of the scalar path alone. See Utf8ValidatePath.

In
The bytes.
uErrorOffsetOut
Where the invalid sequence starts, or NO_ERROR_OFFSET.
true when valid.
function

Utf8ValidatePath

Ethereal::Encoding#
Ethereal::Cpu::ESimdLevel Utf8ValidatePath( std::size_t uBytes ) noexcept;

Instruction set IsValidUtf8At would use for an input of this size.

A test against the scalar path does not prove that the vector path ran. This does. Below 64 bytes, or under a SIMD ceiling below SSE4.1, the answer is Scalar.

uBytes
Input size.
Avx2, Sse41, Neon or Scalar.
Does not allocate. Thread safety: full.
function

IsValidUnicode

Ethereal::Encoding#
bool IsValidUnicode( std::span< const std::uint8_t > In, EUnicodeFormat eFormat, std::size_t & uErrorOffsetOut ) noexcept;

Tells whether the input is valid in the given format.

In
The bytes.
eFormat
The format.
uErrorOffsetOut
Where the first bad unit is, or NO_ERROR_OFFSET.
true when valid.
function

CodePointCount

Ethereal::Encoding#
std::size_t CodePointCount( std::span< const std::uint8_t > In, EUnicodeFormat eFormat ) noexcept;

Number of code points in the input.

In
The bytes.
eFormat
The format.
The count, or zero when the input is not valid.
function

Utf8LengthOfCodePoint

Ethereal::Encoding#
inline constexpr std::size_t Utf8LengthOfCodePoint( const std::uint32_t u ) noexcept

Number of bytes this code point takes in UTF-8.

u
The code point.
1 to 4, or zero when the code point does not exist.
function

Utf8Next

Ethereal::Encoding#
std::uint32_t Utf8Next( std::span< const std::uint8_t > In, std::size_t & uPos ) noexcept;

Reads the code point at uPos and advances uPos.

In
The bytes.
uPos
Position, advanced past the code point.
The code point, or 0xFFFFFFFF when invalid.
function

Utf8Prev

Ethereal::Encoding#
std::uint32_t Utf8Prev( std::span< const std::uint8_t > In, std::size_t & uPos ) noexcept;

Moves uPos back to the start of the previous code point and reads it.

In
The bytes.
uPos
Position, moved back to the start of the code point.
The code point, or 0xFFFFFFFF when invalid.
function

DetectBom

Ethereal::Encoding#
bool DetectBom( std::span< const std::uint8_t > In, EUnicodeFormat & eFormatOut, std::size_t & uBomBytesOut ) noexcept;

Which format the mark at the start of In says the text is.

In
The bytes.
eFormatOut
Receives the format when there is a mark.
uBomBytesOut
Receives the size of the mark. Zero when there is none.
true when there was a mark. Without a mark nothing is guessed: it returns false and the caller decides, because guessing the encoding of a text from its bytes is how files get silently damaged.
function

TranscodeSizeMax

Ethereal::Encoding#
std::size_t TranscodeSizeMax( std::size_t uInputBytes, EUnicodeFormat eFrom, EUnicodeFormat eTo ) noexcept;

Maximum number of bytes the conversion needs.

uInputBytes
Input size in bytes.
eFrom
Input format.
eTo
Output format.
An upper bound, including room for a byte order mark.
function

Transcode

Ethereal::Encoding#
EEncodingError Transcode( std::span< const std::uint8_t > In, EUnicodeFormat eFrom, std::span< std::uint8_t > Out, EUnicodeFormat eTo, std::size_t & uWrittenOut, std::size_t & uErrorOffsetOut, const SUnicodeOptions & Options = {} ) noexcept;

Converts between two of the five formats.

Validation is fused into the conversion, not done in a separate pass: reading the input twice costs twice as much and opens a window in which it can change between the two reads.

In
The input bytes.
eFrom
Input format.
Out
Where to write.
eTo
Output format.
uWrittenOut
Receives the number of bytes written.
uErrorOffsetOut
In strict mode, where the first bad byte is.
Options
Options.
eOk, eBufferTooSmall, or eInvalidCharacter in strict mode.
function

Latin1ToUtf8

Ethereal::Encoding#
EEncodingError Latin1ToUtf8( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut ) noexcept;

Latin-1 (ISO 8859-1) to UTF-8. Never fails: every byte is a valid code point.

In
The input bytes.
Out
Where to write.
uWrittenOut
Receives the number of bytes written.
eOk, or eBufferTooSmall.
function

Utf8ToLatin1

Ethereal::Encoding#
EEncodingError Utf8ToLatin1( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, const SUnicodeOptions & Options = {} ) noexcept;

UTF-8 to Latin-1. Fails on code points above U+00FF, which do not fit.

In
The input bytes.
Out
Where to write.
uWrittenOut
Receives the number of bytes written.
Options
Options. With eReplace, writes '?' instead.
eOk, eBufferTooSmall, or eInvalidCharacter in strict mode.
function

Cp1252ToUtf8

Ethereal::Encoding#
EEncodingError Cp1252ToUtf8( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, const SUnicodeOptions & Options = {} ) noexcept;

Windows-1252 to UTF-8. See the note above on the 0x80 to 0x9F range.

In
The input bytes.
Out
Where to write.
uWrittenOut
Receives the number of bytes written.
Options
Options. Not used, every byte maps to a code point.
eOk, or eBufferTooSmall.
function

Utf8ToCp1252

Ethereal::Encoding#
EEncodingError Utf8ToCp1252( std::span< const std::uint8_t > In, std::span< std::uint8_t > Out, std::size_t & uWrittenOut, const SUnicodeOptions & Options = {} ) noexcept;

UTF-8 to Windows-1252.

In
The input bytes.
Out
Where to write.
uWrittenOut
Receives the number of bytes written.
Options
Options. With eReplace, writes '?' for what does not fit.
eOk, eBufferTooSmall, or eInvalidCharacter in strict mode.
enum

ELineEnding

Ethereal::Encoding#
C++
enum class   ELineEnding : ETL_UINT8
{
    /// @brief  `\n`. Unix, and what almost everything expects today.
    eLf = 0,

    /// @brief  `\r\n`. Windows, and what the internet text protocols require.
    eCrLf,

    /// @brief  `\r`. Classic Mac. Practically extinct, here for completeness.
    eCr,

    /// @brief  More than one kind, or none.
    eMixed
};

Kind of line ending.

function

DetectLineEnding

Ethereal::Encoding#
ELineEnding DetectLineEnding( std::span< const std::uint8_t > In, std::size_t * uLfOut = nullptr, std::size_t * uCrLfOut = nullptr, std::size_t * uCrOut = nullptr ) noexcept;

Which line ending dominates this text.

Returns ELineEnding::eMixed when none clearly dominates. A mixed file is a real problem, and calling it one kind would hide that.

In
The bytes.
uLfOut
Receives the number of LF. May be null.
uCrLfOut
Receives the number of CRLF. May be null.
uCrOut
Receives the number of lone CR. May be null.
The dominant kind, or eMixed.
function

NormalizeLineEndingsSizeMax

Ethereal::Encoding#
inline constexpr std::size_t NormalizeLineEndingsSizeMax( const std::size_t uBytes, const ELineEnding eTo ) noexcept

Maximum number of bytes the normalization needs.

uBytes
Input size in bytes.
eTo
Target line ending.
The upper bound.
function

NormalizeLineEndings

Ethereal::Encoding#
EEncodingError NormalizeLineEndings( std::span< const std::uint8_t > In, ELineEnding eTo, std::span< std::uint8_t > Out, std::size_t & uWrittenOut ) noexcept;

Puts all line endings in the same form.

In
The input bytes.
eTo
Target line ending. eMixed is rejected.
Out
Where to write. Needs NormalizeLineEndingsSizeMax bytes.
uWrittenOut
Receives the number of bytes written.
eOk, eBufferTooSmall, or eInvalidCharacter for eMixed.
function

NormalizeLineEndingsInPlace

Ethereal::Encoding#
EEncodingError NormalizeLineEndingsInPlace( std::span< std::uint8_t > Buffer, ELineEnding eTo, std::size_t & uWrittenOut ) noexcept;

Normalizes in the same buffer, when the target is never larger than the source.

Only for eLf and eCr, which never grow. For eCrLf it returns eBufferTooSmall instead of writing over what it has not read yet. The spec says "in place where the direction allows", and this is the direction that does not.

Buffer
The text, rewritten in place.
eTo
Target line ending.
uWrittenOut
Receives the new size.
eOk, or eBufferTooSmall for eCrLf and eMixed.

utf.hpp

#include <ethereal/cpp/encoding/utf.hpp>

Conversion between UTF-8 and the native wchar_t encoding.

The width of wchar_t changes with the platform and the conversion follows it: 16 bits on Windows (UTF-16 with surrogate pairs) and 32 bits on Linux and macOS. Malformed input never fails: each bad sequence becomes U+FFFD.

const

REPLACEMENT_CHAR

Ethereal::Encoding#
constexpr char32_t REPLACEMENT_CHAR = 0x0000FFFDu;

Replacement character, U+FFFD.

It takes the place of each malformed sequence. Converting damaged text is routine (a truncated file, a field cut in half), and aborting the whole conversion over a lost byte is usually worse than marking the spot and going on.

function

ToWide

Ethereal::Encoding#
std::wstring ToWide( std::string_view Utf8 );

Converts UTF-8 text to std::wstring.

16 bit wchar_t on Windows, where code points above U+FFFF become a surrogate pair, and 32 bit on Linux and macOS, where each code point takes one wchar_t.

Invalid sequences are replaced by REPLACEMENT_CHAR, one per discarded byte. The function does not fail and does not throw.

Utf8
Input text in UTF-8.
The text in the native wchar_t encoding.
function

ToUtf8

Ethereal::Encoding#
std::string ToUtf8( std::wstring_view Wide );

Converts wchar_t text to UTF-8.

Handles surrogate pairs on Windows. A lone surrogate, without its pair, becomes REPLACEMENT_CHAR instead of producing invalid UTF-8.

Wide
Input text in the native wchar_t encoding.
The text in UTF-8.
function

IsValidUtf8

Ethereal::Encoding#
bool IsValidUtf8( std::string_view Utf8 ) noexcept;

Tells whether the bytes are well formed UTF-8.

Rejects what the standard rejects: a continuation byte without a start, sequences longer than needed (overlong), code points above U+10FFFF and the surrogate range U+D800 to U+DFFF, which cannot appear encoded in UTF-8.

Utf8
Text to validate.
true when well formed.