-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Add MemoryMarshal.CreateReadOnlySpanFromNullTerminated #47539
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+164
−47
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
120 changes: 120 additions & 0 deletions
120
src/libraries/System.Memory/tests/MemoryMarshal/CreateReadOnlySpanFromNullTerminated.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Xunit; | ||
| using System.Runtime.InteropServices; | ||
| using System.Buffers; | ||
| using Microsoft.DotNet.XUnitExtensions; | ||
|
|
||
| namespace System.SpanTests | ||
| { | ||
| public static partial class MemoryMarshalTests | ||
| { | ||
| [Fact] | ||
| public static unsafe void CreateReadOnlySpanFromNullTerminated_Char_Null() | ||
| { | ||
| Assert.True(MemoryMarshal.CreateReadOnlySpanFromNullTerminated((char*)null).IsEmpty); | ||
| Assert.True(MemoryMarshal.CreateReadOnlySpanFromNullTerminated((byte*)null).IsEmpty); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData(0)] | ||
| [InlineData(1)] | ||
| [InlineData(256)] | ||
| public static unsafe void CreateReadOnlySpanFromNullTerminated_Char(int expectedLength) | ||
| { | ||
| using BoundedMemory<char> data = BoundedMemory.Allocate<char>(expectedLength + 1); | ||
| data.Span.Fill('s'); | ||
| data.Span[^1] = '\0'; | ||
| data.MakeReadonly(); | ||
|
|
||
| fixed (char* expectedPtr = data.Span) | ||
| { | ||
| ReadOnlySpan<char> actual = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(expectedPtr); | ||
stephentoub marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| Assert.Equal(expectedLength, actual.Length); | ||
| fixed (char* actualPtr = &MemoryMarshal.GetReference(actual)) | ||
| { | ||
| Assert.Equal((IntPtr)expectedPtr, (IntPtr)actualPtr); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData(0)] | ||
| [InlineData(1)] | ||
| [InlineData(256)] | ||
| public static unsafe void CreateReadOnlySpanFromNullTerminated_Byte(int expectedLength) | ||
| { | ||
| using BoundedMemory<byte> data = BoundedMemory.Allocate<byte>(expectedLength + 1); | ||
| data.Span.Fill(0xFF); | ||
| data.Span[^1] = 0; | ||
| data.MakeReadonly(); | ||
|
|
||
| fixed (byte* expectedPtr = data.Span) | ||
| { | ||
| ReadOnlySpan<byte> actual = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(expectedPtr); | ||
| Assert.Equal(expectedLength, actual.Length); | ||
| fixed (byte* actualPtr = &MemoryMarshal.GetReference(actual)) | ||
| { | ||
| Assert.Equal((IntPtr)expectedPtr, (IntPtr)actualPtr); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| [OuterLoop] | ||
| [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess))] | ||
| public static unsafe void CreateReadOnlySpanFromNullTerminated_Char_ExceedsMaximum() | ||
| { | ||
| char* mem; | ||
| try | ||
| { | ||
| mem = (char*)Marshal.AllocHGlobal((IntPtr)(sizeof(char) * (2L + int.MaxValue))); | ||
| } | ||
| catch (OutOfMemoryException) | ||
| { | ||
| throw new SkipTestException("Unable to allocate 4GB of memory"); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| new Span<char>(mem, int.MaxValue).Fill('s'); | ||
| *(mem + int.MaxValue) = 's'; | ||
| *(mem + int.MaxValue + 1) = '\0'; | ||
|
|
||
| Assert.Throws<ArgumentException>(() => MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mem)); | ||
| } | ||
| finally | ||
| { | ||
| Marshal.FreeHGlobal((IntPtr)mem); | ||
| } | ||
| } | ||
|
|
||
| [OuterLoop] | ||
| [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess))] | ||
| public static unsafe void CreateReadOnlySpanFromNullTerminated_Byte_ExceedsMaximum() | ||
| { | ||
| byte* mem; | ||
| try | ||
| { | ||
| mem = (byte*)Marshal.AllocHGlobal((IntPtr)(2L + int.MaxValue)); | ||
| } | ||
| catch (OutOfMemoryException) | ||
| { | ||
| throw new SkipTestException("Unable to allocate 2GB of memory"); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| new Span<byte>(mem, int.MaxValue).Fill(0xFF); | ||
| *(mem + int.MaxValue) = 0xFF; | ||
| *(mem + int.MaxValue + 1) = 0; | ||
|
|
||
| Assert.Throws<ArgumentException>(() => MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mem)); | ||
| } | ||
| finally | ||
| { | ||
| Marshal.FreeHGlobal((IntPtr)mem); | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -211,27 +211,49 @@ ref Unsafe.As<TFrom, TTo>(ref MemoryMarshal.GetReference(span)), | |
| } | ||
|
|
||
| /// <summary> | ||
| /// Create a new span over a portion of a regular managed object. This can be useful | ||
| /// Creates a new span over a portion of a regular managed object. This can be useful | ||
| /// if part of a managed object represents a "fixed array." This is dangerous because the | ||
| /// <paramref name="length"/> is not checked. | ||
| /// </summary> | ||
| /// <param name="reference">A reference to data.</param> | ||
| /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> | ||
| /// <returns>The lifetime of the returned span will not be validated for safety by span-aware languages.</returns> | ||
| /// <returns>A span representing the specified reference and length.</returns> | ||
| /// <remarks>The lifetime of the returned span will not be validated for safety by span-aware languages.</remarks> | ||
|
||
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
| public static Span<T> CreateSpan<T>(ref T reference, int length) => new Span<T>(ref reference, length); | ||
|
|
||
| /// <summary> | ||
| /// Create a new read-only span over a portion of a regular managed object. This can be useful | ||
| /// Creates a new read-only span over a portion of a regular managed object. This can be useful | ||
| /// if part of a managed object represents a "fixed array." This is dangerous because the | ||
| /// <paramref name="length"/> is not checked. | ||
| /// </summary> | ||
| /// <param name="reference">A reference to data.</param> | ||
| /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> | ||
| /// <returns>The lifetime of the returned span will not be validated for safety by span-aware languages.</returns> | ||
| /// <returns>A read-only span representing the specified reference and length.</returns> | ||
| /// <remarks>The lifetime of the returned span will not be validated for safety by span-aware languages.</remarks> | ||
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
| public static ReadOnlySpan<T> CreateReadOnlySpan<T>(ref T reference, int length) => new ReadOnlySpan<T>(ref reference, length); | ||
|
|
||
| /// <summary>Creates a new read-only span for a null-terminated string.</summary> | ||
| /// <param name="value">The pointer to the null-terminated string of characters.</param> | ||
| /// <returns>A read-only span representing the specified null-terminated string, or an empty span if the pointer is null.</returns> | ||
| /// <remarks>The returned span does not include the null terminator.</remarks> | ||
stephentoub marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| /// <exception cref="ArgumentException">The string is longer than <see cref="int.MaxValue"/>.</exception> | ||
stephentoub marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| [CLSCompliant(false)] | ||
| public static unsafe ReadOnlySpan<char> CreateReadOnlySpanFromNullTerminated(char* value) => | ||
| value != null ? new ReadOnlySpan<char>(value, string.wcslen(value)) : | ||
| default; | ||
|
|
||
| /// <summary>Creates a new read-only span for a null-terminated UTF8 string.</summary> | ||
| /// <param name="value">The pointer to the null-terminated string of bytes.</param> | ||
| /// <returns>A read-only span representing the specified null-terminated string, or an empty span if the pointer is null.</returns> | ||
| /// <remarks>The returned span does not include the null terminator, nor does it validate the well-formedness of the UTF8 data.</remarks> | ||
| /// <exception cref="ArgumentException">The string is longer than <see cref="int.MaxValue"/>.</exception> | ||
| [CLSCompliant(false)] | ||
| public static unsafe ReadOnlySpan<byte> CreateReadOnlySpanFromNullTerminated(byte* value) => | ||
| value != null ? new ReadOnlySpan<byte>(value, string.strlen(value)) : | ||
| default; | ||
|
|
||
| /// <summary> | ||
| /// Get an array segment from the underlying memory. | ||
| /// If unable to get the array segment, return false with a default array segment. | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.