Hreflang Tag Generator — Zig 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 Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.
// hreflang-tag-generator — Zig port: locale-list validation + alternate-link
// emission for the hreflang tool. Zig (0.15+), standard library only.
// Port of src/lib/hreflang.ts — same logic as this dir's typescript.ts and
// the live Go twin at cli/hreflang-tag-generator/hreflang-tag-generator.go.
// All output is allocated through the caller's allocator (an arena works
// well); the Result's slices are the caller's to free.
const std = @import("std");
pub const Error = error{OutOfMemory};
/// One locale/URL pair. Mirrors the TS HreflangRow interface. A missing TS
/// key (`row.locale === undefined`) is passed as "".
pub const Row = struct {
locale: []const u8,
url: []const u8,
};
/// The field set for buildHreflang — rows plus an optional x-default URL.
/// The default value matches the TS shape with the fields omitted entirely.
pub const Input = struct {
rows: []const Row = &.{},
x_default_url: ?[]const u8 = null,
};
/// 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.
pub const Result = struct {
ok: bool,
errors: []const []const u8,
normalized: []Row,
html: []const u8,
sitemap: []const u8,
};
const ws = " \t\r\n\x0b\x0c";
/// TS String#trim() for ASCII whitespace.
fn trim(s: []const u8) []const u8 {
return std.mem.trim(u8, s, ws);
}
fn isAlpha(c: u8) bool {
return (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z');
}
fn allocLower(alloc: std.mem.Allocator, s: []const u8) Error![]const u8 {
const out = try alloc.dupe(u8, s);
for (out) |*c| c.* = std.ascii.toLower(c.*);
return out;
}
fn allocUpper(alloc: std.mem.Allocator, s: []const u8) Error![]const u8 {
const out = try alloc.dupe(u8, s);
for (out) |*c| c.* = std.ascii.toUpper(c.*);
return out;
}
/// 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 null. The Zig twin of normalizeLocale() in
/// src/lib/hreflang.ts — null stands in for the TS null.
pub fn normalizeLocale(alloc: std.mem.Allocator, raw: []const u8) Error!?[]const u8 {
const t = trim(raw);
if (t.len == 2 and isAlpha(t[0]) and isAlpha(t[1])) {
return try allocLower(alloc, t);
}
if (t.len == 5 and t[2] == '-' and isAlpha(t[0]) and isAlpha(t[1]) and
isAlpha(t[3]) and isAlpha(t[4]))
{
const lang = try allocLower(alloc, t[0..2]);
const region = try allocUpper(alloc, t[3..5]);
return try std.fmt.allocPrint(alloc, "{s}-{s}", .{ lang, region });
}
return null;
}
/// Trim raw and return the trimmed value when it starts with http:// or
/// https://, otherwise null. Mirrors the TS validUrl() helper.
fn validUrl(alloc: std.mem.Allocator, raw: []const u8) Error!?[]const u8 {
const t = trim(raw);
if (std.mem.startsWith(u8, t, "http://") or std.mem.startsWith(u8, t, "https://")) {
return try alloc.dupe(u8, t);
}
return null;
}
/// 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 buildHreflang(alloc: std.mem.Allocator, input: Input) Error!Result {
var errors: std.ArrayList([]const u8) = .empty;
var normalized: std.ArrayList(Row) = .empty;
var seen = std.StringHashMap(void).init(alloc);
defer seen.deinit();
for (input.rows, 0..) |row, i| {
const n = i + 1;
const locale = try normalizeLocale(alloc, row.locale);
if (locale == null) {
try errors.append(alloc, try std.fmt.allocPrint(
alloc,
"Row {d}: \"{s}\" is not a valid locale \u{2014} use ll or ll-CC (e.g. en, de-AT).",
.{ n, trim(row.locale) },
));
continue;
}
if (seen.contains(locale.?)) {
try errors.append(alloc, try std.fmt.allocPrint(
alloc,
"Row {d}: locale \"{s}\" is already used.",
.{ n, locale.? },
));
continue;
}
if (trim(row.url).len == 0) {
try errors.append(alloc, try std.fmt.allocPrint(
alloc,
"Row {d}: URL is required.",
.{n},
));
continue;
}
const url = try validUrl(alloc, row.url);
if (url == null) {
try errors.append(alloc, try std.fmt.allocPrint(
alloc,
"Row {d}: URL must start with http:// or https://.",
.{n},
));
continue;
}
try seen.put(locale.?, {});
try normalized.append(alloc, .{ .locale = locale.?, .url = url.? });
}
var x_default: ?[]const u8 = null;
if (input.x_default_url) |raw| {
if (trim(raw).len > 0) {
x_default = try validUrl(alloc, raw);
if (x_default == null) {
try errors.append(alloc, try alloc.dupe(
u8,
"x-default: URL must start with http:// or https://.",
));
}
}
}
if (errors.items.len > 0) {
return .{
.ok = false,
.errors = try errors.toOwnedSlice(alloc),
.normalized = &.{},
.html = "",
.sitemap = "",
};
}
var html: std.ArrayList(u8) = .empty;
var sitemap: std.ArrayList(u8) = .empty;
for (normalized.items, 0..) |r, i| {
if (i > 0) {
try html.append(alloc, '\n');
try sitemap.append(alloc, '\n');
}
try html.appendSlice(alloc, "<link rel=\"alternate\" href=\"");
try html.appendSlice(alloc, r.url);
try html.appendSlice(alloc, "\" hreflang=\"");
try html.appendSlice(alloc, r.locale);
try html.appendSlice(alloc, "\" />");
try sitemap.appendSlice(alloc, " <xhtml:link rel=\"alternate\" hreflang=\"");
try sitemap.appendSlice(alloc, r.locale);
try sitemap.appendSlice(alloc, "\" href=\"");
try sitemap.appendSlice(alloc, r.url);
try sitemap.appendSlice(alloc, "\"/>");
}
if (x_default) |xd| {
if (html.items.len > 0) {
try html.append(alloc, '\n');
try sitemap.append(alloc, '\n');
}
try html.appendSlice(alloc, "<link rel=\"alternate\" href=\"");
try html.appendSlice(alloc, xd);
try html.appendSlice(alloc, "\" hreflang=\"x-default\" />");
try sitemap.appendSlice(alloc, " <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"");
try sitemap.appendSlice(alloc, xd);
try sitemap.appendSlice(alloc, "\"/>");
}
return .{
.ok = true,
.errors = &.{},
.normalized = try normalized.toOwnedSlice(alloc),
.html = try html.toOwnedSlice(alloc),
.sitemap = try sitemap.toOwnedSlice(alloc),
};
}
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 →