Skip to content

Instantly share code, notes, and snippets.

@giann
Last active March 20, 2021 03:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giann/a107e584a25e7391d44c2fbfc63a76b1 to your computer and use it in GitHub Desktop.
Save giann/a107e584a25e7391d44c2fbfc63a76b1 to your computer and use it in GitHub Desktop.
Wrap text to fit into given width
const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
const Allocator = std.mem.Allocator;
const Buffer = std.Buffer;
pub fn wrap(allocator: *Allocator, string: []const u8, width: usize) ![]u8 {
assert(width > 3);
var justified = try Buffer.initSize(allocator, string.len);
var leftover: []const u8 = string[0..];
while (leftover.len > 0) {
const trimmed = mem.trim(u8, leftover, " ");
if (trimmed.len > width) {
if (mem.lastIndexOfScalar(u8, trimmed[0..(width - 1)], ' ')) |last_whitespace_index| {
try justified.append(trimmed[0..last_whitespace_index]);
leftover = trimmed[last_whitespace_index..];
} else {
// If no whitespace before eol, let the line as-is (should not happen)
try justified.append(trimmed);
leftover = trimmed[trimmed.len..];
}
} else {
try justified.append(trimmed);
leftover = trimmed[trimmed.len..];
}
if (leftover.len > 0)
try justified.append("\n");
}
return justified.toOwnedSlice();
}
test "wrap text" {
std.debug.warn("\n{}\n",
try wrap(
std.debug.global_allocator,
("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.")[0..],
50
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment