Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

swap

Exchanges contents of two memory locations.

mem.swap
pub fn swap(comptime T: type, noalias a: *T, noalias b: *T) void

File

lib/std/mem.zig:3851

Code

pub fn swap(comptime T: type, noalias a: *T, noalias b: *T) void {
    if (@inComptime()) {
        // In comptime, accessing bytes of values with no defined layout is a compile error.
        const tmp = a.*;
        a.* = b.*;
        b.* = tmp;
    } else {
        // Swapping in streaming nature from start to end instead of swapping
        // everything in one step allows easier optimizations and less stack usage.
        const a_bytes: []align(@alignOf(T)) u8 = @ptrCast(a);
        const b_bytes: []align(@alignOf(T)) u8 = @ptrCast(b);
        for (a_bytes, b_bytes) |*ab, *bb| {
            const tmp = ab.*;
            ab.* = bb.*;
            bb.* = tmp;
        }
    }
}