Skip to content

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

Merged
mlugg merged 1 commit into
ziglang:masterfrom
mlugg:ptrcast-single-to-slice
May 19, 2025
Merged

Sema: allow @ptrCast single-item pointer to slice#23919
mlugg merged 1 commit into
ziglang:masterfrom
mlugg:ptrcast-single-to-slice

Conversation

@mlugg

Copy link
Copy Markdown
Member

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" {
constval: u32=1;
constbytes: []constu8=@ptrCast(&val);
switch (@import("builtin").target.cpu.arch.endian()) {
.little=>trystd.testing.expect(std.mem.eql(u8, bytes, "\x01\x00\x00\x00")),
.big=>trystd.testing.expect(std.mem.eql(u8, bytes, "\x00\x00\x00\x01")),
}
}
conststd=@import("std");

@mlugg
mlugg requested a review from andrewrkMay 18, 2025 19:25
@mluggmlugg added the proposal This issue suggests language modifications. If it also has the "accepted" label then it is planned. label May 18, 2025
@mluggmlugg 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.
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

acceptedThis proposal is planned.proposalThis issue suggests language modifications. If it also has the "accepted" label then it is planned.release notesThis PR should be mentioned in the release notes.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@mlugg@andrewrk