Skip to content

implement @memcpy and @memset for tuples #15479

Open

Description

@andrewrk

Extracted from #15278.

This test should pass:

const std = @import("std");
const expect = std.testing.expect;

test "memset a tuple" {
    var t: struct { i32, i32 } = .{ 12, 34 };
    @memset(&t, [_]i32{ 56, 78 });
    try expect(t[0] == 56);
    try expect(t[1] == 78);
}

test "memcpy a tuple" {
    var t1: struct { i32, i32 } = .{ 12, 34 };
    var t2: struct { i32, i32 } = .{ 56, 78 };
    @memset(&t1, &t2);
    try expect(t1[0] == 56);
    try expect(t1[1] == 78);
}

Instead, this happens:

$ stage4/bin/zig test test.zig 
test.zig:6:13: error: type '*test.test.memset a tuple__struct_1040' does not support indexing
    @memset(&t, [_]i32{ 56, 78 });
            ^~
test.zig:6:13: note: for loop operand must be an array, slice, tuple, or vector
test.zig:14:13: error: type '*test.test.memcpy a tuple__struct_1041' does not support indexing
    @memset(&t1, &t2);
            ^~~
test.zig:14:13: note: for loop operand must be an array, slice, tuple, or vector

Activity

  1. added
    bug
    enhancement
    frontend
    on Apr 26, 2023
  2. added this to the 0.12.0 milestone on Apr 26, 2023
  3. InKryption commented on Apr 26, 2023

    @InKryption
    Contributor

    What's the use case behind this? Why would one opt for the builtins when we can already do foo = bar and foo = .{ 12, 14 }, bar = .{0} ** bar.len?

  4. andrewrk commented on Apr 26, 2023

    @andrewrk
    MemberAuthor

    Same as the reason that @memcpy supports both src and dest being an array, even though it is equivalent to dest.* = src.*. The reason being language consistency.

  5. mlugg commented on Aug 27, 2023

    @mlugg
    Member

    To implement this reasonably, as well as for more general consistency between arrays and tuples, Zig should define homogeneous tuples (by which I mean tuples whose fields all have the same type) as having the same memory layout as arrays (i.e. fields laid out contiguously in memory with no extra padding). Is this something which the (theoretical) spec already guarantees? (As far as I know the implementation does, although I haven't checked.)

  6. mlugg commented on Feb 7, 2025

    @mlugg
    Member

    I think this is no longer intended behavior given our recent restriction of the definition of @memcpy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugenhancementfrontend

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions