You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Question: What is our policy regarding API support of unaligned spans? #44497
Scenario: Let's say that somebody creates a Span<T> where the addresses are not properly aligned for type T. As far as I'm aware this can only be done via unsafe code (new Span<T>(<unaligned ptr>)) or unsafe-equivalent code (MemoryMarshal.Cast or MemoryMarshal.CreateSpan(<ref to unaligned field>).
Question: What guarantees should our in-box APIs make when such spans are provided as input?
For example, MemoryExtensions.IndexOfcontains special-cased logic to handle unaligned ReadOnlySpan<char> on all platforms, but it doesn't contain special logic for things like unaligned ReadOnlySpan<float>. Depending on the current architecture, such accesses could fault.
As another example, UTF8Encoding.GetBytes(ReadOnlySpan<char>) assumes that the input is always char-aligned, and it could fault or return nonsensical answers if given unaligned input, even on x86 processors.
Is our default stance that all APIs which accept Span<T>, ref T, and similar should guard against misaligned addresses? Or that consumers must assume that misaligned spans do not work unless they API they're calling has been documented as allowing these?
MemoryExtensions.IndexOf contains special-cased logic to handle unaligned ReadOnlySpan
IIRC, this was done to allow IndexOf to be repurposed as wcslen. APIs that take zero-terminated strings always handled misaligned pointers gracefully and we had tests that failed without it.
consumers must assume that misaligned spans do not work unless they API they're calling has been documented as allowing these
Correct, pointers are assumed to be aligned according to the platform rules.
As usual, we may find that code out there depends on undocumented behaviors that we treat case-by-case.
Activity
jkotas commentedon Nov 11, 2020
IIRC, this was done to allow IndexOf to be repurposed as
wcslen. APIs that take zero-terminated strings always handled misaligned pointers gracefully and we had tests that failed without it.Correct, pointers are assumed to be aligned according to the platform rules.
As usual, we may find that code out there depends on undocumented behaviors that we treat case-by-case.
GrabYourPitchforks commentedon Nov 12, 2020
Thank you for the response. :)
If I see any other questions regarding this I'll redirect them to this thread.