|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +#pragma warning disable CA1822 // Mark members as static |
| 5 | + |
| 6 | +using System; |
| 7 | +using System.Text; |
| 8 | +using Microsoft.JavaScript.NodeApi.Runtime; |
| 9 | +using Xunit; |
| 10 | +using static Microsoft.JavaScript.NodeApi.Test.TestUtils; |
| 11 | + |
| 12 | +namespace Microsoft.JavaScript.NodeApi.Test; |
| 13 | + |
| 14 | +public class PooledBufferTests |
| 15 | +{ |
| 16 | + public static TheoryData<string> Strings { get; } = new() |
| 17 | + { |
| 18 | + "", |
| 19 | + "x", |
| 20 | + "module-name", |
| 21 | + "\u00e4\u00f6\u00fc \u4e2d\u6587 \U0001F600", |
| 22 | + }; |
| 23 | + |
| 24 | + [Theory] |
| 25 | + [MemberData(nameof(Strings))] |
| 26 | + public void FromStringUtf8IsNullTerminated(string value) |
| 27 | + { |
| 28 | + FillArrayPoolWithGarbage(); |
| 29 | + using PooledBuffer buffer = PooledBuffer.FromStringUtf8(value); |
| 30 | + AssertNullTerminatedUtf8(value, buffer); |
| 31 | + } |
| 32 | + |
| 33 | + [Theory] |
| 34 | + [MemberData(nameof(Strings))] |
| 35 | + public void FromSpanUtf8IsNullTerminated(string value) |
| 36 | + { |
| 37 | + FillArrayPoolWithGarbage(); |
| 38 | + using PooledBuffer buffer = PooledBuffer.FromSpanUtf8(value.AsSpan()); |
| 39 | + AssertNullTerminatedUtf8(value, buffer); |
| 40 | + } |
| 41 | + |
| 42 | + [Fact] |
| 43 | + public void FromStringUtf8NullIsEmpty() |
| 44 | + { |
| 45 | + // A null string must still produce a null pointer when pinned. |
| 46 | + using PooledBuffer buffer = PooledBuffer.FromStringUtf8(null); |
| 47 | + Assert.Equal(0, buffer.Length); |
| 48 | + Assert.True(buffer.Span.IsEmpty); |
| 49 | + } |
| 50 | + |
| 51 | + private static void AssertNullTerminatedUtf8(string expected, PooledBuffer buffer) |
| 52 | + { |
| 53 | + int byteLength = Encoding.UTF8.GetByteCount(expected); |
| 54 | + Assert.Equal(byteLength, buffer.Length); |
| 55 | + |
| 56 | + // The buffer must hold the terminator so that pinning it never yields a null pointer. |
| 57 | + Assert.True(buffer.Span.Length > byteLength); |
| 58 | + Assert.Equal(0, buffer.Span[byteLength]); |
| 59 | + Assert.Equal(expected, Encoding.UTF8.GetString(buffer.Buffer, 0, byteLength)); |
| 60 | + } |
| 61 | +} |
0 commit comments