gd_gettext ========== .. rust:crate:: gd_gettext :synopsis: GNU gettext message catalogs: reading and writing PO/POT text, reading and writing compiled MO files (both byte orders), Plural-Forms expressions, msgmerge-style updates with fuzzy matching, and translation statistics. GNU gettext message catalogs: reading and writing PO/POT text, reading and writing compiled MO files (both byte orders), Plural-Forms expressions, msgmerge-style updates with fuzzy matching, and translation statistics. State is explicit: a :rust:struct:`Catalog ` or a :rust:struct:`Translator ` instead of the C library's process-wide domain table. Nothing panics on bad input; every failure is an :rust:struct:`Error ` whose ``Display`` is an Elm-style report with a hint. .. code-block:: rust use gd_gettext::Lookup; let cat = gd_gettext::parse_po("msgid \"Hello\"\nmsgstr \"Hallo\"\n", "de.po")?; assert_eq!(cat.text("Hello"), "Hallo"); assert_eq!(cat.plural("%d file", "%d files", 3), "%d files"); Reading, merging, and writing cost what the input is long, never its square: a PO field continued over many lines is gathered once; an MO file whose strings share bytes is refused as damaged; the fuzzy search is bounded by :rust:const:`FUZZY_WORK_PER_BYTE `; and wrapping a long line looks only at the next piece. .. rubric:: Structs .. rust:struct:: pub struct Catalog One message catalog: a PO, POT, or MO file's messages. The catalog owns everything it holds. Lookups (the :rust:trait:`crate::Lookup ` trait) use an index built on first use; :rust:fn:`Catalog::add_message `, :rust:fn:`Catalog::set_header_field ` and :rust:fn:`crate::sort_by_reference ` drop it. After editing ``messages`` or ``header`` directly, call :rust:fn:`Catalog::build_index ` before the next lookup. .. rubric:: Fields .. rust:field:: pub name: String The file name, or the name given to a parser. .. rust:field:: pub header: Option The msgid "" entry; its ``strs[0]`` holds the header fields. .. rust:field:: pub messages: Vec The messages in file order; obsolete ones included. .. rust:field:: pub plural: PluralRule The compiled Plural-Forms rule; ``n != 1`` without a header. .. rust:field:: pub allow_fuzzy: bool Look fuzzy translations up too (Sphinx's ``gettext_allow_fuzzy_translations``). .. rubric:: Implementations .. rust:impl:: impl Catalog :noindex: :for: Catalog .. rust:method:: pub fn new(name: &str) -> Catalog Returns an empty catalog named ``name`` with the germanic plural rule (``n != 1``). .. rust:method:: pub fn add_message(&mut self, m: Message) -> &mut Message Appends a message, which the catalog owns from now on, and returns a reference to it. The lookup index is rebuilt on the next lookup. .. rust:method:: pub fn message_count(&self) -> usize Returns the number of messages, obsolete ones included, without the header. .. rust:method:: pub fn header_field(&self, name: &str) -> Option<&str> Returns the value of a header field (``"Name: value"`` line), compared case-insensitively, borrowed from the header. .. rust:method:: pub fn set_header_field(&mut self, name: &str, value: &str) Replaces a header field, or appends it, keeping the others in order. Setting ``Plural-Forms`` to a valid rule also replaces :rust:field:`Catalog::plural `. .. rust:method:: pub fn charset(&self) -> &str Returns the charset the header's Content-Type names, or ``""`` without one. .. rust:impl:: impl Catalog :noindex: :for: Catalog .. rust:method:: pub fn build_index(&mut self) (Re)builds the lookup index now, so the first lookup does not pay for it. Call it after editing ``messages`` or ``header`` directly. .. rust:method:: pub fn pool(&self) -> &str Returns the text every translation of the catalog is a slice of, so a caller can register it once as a source and give parsed translations exact spans. .. rubric:: Trait Implementations .. rust:impl:: impl Default for Catalog :noindex: :for: Catalog :trait: Default .. rust:method:: fn default() -> Catalog :noindex: .. rust:impl:: impl From<&MoCatalog> for Catalog :noindex: :for: Catalog :trait: From<&MoCatalog> .. rust:method:: fn from(mo: &MoCatalog) -> Catalog :noindex: Copies a compiled catalog into an editable one. Its messages have no comments or references; the first entry with an empty key is the header. .. rust:impl:: impl Lookup for Catalog :noindex: :for: Catalog :trait: Lookup .. rust:method:: fn find(&self, id: &str, ctx: Option<&str>) -> Option> :noindex: Finds a message in the index. A fuzzy message is found only when ``allow_fuzzy`` is set; obsolete and untranslated messages are never found. .. rust:method:: fn plural_rule(&self) -> &PluralRule :noindex: .. rust:struct:: pub struct Message One catalog entry. ``strs`` holds the msgstr, or msgstr[0..n) of a plural message; an empty string is an untranslated form. .. rubric:: Fields .. rust:field:: pub ctx: Option The msgctxt; ``Some("")`` (msgctxt "") is a context too, different from none. .. rust:field:: pub id: String The msgid. .. rust:field:: pub id_plural: Option The msgid_plural of a plural message. .. rust:field:: pub strs: Vec The msgstr, or one string per plural form. .. rust:field:: pub comments: Vec ``#`` translator comments. .. rust:field:: pub notes: Vec ``#.`` comments for translators, from the extractor. .. rust:field:: pub references: Vec ``#:`` locations, ``file:line`` each. .. rust:field:: pub flags: Vec ``#,`` flags other than fuzzy, e.g. ``c-format``. .. rust:field:: pub fuzzy: bool The ``fuzzy`` flag. .. rust:field:: pub obsolete: bool ``#~``: kept for reuse, never looked up. .. rust:field:: pub previous: Option The ``#|`` previous msgid of a fuzzy message. .. rust:field:: pub line: usize The 1-based line the entry starts on in its file; 0 when built in code. .. rubric:: Implementations .. rust:impl:: impl Message :noindex: :for: Message .. rust:method:: pub fn new(id: &str) -> Message Returns a message with this msgid and one empty (untranslated) msgstr. .. rust:method:: pub fn is_translated(&self) -> bool Tells whether every form has a translation (and there is at least one). .. rust:method:: pub fn is_header(&self) -> bool Tells whether this is the header entry: msgid "" without a context, not obsolete. .. rust:method:: pub fn is_plural(&self) -> bool Tells whether the message has a msgid_plural. .. rust:method:: pub fn has_flag(&self, flag: &str) -> bool Tells whether the message carries a ``#,`` flag; ``"fuzzy"`` is :rust:field:`Message::fuzzy `. .. rust:method:: pub fn same_key(&self, other: &Message) -> bool Tells whether two messages have the same context and msgid. .. rust:struct:: pub struct Previous A fuzzy message's earlier msgctxt, msgid, and msgid_plural (the ``#|`` comments msgmerge writes), so a translator sees what changed. .. rubric:: Fields .. rust:field:: pub ctx: Option The previous msgctxt; ``Some("")`` is an empty context, different from none. .. rust:field:: pub id: String The previous msgid. .. rust:field:: pub id_plural: Option The previous msgid_plural. .. rust:struct:: pub struct Error A problem explained the way Elm's compiler explains one: where, what, and what to do. The error owns its strings, so it outlives the input it was made from. ``Display`` renders the report: .. code-block:: text -- PO SYNTAX ERROR ------------------------------------------------------ de.po:2 This string has no closing quote. 2| msgstr "b ^ Hint: End the string with " on the same line; continue on the next line with ... .. rubric:: Fields .. rust:field:: pub kind: ErrorKind What went wrong. .. rust:field:: pub file: String The file (or the name given to a parser); empty when there is none. .. rust:field:: pub line: usize The 1-based line of the problem; 0 when it has no line. .. rust:field:: pub column: usize The 1-based byte column of the problem in ``excerpt``; 0 for none. .. rust:field:: pub excerpt: String The offending line; empty for none. .. rust:field:: pub message: String A plain explanation. .. rust:field:: pub hint: String How to fix it. .. rubric:: Implementations .. rust:impl:: impl Error :noindex: :for: Error .. rust:method:: pub fn title(&self) -> &'static str Returns the report title, e.g. ``PO SYNTAX ERROR``. .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Display for Error :noindex: :for: Error :trait: fmt::Display .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:impl:: impl std::error::Error for Error :noindex: :for: Error :trait: std::error::Error .. rust:struct:: pub struct LoadOptions How catalogs are loaded. Fill it with struct-update syntax: ``LoadOptions { allow_fuzzy: true, ..LoadOptions::default() }``. .. rubric:: Fields .. rust:field:: pub max_bytes: u64 The largest file accepted, in bytes; 1 GiB by default. A larger file is refused with an error of kind :rust:variant:`ErrorKind::TooLarge ` before anything is read. .. rust:field:: pub allow_fuzzy: bool Look fuzzy translations up too (Sphinx's ``gettext_allow_fuzzy_translations``). .. rubric:: Trait Implementations .. rust:impl:: impl Default for LoadOptions :noindex: :for: LoadOptions :trait: Default .. rust:method:: fn default() -> LoadOptions :noindex: .. rust:struct:: pub struct Forms<'a> The translated forms of one message, borrowed from the catalog that found them. An editable :rust:struct:`crate::Catalog ` keeps each form apart in its pool; a zero-copy :rust:struct:`crate::MoCatalog ` keeps them as the MO file does, joined by NUL. Both look the same from here. .. rubric:: Implementations .. rust:impl:: impl<'a> Forms<'a> :noindex: :for: Forms<'a> .. rust:method:: pub fn len(&self) -> usize Returns the number of forms. .. rust:method:: pub fn is_empty(&self) -> bool Tells whether there are no forms. .. rust:method:: pub fn get(&self, k: usize) -> Option<&'a str> Returns form ``k`` (0 is the singular), borrowed from the catalog, if it exists. .. rust:method:: pub fn iter(&self) -> impl Iterator + 'a Iterates the forms in order. .. rust:struct:: pub struct MergeOptions How :rust:fn:`merge ` works. The default is msgmerge's: fuzzy matching on, obsolete messages kept. .. rubric:: Fields .. rust:field:: pub fuzzy_matching: bool Look for similar messages (msgmerge without ``-N``). .. rust:field:: pub keep_obsolete: bool Keep translated messages that left the template as ``#~``. .. rubric:: Trait Implementations .. rust:impl:: impl Default for MergeOptions :noindex: :for: MergeOptions :trait: Default .. rust:method:: fn default() -> MergeOptions :noindex: .. rust:struct:: pub struct MergeStats What a merge's fuzzy search did; :rust:fn:`merge_counted ` returns it. .. rubric:: Fields .. rust:field:: pub searches: usize msgids searched for (each distinct msgid once). .. rust:field:: pub bounds: usize Candidates whose byte counts were compared (the cheap bound). .. rust:field:: pub comparisons: usize Candidates compared in full (:rust:fn:`similarity `). .. rust:field:: pub work: usize Bytes those comparisons read. .. rust:field:: pub cut_short: usize Searches the work bound stopped before they had looked everywhere. .. rust:struct:: pub struct Stats Counts of a catalog's messages, as sphinx-intl stat reports them. .. rubric:: Fields .. rust:field:: pub translated: usize Translated and not fuzzy. .. rust:field:: pub fuzzy: usize Translated but fuzzy. .. rust:field:: pub untranslated: usize Missing a form. .. rust:field:: pub obsolete: usize Obsolete (``#~``). .. rubric:: Implementations .. rust:impl:: impl Stats :noindex: :for: Stats .. rust:method:: pub fn add(&mut self, m: &Message) Counts one message, as sphinx-intl stat does; the header does not count. With a :rust:struct:`crate::PoReader `, this counts a file without holding it. .. rust:struct:: pub struct MoCatalog A compiled catalog served from one text pool: the file's strings. It owns the pool (the file's buffer, reused), a span per string, and a copy of the hash table; lookups (:rust:trait:`Lookup `) borrow from the pool and allocate nothing. Make one with :rust:fn:`MoCatalog::load ` or :rust:fn:`MoCatalog::from_bytes `; for an editable catalog, use :rust:fn:`crate::parse_mo ` instead. .. rubric:: Implementations .. rust:impl:: impl MoCatalog :noindex: :for: MoCatalog .. rust:method:: pub fn load(path: impl AsRef, options: &LoadOptions) -> Result Reads and checks a compiled catalog. Fails when the file cannot be read, is larger than ``options.max_bytes``, or as :rust:fn:`MoCatalog::from_bytes ` fails. .. rust:method:: pub fn from_bytes(data: impl Into>, name: &str) -> Result Takes MO bytes and checks them once, so lookups need no checks. Fails with :rust:variant:`ErrorKind::MoFormat ` when the header, a table entry, or a string is truncated or out of bounds, when strings share bytes or keys repeat (no compiler writes either), or when a string is not UTF-8; with :rust:variant:`ErrorKind::Charset ` for a header naming another charset, and :rust:variant:`ErrorKind::Plural ` for a bad Plural-Forms. .. rust:method:: pub fn name(&self) -> &str Returns the file name, or the name given to :rust:fn:`MoCatalog::from_bytes `. .. rust:method:: pub fn entry_count(&self) -> usize Returns the number of entries, the header included. .. rust:method:: pub fn search(&self) -> &MoSearch Returns how lookups find keys. .. rust:method:: pub fn header(&self) -> Option<&str> Returns the header entry's text (the translation of ""), if there is one. .. rust:method:: pub fn header_field(&self, name: &str) -> Option<&str> Returns the value of a header field, compared case-insensitively. .. rust:method:: pub fn entries(&self) -> impl Iterator> + '_ Returns the entries in file order (sorted by key in a file msgfmt wrote). .. rubric:: Trait Implementations .. rust:impl:: impl Lookup for MoCatalog :noindex: :for: MoCatalog :trait: Lookup .. rust:method:: fn find(&self, id: &str, ctx: Option<&str>) -> Option> :noindex: .. rust:method:: fn plural_rule(&self) -> &PluralRule :noindex: .. rust:struct:: pub struct MoEntry<'a> One message of a :rust:struct:`MoCatalog `, borrowed from its buffer. .. rubric:: Fields .. rust:field:: pub ctx: Option<&'a str> The msgctxt, if any. .. rust:field:: pub id: &'a str The msgid. .. rust:field:: pub id_plural: Option<&'a str> The msgid_plural of a plural message. .. rust:field:: pub translation: &'a str The translation as stored: plural forms joined by NUL. .. rubric:: Implementations .. rust:impl:: impl<'a> MoEntry<'a> :noindex: :for: MoEntry<'a> .. rust:method:: pub fn forms(&self) -> Forms<'a> Returns the translated forms. .. rust:struct:: pub struct PluralProblem Where and why an expression was refused. .. rubric:: Fields .. rust:field:: pub message: &'static str What is wrong, in lower case without a full stop. .. rust:field:: pub column: usize The 1-based byte column in the expression. .. rust:struct:: pub struct PluralRule A compiled Plural-Forms header: ``nplurals`` and the plural expression. .. rubric:: Fields .. rust:field:: pub nplurals: usize The number of plural forms, 1 to :rust:const:`MAX_NPLURALS `. .. rubric:: Trait Implementations .. rust:impl:: impl Default for PluralRule :noindex: :for: PluralRule :trait: Default .. rust:method:: fn default() -> PluralRule :noindex: gettext's rule without a header: two forms, ``plural = n != 1``. .. rust:struct:: pub struct PoReader Reads PO or POT entries one at a time from any buffered source, so a large file need not be held whole. It is an iterator of ``Result``: the header entry first when the file has one (:rust:fn:`Message::is_header `), then the messages, obsolete ones included, in file order. After an error it yields nothing more. It keeps only the current entry and the keys seen so far (to report duplicates), plus one reused line buffer. .. code-block:: rust use gd_gettext::{PoReader, Stats}; let text = "msgid \"a\"\nmsgstr \"b\"\n\nmsgid \"c\"\nmsgstr \"\"\n"; let mut stats = Stats::default(); for message in PoReader::new(text.as_bytes(), "de.po") { stats.add(&message?); } assert_eq!((stats.translated, stats.untranslated), (1, 1)); .. rubric:: Implementations .. rust:impl:: impl PoReader :noindex: :for: PoReader .. rust:method:: pub fn new(source: R, name: &str) -> PoReader Returns a reader of ``source``; ``name`` labels errors. There is no size limit. .. rust:method:: pub fn plural_rule(&self) -> &PluralRule Returns the Plural-Forms rule of the header read so far (``n != 1`` before it). .. rust:impl:: impl PoReader> :noindex: :for: PoReader> .. rust:method:: pub fn open(path: impl AsRef, options: &LoadOptions) -> Result Opens a PO or POT file for reading entry by entry. Fails when it cannot be opened or is larger than ``options.max_bytes``; reading stops with the same error if it grows past the limit. .. rubric:: Trait Implementations .. rust:impl:: impl Iterator for PoReader :noindex: :for: PoReader :trait: Iterator .. rust:associatedtype:: type Item = Result :noindex: .. rust:method:: fn next(&mut self) -> Option :noindex: .. rust:struct:: pub struct WriteOptions How :rust:fn:`write_po ` lays a catalog out. The default wraps at 76 columns, as sphinx-intl (through Babel) does, and writes previous msgids and obsolete messages. .. rubric:: Fields .. rust:field:: pub width: usize Lines are wrapped to this many characters; 0: no wrapping. .. rust:field:: pub references: ReferenceStyle How locations are written. .. rust:field:: pub previous: bool Write ``#|`` previous msgids of fuzzy messages. .. rust:field:: pub obsolete: bool Write ``#~`` obsolete messages. .. rubric:: Trait Implementations .. rust:impl:: impl Default for WriteOptions :noindex: :for: WriteOptions :trait: Default .. rust:method:: fn default() -> WriteOptions :noindex: .. rust:struct:: pub struct BoundCatalog A catalog a translator serves for a domain. .. rubric:: Fields .. rust:field:: pub domain: String The text domain, e.g. ``guidedog`` or ``sphinx``. .. rust:field:: pub catalog: Box The catalog, owned by the translator: an editable :rust:struct:`crate::Catalog `, a zero-copy :rust:struct:`MoCatalog `, or anything else that implements :rust:trait:`Lookup `. .. rust:struct:: pub struct Translator Serves several text domains, each from a chain of catalogs: the first bound catalog that translates a message wins, as Sphinx searches ``locale_dirs`` in order before its own catalogs. It stands in for the C library's global state (bindtextdomain, textdomain, setlocale). .. rubric:: Fields .. rust:field:: pub language: String The language catalogs are looked for, e.g. ``pt_BR``. .. rust:field:: pub domain: String The current domain (textdomain); ``messages`` by default. .. rust:field:: pub bound: Vec The bound catalogs, in search order. .. rubric:: Implementations .. rust:impl:: impl Translator :noindex: :for: Translator .. rust:method:: pub fn new(language: &str) -> Translator Returns a translator for ``language`` with no catalogs bound, in the ``messages`` domain. .. rust:method:: pub fn add_catalog(&mut self, domain: &str, catalog: impl Lookup + Send + Sync + 'static) Binds a catalog to a domain after those already bound; the translator owns it. .. rust:method:: pub fn text_domain(&mut self, domain: &str) Sets the current domain, as textdomain does. .. rust:method:: pub fn bind_text_domain(&mut self, domain: &str, dir: &Path, options: &LoadOptions) -> Result Looks for ``dir//LC_MESSAGES/.po``, then ``.mo``, trying the language, then its base language (pt_BR, then pt), and binds the first catalog found: a ``.mo`` file as a zero-copy :rust:struct:`MoCatalog `, a ``.po`` file as an editable catalog. Returns ``Ok(false)`` when there is none; fails when the file found cannot be read or parsed, or is larger than ``options.max_bytes``. .. rust:method:: pub fn domain_text<'a>(&'a self, domain: &str, id: &'a str) -> &'a str dgettext: the translation of ``id`` in a domain, or ``id``. .. rust:method:: pub fn domain_with_context<'a>(&'a self, domain: &str, ctx: &str, id: &'a str) -> &'a str dpgettext: :rust:fn:`Translator::domain_text ` in context ``ctx``. .. rust:method:: pub fn domain_plural<'a>(&'a self, domain: &str, id: &'a str, id_plural: &'a str, n: u64) -> &'a str dngettext: the form for ``n`` in a domain, or the English singular or plural. .. rust:method:: pub fn domain_plural_with_context<'a>(&'a self, domain: &str, ctx: Option<&str>, id: &'a str, id_plural: &'a str, n: u64) -> &'a str dnpgettext: :rust:fn:`Translator::domain_plural ` with an optional context. .. rust:method:: pub fn text<'a>(&'a self, id: &'a str) -> &'a str gettext in the current domain. .. rust:method:: pub fn plural<'a>(&'a self, id: &'a str, id_plural: &'a str, n: u64) -> &'a str ngettext in the current domain. .. rust:method:: pub fn with_context<'a>(&'a self, ctx: &str, id: &'a str) -> &'a str pgettext in the current domain. .. rust:method:: pub fn plural_with_context<'a>(&'a self, ctx: &str, id: &'a str, id_plural: &'a str, n: u64) -> &'a str npgettext in the current domain. .. rubric:: Enums .. rust:enum:: pub enum ErrorKind What kind of problem an :rust:struct:`Error ` reports. .. rubric:: Variants .. rust:variant:: Syntax The PO text breaks the format. .. rust:variant:: Duplicate A message is defined twice. .. rust:variant:: Charset The catalog is not UTF-8. .. rust:variant:: Encoding Bytes that are not valid UTF-8. .. rust:variant:: Plural A Plural-Forms header that cannot be used. .. rust:variant:: MoFormat A truncated or inconsistent MO file. .. rust:variant:: Io The file could not be read or written. .. rust:variant:: Memory There was not enough memory to hold the catalog. .. rust:variant:: TooLarge The file is larger than :rust:field:`crate::LoadOptions::max_bytes `. .. rubric:: Implementations .. rust:impl:: impl ErrorKind :noindex: :for: ErrorKind .. rust:method:: pub fn title(self) -> &'static str Returns the report title of this kind, e.g. ``PO SYNTAX ERROR``. .. rust:enum:: pub enum MoSearch How a :rust:struct:`MoCatalog ` finds a key. .. rubric:: Variants .. rust:variant:: Hash { size: u32, probes: u32 } Through the file's hash table: one to a few probes. ``probes`` is the most any key of the file takes, so a lookup of a missing key stops there too. .. rust:field:: size: u32 The table's size (a prime). .. rust:field:: probes: u32 The most probes a key of the file takes. .. rust:variant:: Sorted Binary search on the original-string table, which is sorted. .. rust:variant:: Permuted(Box<[u32]>) Binary search through an order built at load, for a file whose table is not sorted (msgfmt always sorts it). .. rust:enum:: pub enum ReferenceStyle How ``#:`` locations are written. .. rubric:: Variants .. rust:variant:: Wrapped ``#: a.rst:1 b.rst:2``, wrapped at the width, as msgmerge writes. .. rust:variant:: OnePerLine One ``#:`` line per location, as Sphinx's gettext builder writes. .. rust:variant:: None No locations (``gettext_location = False``). .. rubric:: Traits .. rust:trait:: pub trait Lookup: fmt::Debug The gettext lookups, for any catalog that can find a message's forms. Implementors provide :rust:fn:`Lookup::find ` and :rust:fn:`Lookup::plural_rule `; the C library's gettext, ngettext, pgettext and npgettext follow from them. Every string returned is borrowed from the catalog, or is the ``id`` passed in. .. rust:method:: fn find(&self, id: &str, ctx: Option<&str>) -> Option> Returns the translated forms of a message; ``ctx`` ``None`` means no context. A message without a translation is not found. .. rust:method:: fn plural_rule(&self) -> &PluralRule Returns the catalog's compiled Plural-Forms rule. .. rust:method:: fn translation(&self, id: &str, ctx: Option<&str>) -> Option<&str> :provided: Returns a message's singular translation when it has a non-empty one. .. rust:method:: fn text<'a>(&'a self, id: &'a str) -> &'a str :provided: gettext: returns the translation of ``id``, or ``id`` itself. .. rust:method:: fn with_context<'a>(&'a self, ctx: &str, id: &'a str) -> &'a str :provided: pgettext: returns the translation of ``id`` in context ``ctx``, or ``id`` itself. .. rust:method:: fn plural<'a>(&'a self, id: &'a str, id_plural: &'a str, n: u64) -> &'a str :provided: ngettext: returns the form for ``n``, or the English singular (n == 1) or plural when there is no translation or the form is empty. .. rust:method:: fn plural_with_context<'a>(&'a self, ctx: Option<&str>, id: &'a str, id_plural: &'a str, n: u64) -> &'a str :provided: npgettext: :rust:fn:`Lookup::plural ` with an optional context. .. rubric:: Implementors .. rust:impl:: impl Lookup for Catalog :noindex: :module: gd_gettext::index :for: Catalog :trait: Lookup .. rust:impl:: impl Lookup for MoCatalog :noindex: :module: gd_gettext::mo_read :for: MoCatalog :trait: Lookup .. rubric:: Functions .. rust:function:: pub fn format_stats(s: &Stats) -> String Returns sphinx-intl's summary line: ``3 translated, 1 fuzzy, 2 untranslated.`` .. rust:function:: pub fn merge(def: &Catalog, reference: &Catalog, options: &MergeOptions) -> Catalog Updates a translation (``def``) to a new template (``reference``), as msgmerge and sphinx-intl update do, and returns the result as a new catalog; both inputs are borrowed. The result has the template's messages in the template's order, with its locations, notes, and flags: - a message found in ``def`` keeps its translation, translator comments, and fuzzy flag; - a new message similar to an old translated one gets that translation, marked fuzzy, with the old msgid kept as its previous msgid (``#|``); - old translated messages the template lost become obsolete (``#~``). The header is ``def``'s, with the template's POT-Creation-Date. .. rust:function:: pub fn merge_counted(def: &Catalog, reference: &Catalog, options: &MergeOptions) -> (Catalog, MergeStats) :rust:fn:`merge `, also returning what its fuzzy search did. .. rust:function:: pub fn similarity(a: &str, b: &str) -> f64 ``2·M / (|a| + |b|)``, where M is the length of the longest common subsequence of bytes: 1 for equal strings, 0 for strings with nothing in common. It is the measure msgmerge's fstrcmp approximates. Long strings are compared by their first 2000 bytes. .. rust:function:: pub fn sort_by_reference(cat: &mut Catalog) Orders messages by their first location: file name, then line number as a number, then msgid; messages without locations go last. Obsolete messages keep their place after the live ones. Each message's own locations are sorted the same way, as Sphinx sorts them. .. rust:function:: pub fn stats(cat: &Catalog) -> Stats Counts a catalog's messages as sphinx-intl stat does; the header does not count. .. rust:function:: pub fn load_mo(path: impl AsRef, options: &LoadOptions) -> Result Reads a compiled catalog into an editable :rust:struct:`crate::Catalog ` (strings copied). Use :rust:fn:`MoCatalog::load ` to look up without copying. Fails as :rust:fn:`MoCatalog::load ` fails. .. rust:function:: pub fn parse_mo(data: &[u8], name: &str) -> Result Decodes MO bytes into an editable :rust:struct:`crate::Catalog ` that copies what it keeps, so ``data`` is only borrowed. Fails as :rust:fn:`MoCatalog::from_bytes ` fails, or with :rust:variant:`ErrorKind::Memory ` when the copy cannot be allocated. .. rust:function:: pub fn save_mo(cat: &Catalog, path: impl AsRef, include_fuzzy: bool) -> Result<(), Error> Compiles a catalog into a file, through a buffer. See :rust:fn:`write_mo_to `. .. rust:function:: pub fn write_mo(cat: &Catalog, include_fuzzy: bool) -> Result, Error> Compiles a catalog as msgfmt does and returns the bytes. See :rust:fn:`write_mo_to `. .. rust:function:: pub fn write_mo_to(out: &mut impl Write, cat: &Catalog, include_fuzzy: bool) -> Result<(), Error> Compiles a catalog into ``out`` as msgfmt does: the header and every translated message, sorted by key, with a hash table, little-endian. Fuzzy messages are left out unless ``include_fuzzy``; obsolete and untranslated ones always are; of messages with the same key, the first is written. The output depends only on the catalog. The strings are written straight from the catalog; only the tables are built in memory. Pass a buffered writer: entries are written piece by piece. Fails with :rust:variant:`ErrorKind::Io ` when writing fails, and :rust:variant:`ErrorKind::MoFormat ` when the output would pass the format's 4 GiB of offsets. .. rust:function:: pub fn compile_plural(expr: &str, nplurals: usize) -> Result Compiles a plural expression for ``nplurals`` forms. Fails with the first problem found: a syntax error, nplurals out of 1 to 32, or an expression past the node or depth bounds. .. rust:function:: pub fn parse_plural_forms(value: &str) -> Result Compiles a Plural-Forms header value such as ``nplurals=2; plural=(n != 1);``. Fails with an error of kind :rust:variant:`ErrorKind::Plural ` whose excerpt is the value and whose column points at the problem; the caller fills in the file and line. .. rust:function:: pub fn plural_forms_for(language: &str) -> &'static str Returns a Plural-Forms header value for a new catalog of a language: the rules the GNU gettext manual lists for common languages, and the germanic rule (``n != 1``) for others. ``pt_BR`` and ``pt-BR`` find ``pt_BR``, then ``pt``. .. rust:function:: pub fn plural_index(rule: &PluralRule, n: u64) -> usize Returns the msgstr index for ``n``; a result out of range selects form 0, as the C library does. .. rust:function:: pub fn load_po(path: impl AsRef, options: &LoadOptions) -> Result Reads a PO or POT file into an editable catalog, entry by entry through a buffer. Fails when the file cannot be read or is larger than ``options.max_bytes``, or as :rust:fn:`parse_po ` fails. .. rust:function:: pub fn parse_po(text: &str, name: &str) -> Result Parses PO or POT text into an editable catalog; ``name`` labels errors and the catalog, and ``text`` is only borrowed. Fails on the first syntax error, a duplicate message, a header naming a charset other than UTF-8, or an invalid Plural-Forms header; the error names the line and column. .. rust:function:: pub fn parse_po_bytes(data: &[u8], name: &str) -> Result :rust:fn:`parse_po ` for bytes that may not be UTF-8: fails with :rust:variant:`ErrorKind::Encoding ` at the first byte that does not start a character. .. rust:function:: pub fn escape_string(s: &str) -> Cow<'_, str> Escapes a value for a PO string body: backslash, quote, and the control characters C names (others as octal). Borrows ``s`` when nothing needs escaping. .. rust:function:: pub fn save_po(cat: &Catalog, path: impl AsRef, options: &WriteOptions) -> Result<(), Error> Writes a catalog to a file as :rust:fn:`write_po ` formats it, entry by entry through a buffer. Fails with :rust:variant:`ErrorKind::Io ` when the file cannot be written. .. rust:function:: pub fn write_po(cat: &Catalog, options: &WriteOptions) -> String Returns a catalog as PO text: the header, then the messages in order, then the obsolete ones, each entry laid out as msgmerge lays it out. The output depends on nothing but the catalog and the options, so files diff cleanly. .. rust:function:: pub fn write_po_into(out: &mut String, cat: &Catalog, options: &WriteOptions) :rust:fn:`write_po ` appending to ``out``, so a caller can reuse one buffer for many catalogs. .. rust:function:: pub fn write_po_to(out: &mut impl Write, cat: &Catalog, options: &WriteOptions) -> Result<(), Error> :rust:fn:`write_po ` streaming into ``out`` one entry at a time, through one reused buffer, so the whole text is never held. Pass a buffered writer for a file. Fails with :rust:variant:`ErrorKind::Io ` when writing fails. .. rust:function:: pub fn find_catalog_file(dir: &Path, language: &str, domain: &str) -> Option Returns the path of a domain's catalog for a language, ``dir//LC_MESSAGES/.po`` (or ``.mo``), trying each of :rust:fn:`language_candidates `; ``None`` when there is none. .. rust:function:: pub fn language_candidates(language: &str) -> Vec Lists the catalog directory names to try for a language, most specific first: ``pt-BR`` gives ``pt-BR``, ``pt_BR``, and ``pt``; ``sr@latin`` gives it, then ``sr``. Empty for an empty language. .. rubric:: Constants .. rust:const:: pub const FUZZY_MIN_WORK: usize = 1 << 26 The least work a merge's fuzzy search is allowed. .. rust:const:: pub const FUZZY_WORK_PER_BYTE: usize = 256 Bytes a merge's fuzzy search may read per byte of the two catalogs' msgids. .. rust:const:: pub const FUZZY_THRESHOLD: f64 = 0.6 msgmerge's threshold: a changed message inherits the translation of the most similar old message when their similarity is at least this. .. rust:const:: pub const MAX_NPLURALS: usize = 32 The most plural forms a catalog may have. .. rust:const:: pub const MAX_PLURAL_DEPTH: usize = 100 The deepest a plural expression may nest (parser levels). .. rust:const:: pub const MAX_PLURAL_NODES: usize = 128 The most nodes a compiled plural expression may have.