Skip to content

Sema: allow @ptrCast single-item pointer to slice #23919

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

mlugg
Copy link
Member

@mlugg mlugg commented May 18, 2025

This is a proposal, but I think it makes sense as a trivial extension of #22706. The idea there is that we know the exact number of bytes the operand slice refers to, so we can use it to compute the length of the result slice. Well, there's another case in which we know the number of bytes the operand refers to: a single-item pointer!

Notably, where #22706 allowed replacing mem.sliceAsBytes(slice) with @ptrCast(slice), this proposal allows replacing mem.asBytes(single_ptr) with @ptrCast(single_ptr) (at least, in cases where you want a slice rather than an array pointer):

test "value to byte slice with @ptrCast" {
    const val: u32 = 1;
    const bytes: []const u8 = @ptrCast(&val);
    switch (@import("builtin").target.cpu.arch.endian()) {
        .little => try std.testing.expect(std.mem.eql(u8, bytes, "\x01\x00\x00\x00")),
        .big => try std.testing.expect(std.mem.eql(u8, bytes, "\x00\x00\x00\x01")),
    }
}
const std = @import("std");

@mlugg mlugg requested a review from andrewrk May 18, 2025 19:25
@mlugg mlugg added the proposal This issue suggests modifications. If it also has the "accepted" label then it is planned. label May 18, 2025
@mlugg mlugg added accepted This proposal is planned. release notes This PR should be mentioned in the release notes. labels May 18, 2025
@mlugg mlugg enabled auto-merge (rebase) May 18, 2025 19:42
Also, rework this logic a little to make it simpler. The length of the
result slice is now computed in one place.
@mlugg mlugg force-pushed the ptrcast-single-to-slice branch from ea39a2a to 16e1f28 Compare May 19, 2025 12:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
accepted This proposal is planned. proposal This issue suggests modifications. If it also has the "accepted" label then it is planned. release notes This PR should be mentioned in the release notes.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants