日本語

The Locale trait

The Locale trait names the languages of an application and picks the text of one of them.

The trait

pub trait Locale: Variants + Serialize + Copy + Eq {
    type Text<T>;

    fn pick<T>(self, text: Self::Text<T>) -> T;

    fn tag(self) -> LanguageTag { ... }
}

pub fn locales<L: Locale>() -> &'static [L];

Locale is implemented by an enum whose variants are the languages of the application. Each bound lets the enum be used in one way:

  • Variants comes only from #[derive(Segment)], which also implements Segment. It lists the variants for locales, and Segment lets the language be a parameter of a route.
  • Serialize gives tag the language's tag, the string serde writes for the variant.
  • Copy and Eq let a handler pass the language around by value and compare it, as in lang == Lang::En.

The trait does not ask for Deserialize. The route reads the language from the URL through Segment. A signal struct needs it to hold a Lang in a field, because the signals are deserialized.

An enum without #[derive(Segment)] fails to compile at the impl with E0277, Lang does not list its variants:

use hypersig_i18n::Locale;
use serde::{Deserialize, Serialize};

// No `#[derive(Segment)]`.
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
#[serde(rename_all = "lowercase")]
enum Lang {
    En,
    Ja,
}

struct ByLang<T> {
    en: T,
    ja: T,
}

// error[E0277]: `Lang` does not list its variants
impl Locale for Lang {
    type Text<T> = ByLang<T>;

    fn pick<T>(self, text: ByLang<T>) -> T {
        match self {
            Self::En => text.en,
            Self::Ja => text.ja,
        }
    }
}

An enum without Serialize is E0277 at the impl too, because tag has no string to read:

use hypersig::Segment;
use hypersig_i18n::Locale;

// No `Serialize`.
#[derive(Segment, Clone, Copy, PartialEq, Eq, Debug)]
enum Lang {
    En,
    Ja,
}

struct ByLang<T> {
    en: T,
    ja: T,
}

// error[E0277]: the trait bound `Lang: serde::Serialize` is not satisfied
impl Locale for Lang {
    type Text<T> = ByLang<T>;

    fn pick<T>(self, text: ByLang<T>) -> T {
        match self {
            Self::En => text.en,
            Self::Ja => text.ja,
        }
    }
}

Text and pick

type Text<T> is the type that holds one value per language, and pick returns the value of self. Usually Text<T> is a struct with one field of type T per language, and pick is a match with one arm per variant, as Lang and ByLang in Declare the languages are. T is any type, so the same struct holds a &str, a function, or an element, which Writing a text shows.

pick takes the text by value and moves the chosen field out. A match without the arm of a variant is E0004, so every language has its field read:

use hypersig::Segment;
use hypersig_i18n::Locale;
use serde::{Deserialize, Serialize};

#[derive(Segment, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
#[serde(rename_all = "lowercase")]
enum Lang {
    En,
    Ja,
}

struct ByLang<T> {
    en: T,
    ja: T,
}

impl Locale for Lang {
    type Text<T> = ByLang<T>;

    fn pick<T>(self, text: ByLang<T>) -> T {
        // error[E0004]: non-exhaustive patterns: `Lang::Ja` not covered
        match self {
            Self::En => text.en,
        }
    }
}

A wildcard arm, _ => text.en, compiles and gives every other language the English text. It also keeps a language added later from failing to compile here, so write one arm per variant.

The tag

tag returns the variant's BCP 47 language tag as a LanguageTag, which Page::lang and Page::alternate take. It is the string serde writes for the variant, and #[derive(Segment)] reads the same #[serde(rename_all)] and #[serde(rename)] attributes, so the tag and the route segment are one string. rename_all = "kebab-case" turns PtBr into pt-br, and #[serde(rename = "zh-Hant")] names one variant by hand:

use hypersig::Segment;
use hypersig_i18n::Locale;
use serde::{Deserialize, Serialize};

#[derive(Segment, Serialize, Clone, Copy, PartialEq, Eq, Debug)]
#[serde(rename_all = "kebab-case")]
enum Lang {
    // `en`, the default.
    En,
    // `pt-br`.
    PtBr,
    // `zh-Hant`, renamed by hand.
    #[serde(rename = "zh-Hant")]
    ZhHant,
}

struct ByLang<T> {
    en: T,
    pt_br: T,
    zh_hant: T,
}

impl Locale for Lang {
    type Text<T> = ByLang<T>;

    fn pick<T>(self, text: ByLang<T>) -> T {
        match self {
            Self::En => text.en,
            Self::PtBr => text.pt_br,
            Self::ZhHant => text.zh_hant,
        }
    }
}

assert_eq!(Lang::PtBr.tag().as_str(), "pt-br");
assert_eq!(Lang::ZhHant.tag().as_str(), "zh-Hant");

tag checks only the shape of the string: subtags of one to eight ASCII letters and digits joined by -, the first of two, three, or five to eight letters. It panics where the string does not have that shape, as en_US does, and the panic happens on the first call, often while rendering a page. Whether the language exists in the IANA registry is not checked.

use hypersig::Segment;
use hypersig_i18n::Locale;
use serde::{Deserialize, Serialize};

#[derive(Segment, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
enum Lang {
    // A BCP 47 tag separates its subtags with `-`, not `_`.
    #[serde(rename = "en_US")]
    EnUs,
    #[serde(rename = "ja")]
    Ja,
}

struct ByLang<T> {
    en_us: T,
    ja: T,
}

impl Locale for Lang {
    type Text<T> = ByLang<T>;

    fn pick<T>(self, text: ByLang<T>) -> T {
        match self {
            Self::EnUs => text.en_us,
            Self::Ja => text.ja,
        }
    }
}

// panicked: a locale's segment is its language tag:
// `en_US` is not a BCP 47 language tag
let _ = Lang::EnUs.tag();

Every language and the default

locales::<L>() returns every variant in declaration order. The first variant is the default language: negotiate returns it when the Accept-Language header matches no language, and LocalePage::alternates writes it as x-default. To change the default, move its variant to the top.

// `Lang` and `ByLang` are the ones the Overview declares.
use hypersig_i18n::{locales, negotiate};

// Every variant, in declaration order.
assert_eq!(locales::<Lang>(), [Lang::En, Lang::Ja]);
// The tag is the string serde writes for the variant.
assert_eq!(Lang::Ja.tag().as_str(), "ja");
// The first variant is the default.
assert_eq!(negotiate::<Lang>("fr"), Lang::En);

#[derive(Segment)] refuses an enum with no variant, with the error Segment needs an enum with at least one variant, so every language enum has a default.

What stays unchecked

  • Which field pick returns for each variant. An arm Self::Ja => text.en compiles, and Japanese pages show the English text.
  • The shape of the tag, until tag runs. A tag such as en_US panics then.
  • Whether the tag names a real language. xx is shaped as a tag and passes.

Example

The declaration of Declare the languages, complete:

use hypersig::Segment;
use hypersig_i18n::Locale;
use serde::{Deserialize, Serialize};

// The segment of each language is its BCP 47 tag, here `en` and `ja`.
#[derive(Segment, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
#[serde(rename_all = "lowercase")]
enum Lang {
    En,
    Ja,
}

/// One value per language.
struct ByLang<T> {
    en: T,
    ja: T,
}

impl Locale for Lang {
    type Text<T> = ByLang<T>;

    fn pick<T>(self, text: ByLang<T>) -> T {
        match self {
            Self::En => text.en,
            Self::Ja => text.ja,
        }
    }
}

assert_eq!(Lang::Ja.pick(ByLang { en: "Hello", ja: "こんにちは" }), "こんにちは");

Next, Writing a text covers the texts that pick chooses from.