@@ 14,7 14,10 @@ fn escapeAndLower(s: []const u8, allocator: mem.Allocator) !util.CharBuffer {
return EscapeError.TerminalPeriod;
}
- var escaped = try util.CharBuffer.initCapacity(allocator, s.len * 2);
+ // Initialize double the length of `s`, covering the pessimal case where
+ // every character of `s` needs escaping.
+ const total_capacity = s.len * 2;
+ var escaped = try util.CharBuffer.initCapacity(allocator, total_capacity);
for (s) |char| {
switch (char) {
@@ 26,6 29,8 @@ fn escapeAndLower(s: []const u8, allocator: mem.Allocator) !util.CharBuffer {
const lower_char = std.ascii.toLower(char);
escaped.appendAssumeCapacity(lower_char);
}
+ // Free the extra head room allocated for unneeded escape chars.
+ escaped.shrinkAndFree(escaped.items.len);
return escaped;
}