Skip to content

DataObject.SetAudio should be exposed with a new overload taking Span<byte> #218

@raffaeler

Description

@raffaeler

The DataObject class currently exposes two audio overloads. The first one taking a byte[] calls the second who takes a Stream.

Rationale

Since the introduction of Span<T> it become preferable exposing APIs using Span<T> because they are stack-only types minimizing the use of the garbage collector and easily allows slicing the referenced memory.

Proposed API

namespace System.Windows.Forms
{
    public partial class DataObject : IDataObject
    {
        // Existing methods
        public virtual void SetAudio(byte[] audioBytes);
        public virtual void SetAudio(Stream audioStream);

        // Proposed method
        public virtual void SetAudio(Span<byte> audioBytes);
    }
}

An additional advantage of Span<T> is that it self describes the contiguous memory to be processed from the API. The existing overload taking byte[] does not even allow to specify an offset and length of the array.

Since the current overloads allow specifying an empty interval and only check whether the parameter (byte[] or Stream is null), it is also possible to avoid any parameter check since Span<T> is a ref struct and cannot be null.
The parameter Span<byte> can be empty, as it is for the other overloads.

Implementation

The proposed implementation of the new public API is the following:

public virtual void SetAudio(Span<byte> audioBytes)
{
    var stream = new MemoryStream(audioBytes.Length);
    stream.Write(audioBytes);
    stream.Seek(0, SeekOrigin.Begin);
    SetAudio(stream);
}

The MemoryStream is not disposed as it is not directly consumed from the called methods. The other overload does the same.

The PR for this new API is available and contains also a test with four different types of blobs, including an empty one.

Metadata

Metadata

Labels

api-ready-for-review(2) API is ready for formal API review; applied by the issue owner

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions