seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
Documentation
//! # Locales
//!
//! `--locale de_DE` or `[generate] locale = "de_DE"` localizes names,
//! addresses, companies, job titles, and phone numbers. Emails, usernames,
//! domains, and lorem text stay in English so they remain ASCII.
//!
//! English uses the original generators, so English output is unchanged.

use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;

use fake::faker::impls::address::CityNameGenFn;
use fake::faker::{address::raw as address, company::raw as company};
use fake::faker::{name::raw as name, phone_number::raw as phone};
use fake::locales::{AR_SA, CY_GB, DE_DE, FR_FR, IT_IT, JA_JP, PT_BR, PT_PT, ZH_CN, ZH_TW};
use fake::Fake;
use rand::Rng;
use serde::{Deserialize, Serialize};

use crate::classify::semantic::SemanticType;
use crate::generate::value::Value;

/// A locale supported by the `fake` crate.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Locale {
    #[default]
    En,
    ArSa,
    CyGb,
    DeDe,
    FrFr,
    ItIt,
    JaJp,
    PtBr,
    PtPt,
    ZhCn,
    ZhTw,
}

const CODES: [(Locale, &str); 11] = [
    (Locale::En, "en"),
    (Locale::ArSa, "ar_SA"),
    (Locale::CyGb, "cy_GB"),
    (Locale::DeDe, "de_DE"),
    (Locale::FrFr, "fr_FR"),
    (Locale::ItIt, "it_IT"),
    (Locale::JaJp, "ja_JP"),
    (Locale::PtBr, "pt_BR"),
    (Locale::PtPt, "pt_PT"),
    (Locale::ZhCn, "zh_CN"),
    (Locale::ZhTw, "zh_TW"),
];

impl Locale {
    /// Whether this locale has its own data for a type. Where `fake` lacks
    /// it, the locale would mix local names into English templates
    /// ("加藤 shire") or return US states, so the English generators are used.
    pub fn localizes(self, semantic: SemanticType) -> bool {
        use Locale::*;
        use SemanticType as T;
        match semantic {
            T::FirstName | T::LastName | T::FullName | T::DisplayName => self != En,
            T::City => matches!(self, DeDe | ItIt | PtPt),
            T::StreetAddress => matches!(self, CyGb | DeDe | FrFr | ItIt | PtBr | PtPt),
            T::State => matches!(self, DeDe | ItIt | PtBr | PtPt),
            T::ZipCode | T::PostalCode => matches!(self, DeDe | FrFr | ItIt | PtPt),
            T::Country => matches!(self, CyGb | DeDe | FrFr | ItIt | PtPt),
            T::Phone => matches!(self, CyGb | FrFr | ItIt | JaJp | PtBr | PtPt),
            T::CompanyName => matches!(self, DeDe | ItIt | JaJp | PtBr | PtPt),
            T::JobTitle => matches!(self, PtPt),
            _ => false,
        }
    }

    /// A localized value, or `None` when the locale has no data of its own
    /// for the type (the caller then uses the English generators).
    pub fn sample(self, semantic: SemanticType, rng: &mut impl Rng) -> Option<Value> {
        if !self.localizes(semantic) {
            return None;
        }
        match self {
            Locale::En => None,
            Locale::ArSa => localized(AR_SA, semantic, rng),
            Locale::CyGb => localized(CY_GB, semantic, rng),
            Locale::DeDe => localized(DE_DE, semantic, rng),
            Locale::FrFr => localized(FR_FR, semantic, rng),
            Locale::ItIt => localized(IT_IT, semantic, rng),
            Locale::JaJp => localized(JA_JP, semantic, rng),
            Locale::PtBr => localized(PT_BR, semantic, rng),
            Locale::PtPt => localized(PT_PT, semantic, rng),
            Locale::ZhCn => localized(ZH_CN, semantic, rng),
            Locale::ZhTw => localized(ZH_TW, semantic, rng),
        }
    }
}

fn localized<L: CityNameGenFn>(
    locale: L,
    semantic: SemanticType,
    rng: &mut impl Rng,
) -> Option<Value> {
    let text: String = match semantic {
        SemanticType::FirstName => name::FirstName(locale).fake_with_rng(rng),
        SemanticType::LastName => name::LastName(locale).fake_with_rng(rng),
        SemanticType::FullName | SemanticType::DisplayName => name::Name(locale).fake_with_rng(rng),
        SemanticType::Phone => phone::PhoneNumber(locale).fake_with_rng(rng),
        SemanticType::StreetAddress => address::StreetName(locale).fake_with_rng(rng),
        SemanticType::City => address::CityName(locale).fake_with_rng(rng),
        SemanticType::State => address::StateName(locale).fake_with_rng(rng),
        SemanticType::ZipCode | SemanticType::PostalCode => {
            address::ZipCode(locale).fake_with_rng(rng)
        }
        SemanticType::Country => address::CountryName(locale).fake_with_rng(rng),
        SemanticType::CompanyName => company::CompanyName(locale).fake_with_rng(rng),
        SemanticType::JobTitle => company::Profession(locale).fake_with_rng(rng),
        _ => return None,
    };
    Some(Value::String(Cow::Owned(text)))
}

/// Lowercase ASCII for an email or username part: common Latin diacritics
/// are transliterated (`ü` -> `ue`, `ß` -> `ss`, `é` -> `e`), anything else
/// that is not a letter or digit is dropped.
pub fn ascii_slug(text: &str) -> String {
    let mut slug = String::new();
    for c in text.chars().flat_map(char::to_lowercase) {
        let mapped = match c {
            'a'..='z' | '0'..='9' => {
                slug.push(c);
                continue;
            }
            'ä' | 'æ' => "ae",
            'ö' | 'ø' | 'œ' => "oe",
            'ü' => "ue",
            'ß' => "ss",
            'à' | 'á' | 'â' | 'ã' | 'å' | 'ā' => "a",
            'ç' | 'ć' | 'č' => "c",
            'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ę' => "e",
            'ì' | 'í' | 'î' | 'ï' => "i",
            'ŵ' => "w",
            'ñ' | 'ń' => "n",
            'ò' | 'ó' | 'ô' | 'õ' | 'ō' => "o",
            'ù' | 'ú' | 'û' | 'ū' => "u",
            'ý' | 'ÿ' | 'ŷ' => "y",
            'ł' => "l",
            'ś' | 'š' => "s",
            'ź' | 'ż' | 'ž' => "z",
            _ => "",
        };
        slug.push_str(mapped);
    }
    slug
}

impl fmt::Display for Locale {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let code = CODES.iter().find(|(l, _)| l == self).map(|(_, c)| *c);
        f.write_str(code.unwrap_or("en"))
    }
}

impl FromStr for Locale {
    type Err = String;

    /// Accepts `de_DE`, `de-DE`, or `de_de`; `en_US` means English.
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let normalized = value.replace('-', "_").to_ascii_lowercase();
        if normalized == "en_us" {
            return Ok(Locale::En);
        }
        CODES
            .iter()
            .find(|(_, code)| code.to_ascii_lowercase() == normalized)
            .map(|(locale, _)| *locale)
            .ok_or_else(|| {
                let supported: Vec<&str> = CODES.iter().map(|(_, code)| *code).collect();
                format!(
                    "unknown locale '{value}'; supported: {}",
                    supported.join(", ")
                )
            })
    }
}

impl Serialize for Locale {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for Locale {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::classify::semantic::SemanticType;
    use rand::{rngs::StdRng, SeedableRng};

    #[test]
    fn locale_codes_parse_leniently_and_print_canonically() {
        for (code, locale) in [
            ("de_DE", Locale::DeDe),
            ("de-de", Locale::DeDe),
            ("EN", Locale::En),
            ("en_US", Locale::En),
            ("ja-JP", Locale::JaJp),
            ("pt_br", Locale::PtBr),
        ] {
            assert_eq!(code.parse::<Locale>().unwrap(), locale, "{code}");
        }
        assert_eq!(Locale::DeDe.to_string(), "de_DE");
        let err = "xx_YY".parse::<Locale>().unwrap_err();
        assert!(err.contains("xx_YY") && err.contains("fr_FR"), "{err}");
        let json = serde_json::to_string(&Locale::ZhCn).unwrap();
        assert_eq!(json, "\"zh_CN\"");
        assert_eq!(serde_json::from_str::<Locale>(&json).unwrap(), Locale::ZhCn);
    }

    #[test]
    fn english_keeps_the_existing_generators() {
        let mut rng = StdRng::seed_from_u64(1);
        assert!(Locale::En
            .sample(SemanticType::FirstName, &mut rng)
            .is_none());
    }

    #[test]
    fn other_locales_localize_names_places_and_companies() {
        let mut rng = StdRng::seed_from_u64(1);
        let mut non_ascii = |semantic| {
            (0..20).any(|_| {
                let value = Locale::JaJp.sample(semantic, &mut rng).unwrap();
                !value.as_string().unwrap().is_ascii()
            })
        };
        assert!(non_ascii(SemanticType::FullName));
        assert!(non_ascii(SemanticType::LastName));
        // Emails and usernames stay ASCII through the English generators.
        assert!(Locale::JaJp.sample(SemanticType::Email, &mut rng).is_none());
        assert!(Locale::DeDe.sample(SemanticType::City, &mut rng).is_some());
        assert!(Locale::ItIt
            .sample(SemanticType::CompanyName, &mut rng)
            .is_some());
        assert!(Locale::JaJp.sample(SemanticType::Phone, &mut rng).is_some());
    }

    #[test]
    fn locales_without_data_for_a_type_use_english() {
        let mut rng = StdRng::seed_from_u64(1);
        // fake would return "加藤 shire" and US states for these.
        assert!(Locale::JaJp.sample(SemanticType::City, &mut rng).is_none());
        assert!(Locale::FrFr.sample(SemanticType::State, &mut rng).is_none());
        assert!(Locale::ZhCn
            .sample(SemanticType::CompanyName, &mut rng)
            .is_none());
    }

    #[test]
    fn email_parts_are_ascii() {
        assert_eq!(ascii_slug("Jürgen"), "juergen");
        assert_eq!(ascii_slug("Groß-Müller"), "grossmueller");
        assert_eq!(ascii_slug("Hélène Ô'Brien"), "heleneobrien");
        assert_eq!(ascii_slug("佐藤"), "");
    }
}