Mojibake library v0.8, added Rust and Elixir support – Defeating AIs with a screwdriver

6 min read Original article ↗

Mojibake library v0.8 is out, and I’ve stabilized the C/C++/WASM API, which won’t change going forward. Rust and Elixir support are now mature and usable.

Why add a new Unicode library for Rust and Elixir (and C++) when they already have very good Unicode support? A summary:

Unicode featureC++ (mjb::)Rust (mojibake-rs)Elixir (Mojibake)
UTF-8/16/32 validation and conversion, with malformed-input policies and byte offsets✚ (<codecvt> was deprecated in C++17 and removed in C++26)◐ std has UTF-8 and UTF-16 but no UTF-32, BOM detection, or skip/stop policies◐ :unicode converts, but has no detection and no stop/replace/skip choice
Normalization NFC/NFD/NFKC/NFKD (UAX #15)✚✚— String.normalize/2 already does these
NFKC_Casefold, quick check, is_normalized✚✚✚
Full upper/lowercase✚ (toupper only maps one unit at a time)——
Titlecase✚✚◐ (String.capitalize only changes the first grapheme)
Casing for any BCP 47 locale (tr, az, lt, …)✚✚◐ (only :turkic and :greek)
Case folding, full and simple✚✚◐ (:string.casefold gives full folding only)
Caseless matching (D144–D147)✚✚✚
Grapheme clusters (UAX #29)✚✚◐ graphemes exist. Mojibake adds counts and prefixes
Word and sentence segmentation (UAX #29)✚✚✚
Line breaking (UAX #14)✚✚✚
Bidirectional algorithm (UAX #9)✚✚— not wrapped yet
Terminal / East Asian width (UAX #11), truncate to width◐ (C++23 std::format only estimates width)✚✚
Character names✚✚✚
General category, scripts, Script_Extensions, blocks, planes✚✚✚
Combining class, bidi class, decomposition type, numeric values✚✚ (Rust has is_numeric but no values)✚
Any binary or enumerated UCD property✚◐ (Rust has a few predicates such as is_alphabetic and is_whitespace)✚
Emoji properties and sequences, RGI (UTS #51)✚✚✚
Hangul composition, decomposition and syllable names✚✚✚
Collation and sort keys (UTS #10, DUCET)✚ (std::collate depends on the platform locale and isn’t UCA)✚✚
IDNA to_ascii / to_unicode (UTS #46, Punycode)✚✚✚
Confusables, skeletons, mixed scripts (UTS #39)✚✚✚ (Elixir’s compiler checks these internally, but there’s no public API)
Identifiers, XID_Start/Continue (UAX #31)✚✚✚ (internal to the tokenizer, not public)
Strict BCP 47 language-tag parsing✚ (std::locale names depend on the platform)✚✚
Text filters (normalize, collapse spaces, …)✚✚— not wrapped

What I needed to do to support C++, WASM Rust, and Elixir

The best thing about C is that it is “easy” to call the exported functions from other languages/frameworks. That’s why I decided to add support for multiple languages. Let’s see what these frameworks/languages provide.

C++

C++ is an extension of C, but C is NOT a subset of C++. Most ordinary C code can be compiled as C++, but Mojibake wasn’t very easy. C++ doesn’t like out-of-place pointers, implicit conversions, designated initializers, or implicit function declarations (among other things).

I was lucky because months (years?) ago I added a make test-cpp to the Makefile that tried to compile the project in C++. That helped me fix a long list of warnings/errors.

What was unusable was the Attractor library that was using the _Generic C11 feature. I needed to add a C++-specific function, which wasn’t ideal, but I was forced to. I’ve created a C++-specific assertion.

This was interesting because it helped me keep up with the latest C++ additions.

  1. std::is_enum_v
  2. std::is_signed_v
  3. std::att_is_wide_integer
  4. std::is_same_v
  5. And so on.

The C++ wrapper is very simple. An example of normalization:

The mjb::nfc, or mjb::normalize functions call the mjb_normalize_into C function. Check the README.md for the C++ API.

WASM

Compiling the project with Emscripten was also very easy; it compiled with just a few fixes here and there, and it also provides a __EMSCRIPTEN__ macro to detect if you are working with WASM.

What the Mojibake module needed was only to locate the compiled mojibake.wasm WASM file. In a WASM Emscripten-generated module, you can call C functions in multiple ways. Let’s imagine a function that adds two integers called add().

From JavaScript:

This wasn’t enough for me because I had a big API, and it was creating a lot of noise. Fortunately, Emscripten lets you “export” the functions you want. See the EXPORTED_FUNCTIONS in the CMakeLists.txt file and the MojibakeWasmModule, automatically generated with all the exported functions. This lets you do this; for example, with the mjb_is_rgi_emoji:

The JavaScript code calls the _mjb_is_rgi_emoji function. It has an underscore before the name so it doesn’t pollute the Emscripten namespace.

Important thing to consider when you use it with WASM. JavaScript uses UTF-16 by default for strings. Be sure to pass UTF_16 in the options, or if you want to use UTF-8, JavaScript provides a TextEncoder.encode() API. But usually it is not a good idea. Mojibake support UTF-8, UTF-16 and UTF-32.

So, a little summary:

Another thing I needed to change is the mjb_for_each_codepoint function. That’s a function that calls a callback for every codepoint of a string.

You can’t pass a JavaScript function to a C function, or better, you can call JavaScript code from C/C++, but it was too slow. That’s why I’ve added a _mjbForEachCodepointCallback function.

From C:

From JavaScript:

Probably not the best solution, but enough for us.

Rust

Rust also lets you call C functions with ease. It’s called the FFI (Foreign Function Interface). I chose to have a low-level “sys” library with raw FFI bindings and another “safe” one.

Important things:

  1. The shim is a C file used to add some test helpers
  2. &src is a list of all C files
  3. MSVC uses /something kind of CLI arguments. I needed it to use C11
  4. Mojibake lets you strip away part of the library. Example: MJB_FEATURE_CHARACTER_NAMES

After this, we declare an FFI binding:

In the safe library, we declare instead a Rust function that calls it:

And to use that:

And that’s it, very simple. The only tedious thing is that I needed to recreate all the C enums and function declarations. Fortunately, a lot of files are automatically generated, such as src/rust/mojibake-sys/src/functions.rs.

Elixir

I’ve been studying Erlang and Elixir lately, which is why I’ve added Mojibake to it. Elixir has the best Unicode support I’ve seen, but it was missing something, not very important for Unicode support but interesting enough.

Elixir and Erlang have what are called NIFs (Native Implemented Functions). The NIFs of a module are compiled and linked into a dynamic loadable shared library (.so on Linux, .dll on Windows). To compile the Elixir package, you need a C compiler. Fortunately, Elixir lets you use precompiled libraries, and I have a GitHub job that does this so users can simply import and use them.

mix.exs adds :elixir_make to the project’s compilers, so mix compile runs a small Makefile. The Makefile compiles each library file plus the binding, c_src/mojibake_nif.c, as C11 against erl_nif.h and links them to mojibake_nif.so.

The Mojibake.Nif module then:

The load callback runs once; it creates the atoms that the binding returns. A very important thing is that Elixir uses the custom allocators Mojibake let you use:

This lets us use the enif_alloc function. This way, every allocation the library makes goes through the BEAM’s memory allocator.

Now we see an example of a NIF function declaration:

All the mjb_nif_something functions you see are utilities that call enif_get_atom to create a Mojibake argument. Example:

Now we can call quick_check/2 this way:

Using C from Elixir was much easier than I thought. I just needed to generate a list of all the functions and the enums (see src/elixir/lib/mojibake/unicode_data.ex).