// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The little that this library does about charsets, and why it is little. //! //! Mail names its charsets — in a `Content-Type`, in an RFC 2047 encoded word, //! in an RFC 2231 parameter — and the set of names is open. Handling them //! properly means the IANA registry and a few hundred kilobytes of mapping //! tables, which is a real library and a dependency, and which belongs beside //! whatever a program already uses for text rather than buried inside its mail //! parser. So this library reports the charset and hands over the bytes, and //! the caller converts. //! //! What is here is the part that needs no tables at all: //! //! * **UTF-8** and **US-ASCII** are already the answer. //! * **ISO-8859-1** is the answer too, in a sense that no other charset shares: //! its 256 bytes are exactly the first 256 Unicode code points, so //! converting it is `utf8Encode` in a loop and not a table. //! //! Anything else is passed through with invalid UTF-8 sequences replaced by //! U+FFFD, which is not a conversion and does not pretend to be. It exists so //! that `textAlloc` always returns something a UTF-8 consumer can hold: a //! Shift-JIS body comes back as mojibake, which is what a reader without a //! Shift-JIS table can honestly show, rather than as an error that makes the //! whole message unopenable. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; /// How a charset name will be treated. Ask before converting if the difference /// matters — a program with a transcoder of its own wants `.foreign` to be its /// own business. pub const Kind = enum { /// UTF-8 or US-ASCII: the bytes are already UTF-8, or are meant to be. utf8, /// ISO-8859-1 and its aliases: every byte is its own code point. latin1, /// Everything else. Converting it here is lossy; see the module comment. foreign, }; pub fn kind(charset: []const u8) Kind { const utf8_names = [_][]const u8{ "utf-8", "utf8", "us-ascii", "ascii", "iso-ir-6", "ansi_x3.4-1968" }; for (utf8_names) |name| if (std.ascii.eqlIgnoreCase(charset, name)) return .utf8; const latin1_names = [_][]const u8{ "iso-8859-1", "iso8859-1", "iso_8859-1", "latin-1", "latin1", "l1", "cp819" }; for (latin1_names) |name| if (std.ascii.eqlIgnoreCase(charset, name)) return .latin1; return .foreign; } /// Writes `bytes`, which are in `charset`, as UTF-8. pub fn toUtf8Writer(w: *Io.Writer, bytes: []const u8, charset: []const u8) Io.Writer.Error!void { switch (kind(charset)) { .utf8, .foreign => return writeValidUtf8(w, bytes), .latin1 => { for (bytes) |c| { var buffer: [4]u8 = undefined; const n = std.unicode.utf8Encode(c, &buffer) catch unreachable; try w.writeAll(buffer[0..n]); } }, } } pub fn toUtf8Alloc(gpa: Allocator, bytes: []const u8, charset: []const u8) Allocator.Error![]u8 { // The common case by a wide margin: already UTF-8 and already valid. if (kind(charset) != .latin1 and std.unicode.utf8ValidateSlice(bytes)) return gpa.dupe(u8, bytes); var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); toUtf8Writer(&out.writer, bytes, charset) catch return error.OutOfMemory; return out.toOwnedSlice(); } /// Writes `text` with every byte that is not part of a well-formed UTF-8 /// sequence replaced by U+FFFD, so that what comes out can be handed to /// anything that expects UTF-8. pub fn writeValidUtf8(w: *Io.Writer, text: []const u8) Io.Writer.Error!void { var i: usize = 0; while (i < text.len) { const len = std.unicode.utf8ByteSequenceLength(text[i]) catch { try w.writeAll("\u{fffd}"); i += 1; continue; }; if (i + len > text.len or !std.unicode.utf8ValidateSlice(text[i..][0..len])) { try w.writeAll("\u{fffd}"); i += 1; continue; } try w.writeAll(text[i..][0..len]); i += len; } } test kind { try testing.expectEqual(Kind.utf8, kind("UTF-8")); try testing.expectEqual(Kind.utf8, kind("us-ascii")); try testing.expectEqual(Kind.latin1, kind("ISO-8859-1")); try testing.expectEqual(Kind.foreign, kind("shift_jis")); try testing.expectEqual(Kind.foreign, kind("iso-8859-15")); // Close, and not the same. } test toUtf8Alloc { const latin1 = try toUtf8Alloc(testing.allocator, "caf\xe9", "iso-8859-1"); defer testing.allocator.free(latin1); try testing.expectEqualStrings("café", latin1); const already = try toUtf8Alloc(testing.allocator, "café", "utf-8"); defer testing.allocator.free(already); try testing.expectEqualStrings("café", already); const foreign = try toUtf8Alloc(testing.allocator, "\x82\xa0\x82\xa2", "shift_jis"); defer testing.allocator.free(foreign); try testing.expect(std.unicode.utf8ValidateSlice(foreign)); }