Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Code review feedback.
Changed the underlying buffer to never be null.
  • Loading branch information
vcsjones committed Sep 24, 2023
commit 738b230ac37ee60353e243e11d7b316b39140136
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ public CborWriter(

_buffer = initialCapacity switch
{
DefaultCapacitySentinel or 0 => null!,
DefaultCapacitySentinel or 0 => Array.Empty<byte>(),
< -1 => throw new ArgumentOutOfRangeException(nameof(initialCapacity)),
_ => new byte[initialCapacity]
_ => new byte[initialCapacity],
};
}

Expand Down Expand Up @@ -235,7 +235,7 @@ private void EnsureWriteCapacity(int pendingCount)
throw new OverflowException();
}

if (_buffer is null || _buffer.Length - _offset < pendingCount)
if (_buffer.Length - _offset < pendingCount)
{
const int BlockSize = 1024;
int blocks = checked(_offset + pendingCount + (BlockSize - 1)) / BlockSize;
Expand Down
31 changes: 19 additions & 12 deletions src/libraries/System.Formats.Cbor/tests/Writer/CborWriterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -345,24 +345,31 @@ public static void InvalidInitialCapacity_ShouldThrowArgumentOutOfRangeException
}

[Theory]
[InlineData(-1, null)]
[InlineData(0, null)]
[InlineData(-1, 0)]
[InlineData(0, 0)]
[InlineData(1, 1)]
[InlineData(1023, 1023)]
public static void InitialCapacity_ShouldSetInitialBuffer(int capacity, int? expectedBufferLength)
public static void InitialCapacity_ShouldSetInitialBuffer(int capacity, int expectedBufferLength)
{
CborWriter writer = new CborWriter(initialCapacity: capacity);
byte[]? buffer = (byte[]?)typeof(CborWriter).GetField("_buffer", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(writer);

if (expectedBufferLength is null)
{
Assert.Null(buffer);
}
else
{
Assert.NotNull(buffer);
Assert.Equal(expectedBufferLength.Value, buffer.Length);
}
Assert.NotNull(buffer);
Assert.Equal(expectedBufferLength, buffer.Length);
}

[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(1)]
public static void Encode_InitialCapacity_Grows(int capacity)
{
CborWriter writer = new CborWriter(initialCapacity: capacity);
writer.WriteByteString((ReadOnlySpan<byte>)new byte[] { 1, 2, 3, 4, 5, 6 });
byte[] encoded = writer.Encode();

ReadOnlySpan<byte> expected = new byte[] { (2 << 5) | 6, 1, 2, 3, 4, 5, 6 };
AssertExtensions.SequenceEqual(expected, encoded);
}

public static IEnumerable<object[]> EncodedValueInputs => CborReaderTests.SampleCborValues.Select(x => new [] { x });
Expand Down