### Base64 and Base32 Encoding/Decoding Example Source: https://github.com/tplgy/cppcodec/blob/master/README.md Demonstrates decoding a base64 string and then encoding the result using base32_crockford. Requires including specific codec headers. ```C++ #include #include #include int main() { using base32 = cppcodec::base32_crockford; using base64 = cppcodec::base64_rfc4648; std::vector decoded = base64::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); std::cout << "decoded size ("any carnal pleasure"): " << decoded.size() << '\n'; std::cout << base32::encode(decoded) << std::endl; // "C5Q7J833C5S6WRBC41R6RSB1EDTQ4S8" return 0; } ``` -------------------------------- ### Define Minimal Decode Executable Source: https://github.com/tplgy/cppcodec/blob/master/test/CMakeLists.txt Creates an executable target named 'minimal_decode' from the 'minimal_decode.cpp' source file and links it against the 'cppcodec' library. This likely serves as a simple example or test case for decoding functionality. ```cmake add_executable(minimal_decode minimal_decode.cpp) target_link_libraries(minimal_decode cppcodec) ``` -------------------------------- ### Build helloworld Executable Source: https://github.com/tplgy/cppcodec/blob/master/example/CMakeLists.txt Creates an executable target named 'helloworld' from the 'helloworld.cpp' source file and links it with the 'cppcodec' library. ```cmake add_executable(helloworld helloworld.cpp) target_link_libraries(helloworld cppcodec) ``` -------------------------------- ### Build type_support_wrapper Executable Source: https://github.com/tplgy/cppcodec/blob/master/example/CMakeLists.txt Creates an executable target named 'type_support_wrapper' from the 'type_support_wrapper.cpp' source file and links it with the 'cppcodec' library. ```cmake add_executable(type_support_wrapper type_support_wrapper.cpp) target_link_libraries(type_support_wrapper cppcodec) ``` -------------------------------- ### Check for PkgConfig and Catch2 Source: https://github.com/tplgy/cppcodec/blob/master/test/CMakeLists.txt This snippet checks if PkgConfig is available and then attempts to find the Catch2 testing framework. If found, it configures C++ flags; otherwise, it includes the bundled version of Catch2. ```cmake find_package(PkgConfig) if(PKG_CONFIG_FOUND) pkg_check_modules(CATCH2 catch2) endif() if(CATCH2_FOUND) message(STATUS "Found system Catch2, not using bundled version") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CATCH2_CFLAGS}") else() message(STATUS "Did NOT find system Catch2, instead using bundled version") include_directories(${CMAKE_CURRENT_SOURCE_DIR}/catch/single_include) endif() ``` -------------------------------- ### Cross-Codec Transcoding and Size Calculation Source: https://context7.com/tplgy/cppcodec/llms.txt Shows how to chain encode/decode operations between different codecs (e.g., base64 to base32, binary to hex) without intermediate heap allocations. It also demonstrates using `constexpr` size helpers for static buffer sizing. ```cpp #include #include #include #include int main() { using base64 = cppcodec::base64_rfc4648; using base32 = cppcodec::base32_crockford; using hex = cppcodec::hex_lower; // base64 -> binary -> base32 std::vector binary = base64::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); std::string as_base32 = base32::encode(binary); std::cout << as_base32 << "\n"; // "C5Q7J833C5S6WRBC41R6RSB1EDTQ4S8" // binary -> hex -> binary round-trip std::vector data = {0xCA, 0xFE, 0xBA, 0xBE}; std::string hexed = hex::encode(data); std::cout << hexed << "\n"; // "cafebabe" std::vector roundtrip = hex::decode(hexed); std::cout << (roundtrip == data ? "round-trip OK" : "MISMATCH") << "\n"; // Compute encoded size before allocating (stack or custom allocator friendly) constexpr size_t INPUT_LEN = 32; char encoded_buf[base64::encoded_size(INPUT_LEN) + 1]; uint8_t input[INPUT_LEN] = {}; size_t n = base64::encode(encoded_buf, sizeof(encoded_buf), input, INPUT_LEN); std::cout << "32 zero bytes in base64 (" << n << " chars): " << encoded_buf << "\n"; return 0; } ``` -------------------------------- ### encode() - All Output Overloads Source: https://context7.com/tplgy/cppcodec/llms.txt The `encode()` function provides four overloads to handle different output scenarios: returning a string, returning a specific container type, encoding in-place into a pre-existing container, and writing into pre-allocated raw memory. The raw-pointer version is noexcept and calls abort() if the buffer is too small. It also supports templated input from containers with .data() and .size(). ```APIDOC ## encode() - All Output Overloads Every codec provides four `encode()` overloads covering different output scenarios: return-by-value (string or templated), in-place into a pre-existing container, and writing into pre-allocated raw memory. The raw-pointer version is `noexcept` and calls `abort()` if the buffer is too small. ### Usage Examples: 1. **Return std::string (most convenient):** ```cpp std::string s = base64::encode(data, data_size); ``` 2. **Return a specific container type:** ```cpp std::vector v = base64::encode>(data, data_size); ``` 3. **Reuse an existing result container (avoids reallocation on repeated calls):** ```cpp std::string reused; base64::encode(reused, data, data_size); ``` 4. **Pre-allocated raw char buffer:** ```cpp size_t buf_size = base64::encoded_size(data_size) + 1; std::vector buf(buf_size); size_t written = base64::encode(buf.data(), buf_size, data, data_size); ``` 5. **Template input (encode any container with .data() and .size()):** ```cpp std::vector vec = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; std::string from_vec = base64::encode(vec); ``` ``` -------------------------------- ### Include cppcodec Headers Source: https://context7.com/tplgy/cppcodec/llms.txt Include the specific header files for the codec variants you need. No separate compilation or linking is required. ```cpp #include #include #include #include #include #include #include #include ``` -------------------------------- ### Encode Data to Various Output Formats Source: https://context7.com/tplgy/cppcodec/llms.txt Demonstrates the four encode overloads: returning a std::string, returning a specific container type, encoding into a pre-existing container, and encoding into a pre-allocated raw buffer. Also shows encoding from a std::vector. ```cpp #include #include #include int main() { using base64 = cppcodec::base64_rfc4648; const uint8_t data[] = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello" size_t data_size = sizeof(data); // 1. Return std::string (most convenient) std::string s = base64::encode(data, data_size); std::cout << s << "\n"; // "SGVsbG8=" // 2. Return a specific container type std::vector v = base64::encode>(data, data_size); // 3. Reuse an existing result container (avoids reallocation on repeated calls) std::string reused; base64::encode(reused, data, data_size); std::cout << reused << "\n"; // "SGVsbG8=" // 4. Pre-allocated raw char buffer size_t buf_size = base64::encoded_size(data_size) + 1; // +1 for null terminator std::vector buf(buf_size); size_t written = base64::encode(buf.data(), buf_size, data, data_size); std::cout << buf.data() << " (" << written << " bytes)\n"; // "SGVsbG8= (8 bytes)" // Template input: encode any container with .data() and .size() std::vector vec = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; std::string from_vec = base64::encode(vec); std::cout << from_vec << "\n"; // "SGVsbG8=" return 0; } ``` -------------------------------- ### Define Test Executable Source: https://github.com/tplgy/cppcodec/blob/master/test/CMakeLists.txt Creates an executable target named 'test_cppcodec' from the 'test_cppcodec.cpp' source file and links it against the 'cppcodec' library. It also registers this executable as a test case named 'cppcodec'. ```cmake add_executable(test_cppcodec test_cppcodec.cpp) target_link_libraries(test_cppcodec cppcodec) add_test(NAME cppcodec COMMAND test_cppcodec) ``` -------------------------------- ### Define Benchmark Executable Source: https://github.com/tplgy/cppcodec/blob/master/test/CMakeLists.txt Creates an executable target named 'benchmark_cppcodec' from the 'benchmark_cppcodec.cpp' source file and links it against the 'cppcodec' library. This is used for performance testing. ```cmake add_executable(benchmark_cppcodec benchmark_cppcodec.cpp) target_link_libraries(benchmark_cppcodec cppcodec) ``` -------------------------------- ### Base64 RFC 4648 Encoding and Decoding Source: https://context7.com/tplgy/cppcodec/llms.txt Demonstrates encoding binary data and strings to Base64 RFC 4648 format and decoding back. Handles errors by throwing `cppcodec::parse_error`. ```cpp #include #include #include int main() { using base64 = cppcodec::base64_rfc4648; // Encode a binary vector to std::string std::vector binary = {0x61, 0x6E, 0x79, 0x20, 0x63, 0x61, 0x72, 0x6E}; std::string encoded = base64::encode(binary); std::cout << encoded << "\n"; // "YW55IGNhcm4=" // Encode a string directly std::string encoded2 = base64::encode(std::string("any carnal pleasure")); std::cout << encoded2 << "\n"; // "YW55IGNhcm5hbCBwbGVhc3VyZQ==" // Decode back to vector std::vector decoded = base64::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); std::cout << std::string(decoded.begin(), decoded.end()) << "\n"; // "any carnal pleasure" // Decode directly to std::string std::string decoded_str = base64::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); std::cout << decoded_str << "\n"; // "any carnal pleasure" // Error handling: throws cppcodec::parse_error on bad input try { base64::decode("YW55 IGNhcm4="); // space is not allowed in rfc4648 } catch (const cppcodec::parse_error& e) { std::cerr << "Decode failed: " << e.what() << "\n"; } return 0; } ``` -------------------------------- ### Encode and Decode URL-Safe Base64 Source: https://context7.com/tplgy/cppcodec/llms.txt Use `base64_url` for encoding binary data into a URL-safe string. It replaces '+' with '-' and '/' with '_'. Decoding requires valid padding; missing padding throws `cppcodec::padding_error`. ```cpp #include #include int main() { using base64url = cppcodec::base64_url; // Encodes with '-' and '_' instead of '+' and '/' std::string encoded = base64url::encode(std::string("any carnal pleasure")); std::cout << encoded << "\n"; // "YW55IGNhcm5hbCBwbGVhc3VyZQ==" // (differs from rfc4648 only when the bit pattern maps to '+' or '/') // Safe for use directly in URLs std::vector binary = {0xFB, 0xFF, 0xFE}; std::string url_safe = base64url::encode(binary); std::cout << url_safe << "\n"; // "+__+" in rfc4648 becomes "-___" here... example variant // Decode requires valid padding std::vector decoded = base64url::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); std::cout << std::string(decoded.begin(), decoded.end()) << "\n"; // "any carnal pleasure" // Missing padding throws cppcodec::padding_error (a subclass of parse_error) try { base64url::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ"); // missing '==' } catch (const cppcodec::padding_error& e) { std::cerr << "Padding error: " << e.what() << "\n"; } return 0; } ``` -------------------------------- ### Hexadecimal (Base16) Encoding and Decoding Source: https://context7.com/tplgy/cppcodec/llms.txt Illustrates uppercase and lowercase hexadecimal encoding and decoding. These codecs work on raw bytes, do not use padding or prefixes, and accept cross-case input for decoding. Input must have an even number of hex digits. ```cpp #include #include #include #include int main() { using hex_up = cppcodec::hex_upper; using hex_low = cppcodec::hex_lower; std::vector binary = {0xDE, 0xAD, 0xBE, 0xEF}; // Uppercase encoding std::string upper = hex_up::encode(binary); std::cout << upper << "\n"; // "DEADBEEF" // Lowercase encoding std::string lower = hex_low::encode(binary); std::cout << lower << "\n"; // "deadbeef" // Cross-decode: hex_upper accepts lowercase input std::vector decoded = hex_up::decode("deadbeef"); // decoded == {0xDE, 0xAD, 0xBE, 0xEF} // Encode a string (raw bytes) std::string hex_str = hex_low::encode(std::string("Hi!")); std::cout << hex_str << "\n"; // "486921" // Error: odd-length input throws cppcodec::invalid_input_length try { hex_up::decode("ABC"); // odd number of symbols } catch (const cppcodec::invalid_input_length& e) { std::cerr << "Error: " << e.what() << "\n"; } // Error: out-of-alphabet symbol throws cppcodec::symbol_error try { hex_up::decode("GGGG"); // 'G' is not a hex digit } catch (const cppcodec::symbol_error& e) { std::cerr << "Symbol error: " << e.what() << "\n"; // includes char code } return 0; } ``` -------------------------------- ### Decode Data from Various Input Formats Source: https://context7.com/tplgy/cppcodec/llms.txt Illustrates the symmetric decode overloads: returning a std::vector, returning a specific type (like std::string), decoding into a pre-existing container, and decoding into a pre-allocated raw buffer. Includes error handling for invalid input. ```cpp #include #include #include int main() { using base64 = cppcodec::base64_rfc4648; const std::string encoded = "SGVsbG8="; // 1. Return std::vector (most convenient) std::vector v = base64::decode(encoded); std::cout << std::string(v.begin(), v.end()) << "\n"; // "Hello" // 2. Return a specific type std::string s = base64::decode(encoded); std::cout << s << "\n"; // "Hello" // 3. Reuse an existing result container std::vector reused; base64::decode(reused, encoded); std::cout << reused.size() << " bytes\n"; // "5 bytes" // 4. Pre-allocated raw buffer size_t max_size = base64::decoded_max_size(encoded.size()); std::vector buf(max_size); size_t actual = base64::decode(buf.data(), buf.size(), encoded); buf.resize(actual); // trim to actual decoded size std::cout << std::string(buf.begin(), buf.end()) << "\n"; // "Hello" // All decode variants throw parse_error on invalid input try { base64::decode("SGVs!G8="); // '!' is not in the base64 alphabet } catch (const cppcodec::symbol_error& e) { std::cerr << "Bad symbol: " << e.what() << "\n"; std::cerr << "Offending char code: " << static_cast(e.symbol()) << "\n"; } return 0; } ``` -------------------------------- ### Encoding Functions Source: https://github.com/tplgy/cppcodec/blob/master/README.md Provides methods to encode binary data into a string representation. Supports convenient string returns, templated result types, and direct buffer manipulation. ```APIDOC ## Encoding Encode binary data into an encoded (base64/base32/hex) string. Won't throw by itself, but the result type might throw on `.resize()`. ### Convenient Versions (returns std::string or templated Result) ```C++ std::string ::encode(const [uint8_t|char]* binary, size_t binary_size); std::string ::encode(const T& binary); Result ::encode(const [uint8_t|char]* binary, size_t binary_size); Result ::encode(const T& binary); ``` ### Reused Result Container Version Resizes `encoded_result` before writing to it. ```C++ void ::encode(Result& encoded_result, const [uint8_t|char]* binary, size_t binary_size); void ::encode(Result& encoded_result, const T& binary); ``` ### Pre-allocated Memory Version Encodes binary data into pre-allocated memory. Returns the byte size of the encoded string excluding null termination. Writes a null termination character if buffer size is sufficient. Calls `abort()` if `encoded_buffer_size` is insufficient. ```C++ size_t ::encode(char* encoded_result, size_t encoded_buffer_size, const [uint8_t|char]* binary, size_t binary_size) noexcept; size_t ::encode(char* encoded_result, size_t encoded_buffer_size, const T& binary) noexcept; ``` ### Calculate Encoded Size Calculates the exact length of the encoded string based on binary size, excluding null termination but including padding. ```C++ size_t ::encoded_size(size_t binary_size) noexcept; ``` ``` -------------------------------- ### Build Base64 Decoder Executable Source: https://github.com/tplgy/cppcodec/blob/master/tool/CMakeLists.txt Defines a build target for the base64 decoder executable. It compiles the 'base64dec.cpp' source file and links it with the 'cppcodec' library. ```cmake add_executable(base64dec base64dec.cpp) target_link_libraries(base64dec cppcodec) ``` -------------------------------- ### Build Base64 Encoder Executable Source: https://github.com/tplgy/cppcodec/blob/master/tool/CMakeLists.txt Defines a build target for the base64 encoder executable. It compiles the 'base64enc.cpp' source file and links it with the 'cppcodec' library. ```cmake add_executable(base64enc base64enc.cpp) target_link_libraries(base64enc cppcodec) ``` -------------------------------- ### Encode/Decode with Base32 Crockford Source: https://context7.com/tplgy/cppcodec/llms.txt Demonstrates encoding strings and byte vectors to Base32 Crockford format and decoding them back. This codec is case-insensitive, ignores hyphens, and is forgiving of visually similar characters (I/L->1, O->0). ```cpp #include #include int main() { using base32 = cppcodec::base32_crockford; // Encode std::string encoded = base32::encode(std::string("Hello World")); std::cout << encoded << "\n"; // "91JPRV3F41BPYWKCCG" // No padding characters in output std::cout << base32::encode(std::string("foo")) << "\n"; // "CSQPY" // Decode: case-insensitive, ignores hyphens std::vector decoded = base32::decode("91JPR-V3F4-1BPYW-KCCG"); // hyphens ignored std::cout << std::string(decoded.begin(), decoded.end()) << "\n"; // "Hello World" // Forgiving of visually similar characters: I->1, O->0, L->1 std::vector dec2 = base32::decode("9IJPRV3F4IBPYWKCCG"); // I decoded as 1 std::cout << std::string(dec2.begin(), dec2.end()) << "\n"; // "Hello World" // Combine with other codecs std::vector bin = {0x01, 0x02, 0x03, 0x04}; std::cout << base32::encode(bin) << "\n"; // "041061G0" return 0; } ``` -------------------------------- ### Common Codec API Source: https://github.com/tplgy/cppcodec/blob/master/README.md All codecs in cppcodec expose a consistent API. Users can interact with codecs using default aliases like `base64`, `base32`, `hex`, or fully qualified namespaces such as `cppcodec::base64_rfc4648` or `cppcodec::base32_crockford`. The template parameters `T` and `Result` support types like `std::vector` and `std::string`, provided they meet specific interface requirements. ```APIDOC ## Common Codec API All codecs expose the same API. In the below documentation, replace `` with a default alias such as `base64`, `base32` or `hex`, or with the full namespace such as `cppcodec::base64_rfc4648` or `cppcodec::base32_crockford`. For templated parameters `T` and `Result`, you can use e.g. `std::vector`, `std::string` or anything that supports: * `.data()` and `.size()` for `T` (read-only) template parameters, * for `Result` template parameters, also `.reserve(size_t)`, `.resize(size_t)` and `.push_back([uint8_t|char])`. It's possible to support types lacking these functions, consult the code directly if you need this. ``` -------------------------------- ### Build Hex Decoder Executable Source: https://github.com/tplgy/cppcodec/blob/master/tool/CMakeLists.txt Defines a build target for the hexadecimal decoder executable. It compiles the 'hexdec.cpp' source file and links it with the 'cppcodec' library. ```cmake add_executable(hexdec hexdec.cpp) target_link_libraries(hexdec cppcodec) ``` -------------------------------- ### Build Hex Encoder Executable Source: https://github.com/tplgy/cppcodec/blob/master/tool/CMakeLists.txt Defines a build target for the hexadecimal encoder executable. It compiles the 'hexenc.cpp' source file and links it with the 'cppcodec' library. ```cmake add_executable(hexenc hexenc.cpp) target_link_libraries(hexenc cppcodec) ``` -------------------------------- ### cppcodec::base64_url Source: https://context7.com/tplgy/cppcodec/llms.txt URL-Safe Base64 encoding and decoding. Replaces '+' with '-' and '/' with '_', making the output safe for URLs and filenames. Padding with '=' is required. ```APIDOC ## cppcodec::base64_url ### Description URL-Safe Base64 (RFC 4648). Same as `base64_rfc4648` but replaces `+` with `-` and `/` with `_`, making the output safe for use in URLs and filenames. Padding with `=` is required. ### Methods - `encode(const std::string&)`: Encodes a string to URL-safe Base64. - `encode(const std::vector&)`: Encodes a byte vector to URL-safe Base64. - `decode(const std::string&)`: Decodes a URL-safe Base64 string to a byte vector. Requires valid padding. ### Example Usage ```cpp #include #include int main() { using base64url = cppcodec::base64_url; std::string encoded = base64url::encode(std::string("any carnal pleasure")); std::cout << encoded << "\n"; // "YW55IGNhcm5hbCBwbGVhc3VyZQ==" std::vector binary = {0xFB, 0xFF, 0xFE}; std::string url_safe = base64url::encode(binary); std::cout << url_safe << "\n"; // "- __-" std::vector decoded = base64url::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); std::cout << std::string(decoded.begin(), decoded.end()) << "\n"; // "any carnal pleasure" try { base64url::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ"); // missing '==' } catch (const cppcodec::padding_error& e) { std::cerr << "Padding error: " << e.what() << "\n"; } return 0; } ``` ``` -------------------------------- ### Encode and Decode Standard Base32 (RFC 4648) Source: https://context7.com/tplgy/cppcodec/llms.txt Use `base32_rfc4648` for standard Base32 encoding. It uses the alphabet A-Z and digits 2-7, with '=' padding. Decoding is case-insensitive. ```cpp #include #include int main() { using base32 = cppcodec::base32_rfc4648; // Encode std::string encoded = base32::encode(std::string("Hello World")); std::cout << encoded << "\n"; // "JBSWY3DPEBLW64TMMQ======" // Decode std::vector decoded = base32::decode("JBSWY3DPEBLW64TMMQ======"); std::cout << std::string(decoded.begin(), decoded.end()) << "\n"; // "Hello World" // Decode to std::string directly std::string decoded_str = base32::decode("MFRA===="); std::cout << decoded_str << "\n"; // "a" // Case-insensitive decoding (lowercase accepted) std::vector dec = base32::decode("jbswy3dpeblw64tmmq======"); std::cout << std::string(dec.begin(), dec.end()) << "\n"; // "Hello World" // Size helpers std::cout << base32::encoded_size(5) << "\n"; // 8 std::cout << base32::decoded_max_size(8) << "\n"; // 5 return 0; } ``` -------------------------------- ### Build Base32 Decoder Executable Source: https://github.com/tplgy/cppcodec/blob/master/tool/CMakeLists.txt Defines a build target for the base32 decoder executable. It compiles the 'base32dec.cpp' source file and links it with the 'cppcodec' library. ```cmake add_executable(base32dec base32dec.cpp) target_link_libraries(base32dec cppcodec) ``` -------------------------------- ### Build Base32 Encoder Executable Source: https://github.com/tplgy/cppcodec/blob/master/tool/CMakeLists.txt Defines a build target for the base32 encoder executable. It compiles the 'base32enc.cpp' source file and links it with the 'cppcodec' library. ```cmake add_executable(base32enc base32enc.cpp) target_link_libraries(base32enc cppcodec) ``` -------------------------------- ### Decoding Functions Source: https://github.com/tplgy/cppcodec/blob/master/README.md Provides methods to decode encoded strings back into binary data. Supports convenient vector returns, templated result types, and direct buffer manipulation. ```APIDOC ## Decoding Decode an encoded (base64/base32/hex) string into a binary buffer. Throws `cppcodec::parse_error` on invalid input. The result type might throw on `.resize()`. ### Convenient Versions (returns std::vector or templated Result) ```C++ std::vector ::decode(const char* encoded, size_t encoded_size); std::vector ::decode(const T& encoded); Result ::decode(const char* encoded, size_t encoded_size); Result ::decode(const T& encoded); ``` ### Reused Result Container Version Resizes `binary_result` before writing to it. ```C++ void ::decode(Result& binary_result, const char* encoded, size_t encoded_size); void ::decode(Result& binary_result, const T& encoded); ``` ### Pre-allocated Memory Version Decodes an encoded string into pre-allocated memory. Returns the byte size of the decoded binary data. Calls `abort()` if `binary_buffer_size` is insufficient. Throws `cppcodec::parse_error` on invalid input. ```C++ size_t ::decode([uint8_t|char]* binary_result, size_t binary_buffer_size, const char* encoded, size_t encoded_size); size_t ::decode([uint8_t|char]* binary_result, size_t binary_buffer_size, const T& encoded); ``` ### Calculate Decoded Max Size Calculates the maximum size of the decoded binary buffer based on the encoded string length. This accounts for potential padding or whitespace/line breaks allowed by the codec variant. ```C++ size_t ::decoded_max_size(size_t encoded_size) noexcept; ``` ``` -------------------------------- ### Add Compile Options Source: https://github.com/tplgy/cppcodec/blob/master/example/CMakeLists.txt Applies private compile options to the build targets. These options are specific to the internal implementation of the project. ```cmake add_compile_options(${CPPCODEC_PRIVATE_COMPILE_OPTIONS}) ``` -------------------------------- ### Calculate Encoded and Decoded Sizes with cppcodec Source: https://context7.com/tplgy/cppcodec/llms.txt Use `encoded_size()` and `decoded_max_size()` to compute buffer sizes at compile time or runtime without actual encoding/decoding. `encoded_size()` returns the exact encoded length, including padding. `decoded_max_size()` returns the maximum possible decoded binary size. ```cpp #include #include #include #include int main() { // base64: 3 binary bytes -> 4 encoded chars (always a multiple of 4) static_assert(cppcodec::base64_rfc4648::encoded_size(3) == 4, ""); static_assert(cppcodec::base64_rfc4648::encoded_size(4) == 8, ""); static_assert(cppcodec::base64_rfc4648::decoded_max_size(4) == 3, ""); // base32 crockford: 5 binary bytes -> 8 encoded chars (no padding) static_assert(cppcodec::base32_crockford::encoded_size(5) == 8, ""); static_assert(cppcodec::base32_crockford::encoded_size(1) == 2, ""); // hex: always 2 chars per byte static_assert(cppcodec::hex_upper::encoded_size(4) == 8, ""); static_assert(cppcodec::hex_upper::decoded_max_size(8) == 4, ""); // Runtime use: allocate a stack buffer of exact size size_t binary_len = 16; char stack_buf[cppcodec::base64_rfc4648::encoded_size(16) + 1]; // +1 null uint8_t dummy[16] = {}; size_t n = cppcodec::base64_rfc4648::encode(stack_buf, sizeof(stack_buf), dummy, binary_len); std::cout << "Encoded " << binary_len << " bytes -> " << n << " chars: " << stack_buf << "\n"; // "Encoded 16 bytes -> 24 chars: AAAAAAAAAAAAAAAAAAAAAA==" return 0; } ``` -------------------------------- ### Encode and Decode URL-Safe Base64 Without Padding Source: https://context7.com/tplgy/cppcodec/llms.txt Use `base64_url_unpadded` for compact formats like JWT. It omits '=' padding during encoding and accepts both padded and unpadded strings during decoding. ```cpp #include #include int main() { using base64u = cppcodec::base64_url_unpadded; // Encoding never appends '=' padding std::string encoded = base64u::encode(std::string("any carnal pleasure")); std::cout << encoded << "\n"; // "YW55IGNhcm5hbCBwbGVhc3VyZQ" (no trailing '==') // Decode accepts both padded and unpadded std::vector dec1 = base64u::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ"); std::vector dec2 = base64u::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); // dec1 == dec2 == "any carnal pleasure" // Useful for JWT header/payload segments std::string jwt_payload = R"({\"sub\":\"1234567890\",\"name\":\"John Doe\",\"iat\":1516239022})"; std::string token_segment = base64u::encode(jwt_payload); std::cout << token_segment << "\n"; // no padding, URL-safe return 0; } ``` -------------------------------- ### Encode Binary Data to Pre-allocated Memory Source: https://github.com/tplgy/cppcodec/blob/master/README.md Encode binary data directly into a pre-allocated buffer. Ensure the buffer size is sufficient; otherwise, the function calls abort(). Returns the size of the encoded data. ```C++ size_t ::encode(char* encoded_result, size_t encoded_buffer_size, const [uint8_t|char]* binary, size_t binary_size) noexcept; size_t ::encode(char* encoded_result, size_t encoded_buffer_size, const T& binary) noexcept; ``` -------------------------------- ### decode() - All Output Overloads Source: https://context7.com/tplgy/cppcodec/llms.txt The `decode()` function offers symmetric overloads to `encode()`. Convenient versions return a `std::vector` or a templated result type. The raw-pointer version writes into pre-allocated memory and returns the actual decoded byte count. All decode variants throw `parse_error` on invalid input. ```APIDOC ## decode() - All Output Overloads Every codec provides symmetric `decode()` overloads. The convenient versions return a `std::vector` or templated result. The raw-pointer version writes into pre-allocated memory and returns the actual decoded byte count (which may be less than `decoded_max_size()` for padded codecs). ### Usage Examples: 1. **Return std::vector (most convenient):** ```cpp std::vector v = base64::decode(encoded); ``` 2. **Return a specific type:** ```cpp std::string s = base64::decode(encoded); ``` 3. **Reuse an existing result container:** ```cpp std::vector reused; base64::decode(reused, encoded); ``` 4. **Pre-allocated raw buffer:** ```cpp size_t max_size = base64::decoded_max_size(encoded.size()); std::vector buf(max_size); size_t actual = base64::decode(buf.data(), buf.size(), encoded); buf.resize(actual); // trim to actual decoded size ``` ### Error Handling: All decode variants throw `parse_error` on invalid input. ```cpp try { base64::decode("SGVs!G8="); // '!' is not in the base64 alphabet } catch (const cppcodec::symbol_error& e) { std::cerr << "Bad symbol: " << e.what() << "\n"; std::cerr << "Offending char code: " << static_cast(e.symbol()) << "\n"; } ``` ``` -------------------------------- ### Custom Result Type for Appending to std::string Source: https://context7.com/tplgy/cppcodec/llms.txt Demonstrates how to create a custom result type that appends encoded output directly to an existing std::string. This requires specializing `init` and `finish` in the `cppcodec::data` namespace and implementing `push_back(char)` and `size()` methods. ```cpp #include #include #include #include // A wrapper that appends encoded output to an existing std::string class string_append_wrapper { public: string_append_wrapper(std::string& backing) : m_backing(backing), m_offset(0), m_orig_size(0) {} void init(size_t capacity) { m_orig_size = m_backing.size(); m_offset = m_orig_size; m_backing.resize(m_orig_size + capacity); } void finish() { m_backing.resize(m_offset); } CPPCODEC_ALWAYS_INLINE void push_back(char c) { m_backing[m_offset++] = c; } CPPCODEC_ALWAYS_INLINE size_t size() const { return m_offset - m_orig_size; } private: std::string& m_backing; size_t m_offset; size_t m_orig_size; }; // Specializations must be declared in cppcodec::data namespace namespace cppcodec { namespace data { template <> inline void init( string_append_wrapper& result, empty_result_state&, size_t capacity) { result.init(capacity); } template <> inline void finish( string_append_wrapper& result, empty_result_state&) { result.finish(); } } } int main() { using base64 = cppcodec::base64_rfc4648; std::string output = "Encoded: "; string_append_wrapper appender(output); base64::encode(appender, std::string("any carnal pleasure")); std::cout << output << "\n"; // "Encoded: YW55IGNhcm5hbCBwbGVhc3VyZQ==" return 0; } ``` -------------------------------- ### Encode Binary Data to String Source: https://github.com/tplgy/cppcodec/blob/master/README.md Use these convenient versions to encode binary data into an std::string or a templated result type. They handle memory management internally. ```C++ std::string ::encode(const [uint8_t|char]* binary, size_t binary_size); std::string ::encode(const T& binary); // Convenient version with templated result type. Result ::encode(const [uint8_t|char]* binary, size_t binary_size); Result ::encode(const T& binary); ``` -------------------------------- ### cppcodec::base64_url_unpadded Source: https://context7.com/tplgy/cppcodec/llms.txt URL-Safe Base64 encoding and decoding without padding. Produces no '=' padding when encoding and accepts both padded and unpadded strings when decoding. Commonly used in JWT tokens. ```APIDOC ## cppcodec::base64_url_unpadded ### Description URL-Safe Base64 Without Padding. Identical to `base64_url` but produces no `=` padding when encoding, and accepts both padded and unpadded strings when decoding. Commonly used in JWT tokens and similar compact formats. ### Methods - `encode(const std::string&)`: Encodes a string to URL-safe Base64 without padding. - `decode(const std::string&)`: Decodes a URL-safe Base64 string (padded or unpadded) to a byte vector. ### Example Usage ```cpp #include #include int main() { using base64u = cppcodec::base64_url_unpadded; std::string encoded = base64u::encode(std::string("any carnal pleasure")); std::cout << encoded << "\n"; // "YW55IGNhcm5hbCBwbGVhc3VyZQ" std::vector dec1 = base64u::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ"); std::vector dec2 = base64u::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); // dec1 == dec2 std::string jwt_payload = R"({\"sub\":\"1234567890\",\"name\":\"John Doe\",\"iat\":1516239022})"; std::string token_segment = base64u::encode(jwt_payload); std::cout << token_segment << "\n"; // no padding, URL-safe return 0; } ``` ``` -------------------------------- ### Handle Decoding Errors with cppcodec::parse_error Source: https://context7.com/tplgy/cppcodec/llms.txt All decoding failures throw exceptions derived from `cppcodec::parse_error`. Sub-types like `symbol_error`, `invalid_input_length`, and `padding_error` allow distinguishing specific failure modes. Ensure necessary headers like `` are included. ```cpp #include #include #include #include void try_decode(const std::string& input) { using base64 = cppcodec::base64_rfc4648; try { auto result = base64::decode(input); std::cout << "OK: " << result.size() << " bytes\n"; } catch (const cppcodec::padding_error& e) { // Missing or wrong number of '=' padding characters std::cerr << "[padding_error] " << e.what() << "\n"; } catch (const cppcodec::symbol_error& e) { // A character was found that is not in the codec's alphabet std::cerr << "[symbol_error] char=" << e.symbol() << " code=" << static_cast(e.symbol()) << " - " << e.what() << "\n"; } catch (const cppcodec::invalid_input_length& e) { // Input length is not valid for the codec (e.g. 1 symbol in a base64 block) std::cerr << "[invalid_input_length] " << e.what() << "\n"; } catch (const cppcodec::parse_error& e) { // Catch-all for any other decode error std::cerr << "[parse_error] " << e.what() << "\n"; } } int main() { try_decode("SGVsbG8="); // OK: 5 bytes try_decode("SGVsbG8"); // [padding_error] ... try_decode("SGVs!G8="); // [symbol_error] char=! code=33 ... try_decode("A"); // [invalid_input_length] found 1, expected 2 or 3 return 0; } ``` -------------------------------- ### Calculate Encoded Size Source: https://github.com/tplgy/cppcodec/blob/master/README.md Calculate the exact byte length required for the encoded string, including padding, based on the original binary data size. This function is noexcept. ```C++ size_t ::encoded_size(size_t binary_size) noexcept; ```