-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
add std/pointers to handle ptr[T] in a safer way than using cast directly #15490
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
Conversation
How often are these kinds of facilities even used though? If one needs to increment/decrement a pointer, 95% of the time the type is better represented as a pointer to an unchecked array |
template `[]`*[T](p: ptr T, off: int): T = | ||
(p + off)[] | ||
|
||
template `[]=`*[T](p: ptr T, off: int, val: T) = | ||
(p + off)[] = val |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These are far too dangerous to have this innocent, common syntax.
In my code I prefer to have operators like |
Instead I would prefer to see |
I don't see how
using non-standard operator names isn't good; Most code would not deal with pointer indexing and code that does will have explicit regarding safety:A misused using operators from [1] and import at local scope (as I've implemented in a local fork) makes it even clearer |
How about implementing this so that it's only possible within a |
good idea, maybe. one caveat is that cast doesn't require it (since import std/pointers
proc fn=
let a = getPtr()
{.unsafe.}:
let b = a+1
echo b[2]
echo b[] # b is in scope (it'd be analog to |
see alternative approach here: #15500 |
If we have to have a module dedicated to pointer arithmetic (and I still don't feel that there's much call for one) I would much prefer this over regular arithmetic operators. |
That's not a caveat, as someone that uses Nim you should learn to grep for There is an argument to be made that Nim should have only allowed it under an |
There is nothing to regret here, Rust's way doesn't work as well as Nim's and both don't really work all that well when you use extensive interfacing to C(++). |
Given that the |
it's still pending nim-lang/fusion#21 |
Nevertheless it should be in fusion. Or in your own Nimble package. |
this allows safer code than using cast directly in user code, and its lack in stdlib is a common complaint, having it in stdlib instead of as a separate nimble package makes sense for something that common; it also enables using it in compiler/nim sources