Something went wrong. Try again.
An XSLT 1.0 processor for Zig 0.16, built on zxml.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The two places XSLT turns a number into text on its own terms://! `format-number`, which reads a picture string, and `xsl:number`, which//! counts a node's place in the document and writes it as a numeral.//!//! Both are self-contained enough to test directly, which is why they are//! here rather than in the engine: a picture string is a small language, and//! the difference between `#,##0.00` and `###0.00` is the kind of thing that//! is obvious in a table of cases and invisible in a transformation.
const std = @import("std");const Allocator = std.mem.Allocator;const stylesheet = @import("stylesheet.zig");const functions = @import("zxpath").functions;
const DecimalFormat = stylesheet.DecimalFormat;
pub const Error = Allocator.Error || error{InvalidPicture};
// -- format-number -----------------------------------------------------------
/// One side of a picture string: what goes before the digits, how many digit/// positions of each kind there are, and what goes after.////// The four counts are kept apart rather than reduced to a minimum and a/// maximum, because `0` and `#` do not differ only in whether a digit is/// mandatory -- they also decide whether a leading zero is written at all,/// and JDK `DecimalFormat`, which XSLT 12.3 defers to, has a rule that reads/// the two integer counts together. Collapsing them loses the distinction the/// rule needs.const SubPicture = struct { prefix: []const u8 = "", suffix: []const u8 = "", /// `0` positions before the decimal separator: digits that must appear. integer_digits: usize = 0, /// `#` positions before it: digits that may. integer_hash: usize = 0, frac_digits: usize = 0, frac_hash: usize = 0, /// Zero when the subpicture has no grouping separator. grouping: usize = 0, /// Whether the picture contains a decimal separator at all. One with no /// fraction positions after it still writes the separator: `format-number(1, /// '.')` is `1.`. add_decimal: bool = false, /// The multiplier a `%` or `\u{2030}` in the picture implies. multiplier: f64 = 1,};
/// `format-number`.////// The picture is two subpictures separated by the pattern separator: one for/// positive numbers and one for negative. When only one is given, negatives/// get the minus sign in front of it -- which is why `format-number(-5,/// '#;(#)')` is `(5)` and `format-number(-5, '#')` is `-5`.pub fn formatNumber(gpa: Allocator, n: f64, picture: []const u8, format: DecimalFormat) Error![]u8 { var sep_buf: [4]u8 = undefined; const sep_len = std.unicode.utf8Encode(format.pattern_separator, &sep_buf) catch 1; const sep = sep_buf[0..sep_len];
const split = std.mem.indexOf(u8, picture, sep); const positive_src = if (split) |i| picture[0..i] else picture; const negative_src = if (split) |i| picture[i + sep.len ..] else null;
const negative = std.math.signbit(n) and !std.math.isNan(n); const chosen_src = if (negative and negative_src != null) negative_src.? else positive_src; const sub = try parseSubPicture(chosen_src, format);
// NaN is written as the format's NaN string, with nothing around it. if (std.math.isNan(n)) return gpa.dupe(u8, format.nan);
var out: std.ArrayList(u8) = .empty; errdefer out.deinit(gpa);
// A negative number with only a positive subpicture gets the minus sign // *before* the prefix, not between the prefix and the digits: JDK // `DecimalFormat` builds the default negative pattern by prefixing a minus // to the whole positive one, so `format-number(-3.14, '_#.##_')` is // `-_3.14_`. if (negative and negative_src == null) try appendCodepoint(gpa, &out, format.minus_sign); try out.appendSlice(gpa, sub.prefix);
const magnitude = @abs(n) * sub.multiplier; if (std.math.isInf(magnitude)) { try out.appendSlice(gpa, format.infinity); } else { try appendDigits(gpa, &out, magnitude, sub, format); } try out.appendSlice(gpa, sub.suffix); return out.toOwnedSlice(gpa);}
fn parseSubPicture(src: []const u8, format: DecimalFormat) Error!SubPicture { var sub: SubPicture = .{};
// The active part is everything from the first digit-ish character to the // last; what is on either side is literal text. var start: usize = 0; var end: usize = src.len; var it = CodepointIterator{ .src = src }; var first: ?usize = null; var last: usize = 0; while (it.next()) |cp| { if (isActive(cp.value, format)) { if (first == null) first = cp.start; last = cp.start + cp.len; } } if (first) |f| { start = f; end = last; } else { // A picture with no digit positions at all is not a picture. return error.InvalidPicture; }
sub.prefix = src[0..start]; sub.suffix = src[end..];
// A percent or per-mille sign anywhere scales the number. for ([_]struct { u21, f64 }{ .{ format.percent, 100 }, .{ format.per_mille, 1000 }, }) |pair| { if (containsCodepoint(src, pair[0])) sub.multiplier = pair[1]; }
const active = src[start..end]; const dot = indexOfCodepoint(active, format.decimal_separator); const integer_part = if (dot) |i| active[0..i] else active; const fraction_part = if (dot) |i| active[i + codepointLength(format.decimal_separator) ..] else "";
sub.add_decimal = dot != null; sub.integer_digits = countCodepoint(integer_part, format.zero_digit); sub.integer_hash = countCodepoint(integer_part, format.digit); sub.frac_digits = countCodepoint(fraction_part, format.zero_digit); sub.frac_hash = countCodepoint(fraction_part, format.digit);
// The grouping size is the distance from the decimal point to the last // grouping separator, so `#,##0.0` groups by three and `#,##,##0` by two. if (lastIndexOfCodepoint(integer_part, format.grouping_separator)) |i| { const after = integer_part[i + codepointLength(format.grouping_separator) ..]; sub.grouping = countDigitPositions(after, format); }
return sub;}
/// Writes the digits of a magnitude into the shape a subpicture asks for.////// This follows libxslt's order, which is JDK `DecimalFormat`'s, and the/// order is where the surprises live:////// 1. Round once, at the last fraction position the picture has, by adding/// half of it and cutting the remainder./// 2. Write the integer part, zero-padded to the `0` positions and grouped./// 3. **Then** apply Java's own peculiarity: a picture with no digit/// positions at all except `#` after the decimal separator treats the/// first of those as a `0`, so `.#` behaves as `.0` and `.##` as `.0#`./// 4. Write a leading zero only if the integer part came to nothing *and*/// the picture demands no digit anywhere -- which is why `#.0` of zero is/// `.0` and `#.##` of a half is `0.5`./// 5. Write the fraction, dropping trailing zeroes down to the `0`/// positions. A picture with a decimal separator and nothing after it/// still writes the separator.fn appendDigits( gpa: Allocator, out: *std.ArrayList(u8), magnitude: f64, picture: SubPicture, format: DecimalFormat,) Error!void { var sub = picture;
// Rounding happens once, at the last position the picture can show. const places = sub.frac_digits + sub.frac_hash; const scale = std.math.pow(f64, 10, @floatFromInt(places)); var number = magnitude + 0.5 / scale; number -= @mod(number, 1 / scale);
const whole = @floor(number); try appendGroupedFloat(gpa, out, whole, sub.integer_digits, sub.grouping, format);
// Java treats `.#` like `.0`, `.##` like `.0#`, and so on. if (sub.integer_digits + sub.integer_hash + sub.frac_digits == 0 and sub.frac_hash > 0) { sub.frac_digits += 1; sub.frac_hash -= 1; }
if (whole == 0 and sub.integer_digits + sub.frac_digits == 0) { try appendCodepoint(gpa, out, format.zero_digit); }
if (sub.frac_digits + sub.frac_hash == 0) { if (sub.add_decimal) try appendCodepoint(gpa, out, format.decimal_separator); return; }
const fraction = number - whole; if (fraction == 0 and sub.frac_digits == 0) return;
try appendCodepoint(gpa, out, format.decimal_separator); // The fraction is carried up to an integer at the picture's precision, and // its trailing zeroes then come off one `#` at a time -- never past the // `0` positions, which are what "must appear" means. var scaled = @floor(scale * fraction + 0.5); var optional = sub.frac_hash; while (optional > 0) { if (@mod(scaled, 10) >= 1) break; scaled /= 10; optional -= 1; } try appendGroupedFloat(gpa, out, @floor(scaled), sub.frac_digits + optional, 0, format);}
/// Writes a non-negative whole number, zero-padded to `width` digits and with/// a separator every `group` of them counted from the right.////// It works from a `f64` rather than an integer because that is what the/// rounding above leaves, and because a magnitude can exceed what an integer/// holds while still having digits worth writing. Digits come off the bottom/// with `@mod`, which is why the answer is built backwards.////// A width of zero and a value of zero write nothing at all, which is what/// lets `#.0` of zero come out as `.0`.fn appendGroupedFloat( gpa: Allocator, out: *std.ArrayList(u8), value: f64, width: usize, group: usize, format: DecimalFormat,) Error!void { var digits: [512]u8 = undefined; var len: usize = 0; var number = value; var i: usize = 0; while (len + 1 < digits.len) { if (i >= width and @abs(number) < 1) break; digits[len] = '0' + @as(u8, @intFromFloat(@mod(number, 10))); len += 1; number = @floor(number / 10); i += 1; }
var written: usize = 0; while (len > 0) { len -= 1; // A separator goes before a digit whenever a whole number of groups // is still to come after it. if (group != 0 and written != 0 and (len + 1) % group == 0) { try appendCodepoint(gpa, out, format.grouping_separator); } try appendDigit(gpa, out, digits[len], format); written += 1; }}
/// Writes one ASCII digit in whatever digit family the format names, which is/// what `zero-digit` is for: setting it to an Arabic-Indic zero renumbers the/// whole output.fn appendDigit(gpa: Allocator, out: *std.ArrayList(u8), ascii: u8, format: DecimalFormat) Error!void { const offset: u21 = ascii - '0'; try appendCodepoint(gpa, out, format.zero_digit + offset);}
fn isActive(cp: u21, format: DecimalFormat) bool { return cp == format.digit or cp == format.zero_digit or cp == format.decimal_separator or cp == format.grouping_separator;}
fn countDigitPositions(s: []const u8, format: DecimalFormat) usize { var count: usize = 0; var it = CodepointIterator{ .src = s }; while (it.next()) |cp| { if (cp.value == format.digit or cp.value == format.zero_digit) count += 1; } return count;}
// -- xsl:number --------------------------------------------------------------
/// The numeral systems `xsl:number` can write a sequence in, taken from the/// first token of the `format` attribute.pub const Numeral = enum { /// `1`, and anything unrecognised, which the specification says to treat /// as `1` rather than as an error. arabic, /// `01`, `001`: zero-padded to the width of the token. padded, /// `a`, `b`, ... `z`, `aa`. lower_alpha, upper_alpha, /// `i`, `ii`, `iii`, `iv`. lower_roman, upper_roman,};
/// One token of a `format` attribute: the separator that precedes a number and/// the numeral system that number is written in.pub const FormatToken = struct { separator: []const u8, numeral: Numeral, width: usize = 1, /// The digit family a decimal numeral is written in: the code point of /// that family's zero. `format="١"` numbers in Arabic-Indic digits. zero: u21 = '0',};
/// Splits a `format` attribute into its alternating separators and numeral/// tokens.////// `format="(1.1)"` is "(" then `1`, then "." then `1`, then ")" at the end./// The last separator belongs after the final number, so it comes back/// separately.pub fn parseFormat(gpa: Allocator, src: []const u8) Allocator.Error!struct { tokens: []FormatToken, trailer: []const u8,} { var tokens: std.ArrayList(FormatToken) = .empty; errdefer tokens.deinit(gpa);
var i: usize = 0; var separator_start: usize = 0; while (i < src.len) { const first = decodeAt(src, i); if (!isTokenCharacter(first.value)) { i += first.len; continue; } const token_start = i; var count: usize = 0; while (i < src.len) { const cp = decodeAt(src, i); if (!isTokenCharacter(cp.value)) break; i += cp.len; count += 1; } const token = src[token_start..i]; try tokens.append(gpa, .{ .separator = src[separator_start..token_start], .numeral = numeralOf(token), .width = count, .zero = digitFamily(first.value) orelse '0', }); separator_start = i; }
if (tokens.items.len == 0) { // A format with no numeral token at all still has to number something. try tokens.append(gpa, .{ .separator = src, .numeral = .arabic }); return .{ .tokens = try tokens.toOwnedSlice(gpa), .trailer = "" }; } return .{ .tokens = try tokens.toOwnedSlice(gpa), .trailer = src[separator_start..], };}
/// The zeroes of the decimal digit families a format token may be written in.////// XSLT 7.7.1 says a format token that is a digit with numeric value one/// numbers in that digit's family, and libxslt's list of families is this one./// Tamil is missing from it because Tamil historically had no zero, and a/// family with no zero cannot pad.const digit_zeroes = [_]u21{ '0', 0x0660, 0x06F0, 0x0966, 0x09E6, 0x0A66, 0x0AE6, 0x0B66, 0x0C66, 0x0CE6, 0x0D66, 0x0E50, 0x0ED0, 0x0F20,};
/// The zero of the family a code point is a decimal digit of, if it is one.fn digitFamily(cp: u21) ?u21 { for (digit_zeroes) |zero| { if (cp >= zero and cp <= zero + 9) return zero; } return null;}
/// Whether a code point belongs to a format token rather than to the separator/// between two of them. ASCII letters and digits, plus the digits of every/// family a numeral may be written in.fn isTokenCharacter(cp: u21) bool { if (cp < 0x80) return std.ascii.isAlphanumeric(@intCast(cp)); return digitFamily(cp) != null;}
/// One character of `src` at `i`: its code point, and how many bytes it took.////// A byte that does not begin a whole, well-formed sequence stands for itself/// and takes one byte. Finding that out is the delicate part, because/// `std.unicode.utf8Decode` must not be handed a *clamped* slice: it dispatches/// on the length it is given and then asserts the lead byte agrees, so a/// four-byte lead with two bytes left behind it panics rather than failing./// Its own doc comment calls the API too easy to use incorrectly; this is how.const Character = struct { value: u21, len: usize };
fn decodeAt(src: []const u8, i: usize) Character { const single: Character = .{ .value = src[i], .len = 1 }; const len = std.unicode.utf8ByteSequenceLength(src[i]) catch return single; if (i + len > src.len) return single; const value = std.unicode.utf8Decode(src[i .. i + len]) catch return single; return .{ .value = value, .len = len };}
fn numeralOf(token: []const u8) Numeral { if (token.len == 0) return .arabic; if (std.mem.eql(u8, token, "i")) return .lower_roman; if (std.mem.eql(u8, token, "I")) return .upper_roman; if (std.mem.eql(u8, token, "a")) return .lower_alpha; if (std.mem.eql(u8, token, "A")) return .upper_alpha; // A token of digits whose first is that family's zero pads to its width: // `01` is 01 02 ... 10, and so is the same pair of Arabic-Indic digits. const first = decodeAt(token, 0); if (digitFamily(first.value)) |zero| { if (first.value == zero) return .padded; } return .arabic;}
/// How `xsl:number` groups the digits of a decimal numeral.////// Only decimal numerals are grouped: a separator in the middle of `MCMXCIV`/// would not mean anything.pub const Grouping = struct { separator: []const u8, /// Digits between separators. Never zero -- a caller that has no grouping /// passes null instead. size: usize,};
/// Writes one number in one numeral system.pub fn appendNumeral( gpa: Allocator, out: *std.ArrayList(u8), n: i64, token: FormatToken, grouping: ?Grouping,) Allocator.Error!void { // Nothing below one has a representation in the alphabetic or roman // systems, so those fall back to plain digits. The decimal ones do not // need to: `format="001"` writes zero as `000`, keeping the width the // token asked for. if (n < 1 and token.numeral != .arabic and token.numeral != .padded) { try out.print(gpa, "{d}", .{n}); return; } switch (token.numeral) { .arabic => try appendGrouped(gpa, out, n, 0, grouping, token.zero), .padded => { // Padded by hand rather than with a format specifier: the width // comes from how the token was written, and a runtime width in a // format string is more machinery than a loop. try appendGrouped(gpa, out, n, token.width, grouping, token.zero); }, .lower_alpha => try appendAlpha(gpa, out, n, 'a'), .upper_alpha => try appendAlpha(gpa, out, n, 'A'), .lower_roman => try appendRoman(gpa, out, n, false), .upper_roman => try appendRoman(gpa, out, n, true), }}
/// Writes a decimal numeral, zero-padded to `width` and with separators every/// `grouping.size` digits counted from the right.////// A grouping size larger than the number has digits simply produces no/// separator, which is what makes `grouping-size="99"` need no special case.fn appendGrouped( gpa: Allocator, out: *std.ArrayList(u8), n: i64, width: usize, grouping: ?Grouping, zero: u21,) Allocator.Error!void { var digits: [24]u8 = undefined; const rendered = std.fmt.bufPrint(&digits, "{d}", .{n}) catch unreachable;
var padding: usize = 0; if (rendered.len < width) padding = width - rendered.len; const total = padding + rendered.len;
var written: usize = 0; for (0..total) |i| { if (grouping) |g| { // A separator goes before a digit whenever the digits still to // come are a multiple of the group size. if (written != 0 and (total - i) % g.size == 0) { try out.appendSlice(gpa, g.separator); } } const digit: u8 = if (i < padding) '0' else rendered[i - padding]; if (zero == '0' or digit < '0' or digit > '9') { try out.append(gpa, digit); } else { try appendCodepoint(gpa, out, zero + (digit - '0')); } written += 1; }}
/// `a`..`z`, then `aa`..`az`, `ba`.. -- bijective base 26, which is why 26 is/// `z` and 27 is `aa` rather than `ba`.fn appendAlpha(gpa: Allocator, out: *std.ArrayList(u8), n: i64, base: u8) Allocator.Error!void { var buf: [16]u8 = undefined; var len: usize = 0; var v = n; while (v > 0 and len < buf.len) { const rem: u8 = @intCast(@mod(v - 1, 26)); buf[len] = base + rem; len += 1; v = @divFloor(v - 1, 26); } var i = len; while (i > 0) { i -= 1; try out.append(gpa, buf[i]); }}
fn appendRoman(gpa: Allocator, out: *std.ArrayList(u8), n: i64, upper: bool) Allocator.Error!void { const values = [_]i64{ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; const upper_symbols = [_][]const u8{ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; const lower_symbols = [_][]const u8{ "m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv", "i" };
// Beyond a few thousand the notation stops being useful and the // specification does not define one, so it falls back to digits. if (n > 4999) { try out.print(gpa, "{d}", .{n}); return; } var v = n; for (values, 0..) |value, i| { while (v >= value) { try out.appendSlice(gpa, if (upper) upper_symbols[i] else lower_symbols[i]); v -= value; } }}
// -- codepoint helpers -------------------------------------------------------
const CodepointIterator = struct { src: []const u8, pos: usize = 0,
const Item = struct { value: u21, start: usize, len: usize };
fn next(it: *CodepointIterator) ?Item { if (it.pos >= it.src.len) return null; const start = it.pos; const c = decodeAt(it.src, start); it.pos = start + c.len; return .{ .value = c.value, .start = start, .len = c.len }; }};
fn codepointLength(cp: u21) usize { return std.unicode.utf8CodepointSequenceLength(cp) catch 1;}
fn containsCodepoint(s: []const u8, cp: u21) bool { return indexOfCodepoint(s, cp) != null;}
fn indexOfCodepoint(s: []const u8, cp: u21) ?usize { var it = CodepointIterator{ .src = s }; while (it.next()) |item| { if (item.value == cp) return item.start; } return null;}
fn lastIndexOfCodepoint(s: []const u8, cp: u21) ?usize { var found: ?usize = null; var it = CodepointIterator{ .src = s }; while (it.next()) |item| { if (item.value == cp) found = item.start; } return found;}
fn countCodepoint(s: []const u8, cp: u21) usize { var count: usize = 0; var it = CodepointIterator{ .src = s }; while (it.next()) |item| { if (item.value == cp) count += 1; } return count;}
fn appendCodepoint(gpa: Allocator, out: *std.ArrayList(u8), cp: u21) Allocator.Error!void { var buf: [4]u8 = undefined; const len = std.unicode.utf8Encode(cp, &buf) catch { try out.append(gpa, '?'); return; }; try out.appendSlice(gpa, buf[0..len]);}
fn appendCodepointN(gpa: Allocator, out: *std.ArrayList(u8), cp: u21, n: usize) Allocator.Error!void { for (0..n) |_| try appendCodepoint(gpa, out, cp);}
// -- tests -------------------------------------------------------------------
const testing = std.testing;
fn expectFormat(expected: []const u8, n: f64, picture: []const u8) !void { const got = try formatNumber(testing.allocator, n, picture, .{}); defer testing.allocator.free(got); testing.expectEqualStrings(expected, got) catch |err| { std.debug.print("format-number({d}, '{s}')\n", .{ n, picture }); return err; };}
test "format-number reads a picture string" { try expectFormat("1234", 1234, "#"); try expectFormat("1,234", 1234, "#,###"); try expectFormat("1,234,567", 1234567, "#,###"); try expectFormat("1234.00", 1234, "0.00"); try expectFormat("1234.5", 1234.5, "#.##"); try expectFormat("1234.57", 1234.567, "#.##"); try expectFormat("0.5", 0.5, "0.0"); // A `#` before the point is padding, not permission to omit the digit. try expectFormat("0.5", 0.5, "#.#"); try expectFormat("007", 7, "000"); try expectFormat("50%", 0.5, "#%"); try expectFormat("-5", -5, "#"); // A negative subpicture replaces the minus sign entirely. try expectFormat("(5)", -5, "#;(#)"); try expectFormat("5", 5, "#;(#)"); try expectFormat("0", 0, "#"); try expectFormat("NaN", std.math.nan(f64), "#"); try expectFormat("Infinity", std.math.inf(f64), "#"); try expectFormat("-Infinity", -std.math.inf(f64), "#");}
test "format-number honours a decimal format's own characters" { const german: DecimalFormat = .{ .decimal_separator = ',', .grouping_separator = '.' }; const got = try formatNumber(testing.allocator, 1234.5, "#.##0,00", german); defer testing.allocator.free(got); try testing.expectEqualStrings("1.234,50", got);}
test "a picture with no digit positions is refused" { try testing.expectError( error.InvalidPicture, formatNumber(testing.allocator, 1, "abc", .{}), );}
fn expectNumeral(expected: []const u8, n: i64, token: FormatToken) !void { var out: std.ArrayList(u8) = .empty; defer out.deinit(testing.allocator); try appendNumeral(testing.allocator, &out, n, token, null); try testing.expectEqualStrings(expected, out.items);}
fn expectGrouped(expected: []const u8, n: i64, separator: []const u8, size: usize) !void { var out: std.ArrayList(u8) = .empty; defer out.deinit(testing.allocator); try appendNumeral(testing.allocator, &out, n, .{ .separator = "", .numeral = .arabic }, .{ .separator = separator, .size = size, }); try testing.expectEqualStrings(expected, out.items);}
test "xsl:number groups digits from the right" { try expectGrouped("1.234.567.890", 1234567890, ".", 3); try expectGrouped("1\u{2019}234\u{2019}567\u{2019}890", 1234567890, "\u{2019}", 3); try expectGrouped("1.2.3.4.5.6.7.8.9.0", 1234567890, ".", 1); // Larger than the number has digits, so nothing is inserted -- which is // why `grouping-size="99"` needs no special case. try expectGrouped("1234567890", 1234567890, ".", 99); try expectGrouped("123", 123, ",", 3); try expectGrouped("1,234", 1234, ",", 3);}
test "the numeral systems xsl:number can write" { try expectNumeral("7", 7, .{ .separator = "", .numeral = .arabic }); try expectNumeral("007", 7, .{ .separator = "", .numeral = .padded, .width = 3 }); try expectNumeral("g", 7, .{ .separator = "", .numeral = .lower_alpha }); try expectNumeral("z", 26, .{ .separator = "", .numeral = .lower_alpha }); // Bijective, so 27 is `aa` and not `ba`. try expectNumeral("aa", 27, .{ .separator = "", .numeral = .lower_alpha }); try expectNumeral("AB", 28, .{ .separator = "", .numeral = .upper_alpha }); try expectNumeral("iv", 4, .{ .separator = "", .numeral = .lower_roman }); try expectNumeral("MCMXCIV", 1994, .{ .separator = "", .numeral = .upper_roman });}
test "a picture of malformed bytes is refused rather than decoded" { // A lead byte announcing more bytes than are there is the trap here: // `std.unicode.utf8Decode` dispatches on the length it is handed and then // asserts the lead byte agrees, so a clamped slice panics rather than // failing. Such a byte stands for itself. const gpa = testing.allocator; for ([_][]const u8{ "\xf0", "\xf0\x9f", "\xf0\x9f\x91", "0\xf0", "\xf00", "\xc2", "\xed\xa0\x80", "\xff#", "#\xf4\x90\x80\x80", }) |picture| { if (formatNumber(gpa, 1.5, picture, .{})) |out| { gpa.free(out); } else |err| { try testing.expectEqual(error.InvalidPicture, err); } }}
test "a format token may name a digit family other than ASCII" { const gpa = testing.allocator; { // Arabic-Indic zero then one: two digits wide, zero-padded, and // written in that family. const parsed = try parseFormat(gpa, "\u{0660}\u{0661}"); defer gpa.free(parsed.tokens); try testing.expectEqual(@as(usize, 1), parsed.tokens.len); try testing.expectEqual(Numeral.padded, parsed.tokens[0].numeral); try testing.expectEqual(@as(usize, 2), parsed.tokens[0].width); try expectNumeral("\u{0660}\u{0669}", 9, parsed.tokens[0]); try expectNumeral( "\u{0661}\u{0662}\u{0663}\u{0664}\u{0665}\u{0666}\u{0667}\u{0668}\u{0669}\u{0660}", 1234567890, parsed.tokens[0], ); } { // A single digit of value one is the unpadded sequence in its family. const parsed = try parseFormat(gpa, "\u{0967}"); defer gpa.free(parsed.tokens); try testing.expectEqual(Numeral.arabic, parsed.tokens[0].numeral); try expectNumeral("\u{0967}\u{0966}", 10, parsed.tokens[0]); } { // A character that is neither a letter nor a digit of a family this // knows is a separator, as it always was. const parsed = try parseFormat(gpa, "\u{2014}1\u{2014}"); defer gpa.free(parsed.tokens); try testing.expectEqual(@as(usize, 1), parsed.tokens.len); try testing.expectEqualStrings("\u{2014}", parsed.tokens[0].separator); try testing.expectEqualStrings("\u{2014}", parsed.trailer); }}
test "a format attribute splits into separators and tokens" { const gpa = testing.allocator; { const parsed = try parseFormat(gpa, "(1.1)"); defer gpa.free(parsed.tokens); try testing.expectEqual(@as(usize, 2), parsed.tokens.len); try testing.expectEqualStrings("(", parsed.tokens[0].separator); try testing.expectEqualStrings(".", parsed.tokens[1].separator); try testing.expectEqualStrings(")", parsed.trailer); } { const parsed = try parseFormat(gpa, "1"); defer gpa.free(parsed.tokens); try testing.expectEqual(@as(usize, 1), parsed.tokens.len); try testing.expectEqualStrings("", parsed.tokens[0].separator); try testing.expectEqual(Numeral.arabic, parsed.tokens[0].numeral); } { const parsed = try parseFormat(gpa, "A. "); defer gpa.free(parsed.tokens); try testing.expectEqual(Numeral.upper_alpha, parsed.tokens[0].numeral); try testing.expectEqualStrings(". ", parsed.trailer); }}