Expand description

This library provides functions to match a set of available languages to those from the http Accept-Language header, urls, or other sources.

Language tags (eg: "en-au") are never validated, this crate simply tries to make sense of whatever value it is given, ignoring any input that it cannot understand, and find the best match based on a few simple rules.

This crate is inspired by Django’s translation handling.

Features

  • No unsafe code (#[forbid(unsafe_code)])
  • No panics
  • Tested; code coverage: 100% (morally)
  • No dependencies

Examples

Simply pass an iterable of language tags to find the best match.

use web_lang::{match_lang, match_accept};

// match a single language tag
assert_eq!(
    match_lang(
        ["en", "en-au", "de"],
        "en-gb"
    ),
    Some("en")
);

// match a set of language tags,
// taken from the http `Accept-Language` header
assert_eq!(
    match_accept(
        ["en", "en-au", "de"],
        "de;q=0.5, en-gb;q=0.9, ja;q=0.2, *;q=0.1"
    ),
    Some("en")
);

Complete example with a custom language enum.

use web_lang::{Language, match_lang, match_accept};

#[derive(Copy, Clone, PartialEq, Debug)]
enum MyLanguage {
    English,
    AustralianEnglish,
    German,
    Japanese,
}

impl Language for MyLanguage {
    fn tag(&self) -> &str {
        match self {
            Self::English => "en",
            Self::AustralianEnglish => "en-au",
            Self::German => "de",
            Self::Japanese => "ja",
        }
    }
}

const LANGUAGES: &[MyLanguage] = &[
    MyLanguage::English,
    MyLanguage::AustralianEnglish,
    MyLanguage::German,
    MyLanguage::Japanese
];

// match a single language tag
assert_eq!(
    match_lang(
        LANGUAGES.iter().copied(),
        "en-gb"
    ),
    Some(MyLanguage::English)
);

// match a set of language tags,
// taken from the http `Accept-Language` header
assert_eq!(
    match_accept(
        LANGUAGES.iter().copied(),
        "de;q=0.5, en-gb;q=0.9, ja;q=0.2, *;q=0.1"
    ),
    Some(MyLanguage::English)
);

Traits

Interface for a language.

Functions

Tries to match an available language to a set of accepted languages.
Tries to match an available language to a single accepted language.