Hreflang Tag Generator — Rust source
Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! hreflang-tag-generator — pure locale-list validation + alternate-link
//! emission (SEO/meta trio). Authored snippet mirroring src/lib/hreflang.ts:
//! normalize_locale + build_hreflang are a pure port of the TS grammar —
//! the ll/ll-CC case-correcting locale rules, the row-located error strings,
//! x-default appended last, and both output flavors (HTML `<link>` block and
//! XML sitemap `<xhtml:link>` block). Std library only — the checks the TS
//! lib does with anchored regexes are hand-rolled character tests.
/// One locale/URL pair. Mirrors the TS HreflangRow interface.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HreflangRow {
pub locale: String,
pub url: String,
}
/// The field set for build_hreflang — rows plus an optional x-default URL.
#[derive(Debug, Clone, Default)]
pub struct HreflangInput {
pub rows: Vec<HreflangRow>,
pub x_default_url: Option<String>,
}
/// Diagnostics plus both emitted flavors. On failure `ok` is false, `errors`
/// lists every row-located problem, and normalized/html/sitemap are empty —
/// exactly like the TS result.
#[derive(Debug, Default)]
pub struct HreflangResult {
pub ok: bool,
pub errors: Vec<String>,
pub normalized: Vec<HreflangRow>,
pub html: String,
pub sitemap: String,
}
/// TS `String#trim()` — strips Unicode whitespace; ASCII whitespace covers
/// every locale/URL this grammar accepts.
fn trim(s: &str) -> &str {
s.trim_matches(|c: char| c.is_whitespace())
}
/// Two ASCII letters, exactly (the anchored TS regex `^[a-zA-Z]{2}$`).
fn is_alpha_pair(s: &str) -> bool {
s.len() == 2 && s.bytes().all(|b| b.is_ascii_alphabetic())
}
/// Normalize a locale tag to Google's hreflang grammar: `ll` (ISO-639-1,
/// lowercase) or `ll-CC` (region uppercase, ISO-3166). Case and surrounding
/// whitespace are corrected (`en-us` -> `en-US`); anything else is invalid
/// and returns None. The Rust twin of normalizeLocale() in
/// src/lib/hreflang.ts — None stands in for the TS null.
pub fn normalize_locale(raw: &str) -> Option<String> {
let t = trim(raw);
if is_alpha_pair(t) {
return Some(t.to_ascii_lowercase());
}
// ll-CC — two ASCII letters, '-', two ASCII letters (bytes and chars are
// 1:1 here because both halves are pure ASCII).
let b = t.as_bytes();
if b.len() == 5 && b[2] == b'-' && is_alpha_pair(&t[0..2]) && is_alpha_pair(&t[3..5]) {
let lang = t[0..2].to_ascii_lowercase();
let region = t[3..5].to_ascii_uppercase();
return Some(format!("{}-{}", lang, region));
}
None
}
/// Trim raw and return it when it starts with http:// or https://, otherwise
/// None. Mirrors the TS validUrl() helper.
fn valid_url(raw: &str) -> Option<&str> {
let t = trim(raw);
if t.starts_with("http://") || t.starts_with("https://") {
Some(t)
} else {
None
}
}
/// Validate a locale/URL table and emit both hreflang flavors. Invalid input
/// collects every error (row-located) and emits empty blocks; valid input
/// normalizes locales, preserves row order, and appends x-default last.
pub fn build_hreflang(input: &HreflangInput) -> HreflangResult {
let mut errors: Vec<String> = Vec::new();
let mut normalized: Vec<HreflangRow> = Vec::new();
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
for (i, row) in input.rows.iter().enumerate() {
let n = i + 1;
let locale = normalize_locale(&row.locale);
let Some(locale) = locale else {
errors.push(format!(
"Row {}: \"{}\" is not a valid locale — use ll or ll-CC (e.g. en, de-AT).",
n,
trim(&row.locale)
));
continue;
};
if seen.contains(&locale) {
errors.push(format!("Row {}: locale \"{}\" is already used.", n, locale));
continue;
}
if trim(&row.url).is_empty() {
errors.push(format!("Row {}: URL is required.", n));
continue;
}
let Some(url) = valid_url(&row.url) else {
errors.push(format!(
"Row {}: URL must start with http:// or https://.",
n
));
continue;
};
seen.insert(locale.clone());
normalized.push(HreflangRow {
locale,
url: url.to_string(),
});
}
let mut x_default: Option<String> = None;
if let Some(raw) = &input.x_default_url {
if !trim(raw).is_empty() {
match valid_url(raw) {
Some(u) => x_default = Some(u.to_string()),
None => errors.push(
"x-default: URL must start with http:// or https://.".to_string(),
),
}
}
}
if !errors.is_empty() {
return HreflangResult {
ok: false,
errors,
normalized: Vec::new(),
html: String::new(),
sitemap: String::new(),
};
}
let mut html_lines: Vec<String> = normalized
.iter()
.map(|r| {
format!(
"<link rel=\"alternate\" href=\"{}\" hreflang=\"{}\" />",
r.url, r.locale
)
})
.collect();
let mut sitemap_lines: Vec<String> = normalized
.iter()
.map(|r| {
format!(
" <xhtml:link rel=\"alternate\" hreflang=\"{}\" href=\"{}\"/>",
r.locale, r.url
)
})
.collect();
if let Some(xd) = &x_default {
html_lines.push(format!(
"<link rel=\"alternate\" href=\"{}\" hreflang=\"x-default\" />",
xd
));
sitemap_lines.push(format!(
" <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"{}\"/>",
xd
));
}
HreflangResult {
ok: true,
errors: Vec::new(),
normalized,
html: html_lines.join("\n"),
sitemap: sitemap_lines.join("\n"),
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →