Skip to content

Commit 0c1a42e

Browse files
committed
fix: Handle array segments correctly
Fixes #209 Signed-off-by: Jon Skeet <[email protected]>
1 parent 8f75a9b commit 0c1a42e

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

src/CloudNative.CloudEvents/Core/BinaryDataUtilities.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,9 @@ public static async Task CopyToStreamAsync(ReadOnlyMemory<byte> source, Stream d
106106
public static byte[] AsArray(ReadOnlyMemory<byte> memory)
107107
{
108108
var segment = GetArraySegment(memory);
109-
return segment.Offset == 0 || segment.Count == memory.Length
109+
// We probably don't actually need to check the offset: if the count is the same as the length,
110+
// I can't see how the offset can be non-zero. But it doesn't *hurt* as a check.
111+
return segment.Offset == 0 && segment.Count == segment.Array.Length
110112
? segment.Array
111113
: memory.ToArray();
112114
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Copyright 2022 Cloud Native Foundation.
2+
// Licensed under the Apache 2.0 license.
3+
// See LICENSE file in the project root for full license information.
4+
5+
using System;
6+
using System.Linq;
7+
using Xunit;
8+
9+
namespace CloudNative.CloudEvents.Core.UnitTests
10+
{
11+
public class BinaryDataUtilitiesTest
12+
{
13+
[Fact]
14+
public void AsArray_ReturningOriginal()
15+
{
16+
byte[] original = { 1, 2, 3, 4, 5 };
17+
var segment = new ArraySegment<byte>(original);
18+
Assert.Same(original, BinaryDataUtilities.AsArray(segment));
19+
}
20+
21+
[Theory]
22+
[InlineData(0)]
23+
[InlineData(1)]
24+
public void AsArray_FromPartialSegment(int offset)
25+
{
26+
byte[] original = { 1, 2, 3, 4, 5 };
27+
var segment = new ArraySegment<byte>(original, offset, 4);
28+
var actual = BinaryDataUtilities.AsArray(segment);
29+
Assert.True(actual.SequenceEqual(segment));
30+
Assert.NotSame(original, actual);
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)