Porting handwritten JavaScript to Zig: Native Messaging host

You could do it like this:

const writePart = struct {
    fn f(write: *std.Io.Writer, send: []const u8, prepend: ?u8, append: ?u8) !void {
        var length: usize = send.len;
        if (prepend != null) {
            length += 1;
        }
        if (append != null) {
            length += 1;
        }
        
        try write.writeInt(u32, @intCast(length), .native);
        
        if (prepend) |char| {
            try write.writeByte(char);
        }
        try write.writeAll(send);
        if (append) |char| {
            try write.writeByte(char);
        }
    }
}.f;

if (start == '[' and end != ',' and end != ']') {
    try writePart(writer, part, null, ']');
} else if (start == ',' and end != ']') {
    try writePart(writer, part[1..], '[', ']');
} else if (start == ',' and end == ']') {
    try writePart(writer, part[1..], '[', null);
} else {
    try writePart(writer, part, null, null);
}

But you could also restructure the function so it doesn’t need the helper function:

const i = std.mem.findScalarPos(u8, message, from_index, ',') orelse message.len;
var part = message[index .. i];
index = i;
from_index += 1024 * 1024 - 8;

const start = part[0];
const end = part[part.len - 1];

var append: ?u8 = null;
var prepend: ?u8 = null;

if (start == '[' and end != ',' and end != ']') {
    append = ']';
} else if (start == ',' and end != ']') {
    part = part[1..];
    prepend = '[';
    append = ']';
} else if (start == ',' and end == ']') {
    part = part[1..];
    prepend = '[';
}

var length: usize = part.len;
if (prepend != null) {
    length += 1;
}
if (append != null) {
    length += 1;
}

try writer.writeInt(u32, @intCast(length), .native);

if (prepend) |char| {
    try writer.writeByte(char);
}
try writer.writeAll(part);
if (append) |char| {
    try writer.writeByte(char);
}
1 Like