Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit7040d07

Browse files
committed
Add MemoryMarshal.CreateReadOnlySpanFromNullTerminated
1 parent42bc286 commit7040d07

File tree

9 files changed

+164
-47
lines changed

9 files changed

+164
-47
lines changed

‎src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs‎

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -183,24 +183,13 @@ internal static unsafe void ConvertFixedToNative(int flags, string strManaged, I
183183

184184
internalstaticunsafestringConvertFixedToManaged(IntPtrcstr,intlength)
185185
{
186-
intallocSize=length+2;
187-
if(allocSize<length)
186+
intend=SpanHelpers.IndexOf(ref*(byte*)cstr,0, length);
187+
if(end!=-1)
188188
{
189-
thrownewOutOfMemoryException();
189+
length=end;
190190
}
191-
Span<sbyte>originalBuffer=newSpan<sbyte>((byte*)cstr,length);
192191

193-
Span<sbyte>tempBuf=stackallocsbyte[allocSize];
194-
195-
originalBuffer.CopyTo(tempBuf);
196-
tempBuf[length-1]=0;
197-
tempBuf[length]=0;
198-
tempBuf[length+1]=0;
199-
200-
fixed(sbyte*buffer=tempBuf)
201-
{
202-
returnnewstring(buffer,0,string.strlen((byte*)buffer));
203-
}
192+
returnnewstring((sbyte*)cstr,0,length);
204193
}
205194
}// class CSTRMarshaler
206195

‎src/libraries/Common/src/System/Globalization/FormatProvider.Number.cs‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -897,23 +897,13 @@ private static void FormatCurrency(ref ValueStringBuilder sb, ref NumberBuffer n
897897
}
898898
}
899899

900-
privatestaticunsafeintwcslen(char*s)
901-
{
902-
intresult=0;
903-
while(*s++!='\0')
904-
{
905-
result++;
906-
}
907-
returnresult;
908-
}
909-
910900
privatestaticunsafevoidFormatFixed(refValueStringBuildersb,refNumberBuffernumber,intnMinDigits,intnMaxDigits,NumberFormatInfoinfo,int[]?groupDigits,stringsDecimal,string?sGroup)
911901
{
912902
Debug.Assert(sGroup!=null||groupDigits==null);
913903

914904
intdigPos=number.scale;
915905
char*dig=number.digits;
916-
intdigLength=wcslen(dig);
906+
intdigLength=MemoryMarshal.CreateReadOnlySpanFromNullTerminated(dig).Length;
917907

918908
if(digPos>0)
919909
{

‎src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -475,22 +475,15 @@ private unsafe void ProcessEvents(int numEvents,
475475

476476
staticParsedEventParseEvent(byte*nativeEventPath)
477477
{
478-
intbyteCount=0;
479478
Debug.Assert(nativeEventPath!=null);
480-
byte*temp=nativeEventPath;
481479

482-
// Finds the position of null character.
483-
while(*temp!=0)
484-
{
485-
temp++;
486-
byteCount++;
487-
}
480+
ReadOnlySpan<byte>eventPath=MemoryMarshal.CreateReadOnlySpanFromNullTerminated(nativeEventPath);
481+
Debug.Assert(!eventPath.IsEmpty,"Empty events are not supported");
488482

489-
Debug.Assert(byteCount>0,"Empty events are not supported");
490-
char[]tempBuffer=ArrayPool<char>.Shared.Rent(Encoding.UTF8.GetMaxCharCount(byteCount));
483+
char[]tempBuffer=ArrayPool<char>.Shared.Rent(Encoding.UTF8.GetMaxCharCount(eventPath.Length));
491484

492485
// Converting an array of bytes to UTF-8 char array
493-
intcharCount=Encoding.UTF8.GetChars(newReadOnlySpan<byte>(nativeEventPath,byteCount),tempBuffer);
486+
intcharCount=Encoding.UTF8.GetChars(eventPath,tempBuffer);
494487
returnnewParsedEvent(tempBuffer.AsSpan(0,charCount),tempBuffer);
495488
}
496489

‎src/libraries/System.Memory/ref/System.Memory.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,10 @@ public static partial class MemoryMarshal
497497
publicstaticSystem.Span<TTo>Cast<TFrom,TTo>(System.Span<TFrom>span)whereTFrom:structwhereTTo:struct{thrownull;}
498498
publicstaticSystem.Memory<T>CreateFromPinnedArray<T>(T[]?array,intstart,intlength){thrownull;}
499499
publicstaticSystem.ReadOnlySpan<T>CreateReadOnlySpan<T>(refTreference,intlength){thrownull;}
500+
[System.CLSCompliant(false)]
501+
publicstaticunsafeReadOnlySpan<byte>CreateReadOnlySpanFromNullTerminated(byte*value){thrownull;}
502+
[System.CLSCompliant(false)]
503+
publicstaticunsafeReadOnlySpan<char>CreateReadOnlySpanFromNullTerminated(char*value){thrownull;}
500504
publicstaticSystem.Span<T>CreateSpan<T>(refTreference,intlength){thrownull;}
501505
publicstaticrefTGetArrayDataReference<T>(T[]array){thrownull;}
502506
publicstaticrefTGetReference<T>(System.ReadOnlySpan<T>span){thrownull;}
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
usingXunit;
5+
usingSystem.Runtime.InteropServices;
6+
usingSystem.Buffers;
7+
usingMicrosoft.DotNet.XUnitExtensions;
8+
9+
namespaceSystem.SpanTests
10+
{
11+
publicstaticpartialclassMemoryMarshalTests
12+
{
13+
[Fact]
14+
publicstaticunsafevoidCreateReadOnlySpanFromNullTerminated_Char_Null()
15+
{
16+
Assert.True(MemoryMarshal.CreateReadOnlySpanFromNullTerminated((char*)null).IsEmpty);
17+
Assert.True(MemoryMarshal.CreateReadOnlySpanFromNullTerminated((byte*)null).IsEmpty);
18+
}
19+
20+
[Theory]
21+
[InlineData(0)]
22+
[InlineData(1)]
23+
[InlineData(256)]
24+
publicstaticunsafevoidCreateReadOnlySpanFromNullTerminated_Char(intexpectedLength)
25+
{
26+
usingBoundedMemory<char>data=BoundedMemory.Allocate<char>(expectedLength+1);
27+
data.Span.Fill('s');
28+
data.Span[^1]='\0';
29+
data.MakeReadonly();
30+
31+
fixed(char*expectedPtr=data.Span)
32+
{
33+
ReadOnlySpan<char>actual=MemoryMarshal.CreateReadOnlySpanFromNullTerminated(expectedPtr);
34+
Assert.Equal(expectedLength,actual.Length);
35+
fixed(char*actualPtr=&MemoryMarshal.GetReference(actual))
36+
{
37+
Assert.Equal((IntPtr)expectedPtr,(IntPtr)actualPtr);
38+
}
39+
}
40+
}
41+
42+
[Theory]
43+
[InlineData(0)]
44+
[InlineData(1)]
45+
[InlineData(256)]
46+
publicstaticunsafevoidCreateReadOnlySpanFromNullTerminated_Byte(intexpectedLength)
47+
{
48+
usingBoundedMemory<byte>data=BoundedMemory.Allocate<byte>(expectedLength+1);
49+
data.Span.Fill(0xFF);
50+
data.Span[^1]=0;
51+
data.MakeReadonly();
52+
53+
fixed(byte*expectedPtr=data.Span)
54+
{
55+
ReadOnlySpan<byte>actual=MemoryMarshal.CreateReadOnlySpanFromNullTerminated(expectedPtr);
56+
Assert.Equal(expectedLength,actual.Length);
57+
fixed(byte*actualPtr=&MemoryMarshal.GetReference(actual))
58+
{
59+
Assert.Equal((IntPtr)expectedPtr,(IntPtr)actualPtr);
60+
}
61+
}
62+
}
63+
64+
[OuterLoop]
65+
[ConditionalFact(typeof(PlatformDetection),nameof(PlatformDetection.Is64BitProcess))]
66+
publicstaticunsafevoidCreateReadOnlySpanFromNullTerminated_Char_ExceedsMaximum()
67+
{
68+
char*mem;
69+
try
70+
{
71+
mem=(char*)Marshal.AllocHGlobal((IntPtr)(sizeof(char)*(2L+int.MaxValue)));
72+
}
73+
catch(OutOfMemoryException)
74+
{
75+
thrownewSkipTestException("Unable to allocate 4GB of memory");
76+
}
77+
78+
try
79+
{
80+
newSpan<char>(mem,int.MaxValue).Fill('s');
81+
*(mem+int.MaxValue)= 's';
82+
*(mem+int.MaxValue+1)='\0';
83+
84+
Assert.Throws<ArgumentException>(()=>MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mem));
85+
}
86+
finally
87+
{
88+
Marshal.FreeHGlobal((IntPtr)mem);
89+
}
90+
}
91+
92+
[OuterLoop]
93+
[ConditionalFact(typeof(PlatformDetection),nameof(PlatformDetection.Is64BitProcess))]
94+
publicstaticunsafevoidCreateReadOnlySpanFromNullTerminated_Byte_ExceedsMaximum()
95+
{
96+
byte*mem;
97+
try
98+
{
99+
mem=(byte*)Marshal.AllocHGlobal((IntPtr)(2L+int.MaxValue));
100+
}
101+
catch(OutOfMemoryException)
102+
{
103+
thrownewSkipTestException("Unable to allocate 2GB of memory");
104+
}
105+
106+
try
107+
{
108+
newSpan<byte>(mem,int.MaxValue).Fill(0xFF);
109+
*(mem+int.MaxValue)=0xFF;
110+
*(mem+int.MaxValue+1)=0;
111+
112+
Assert.Throws<ArgumentException>(()=>MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mem));
113+
}
114+
finally
115+
{
116+
Marshal.FreeHGlobal((IntPtr)mem);
117+
}
118+
}
119+
}
120+
}

‎src/libraries/System.Memory/tests/System.Memory.Tests.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
<CompileInclude="MemoryMarshal\AsReadOnlyRef.cs" />
1515
<CompileInclude="MemoryMarshal\CreateSpan.cs" />
1616
<CompileInclude="MemoryMarshal\CreateReadOnlySpan.cs" />
17+
<CompileInclude="MemoryMarshal\CreateReadOnlySpanFromNullTerminated.cs" />
1718
<CompileInclude="$(CommonPath)..\tests\System\RealFormatterTestsBase.cs"
1819
Link="ParsersAndFormatters\Formatter\RealFormatterTestsBase.cs" />
1920
<CompileInclude="ParsersAndFormatters\Formatter\RealFormatterTests.cs" />

‎src/libraries/System.Private.CoreLib/src/System/Environment.Variables.Windows.cs‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -84,14 +84,12 @@ public static unsafe IDictionary GetEnvironmentVariables()
8484
char*currentPtr=stringPtr;
8585
while(true)
8686
{
87-
intvariableLength=string.wcslen(currentPtr);
88-
if(variableLength==0)
87+
ReadOnlySpan<char>variable=MemoryMarshal.CreateReadOnlySpanFromNullTerminated(currentPtr);
88+
if(variable.IsEmpty)
8989
{
9090
break;
9191
}
9292

93-
varvariable=newReadOnlySpan<char>(currentPtr,variableLength);
94-
9593
// Find the = separating the key and value. We skip entries that begin with =. We also skip entries that don't
9694
// have =, which can happen on some older OSes when the environment block gets corrupted.
9795
inti=variable.IndexOf('=');
@@ -111,7 +109,7 @@ public static unsafe IDictionary GetEnvironmentVariables()
111109
}
112110

113111
// Move to the end of this variable, after its terminator.
114-
currentPtr+=variableLength+1;
112+
currentPtr+=variable.Length+1;
115113
}
116114

117115
returnresults;

‎src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Icu.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -433,7 +433,7 @@ private static unsafe void EnumCalendarInfoCallback(char* calendarStringPtr, Int
433433
{
434434
try
435435
{
436-
varcalendarStringSpan=newReadOnlySpan<char>(calendarStringPtr,string.wcslen(calendarStringPtr));
436+
ReadOnlySpan<char>calendarStringSpan=MemoryMarshal.CreateReadOnlySpanFromNullTerminated(calendarStringPtr);
437437
refIcuEnumCalendarsDatacallbackContext=refUnsafe.As<byte,IcuEnumCalendarsData>(ref*(byte*)context);
438438

439439
if(callbackContext.DisallowDuplicates)

‎src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/MemoryMarshal.cs‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -211,27 +211,49 @@ ref Unsafe.As<TFrom, TTo>(ref MemoryMarshal.GetReference(span)),
211211
}
212212

213213
/// <summary>
214-
///Create a new span over a portion of a regular managed object. This can be useful
214+
///Creates a new span over a portion of a regular managed object. This can be useful
215215
/// if part of a managed object represents a "fixed array." This is dangerous because the
216216
/// <paramref name="length"/> is not checked.
217217
/// </summary>
218218
/// <param name="reference">A reference to data.</param>
219219
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
220-
/// <returns>The lifetime of the returned span will not be validated for safety by span-aware languages.</returns>
220+
/// <returns>A span representing the specified reference and length.</returns>
221+
/// <remarks>The lifetime of the returned span will not be validated for safety by span-aware languages.</remarks>
221222
[MethodImpl(MethodImplOptions.AggressiveInlining)]
222223
publicstaticSpan<T>CreateSpan<T>(refTreference,intlength)=>newSpan<T>(refreference,length);
223224

224225
/// <summary>
225-
///Create a new read-only span over a portion of a regular managed object. This can be useful
226+
///Creates a new read-only span over a portion of a regular managed object. This can be useful
226227
/// if part of a managed object represents a "fixed array." This is dangerous because the
227228
/// <paramref name="length"/> is not checked.
228229
/// </summary>
229230
/// <param name="reference">A reference to data.</param>
230231
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
231-
/// <returns>The lifetime of the returned span will not be validated for safety by span-aware languages.</returns>
232+
/// <returns>A read-only span representing the specified reference and length.</returns>
233+
/// <remarks>The lifetime of the returned span will not be validated for safety by span-aware languages.</remarks>
232234
[MethodImpl(MethodImplOptions.AggressiveInlining)]
233235
publicstaticReadOnlySpan<T>CreateReadOnlySpan<T>(refTreference,intlength)=>newReadOnlySpan<T>(refreference,length);
234236

237+
/// <summary>Creates a new read-only span for a null-terminated string.</summary>
238+
/// <param name="value">The pointer to the null-terminated string of characters.</param>
239+
/// <returns>A read-only span representing the specified null-terminated string, or an empty span if the pointer is null.</returns>
240+
/// <remarks>The returned span does not include the null terminator.</remarks>
241+
/// <exception cref="ArgumentException">The string is longer than <see cref="int.MaxValue"/>.</exception>
242+
[CLSCompliant(false)]
243+
publicstaticunsafeReadOnlySpan<char>CreateReadOnlySpanFromNullTerminated(char*value)=>
244+
value!=null?newReadOnlySpan<char>(value,string.wcslen(value)):
245+
default;
246+
247+
/// <summary>Creates a new read-only span for a null-terminated UTF8 string.</summary>
248+
/// <param name="value">The pointer to the null-terminated string of bytes.</param>
249+
/// <returns>A read-only span representing the specified null-terminated string, or an empty span if the pointer is null.</returns>
250+
/// <remarks>The returned span does not include the null terminator, nor does it validate the well-formedness of the UTF8 data.</remarks>
251+
/// <exception cref="ArgumentException">The string is longer than <see cref="int.MaxValue"/>.</exception>
252+
[CLSCompliant(false)]
253+
publicstaticunsafeReadOnlySpan<byte>CreateReadOnlySpanFromNullTerminated(byte*value)=>
254+
value!=null?newReadOnlySpan<byte>(value,string.strlen(value)):
255+
default;
256+
235257
/// <summary>
236258
/// Get an array segment from the underlying memory.
237259
/// If unable to get the array segment, return false with a default array segment.

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp