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
enhancementThe issue or pull request is an enhancementiOSIssues affecting iOSmacOSIssues affecting macOSrequest-for-commentsThe issue is a suggested idea seeking feedback
With Mono 2017-12 integration done we can now extend public API to use more efficient Span (and possibly Memory) where useful.
I had a quick look at the existing APIs to see where it makes sense to have Span overloads and there are many but I would start with the most likely one under CoreFoundation first.
Few candidates to illustrate the scope
CFData: public byte[] GetBuffer ()
CFSocket.cs: public void SendData (byte[] data, double timeout)
CFWriteStream.cs: public int Write (byte[] buffer)
CFDataBuffer.cs: public unsafe CFDataBuffer (byte[] buffer)
Some types, e.g. CFDataBuffer are not public and only used internally. It might not make sense to add API unless it can be used internally.
Do you have link to implementation examples ? not just what to do but what to avoid to.
E.g. was there guidelines used to add those API inside the BCL ?
I am not aware of any official guideline where to add those APIs but the general idea is to use it everywhere where API consumer can pass or consume a range of data.
For example string constructor was introduced to not require only char[] but Span, similarly Stream API can now produce Span output which when put together in the user code you flow the data without any extra allocation.
Before we implement support for this, we should have a survey of things where this is likely to become a win.
Span<T> has one downside, which is that it can only live in the call stack which needs to be taken into consideration.
GetBuffer is an interesting example, because we would need to introduce an Span<T> UnsafeGetBuffer, because currently the GetBuffer semantics is that the return value can outlive the CFData, as it is a copy, with this new design, the buffer is only valid as long as the object is alive.
CFSocket is a good candidate, but also, I suspect an API that does not see a lot of action generally.
The CF APIs in general will fall in this bucket.
One area that is worth researching are graphic libraries, video libraries, audio libraries. Many of those have been bound to use IntPtr returns or values.
CoreAudio stuff would be nice to have Span support for. Some methods I use that may benefit: AudioQueue.FillAudioData, OutputAudioQueue.AllocateBuffer, AudioFile.ReadFixedPackets
Span<T> has one downside, which is that it can only live in the call stack which needs to be taken into consideration.
This isn't strictly true. The Span itself must live on the stack, yes, but the data may live on the stack (i.e. stackalloc) or the heap (i.e. Array.AsSpan). I suppose whether Span or Memory should be used in a particular API depends on its semantics - methods which keep a long-lived pointer after exiting probably can't use Span, but could use Memory (as long as it gets pinned). Otherwise, Span can be used.
Imagine if there were a CFString constructor accepting ReadOnlySpan<char>: the biggest advantage would be that if caller code is already using Span, they can avoid the allocation of a ToString() call and just pass it right in. CFStringCreateWithCharacters copies the data anyway, so there would be no Span lifetime rule violations here.
GetBuffer is an interesting example, because we would need to introduce an Span<T> UnsafeGetBuffer, because currently the GetBuffer semantics is that the return value can outlive the CFData, as it is a copy, with this new design, the buffer is only valid as long as the object is alive.
Not necessarily. There could be a GetBuffer returning a Span over a copy of the data, keeping the same semantics. But perhaps your point was that this wouldn't improve in a huge way over just returning an array. To this effect, there could be a void GetBuffer(Span<byte> buffer) (perhaps named differently) which fills a caller-allocated buffer with the data, and which would be more powerful than an array-accepting version.
Though obviously a zero-copy ReadOnlySpan<byte> UnsafeGetBuffer() method would be the most powerful version of this. I wonder if there's a way to tie the lifetime of the Span to the native object. Perhaps IMemoryOwner<T>, or an approach like it would be useful here.
I did a first-pass survey of all manually-bound managed APIs (src/<Framework>/*.cs) to identify where Span<T>/ReadOnlySpan<T> (or Memory<T>) overloads would be worthwhile, as the issue's "step 1" asks. Full write-up + per-API determination tables (with GitHub permalinks to every candidate, pinned to commit 8111cb6c):
Zero-copy returns & lifetime.NSData.AsSpan()/UnsafeGetBuffer is the most powerful but hands out a span valid only while the object is alive and unmutated — this is exactly the GetBuffer concern raised above. The always-safe alternative is a CopyTo(Span<T>) fill overload; we may want both.
Span<T> vs Memory<T>. For buffers retained past the call (async Send, GCHandle-pinned inputs released by callbacks) Memory<T> is the right tool, not Span<T> (e.g. Compression.Inflater.SetInput, NWFramerMessage.SetData).
Property setters can't take Span<T> — those need a companion method (e.g. SslContext.PeerId → SetPeerId(ReadOnlySpan<byte>)).
params T[] factories should add a non-params ReadOnlySpan<T> overload rather than replace the ergonomic form.
Side finding (unrelated to Span, worth a separate fix)
NSCoder.Encode(byte[] buffer, int offset, int count, string key) has a latent bug: it validates offset/count but then pins the buffer start and passes buffer.Length (ignoring both offset and count), so it always encodes the whole array. A ReadOnlySpan<byte> overload fixes this as a side-effect, but it deserves its own targeted fix + test.
enhancementThe issue or pull request is an enhancementiOSIssues affecting iOSmacOSIssues affecting macOSrequest-for-commentsThe issue is a suggested idea seeking feedback
Activity
spouliot commentedon Feb 24, 2018
Some types, e.g.
CFDataBufferare not public and only used internally. It might not make sense to add API unless it can be used internally.Do you have link to implementation examples ? not just what to do but what to avoid to.
E.g. was there guidelines used to add those API inside the BCL ?
Thanks!
marek-safar commentedon Feb 27, 2018
I am not aware of any official guideline where to add those APIs but the general idea is to use it everywhere where API consumer can pass or consume a range of data.
For example string constructor was introduced to not require only char[] but Span, similarly Stream API can now produce Span output which when put together in the user code you flow the data without any extra allocation.
migueldeicaza commentedon Feb 27, 2018
Before we implement support for this, we should have a survey of things where this is likely to become a win.
Span<T>has one downside, which is that it can only live in the call stack which needs to be taken into consideration.GetBuffer is an interesting example, because we would need to introduce an
Span<T> UnsafeGetBuffer, because currently theGetBuffersemantics is that the return value can outlive the CFData, as it is a copy, with this new design, the buffer is only valid as long as the object is alive.CFSocket is a good candidate, but also, I suspect an API that does not see a lot of action generally.
The CF APIs in general will fall in this bucket.
One area that is worth researching are graphic libraries, video libraries, audio libraries. Many of those have been bound to use IntPtr returns or values.
jwosty commentedon Jun 25, 2019
CoreAudio stuff would be nice to have Span support for. Some methods I use that may benefit:
AudioQueue.FillAudioData,OutputAudioQueue.AllocateBuffer,AudioFile.ReadFixedPackets3 remaining items
jwosty commentedon Nov 13, 2023
This isn't strictly true. The Span itself must live on the stack, yes, but the data may live on the stack (i.e. stackalloc) or the heap (i.e. Array.AsSpan). I suppose whether Span or Memory should be used in a particular API depends on its semantics - methods which keep a long-lived pointer after exiting probably can't use Span, but could use Memory (as long as it gets pinned). Otherwise, Span can be used.
Imagine if there were a CFString constructor accepting
ReadOnlySpan<char>: the biggest advantage would be that if caller code is already usingSpan, they can avoid the allocation of aToString()call and just pass it right in.CFStringCreateWithCharacterscopies the data anyway, so there would be no Span lifetime rule violations here.Not necessarily. There could be a GetBuffer returning a Span over a copy of the data, keeping the same semantics. But perhaps your point was that this wouldn't improve in a huge way over just returning an array. To this effect, there could be a
void GetBuffer(Span<byte> buffer)(perhaps named differently) which fills a caller-allocated buffer with the data, and which would be more powerful than an array-accepting version.Though obviously a zero-copy
ReadOnlySpan<byte> UnsafeGetBuffer()method would be the most powerful version of this. I wonder if there's a way to tie the lifetime of the Span to the native object. PerhapsIMemoryOwner<T>, or an approach like it would be useful here.rolfbjarne commentedon Jul 9, 2026
I did a first-pass survey of all manually-bound managed APIs (
src/<Framework>/*.cs) to identify whereSpan<T>/ReadOnlySpan<T>(orMemory<T>) overloads would be worthwhile, as the issue's "step 1" asks. Full write-up + per-API determination tables (with GitHub permalinks to every candidate, pinned to commit8111cb6c):📄 Survey gist: https://gist.github.com/rolfbjarne/03fe17b96d98db859a743c3c14c72368 (master summary)
Method
Scanned ~1,473 files / ~291k lines across 142 framework folders, extracting ~572 candidate sites that touch contiguous buffers (blittable-primitive arrays,
Marshal.Copy,fixed,unsafepointers,IntPtr+length). Every candidate got a Yes / Maybe / No verdict, a proposed Span shape, and a rationale, grouped into 6 framework clusters.Results
NSObject[],string[], …) and private/internal helpers — Span gives nothing there.MDLAnimated*family), CoreGraphics, AudioToolbox, Foundation.Suggested phase 1 (highest value / lowest risk)
NSData(FromArray,ToArray→CopyTo(Span<byte>), zero-copyAsSpan()),NSMutableData.AppendBytes,NSInputStream/NSOutputStream,NSCoder,NSUuid,NSIndexPath. (The issue's original motivation.)CGContext.SetFillColor/SetStrokeColor/SetLineDash/ShowGlyphsAtPositions,CGImage/CGGradientcomponent arrays.set*Bytes).AudioFile.Read/Write/ReadPacketData/ReadFixedPackets,AudioConverter.ConvertBuffer,AudioFileStream.ParseBytes(as requested above by @jwosty).Design questions worth settling first (RFC)
NSData.AsSpan()/UnsafeGetBufferis the most powerful but hands out a span valid only while the object is alive and unmutated — this is exactly theGetBufferconcern raised above. The always-safe alternative is aCopyTo(Span<T>)fill overload; we may want both.Span<T>vsMemory<T>. For buffers retained past the call (asyncSend,GCHandle-pinned inputs released by callbacks)Memory<T>is the right tool, notSpan<T>(e.g.Compression.Inflater.SetInput,NWFramerMessage.SetData).Span<T>— those need a companion method (e.g.SslContext.PeerId→SetPeerId(ReadOnlySpan<byte>)).params T[]factories should add a non-paramsReadOnlySpan<T>overload rather than replace the ergonomic form.Side finding (unrelated to Span, worth a separate fix)
NSCoder.Encode(byte[] buffer, int offset, int count, string key)has a latent bug: it validatesoffset/countbut then pins the buffer start and passesbuffer.Length(ignoring bothoffsetandcount), so it always encodes the whole array. AReadOnlySpan<byte>overload fixes this as a side-effect, but it deserves its own targeted fix + test.Side finding fix: #26015
Happy to turn any of the phase-1 groups into concrete PRs.
🤖 Analysis by Copilot
[Foundation] Fix NSCoder.Encode(byte[], offset, count, key) to honor …
[Foundation] Add synchronous span byte-buffer APIs (#26873)
[Foundation][CoreFoundation] Add synchronous stream Span APIs. (#26955)