Something went wrong. Try again.
Classic Unix mailbox files for Zig 0.16: an iterator to read, a predicate to delete, an atomic rewrite for every change.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Which mbox this is, and the quoting that follows from it.//!//! An mbox has no length field and no checksum. A message ends where the next//! one begins, and the only mark of a beginning is a line starting `From `.//! So a body that contains such a line is a body that can split its own//! message in two, and every mbox in the world does something about that.//!//! What it does is the variant, and the four of them are not compatible. The//! difference matters more than it looks: reading an `mboxo` mailbox as//! `mboxrd` corrupts every body that contains a quoted `From `, and reading an//! `mboxrd` one as `mboxo` does the same. Nothing in the file says which it//! is, which is why this is a parameter and not a detection.
const std = @import("std");const Io = std.Io;const testing = std.testing;
/// How a mailbox keeps a body from splitting its own message.pub const Variant = enum { /// A body line beginning `From ` is stored as `>From `. /// /// Undoing it is lossy, and unavoidably so: a line the sender wrote as /// `>From ` and a line this quoted are the same bytes on disk, so reading /// gives back one of them and there is no way to know which. The oldest /// and still the commonest, because it is what a plain `mail(1)` writes. mboxo,
/// A body line matching `>*From ` — any number of `>`, including none — /// gains one more `>`. /// /// The extra `>` on lines that already had one is the whole difference: /// it makes the transformation a bijection, so read-then-write returns /// the bytes that went in. The only variant for which that is true, and /// the reason it is the default here. mboxrd,
/// `mboxo`'s quoting, plus a `Content-Length` header giving the body's /// length so a reader need not scan for the next postmark. mboxcl,
/// `Content-Length` alone. Bodies are stored exactly as written, which is /// the point: nothing is quoted, so nothing has to be unquoted, and the /// message that comes back is the message that went in. /// /// The cost is that the length is now load-bearing. A mailbox whose /// lengths are wrong cannot be read at all without falling back to /// scanning, and scanning an unquoted mailbox splits messages on their own /// bodies. See `Reader` for what is done about that. mboxcl2,
/// Whether bodies are rewritten on the way in and out. pub fn quotes(self: Variant) bool { return self != .mboxcl2; }
/// Whether `unquoteInPlace` undoes `writeQuoted` exactly, for every input. /// /// True for `mboxrd`, which quotes reversibly, and for `mboxcl2`, which /// does not quote at all. False for the two that turn `From ` and `>From ` /// into the same bytes. pub fn reversible(self: Variant) bool { return self == .mboxrd or self == .mboxcl2; }
/// Whether a `Content-Length` header is written, and trusted on the way /// back in once it has been checked against where the next postmark /// actually is. pub fn usesContentLength(self: Variant) bool { return self == .mboxcl or self == .mboxcl2; }};
/// The header `mboxcl` and `mboxcl2` carry the body's length in.pub const content_length_header = "Content-Length";
/// Whether a line, as stored, would be taken for the start of a message.////// Deliberately the loosest test that is still a test — the line begins/// `From ` — because this is what a *quoter* must avoid producing, and it has/// to avoid producing anything that any reader might split on, not merely/// what `From.parse` would accept. Quoting to the strictest reader and being/// read by the loosest is how a message ends up in two pieces.pub fn looksLikeBoundary(line: []const u8) bool { return std.mem.startsWith(u8, line, "From ");}
/// How many `>` characters `line` begins with.fn angleRun(line: []const u8) usize { var i: usize = 0; while (i < line.len and line[i] == '>') i += 1; return i;}
/// Whether storing `line` under `variant` needs a `>` put in front of it.fn needsQuote(line: []const u8, variant: Variant) bool { return switch (variant) { .mboxcl2 => false, .mboxo, .mboxcl => looksLikeBoundary(line), .mboxrd => looksLikeBoundary(line[angleRun(line)..]), };}
/// Whether reading `line` back under `variant` takes a `>` off the front.fn hasQuote(line: []const u8, variant: Variant) bool { const angles = angleRun(line); return switch (variant) { .mboxcl2 => false, // Exactly one `>`, because that is all this variant ever adds; a line // with two came that way and keeps both. .mboxo, .mboxcl => angles == 1 and looksLikeBoundary(line[1..]), .mboxrd => angles >= 1 and looksLikeBoundary(line[angles..]), };}
/// The lines of a message, each including its terminator. The last has one/// only if the message ended with one.const Lines = struct { rest: []const u8,
fn next(self: *Lines) ?[]const u8 { if (self.rest.len == 0) return null; const end = if (std.mem.findScalar(u8, self.rest, '\n')) |i| i + 1 else self.rest.len; const line = self.rest[0..end]; self.rest = self.rest[end..]; return line; }};
/// How many bytes `writeQuoted` will write for `message`.////// Computed before the buffer is allocated, so being wrong about it is a/// bounds failure rather than a wrong answer.pub fn quotedLen(message: []const u8, variant: Variant) usize { if (!variant.quotes()) return message.len; var total = message.len; var lines: Lines = .{ .rest = message }; while (lines.next()) |line| { if (needsQuote(line, variant)) total += 1; } return total;}
/// Writes `message` as it is stored in a mailbox of this variant.pub fn writeQuoted(w: *Io.Writer, message: []const u8, variant: Variant) Io.Writer.Error!void { if (!variant.quotes()) return w.writeAll(message); var lines: Lines = .{ .rest = message }; while (lines.next()) |line| { if (needsQuote(line, variant)) try w.writeByte('>'); try w.writeAll(line); }}
/// Undoes the quoting, in place, returning the shortened slice.////// In place because it only ever removes bytes, never adds them, so the/// scanner can hand it the buffer it just filled rather than paying for a/// second one the size of the message.pub fn unquoteInPlace(message: []u8, variant: Variant) []u8 { if (!variant.quotes()) return message; var read: usize = 0; var write: usize = 0; while (read < message.len) { const end = if (std.mem.findScalarPos(u8, message, read, '\n')) |i| i + 1 else message.len; const line = message[read..end]; const skip: usize = if (hasQuote(line, variant)) 1 else 0; // `write <= read` always, so this never overwrites a byte it has yet // to read, and `copyForwards` is what a possibly-overlapping move of // this direction needs. std.mem.copyForwards(u8, message[write .. write + line.len - skip], line[skip..]); write += line.len - skip; read = end; } return message[0..write];}
// -- tests -------------------------------------------------------------------
fn expectQuoted(variant: Variant, plain: []const u8, stored: []const u8) !void { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try writeQuoted(&w, plain, variant); try testing.expectEqualStrings(stored, w.buffered()); try testing.expectEqual(stored.len, quotedLen(plain, variant));
var scratch: [512]u8 = undefined; @memcpy(scratch[0..stored.len], stored); const back = unquoteInPlace(scratch[0..stored.len], variant); if (variant.reversible()) try testing.expectEqualStrings(plain, back);}
test "mboxrd quotes every run of angle brackets, which is what makes it reversible" { try expectQuoted(.mboxrd, "From here\n", ">From here\n"); try expectQuoted(.mboxrd, ">From here\n", ">>From here\n"); try expectQuoted(.mboxrd, ">>>From here\n", ">>>>From here\n"); try expectQuoted(.mboxrd, "Not from here\n", "Not from here\n"); // `From` without the trailing space is not a boundary and is left alone. try expectQuoted(.mboxrd, "Fromage\n", "Fromage\n");}
test "mboxo quotes only a bare From, which is why it cannot be undone" { try expectQuoted(.mboxo, "From here\n", ">From here\n"); try expectQuoted(.mboxo, ">From here\n", ">From here\n"); // Both of the above stored the same bytes, so reading them back gives one // answer for two different messages. That is the lossiness, made explicit. var scratch = ">From here\n".*; try testing.expectEqualStrings("From here\n", unquoteInPlace(&scratch, .mboxo)); try testing.expect(!Variant.mboxo.reversible());}
test "mboxcl2 stores the body exactly as written" { try expectQuoted(.mboxcl2, "From here\n>From there\n", "From here\n>From there\n"); try testing.expect(Variant.mboxcl2.reversible());}
test "a message whose last line has no terminator keeps not having one" { try expectQuoted(.mboxrd, "From here", ">From here"); try expectQuoted(.mboxrd, "body\nFrom here", "body\n>From here");}
test "the empty message quotes to nothing" { try expectQuoted(.mboxrd, "", ""); try testing.expectEqual(@as(usize, 0), quotedLen("", .mboxrd));}