Writing A Handler

When put together, it can generally look like this:

 1#include <ztd/text/encode.hpp>
 2#include <ztd/text/encoding.hpp>
 3
 4#include <iostream>
 5
 6using ascii_encode_result = ztd::text::encode_result<
 7     // input range type
 8     ztd::span<const char32_t>,
 9     // output range type; figured out from function call
10     ztd::span<char>,
11     // the state type for encode operations
12     ztd::text::encode_state_t<ztd::text::ascii_t>>;
13
14ascii_encode_result my_printing_handler(const ztd::text::ascii_t& encoding,
15     ascii_encode_result result, ztd::span<const char32_t> unused_read_characters,
16     ztd::span<const char> unused_write_characters) noexcept {
17	(void)encoding;
18	// just printing some information
19	std::cout << "An error occurred.\n"
20	          << "\tError code value: " << ztd::text::to_name(result.error_code)
21	          << "\n"
22	          << "\t# of code unit spaces left: " << result.output.size() << "\n"
23	          << "\t# of unused code points: " << unused_read_characters.size()
24	          << "\n"
25	          << "\n"
26	          << "\t# of unused code units: " << unused_write_characters.size()
27	          << "\n"
28	          << "\tInput units left: " << result.input.size() << "\n";
29	// setting the error to "ok"
30	// tells the algorithm to keep spinning,
31	// even if nothing gets written to the output
32	result.error_code = ztd::text::encoding_error::ok;
33	return result;
34}
35
36int main(int, char*[]) {
37	std::string my_ascii_string = ztd::text::encode(
38	     // input
39	     U"안녕",
40	     // to this encoding
41	     ztd::text::ascii,
42	     // handled with our function
43	     &my_printing_handler);
44
45	ZTD_TEXT_ASSERT(my_ascii_string == "");
46
47	return 0;
48}

The result in my_ascii_string should be an empty string: nothing should have succeeded and therefore the function will just return an empty string. The print out will look like this:

An error occurred.
        Error code value: invalid_sequence
        # of unused characters: 1
        Input units left: 1
An error occurred.
        Error code value: invalid_sequence
        # of unused characters: 1
        Input units left: 0

If you would like the higher-level called function to return more information to you, use the lower level encode_to/encode_into_raw, decode_to/decode_into_raw, transcode_to/transcode_into_raw.

If you need to do more, you can change from concrete types to templates, and work at increasingly higher levels of genericity in order to have the printing handler do more and more.