本文整理汇总了C#中ReadOnlySpan.Slice方法的典型用法代码示例。如果您正苦于以下问题:C# ReadOnlySpan.Slice方法的具体用法?C# ReadOnlySpan.Slice怎么用?C# ReadOnlySpan.Slice使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ReadOnlySpan
的用法示例。
在下文中一共展示了ReadOnlySpan.Slice方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CtorReadOnlySpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks
public void CtorReadOnlySpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array)
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(array);
Assert.Equal(array.Length, span.Length);
Assert.NotSame(array, span.CreateArray());
Assert.False(span.Equals(array));
ReadOnlySpan<byte>.Enumerator it = span.GetEnumerator();
for (int i = 0; i < span.Length; i++)
{
Assert.True(it.MoveNext());
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
array[i] = unchecked((byte)(array[i] + 1));
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
}
Assert.False(it.MoveNext());
it.Reset();
for (int i = 0; i < span.Length; i++)
{
Assert.True(it.MoveNext());
Assert.Equal(array[i], it.Current);
}
Assert.False(it.MoveNext());
}
示例2: Encode
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <param name="destination"></param>
/// <returns>Number of bytes written to the destination.</returns>
public static int Encode(ReadOnlySpan<byte> source, Span<byte> destination)
{
int di = 0;
int si = 0;
byte b0, b1, b2, b3;
for (; si<source.Length - 2;) {
var result = Encode(source.Slice(si));
si += 3;
destination.Slice(di).Write(result);
di += 4;
}
if (si == source.Length - 1) {
Encode(source[si], 0, 0, out b0, out b1, out b2, out b3);
destination[di++] = b0;
destination[di++] = b1;
destination[di++] = s_encodingMap[64];
destination[di++] = s_encodingMap[64];
}
else if(si == source.Length - 2) {
Encode(source[si++], source[si], 0, out b0, out b1, out b2, out b3);
destination[di++] = b0;
destination[di++] = b1;
destination[di++] = b2;
destination[di++] = s_encodingMap[64];
}
return di;
}
示例3: ByteReadOnlySpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent
public unsafe void ByteReadOnlySpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent()
{
const int bufferLength = 128;
byte[] buffer1 = new byte[bufferLength];
byte[] buffer2 = new byte[bufferLength];
for (int i = 0; i < bufferLength; i++)
{
buffer1[i] = (byte)(bufferLength + 1 - i);
buffer2[i] = (byte)(bufferLength + 1 - i);
}
fixed (byte* buffer1pinned = buffer1)
fixed (byte* buffer2pinned = buffer2)
{
ReadOnlySpan<byte> b1 = new ReadOnlySpan<byte>(buffer1pinned, bufferLength);
ReadOnlySpan<byte> b2 = new ReadOnlySpan<byte>(buffer2pinned, bufferLength);
for (int i = 0; i < bufferLength; i++)
{
for (int diffPosition = i; diffPosition < bufferLength; diffPosition++)
{
buffer1[diffPosition] = unchecked((byte)(buffer1[diffPosition] + 1));
Assert.False(b1.Slice(i).SequenceEqual(b2.Slice(i)));
}
}
}
}
示例4: Parse
// TODO: format should be ReadOnlySpan<T>
public static Format.Parsed Parse(ReadOnlySpan<char> format)
{
if (format.Length == 0)
{
return default(Format.Parsed);
}
uint precision = NoPrecision;
if (format.Length > 1)
{
var span = format.Slice(1, format.Length - 1);
if (!PrimitiveParser.TryParseUInt32(span, out precision))
{
throw new NotImplementedException("UnableToParsePrecision");
}
if (precision > Parsed.MaxPrecision)
{
// TODO: this is a contract violation
throw new Exception("PrecisionValueOutOfRange");
}
}
// TODO: this is duplicated from above. It needs to be refactored
var specifier = format[0];
return new Parsed(specifier, (byte)precision);
}
示例5: CtorReadOnlySpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks
public void CtorReadOnlySpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array)
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(array);
Assert.Equal(array.Length, span.Length);
Assert.NotSame(array, span.ToArray());
for (int i = 0; i < span.Length; i++)
{
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
array[i] = unchecked((byte)(array[i] + 1));
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
}
}
示例6: IndexOverflow
public static void IndexOverflow()
{
//
// Although Span constrains indexes to 0..2Gb, it does not similarly constrain index * sizeof(T).
// Make sure that internal offset calculcations handle the >2Gb case properly.
//
unsafe
{
byte* pMemory;
try
{
pMemory = (byte*)Marshal.AllocHGlobal((IntPtr)ThreeGiB);
}
catch (Exception)
{
return; // It's not implausible to believe that a 3gb allocation will fail - if so, skip this test to avoid unnecessary test flakiness.
}
try
{
ReadOnlySpan<Guid> span = new ReadOnlySpan<Guid>(pMemory, GuidThreeGiBLimit);
int bigIndex = checked(GuidTwoGiBLimit + 1);
uint byteOffset = checked((uint)bigIndex * (uint)sizeof(Guid));
Assert.True(byteOffset > (uint)int.MaxValue); // Make sure byteOffset actually overflows 2Gb, or this test is pointless.
ref Guid expected = ref Unsafe.AsRef<Guid>(((byte*)pMemory) + byteOffset);
Guid expectedGuid = Guid.NewGuid();
expected = expectedGuid;
Guid actualGuid = span[bigIndex];
Assert.Equal(expectedGuid, actualGuid);
ReadOnlySpan<Guid> slice = span.Slice(bigIndex);
Assert.True(Unsafe.AreSame<Guid>(ref expected, ref slice.DangerousGetPinnableReference()));
slice = span.Slice(bigIndex, 1);
Assert.True(Unsafe.AreSame<Guid>(ref expected, ref slice.DangerousGetPinnableReference()));
}
finally
{
Marshal.FreeHGlobal((IntPtr)pMemory);
}
}
}
示例7: Parse
public static HttpRequest Parse(ReadOnlySpan<byte> bytes)
{
int parsed;
HttpRequestLine requestLine;
if (!HttpRequestParser.TryParseRequestLine(bytes, out requestLine, out parsed)){
throw new NotImplementedException("request line parser");
}
bytes = bytes.Slice(parsed);
HttpHeaders headers;
if (!HttpRequestParser.TryParseHeaders(bytes, out headers, out parsed))
{
throw new NotImplementedException("headers parser");
}
var body = bytes.Slice(parsed);
var request = new HttpRequest(requestLine, headers, body);
return request;
}
示例8: TryParseHeaders
internal static bool TryParseHeaders(ReadOnlySpan<byte> bytes, out HttpHeaders headers, out int parsed)
{
for(int i=0; i<bytes.Length - 3; i++)
{
if(bytes[i] == '\r' && bytes[i+1] == '\n' && bytes[i+2] == '\r' && bytes[i+3] == '\n')
{
parsed = i + 4;
headers = new HttpHeaders(bytes.Slice(0, i + 2));
return true;
}
}
headers = default(HttpHeaders);
parsed = 0;
return false;
}
示例9: TryParseUInt32
public static bool TryParseUInt32(ReadOnlySpan<byte> text, EncodingData encoding, TextFormat numericFormat,
out uint value, out int bytesConsumed)
{
// Precondition replacement
if (text.Length < 1)
{
value = default(uint);
bytesConsumed = 0;
return false;
}
value = default(uint);
bytesConsumed = 0;
if (encoding.IsInvariantUtf8)
{
for (int byteIndex = 0; byteIndex < text.Length; byteIndex++) // loop through the byte array
{
byte nextByteVal = (byte)(text[byteIndex] - '0');
if (nextByteVal > 9) // if nextByteVal > 9, we know it is not a digit because any value less than '0' will overflow
// to greater than 9 since byte is an unsigned type.
{
if (bytesConsumed == 0) // check to see if we've processed any digits at all
{
return false;
}
else
{
return true; // otherwise return true
}
}
else if (value > UInt32.MaxValue / 10)
{
value = default(uint);
bytesConsumed = 0;
return false;
}
// This next check uses a hardcoded 6 because the max values for unsigned types all end in 5s.
else if (value == UInt32.MaxValue / 10 && nextByteVal >= 6) // overflow
{
value = default(uint);
bytesConsumed = 0;
return false;
}
value = (uint)(value * 10 + nextByteVal); // left shift the value and add the nextByte
bytesConsumed++;
}
return true;
}
else if (encoding.IsInvariantUtf16)
{
for (int byteIndex = 0; byteIndex < text.Length - 1; byteIndex += 2) // loop through the byte array two bytes at a time for UTF-16
{
byte byteAfterNext = text[byteIndex + 1];
byte nextByteVal = (byte)(text[byteIndex] - '0');
if (nextByteVal > 9 || byteAfterNext != 0) // if the second byte isn't zero, this isn't an ASCII-equivalent code unit and we can quit here
// if nextByteVal > 9, we know it is not a digit because any value less than '0' will overflow
// to greater than 9 since byte is an unsigned type.
{
if (bytesConsumed == 0) // check to see if we've processed any digits at all
{
return false;
}
else
{
return true; // otherwise return true
}
}
else if (value > UInt32.MaxValue / 10)
{
value = default(uint);
bytesConsumed = 0;
return false;
}
// This next check uses a hardcoded 6 because the max values for unsigned types all end in 5s.
else if (value == UInt32.MaxValue / 10 && nextByteVal >= 6) // overflow
{
value = default(uint);
bytesConsumed = 0;
return false;
}
value = (uint)(value * 10 + nextByteVal); // left shift the value and add the nextByte
bytesConsumed += 2;
}
return true;
}
else
{
int byteIndex = 0;
while (byteIndex < text.Length)
{
uint result;
int consumed;
bool success = encoding.TryParseSymbol(text.Slice(byteIndex), out result, out consumed);
if (!success || result > 9)
{
if (bytesConsumed == 0) // check to see if we've processed any digits at all
//.........这里部分代码省略.........
示例10: TryDecodeCodePointBackwards
public static bool TryDecodeCodePointBackwards(ReadOnlySpan<byte> buffer, out UnicodeCodePoint codePoint, out int encodedBytes)
{
if (TryFindEncodedCodePointBytesCountGoingBackwards(buffer, out encodedBytes))
{
int realEncodedBytes;
// TODO: Inline decoding, as the invalid surrogate check can be done faster
bool ret = TryDecodeCodePoint(buffer.Slice(buffer.Length - encodedBytes), out codePoint, out realEncodedBytes);
if (ret && encodedBytes != realEncodedBytes)
{
// invalid surrogate character
// we know the character length by iterating on surrogate characters from the end
// but the first byte of the character has also encoded length
// seems like the lengths don't match
return false;
}
return true;
}
codePoint = default(UnicodeCodePoint);
encodedBytes = default(int);
return false;
}
示例11: ReadOnlySliceStartLengthUInt32Overflow
public void ReadOnlySliceStartLengthUInt32Overflow()
{
var huge = Marshal.AllocHGlobal(new IntPtr(ThreeGiB));
try
{
var mutable = new Span<Guid>((void*)huge, GuidThreeGiBLimit);
var span = new ReadOnlySpan<Guid>((void*)huge, GuidThreeGiBLimit);
Guid guid = Guid.NewGuid();
var slice = span.Slice(GuidTwoGiBLimit + 1, 20);
mutable[GuidTwoGiBLimit + 1] = guid;
Assert.Equal(guid, slice[0]);
slice = span.Slice(GuidOneGiBLimit).Slice(1).Slice(GuidOneGiBLimit);
Assert.Equal(guid, slice[0]);
}
finally
{
Marshal.FreeHGlobal(huge);
}
}
示例12: TryParseInt16
//.........这里部分代码省略.........
return false;
}
// This next check uses a hardcoded 8 because the max values for unsigned types all end in 7s.
// The min values all end in 8s, which is why that addition exists.
else if (value == Int16.MaxValue / 10 && nextByteVal >= 8 + (negative ? 1 : 0) ) // overflow
{
value = default(short);
bytesConsumed = 0;
return false;
}
value = (short)(value * 10 + nextByteVal); // parse the current digit to a short and add it to the left-shifted value
bytesConsumed += 2; // increment the number of bytes consumed, then loop
}
if (negative) // We check if the value is negative at the very end to save on comp time
{
value = (short)-value;
if (value > 0)
{
value = 0;
bytesConsumed = 0;
return false;
}
}
return true;
}
else
{
int codeUnitsConsumed = 0;
while (bytesConsumed + index < text.Length)
{
uint result;
int consumed;
bool success = encoding.TryParseSymbol(text.Slice(bytesConsumed + index), out result, out consumed);
if (!success || result > 9)
{
if (bytesConsumed == 0 && result == (int)EncodingData.Symbol.MinusSign)
{
negative = true;
signed = true;
bytesConsumed += consumed;
codeUnitsConsumed++;
}
else if (bytesConsumed == 0 && result == (int)EncodingData.Symbol.PlusSign)
{
negative = true;
signed = true;
bytesConsumed += consumed;
}
else if (codeUnitsConsumed == 1 && signed) // if the first character happened to be a '-' or a '+', we reset the byte counter so logic proceeds as normal.
{
bytesConsumed = 0;
return false;
}
else if (bytesConsumed == 0) // check to see if we've processed any digits at all
{
return false;
}
else
{
if (negative) // We check if the value is negative at the very end to save on comp time
{
value = (short)-value;
if (value > 0)
{