Bug 24619 – Allow pointer slicing for slices of length 0 or 1

Status
NEW
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2024-06-20T13:48:45Z
Last change time
2024-12-13T19:35:51Z
Keywords
safe
Assigned to
No Owner
Creator
Bolpat
Moved to GitHub: dmd#20471 →

Comments

Comment #0 by qs.il.paperinik — 2024-06-20T13:48:45Z
Allow `(&x)[0 .. 1]` (and `(&x)[0 .. 0]`) in `@safe` code.
Comment #1 by dkorpel — 2024-06-20T14:21:07Z
Similar situation to this: https://github.com/dlang/dmd/pull/15581#issuecomment-1738649867 Do you have a use case?
Comment #2 by qs.il.paperinik — 2024-06-20T17:11:24Z
(In reply to Dennis from comment #1) > Similar situation to this: > > https://github.com/dlang/dmd/pull/15581#issuecomment-1738649867 It has some vague similarity, but AFAICT, PR 15581 is almost the reverse, going from slice to pointer to the first element. The `@safe` way to get a pointer to the first element is `&xs[0]`. If `xs` has compile-time-known length, surely the compiler does not do a run-time check for index bounds. On the other hand, going from pointer to 1-element slice, best one can do is `(() @trusted => ptr[0 .. 1])()`, and that is unnecessary. I don’t know about the semantics about a slice with a `null` pointer component and a length of 1, but my bet would be that it should be exactly as any other `null` dereference. Any index except `0` would throw an `ArrayIndexError` and the index `0` is a `null` dereference. > Do you have a use case? The use case is passing a single value to a function that expects a slice of such values. While one can create a length-1 array with a copy of the value, not all values are copyable and not all values are cheap to copy. I can’t imagine a use case for `[0 .. 0]` though. I just included that one because it’s obviously safe and if we make an exception for `[0 .. 1]`, it would be weird to disallow it.
Comment #3 by robert.schadek — 2024-12-13T19:35:51Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/20471 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB