当前位置: 首页>>代码示例>>C#>>正文


C# ReadOnlySpan.Slice方法代码示例

本文整理汇总了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());
        }
开发者ID:hanin,项目名称:corefxlab,代码行数:31,代码来源:UsageScenarioTests.cs

示例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; 
        }
开发者ID:jkotas,项目名称:corefxlab,代码行数:35,代码来源:Base64.cs

示例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)));
                    }
                }
            }
        }
开发者ID:GrimDerp,项目名称:corefxlab,代码行数:28,代码来源:BasicUnitTests.cs

示例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);
        }
开发者ID:jkotas,项目名称:corefxlab,代码行数:29,代码来源:ParsedFormat.cs

示例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);
            }
        }
开发者ID:AlexGhiondea,项目名称:corefxlab,代码行数:17,代码来源:UsageScenarioTests.cs

示例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);
                }
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:43,代码来源:Overflow.cs

示例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;
        }
开发者ID:GrimDerp,项目名称:corefxlab,代码行数:20,代码来源:HttpRequestParser.cs

示例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;
        }
开发者ID:GrimDerp,项目名称:corefxlab,代码行数:16,代码来源:HttpRequestParser.cs

示例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
//.........这里部分代码省略.........
开发者ID:AlexGhiondea,项目名称:corefxlab,代码行数:101,代码来源:PrimitiveParser_unsigned.cs

示例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;
        }
开发者ID:benaadams,项目名称:corefxlab,代码行数:22,代码来源:Utf8Encoder.cs

示例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);
            }
        }
开发者ID:AlexGhiondea,项目名称:corefxlab,代码行数:20,代码来源:OverflowTests.cs

示例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)
								{
开发者ID:AlexGhiondea,项目名称:corefxlab,代码行数:67,代码来源:PrimitiveParser_signed.cs


注:本文中的ReadOnlySpan.Slice方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。