-
Notifications
You must be signed in to change notification settings - Fork 17.6k
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
proposal: slices: add IndexPointer #66981
Comments
FYI, there are already helpers in |
With my proposed implementation, it returns -1, since there's a Another edge cases exists with slices of zero-length element types. Again, the optimized version matches the naive implementation in behavior. |
As a concrete example of pre-condition error checking, for |
I would rather see: func IndexPointer[S ~[]E, E any](s S, p *E) (int, bool) I don't like |
The existing |
Ah nvm, well forget what I said. thx |
Technically What if we instead use |
For the use cases that I'm wrestling with, That said, I think func Overlapping[S ~[]E, E any](s1, s2 S) bool {
return len(s1) > 0 && len(s2) > 0 && (
IndexPointer(s1, &s2[0]) >= 0 ||
IndexPointer(s2, &s1[0]) >= 0 ||
IndexPointer(s1, &s2[len(s2)-1]) >= 0 ||
IndexPointer(s2, &s1[len(s1)-1]) >= 0)
} We could provide both |
The real win would be to teach the compiler that seeing |
Proposal Details
I propose the addition of:
A use of this is to check whether some slice is a subslice of another slice, by checking:
len(subslice) > 0 && slices.IndexPointer(s, &subslice[0]) >= 0
Such an operation is useful:
AppendFoo(dst, src)
is will produce corrupt data ifsrc
is a subslice ofdst
and the operation writes more bytes todst
than it reads fromsrc
. Such bugs are difficult to track down and ideally the API can return an error by detecting such situations (or just clone thesrc
for a slower but correct implementation).An alternative API is:
but:
s
andsubslice
are of typeS
.s
andsubslice
overlap, but neither is subslice of the other.bool
is strictly less flexible than returning an index.IndexPointer
is more clear about it's meaning.Implementation
The naive implementation is straight forward:
but is unfortunately non-performant as it performs an O(n) search over the slice.
A more efficient implementation takes advantage of pointer arithmetic:
which can now compute the result in O(1).
Without the helper function in "slices", it is currently impossible in Go to identify whether a given slice is a sub-slice of another slice in O(1) without the use of "unsafe". By including this helper in the "slices" package, callers can avoid the use of "unsafe" to perform this operation.
The text was updated successfully, but these errors were encountered: