Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/std/mem/Allocator.zig
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,16 @@ pub fn allocSentinel(
return self.allocWithOptionsRetAddr(Elem, n, null, sentinel, @returnAddress());
}

/// Allocates with an alignment which is incorporated into the returned type.
/// Call `free` when done.
///
/// Prefer inferred types like `const data = alignedAlloc(...)` as it will use
/// the correctly aligned type.
///
/// Avoid explicit types like `const data: u8[] = alignedAlloc(...)` as they
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[]u8 would be the correct type here, u8[] is invalid.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, sorry, I didn't actually pull the latest version of the comment into this branch. Please take a look again, it has been rewritten.

/// can change the alignment type information needed when calling `free`.
///
/// If alignment is not comptime known use `rawAlloc` and `rawFree`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it is runtime known you would use an alignment of 1, not the raw methods.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed this part as it's inconsistent with other advice in this file to not use rawAlloc and rawFree althgouh right now the API does not allow specifying alignment at runtime.

There are cases when you want to request your data to be specifically aligned (beyond alignment = 1) but you don't know the exact alignment until runtime. The case I'm hitting against is manipulating bit-matrices and aligning them for cache-lines and simd widths but also not wasting space for small matrices (typically values range between 10 to >1024 bits).

pub fn alignedAlloc(
self: Allocator,
comptime T: type,
Expand Down Expand Up @@ -432,7 +442,7 @@ pub fn reallocAdvanced(
return mem.bytesAsSlice(T, new_bytes);
}

/// Free an array allocated with `alloc`.
/// Free an array allocated with `alloc` or `alignedAlloc`.
/// If memory has length 0, free is a no-op.
/// To free a single item, see `destroy`.
pub fn free(self: Allocator, memory: anytype) void {
Expand Down