localize.zig
localize.zig

karlseguin/localize.zig

MIT

ICU Message Parser and Renderer

5 5 0 0
4
build.zig.zon  build.zig 
View on Github  
Updated: 1:05:59 PM Wed Nov 20 2024 Size: 21KB Created: 4:33:38 AM Wed Nov 13 2024
Dependencies:
No known dependencies
zig  fetch  --save  git+https://github.com/karlseguin/localize.zig

ICU Message Format for Zig

Very basic support for parsing and rendering ICU message formats.

Install

  1. Add localize.zig as a dependency in your build.zig.zon:
zig fetch --save git+https://github.com/karlseguin/localize.zig#master
  1. In your build.zig, add the localize module as a dependency you your program:
const localize = b.dependency("localize", .{
    .target = target,
    .optimize = optimize,
});

// the executable from your call to b.addExecutable(...)
exe.root_module.addImport("localize", localize.module("localize"));

Usage

First, create a Resource:

const locales: []const []const u8 = &.{"en-US", "fr-FR"}
var resource = try localize.Resource.init(allocator, locales);
defer resource.deinit();

This will likely be a long-lived object. The locales can be freed after init returns (init clones the values).

Next, create a parser for each locale and add messages:

var parser = try resource.parser("en-US", .{});
defer parser.deinit();

// loop over entries in a file, or something
// localize.zig currently doesn't "read" files

try parser.add("string_len_min", \\ must be at least {min}
    \\ {min, plural,
    \\  =1 {character}
    \\  other {characters}
    \\  }
    \\ long
);

Once all messages have been loaded, you can use resource.write to write a localized message:

try resource.write(writer, "en-US", "string_len_min", .{.min = 6});

The write method is thread-safe.

In cases where you'll be generating multiple message for a single locale, you can first get a Locale and then use its thread-safe write:</

// you very likely have logic in your code that makes it so that
// this could never return null
var locale = resource.getLocale("en-US") orelse unreachable;

locale.write("string_len_min", .{.min = 6});

Limited Functionality

Currently, this only supports:

  • variables
  • plural
    • =0 or zero
    • =1 or one
    • other