Skip to content

IStringEncoding

Jay edited this page Oct 3, 2026 · 2 revisions

IStringEncoding<...>

#include <certpp/string.hpp> --- certpp

Template: template <typename TChar>

Interface for string encoding conversions. @tparam TChar The character type for this encoding.

Methods

virtual ~IStringEncoding() = default

virtual size_t measure(const TReadOnlySpan<TChar>& src) = 0

Measures the number of bytes required to encode the source string span.

  • src --- The source string span.

Returns: The number of bytes required for encoding.

virtual size_t encodeTo(const SByteSpan& dst, const TReadOnlySpan<TChar>& src) = 0

Encodes the source string span into the destination byte span.

  • dst --- The destination byte span.
  • src --- The source string span.

Returns: The number of bytes written to the destination span, or 0 if encoding fails.

virtual size_t decodeFrom(TSpan<TChar>& dst, const SReadOnlyByteSpan& src) = 0

Decodes the source byte span into the destination string span.

  • dst --- The destination string span.
  • src --- The source byte span.

Returns: The number of characters written to the destination span, or 0 if decoding fails.

Example

Obtained from an encoding's get() factory, never constructed directly. Call measure() first: the number of bytes an encoding needs is not the number of characters it was handed, for anything outside ASCII.

// given: const CString& text
IStringEncoding<char>& enc = TUtf8Encoding<char>::get();

TReadOnlySpan<char> src = text.toSpan();
const size_t needed = enc.measure(src);
if (needed == 0) {
    return;
}

CBuffer out;
if (!out.resize(needed)) {
    return;
}

const size_t written = enc.encodeTo(out.toSpan(), src);
if (written == 0) {
    return;   // 0 is the failure report; there is no error code here
}

// written, not needed, is the length to carry forward.
COctet encoded;
if (!encoded.store(out.toPtr(), written)) {
    return;
}

Reference generated from certpp/string.hpp at commit 0834b29 (v1.0.1). The header is authoritative --- if this page disagrees with it, the header is right and this page needs regenerating.

Clone this wiki locally