|
| 1 | +using System; |
| 2 | +using System.Buffers; |
| 3 | +using Shouldly; |
| 4 | +using Xunit; |
| 5 | + |
| 6 | +namespace ProGaudi.MsgPack.Tests.ReadOnlySequence.MultipleSegments |
| 7 | +{ |
| 8 | + public class GetIntLength |
| 9 | + { |
| 10 | + [Theory] |
| 11 | + [InlineData(new byte[0])] |
| 12 | + [InlineData(new byte[] {1})] |
| 13 | + [InlineData(new byte[] {byte.MaxValue, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})] |
| 14 | + public void GetIntLengthByte(byte[] data) |
| 15 | + { |
| 16 | + data.ToMultipleSegments().GetIntLength().ShouldBe(data.Length); |
| 17 | + } |
| 18 | + |
| 19 | + [Theory] |
| 20 | + [InlineData(new int[0])] |
| 21 | + [InlineData(new[] {1})] |
| 22 | + [InlineData(new[] {int.MaxValue, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})] |
| 23 | + public void GetIntLengthNonByte(int[] data) |
| 24 | + { |
| 25 | + data.ToMultipleSegments().GetIntLength().ShouldBe(data.Length); |
| 26 | + } |
| 27 | + |
| 28 | + [Fact] |
| 29 | + public void LongLength() |
| 30 | + { |
| 31 | + using (var megabyte = MemoryPool<byte>.Shared.Rent(1024 * 1024)) |
| 32 | + { |
| 33 | + var memory = megabyte.Memory; |
| 34 | + var desiredLength = (1 + (int.MaxValue + 1L) / memory.Length) * memory.Length; |
| 35 | + desiredLength.ShouldBeGreaterThan(int.MaxValue); |
| 36 | + |
| 37 | + var sequence = CreateReadOnlySequence(memory, desiredLength); |
| 38 | + sequence.Length.ShouldBe(desiredLength); |
| 39 | + var e = Should.Throw<InvalidOperationException>(() => sequence.GetIntLength()); |
| 40 | + e.Message.ShouldBe($@"You can't create arrays or string longer than int.MaxValue in .net. Packet length was: {desiredLength}. |
| 41 | +See https://blogs.msdn.microsoft.com/joshwil/2005/08/10/bigarrayt-getting-around-the-2gb-array-size-limit/"); |
| 42 | + } |
| 43 | + |
| 44 | + ReadOnlySequence<byte> CreateReadOnlySequence(Memory<byte> memory, long desiredLength) |
| 45 | + { |
| 46 | + ReadOnlySequenceSegment<byte> end = null; |
| 47 | + ReadOnlySequenceSegment<byte> current = null; |
| 48 | + while (desiredLength > 0) |
| 49 | + { |
| 50 | + desiredLength -= memory.Length; |
| 51 | + var next = new LongSequenceSegment<byte>(memory, desiredLength, current); |
| 52 | + current = next; |
| 53 | + end = end ?? next; |
| 54 | + } |
| 55 | + |
| 56 | + var sequence = new ReadOnlySequence<byte>(current, 0, end, end.Memory.Length); |
| 57 | + return sequence; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + private sealed class LongSequenceSegment<T> : ReadOnlySequenceSegment<T> |
| 62 | + { |
| 63 | + public LongSequenceSegment(in Memory<T> memory, long runningIndex, ReadOnlySequenceSegment<T> next) |
| 64 | + { |
| 65 | + Memory = memory; |
| 66 | + RunningIndex = runningIndex; |
| 67 | + Next = next; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments