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


C# Span.Slice方法代码示例

本文整理汇总了C#中Span.Slice方法的典型用法代码示例。如果您正苦于以下问题:C# Span.Slice方法的具体用法?C# Span.Slice怎么用?C# Span.Slice使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Span的用法示例。


在下文中一共展示了Span.Slice方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CtorSpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks

        public void CtorSpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array)
        {
            Span<byte> span = new Span<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);

                span.Slice(i).Write<byte>(unchecked((byte)(array[i] + 1)));
                Assert.Equal(array[i], span.Slice(i).Read<byte>());
                Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);

                span.Slice(i).Write<MyByte>(unchecked(new MyByte((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,代码行数:25,代码来源:UsageScenarioTests.cs

示例2: TryFormatInt64

        internal static bool TryFormatInt64(long value, byte numberOfBytes, Span<byte> buffer, TextFormat format, EncodingData formattingData, out int bytesWritten)
        {
            Precondition.Require(numberOfBytes <= sizeof(long));

            if (value >= 0)
            {
                return TryFormatUInt64(unchecked((ulong)value), numberOfBytes, buffer, format, formattingData, out bytesWritten);
            }
            else if (format.IsHexadecimal)
            {
                ulong bitMask = GetBitMask(numberOfBytes);
                return TryFormatUInt64(unchecked((ulong)value) & bitMask, numberOfBytes, buffer, format, formattingData, out bytesWritten);
            }
            else
            {
                int minusSignBytes = 0;
                if(!formattingData.TryEncode(EncodingData.Symbol.MinusSign, buffer, out minusSignBytes))
                {
                    bytesWritten = 0;
                    return false;
                }

                int digitBytes = 0;
                if(!TryFormatUInt64(unchecked((ulong)-value), numberOfBytes, buffer.Slice(minusSignBytes), format, formattingData, out digitBytes))
                {
                    bytesWritten = 0;
                    return false;
                }
                bytesWritten = digitBytes + minusSignBytes;
                return true;
            }
        }
开发者ID:AlexGhiondea,项目名称:corefxlab,代码行数:32,代码来源:IntegerFormatter.cs

示例3: ByteSpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent

        public unsafe void ByteSpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent()
        {
            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)
            {
                Span<byte> b1 = new Span<byte>(buffer1pinned, bufferLength);
                Span<byte> b2 = new Span<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(Span<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 (!InvariantParser.TryParse(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:tarekgh,项目名称:corefxlab,代码行数:29,代码来源:ParsedFormat.cs

示例5: SliceStartLengthInt32Overflow

        public void SliceStartLengthInt32Overflow()
        {
            var huge = Marshal.AllocHGlobal(new IntPtr(ThreeGiB));
            try
            {
                var span = new Span<Guid>((void*)huge, GuidThreeGiBLimit);
                Guid guid = Guid.NewGuid();
                var slice = span.Slice(GuidTwoGiBLimit + 1, 20);
                slice[0] = guid;

                slice = span.Slice(GuidOneGiBLimit).Slice(1).Slice(GuidOneGiBLimit);
                Assert.Equal(guid, slice[0]);
            }
            finally
            {
                Marshal.FreeHGlobal(huge);
            }
        }
开发者ID:AlexGhiondea,项目名称:corefxlab,代码行数:18,代码来源:OverflowTests.cs

示例6: TryFormat

        public bool TryFormat(Span<byte> buffer, Format.Parsed format, FormattingData formattingData, out int bytesWritten)
        {
            if (!PrimitiveFormatters.TryFormat(_age, buffer, format, formattingData, out bytesWritten)) return false;

            char symbol = _inMonths ? 'm' : 'y';
            int symbolBytes;
            if (!PrimitiveFormatters.TryFormat(symbol, buffer.Slice(bytesWritten), format, formattingData, out symbolBytes)) return false;

            bytesWritten += symbolBytes;
            return true;
        }
开发者ID:ReedKimble,项目名称:corefxlab,代码行数:11,代码来源:CustomTypeFormatting.cs

示例7: Parse

        public static HttpRequest Parse(Span<byte> bytes)
        {
            int parsed;
            HttpRequestLine requestLine;
            if (!HttpRequestParser.TryParseRequestLine(bytes, out requestLine, out parsed)){
                throw new NotImplementedException();
            }
            bytes = bytes.Slice(parsed);

            HttpHeaders headers;
            if (!HttpRequestParser.TryParseHeaders(bytes, out headers, out parsed))
            {
                throw new NotImplementedException();
            }
            var body = bytes.Slice(parsed + 4); // TODO: this needs to verify two newlines 

            var request = new HttpRequest(requestLine, headers, body);

            return request;
        }
开发者ID:TerabyteX,项目名称:corefxlab,代码行数:20,代码来源:HttpRequestParser.cs

示例8: 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
                {
                    Span<Guid> span = new Span<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);

                    Assert.True(Unsafe.AreSame<Guid>(ref expected, ref span.GetItem(bigIndex)));

                    Span<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,代码行数:41,代码来源:Overflow.cs

示例9: CtorSpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks

        public void CtorSpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array)
        {
            Span<byte> span = new Span<byte>(array);
            Assert.Equal(array.Length, span.Length);

            Assert.NotSame(array, span.ToArray());
            Assert.True(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);

                span.Slice(i).Write<byte>(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);

                span.Slice(i).Write<MyByte>(unchecked(new MyByte((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:jkotas,项目名称:corefxlab,代码行数:41,代码来源:UsageScenarioTests.cs

示例10: TryFormat

        public bool TryFormat(Span<byte> buffer, out int bytesWritten, TextFormat format, EncodingData encoding)
        {
            if (!PrimitiveFormatter.TryFormat(_age, buffer, out bytesWritten, format, encoding)) return false;


            char symbol = _inMonths ? 'm' : 'y';
            int symbolBytes;
            if (!PrimitiveFormatter.TryEncode(symbol, buffer.Slice(bytesWritten), out symbolBytes, encoding.TextEncoding)) return false;

            bytesWritten += symbolBytes;
            return true;
        }
开发者ID:AlexGhiondea,项目名称:corefxlab,代码行数:12,代码来源:CustomTypeFormatting.cs

示例11: TestCore

        protected override void TestCore(string raw, string expected)
        {
            var input = GetBytes(raw);
            var destination = new Span<byte>(new byte[input.Length]);

            var len = UrlEncoder.Decode(input, destination);
            Assert.True(len <= input.Length);

            var unescaped = destination.Slice(0, len);
            Assert.False(unescaped == input.Slice(0, len));

            var outputDecoded = Encoding.UTF8.GetString(unescaped.ToArray());
            Assert.Equal(expected, outputDecoded);
        }
开发者ID:AlexGhiondea,项目名称:corefxlab,代码行数:14,代码来源:UnescapeUrlPathTests.cs

示例12: TryDecodeCodePointBackwards

        public static bool TryDecodeCodePointBackwards(Span<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:hanin,项目名称:corefxlab,代码行数:22,代码来源:Utf8Encoder.cs

示例13: TryFormatNumber

        public static bool TryFormatNumber(double value, bool isSingle, Span<byte> buffer, Format.Parsed format, FormattingData formattingData, out int bytesWritten)
        {
            Precondition.Require(format.Symbol == 'G' || format.Symbol == 'E' || format.Symbol == 'F');

            bytesWritten = 0;
            int written;

            if (Double.IsNaN(value))
            {
                return formattingData.TryWriteSymbol(FormattingData.Symbol.NaN, buffer, out bytesWritten);
            }

            if (Double.IsInfinity(value))
            {
                if (Double.IsNegativeInfinity(value))
                {
                    if (!formattingData.TryWriteSymbol(FormattingData.Symbol.MinusSign, buffer, out written))
                    {
                        bytesWritten = 0;
                        return false;
                    }
                    bytesWritten += written;
                }
                if (!formattingData.TryWriteSymbol(FormattingData.Symbol.InfinitySign, buffer.Slice(bytesWritten), out written))
                {
                    bytesWritten = 0;
                    return false;
                }
                bytesWritten += written;
                return true;
            }

            // TODO: the lines below need to be replaced with properly implemented algorithm
            // the problem is the algorithm is complex, so I am commiting a stub for now
            var hack = value.ToString(format.Symbol.ToString());
            return hack.TryFormat(buffer, default(Format.Parsed), formattingData, out bytesWritten);
        }
开发者ID:geoffkizer,项目名称:corefxlab,代码行数:37,代码来源:FloatFormatter.cs

示例14: ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCasesNative

        public unsafe void ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCasesNative(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount)
        {
            IntPtr pa = Marshal.AllocHGlobal(a.Length);
            Span<byte> na = new Span<byte>(pa.ToPointer(), a.Length);
            a.CopyTo(na);

            IntPtr pb = Marshal.AllocHGlobal(b.Length);
            Span<byte> nb = new Span<byte>(pb.ToPointer(), b.Length);
            b.CopyTo(nb);

            ReadOnlySpan<byte> spanA = na.Slice(aidx, acount);
            Span<byte> spanB = nb.Slice(bidx, bcount);

            if (expected != null) {               
                spanA.CopyTo(spanB);
                Assert.Equal(expected, b);

                ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected);
                ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b);
                Assert.True(spanExpected.SequenceEqual(spanBAll));
            }
            else {
                Assert.ThrowsAny<Exception>(() => { spanA.CopyTo(spanB); });
            }

            Marshal.FreeHGlobal(pa);
            Marshal.FreeHGlobal(pb);
        }
开发者ID:AlexGhiondea,项目名称:corefxlab,代码行数:28,代码来源:UsageScenarioTests.cs

示例15: TryFormatDateTimeFormatO

        static bool TryFormatDateTimeFormatO(DateTimeOffset value, bool isDateTime, Span<byte> buffer, FormattingData formattingData, out int bytesWritten)
        {
            bytesWritten = 0;
            if (!TryWriteInt32(value.Year, buffer, D4, formattingData, ref bytesWritten)) { return false; }
            if (!TryWriteChar('-', buffer, formattingData, ref bytesWritten)) { return false; }

            if (!TryWriteInt32(value.Month, buffer, D2, formattingData, ref bytesWritten)) { return false; }
            if (!TryWriteChar('-', buffer, formattingData, ref bytesWritten)) { return false; }

            if (!TryWriteInt32(value.Day, buffer, D2, formattingData, ref bytesWritten)) { return false; }
            if (!TryWriteChar('T', buffer, formattingData, ref bytesWritten)) { return false; }

            if (!TryWriteInt32(value.Hour, buffer, D2, formattingData, ref bytesWritten)) { return false; }
            if (!TryWriteChar(':', buffer, formattingData, ref bytesWritten)) { return false; }

            if (!TryWriteInt32(value.Minute, buffer, D2, formattingData, ref bytesWritten)) { return false; }
            if (!TryWriteChar(':', buffer, formattingData, ref bytesWritten)) { return false; }

            if (!TryWriteInt32(value.Second, buffer, D2, formattingData, ref bytesWritten)) { return false; }

            // add optional fractional second only if needed...
            var rounded = new DateTimeOffset(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second, TimeSpan.Zero);
            var delta = value - rounded;

            if (delta.Ticks != 0)
            {
                if (!TryWriteChar('.', buffer, formattingData, ref bytesWritten)) { return false; }
                var timeFrac = delta.Ticks * FractionalTimeScale / System.TimeSpan.TicksPerSecond;
                if (!TryWriteInt64(timeFrac, buffer, D7, formattingData, ref bytesWritten)) { return false; }
            }

            if (isDateTime)
            {
                if (!TryWriteChar('Z', buffer, formattingData, ref bytesWritten)) { return false; }
            }
            else
            {
                if (!TryWriteChar('+', buffer, formattingData, ref bytesWritten)) { return false; }
                int bytes;
                if (!value.Offset.TryFormat(buffer.Slice(bytesWritten), t, formattingData, out bytes)) { return false; }
                bytesWritten += bytes;
            }

            return true;
        }
开发者ID:ryaneliseislalom,项目名称:corefxlab,代码行数:45,代码来源:PrimitiveFormatters_time.cs


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