std.compress.lzma2: optimize appendLz

make the hot loop be a for loop without any failures or allocation.
change a O(N) addition into O(1)
This commit is contained in:
Andrew Kelley 2025-09-02 12:00:43 -07:00
parent 00b0beb682
commit 90ac62cc75

View file

@ -79,23 +79,18 @@ pub const AccumBuffer = struct {
_ = writer; _ = writer;
const buf_len = self.buf.items.len; const buf_len = self.buf.items.len;
if (dist > buf_len) { if (dist > buf_len) return error.CorruptInput;
return error.CorruptInput;
}
// ensure we have enough capacity for all new bytes. try self.buf.ensureUnusedCapacity(allocator, len);
// This prevents the buffer's memory from being reallocated (and freed) const buffer = self.buf.allocatedSlice();
// while we are still reading from it. const src = buffer[buf_len - dist ..][0..len];
try self.buf.ensureTotalCapacity(allocator, buf_len + len); const dst = buffer[buf_len..][0..len];
var offset = buf_len - dist; // This is not a @memmove; it intentionally repeats patterns caused by
var i: usize = 0; // iterating one byte at a time.
while (i < len) : (i += 1) { for (dst, src) |*d, s| d.* = s;
const x = self.buf.items[offset];
// Since capacity is guaranteed, it's safe to use appendAssumeCapacity. self.buf.items.len = buf_len + len;
self.buf.appendAssumeCapacity(x);
offset += 1;
}
self.len += len; self.len += len;
} }