/** * The Mojibake library * * This file is distributed under the MIT License. See LICENSE for details. */ #include #include #include "../build-amalgamation/mojibake.h" void print_string(const char *input, size_t length); // This is a simple C example of how to use the Mojibake library. // Run `make` from the examples directory to compile it. // ./build/example to run it. int main(int argc, char *const argv[]) { const char *input = "Cafe\xCC\x81"; size_t length = strlen(input); mjb_result result; // Normalize example: in NFC e + ◌́ -> é (U+00E9) mjb_text input_text = mjb_text_utf8(input, length); if(mjb_normalize(&input_text, MJB_MALFORMED_STOP, MJB_NORMALIZATION_NFC, MJB_ENC_UTF_8, &result, NULL) != MJB_STATUS_OK) { return 1; } // Cafe + ◌́ (U+0301, COMBINING ACUTE ACCENT) -> Café print_string(input, length); // Caf + é (U+00E9, LATIN SMALL LETTER E WITH ACUTE) -> Café print_string(result.output, result.output_size); const char *mojibake = "文字化け"; length = strlen(mojibake); // Codepoint count example: mjb_codepoint_count counts Unicode codepoints, not bytes. size_t codepoint_count = 0; mjb_text text = mjb_text_utf8(mojibake, length); if(mjb_codepoint_count(&text, MJB_MALFORMED_STOP, &codepoint_count, NULL) != MJB_STATUS_OK) { return 1; } printf("\"%s\" encoded in UTF-8 is %zu bytes long, and %zu codepoints long\n", mojibake, length, codepoint_count); mjb_result_free(&result); const char *case_input = "Straße"; // NFKC casefold example: in NFKC casefold, ß -> ss mjb_text case_text = mjb_text_utf8(case_input, strlen(case_input)); if(mjb_nfkc_casefold(&case_text, MJB_MALFORMED_STOP, MJB_ENC_UTF_8, &result, NULL) != MJB_STATUS_OK) { return 1; } printf("%s -> %.*s\n", case_input, (int)result.output_size, result.output); mjb_result_free(&result); return 0; } void print_string(const char *input, size_t length) { for(size_t i = 0; i < length; ++i) { unsigned char byte = (unsigned char)input[i]; if(byte >= 0x21 && byte <= 0x7E) { printf("%c", byte); } else { printf("<%02X>", byte); } } printf("\n"); }