Skip to content

Commit

Permalink
[System.Memory.Data] Add Empty to BinaryData (#49777)
Browse files Browse the repository at this point in the history
This is useful for APIs which return `BinaryData` and want to use a
singleton instead of allocating a new `BinaryData` each
time. Previously, developers would need to create their own static
copy of an empty binary data, now they can just use `Empty`

Fixes #49670
  • Loading branch information
ellismg authored Mar 18, 2021
1 parent 6f12c00 commit 1cee50a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/libraries/System.Memory.Data/ref/System.Memory.Data.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public BinaryData(byte[] data) { }
public BinaryData(object? jsonSerializable, System.Text.Json.JsonSerializerOptions? options = null, System.Type? type = null) { }
public BinaryData(System.ReadOnlyMemory<byte> data) { }
public BinaryData(string data) { }
public static BinaryData Empty { get; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) { throw null; }
public static System.BinaryData FromBytes(byte[] data) { throw null; }
Expand Down
5 changes: 5 additions & 0 deletions src/libraries/System.Memory.Data/src/System/BinaryData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ public class BinaryData
/// </summary>
private readonly ReadOnlyMemory<byte> _bytes;

/// <summary>
/// Returns an empty BinaryData.
/// </summary>
public static BinaryData Empty { get; } = new BinaryData(ReadOnlyMemory<byte>.Empty);

/// <summary>
/// Creates a <see cref="BinaryData"/> instance by wrapping the
/// provided byte array.
Expand Down
13 changes: 13 additions & 0 deletions src/libraries/System.Memory.Data/tests/BinaryDataTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
Expand Down Expand Up @@ -572,6 +573,18 @@ public void CloseStreamValidation()

}

[Fact]
public void EmptyIsEmpty()
{
Assert.Equal(Array.Empty<byte>(), BinaryData.Empty.ToArray());
}

[Fact]
public void EmptyIsSingleton()
{
Assert.Same(BinaryData.Empty, BinaryData.Empty);
}

private class TestModel
{
public string A { get; set; }
Expand Down

0 comments on commit 1cee50a

Please sign in to comment.