• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ArraySegment类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ArraySegment的典型用法代码示例。如果您正苦于以下问题:C# ArraySegment类的具体用法?C# ArraySegment怎么用?C# ArraySegment使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ArraySegment类属于命名空间,在下文中一共展示了ArraySegment类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: HandleTcpReceived

        internal void HandleTcpReceived(uint sequenceNumber, ArraySegment<byte> data)
        {
            var dataPosition = SequenceNumberToBytesReceived(sequenceNumber);
            if (dataPosition == BytesReceived)
            {
                OnDataReceived(data);
                BytesReceived += data.Count;
            }
            else
            {
                var dataArray = new byte[data.Count];
                Array.Copy(data.Array, data.Offset, dataArray, 0, data.Count);
                if (!_bufferedPackets.ContainsKey(dataPosition) || _bufferedPackets[dataPosition].Length < dataArray.Length)
                {
                    _bufferedPackets[dataPosition] = dataArray;
                }
            }

            long firstBufferedPosition;
            while (_bufferedPackets.Any() && ((firstBufferedPosition = _bufferedPackets.Keys.First()) <= BytesReceived))
            {
                var dataArray = _bufferedPackets[firstBufferedPosition];
                _bufferedPackets.Remove(firstBufferedPosition);

                var alreadyReceivedBytes = BytesReceived - firstBufferedPosition;
                Debug.Assert(alreadyReceivedBytes >= 0);

                if (alreadyReceivedBytes < dataArray.Length)
                {
                    var count = dataArray.Length - alreadyReceivedBytes;
                    OnDataReceived(new ArraySegment<byte>(dataArray, (int)alreadyReceivedBytes, (int)count));
                    BytesReceived += count;
                }
            }
        }
开发者ID:kuko0411,项目名称:TeraDamageMeter,代码行数:35,代码来源:TcpConnection.cs


示例2: DeserializeObject

		protected override object DeserializeObject(ArraySegment<byte> value)
		{
			var ds = new NetDataContractSerializer();

			using (var ms = new MemoryStream(value.Array, value.Offset, value.Count))
				return ds.Deserialize(ms);
		}
开发者ID:javithalion,项目名称:NCache,代码行数:7,代码来源:DataContractTranscoder.cs


示例3: Encrypt_KnownKey

        public void Encrypt_KnownKey()
        {
            // Arrange
            Secret kdk = new Secret(Encoding.UTF8.GetBytes("master key"));
            GcmAuthenticatedEncryptor encryptor = new GcmAuthenticatedEncryptor(kdk, CachedAlgorithmHandles.AES_GCM, symmetricAlgorithmKeySizeInBytes: 128 / 8, genRandom: new SequentialGenRandom());
            ArraySegment<byte> plaintext = new ArraySegment<byte>(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }, 2, 3);
            ArraySegment<byte> aad = new ArraySegment<byte>(new byte[] { 7, 6, 5, 4, 3, 2, 1, 0 }, 1, 4);

            // Act
            byte[] retVal = encryptor.Encrypt(
                plaintext: plaintext,
                additionalAuthenticatedData: aad,
                preBufferSize: 3,
                postBufferSize: 4);

            // Assert

            // retVal := 00 00 00 (preBuffer)
            //         | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F (keyModifier)
            //         | 10 11 12 13 14 15 16 17 18 19 1A 1B (nonce)
            //         | 43 B6 91 (encryptedData)
            //         | 8D 0D 66 D9 A1 D9 44 2D 5D 8E 41 DA 39 60 9C E8 (authTag)
            //         | 00 00 00 00 (postBuffer)

            string retValAsString = Convert.ToBase64String(retVal);
            Assert.Equal("AAAAAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaG0O2kY0NZtmh2UQtXY5B2jlgnOgAAAAA", retValAsString);
        }
开发者ID:leloulight,项目名称:DataProtection,代码行数:27,代码来源:GcmAuthenticatedEncryptorTests.cs


示例4: MinimumSubsequenceProduct

        static int MinimumSubsequenceProduct(ArraySegment<int> Sequence)
        {
            if (Sequence.Count == 1)
                return Sequence.Array[Sequence.Offset];
            int Middle = Sequence.Count / 2;
            int LeftProduct = MinimumSubsequenceProduct(new ArraySegment<int>(Sequence.Array, Sequence.Offset, Middle));
            int RightProduct = MinimumSubsequenceProduct(new ArraySegment<int>(Sequence.Array, Sequence.Offset + Middle, Middle));

            int MiddleProduct = 1;
            int MiddleLeftProduct = 1;
            int TempLeftProduct = 1;
            for (int i = Middle; i >= Sequence.Offset; i--) {
                TempLeftProduct *= Sequence.Array[i];
                if (TempLeftProduct < MiddleLeftProduct)
                    MiddleLeftProduct = TempLeftProduct;
            }

            int MiddleRightProduct = 1;
            int TempRightProduct = 1;
            for (int i = Middle + 1; i < Sequence.Offset + Sequence.Count; i++) {
                TempRightProduct *= Sequence.Array[i];
                if (TempRightProduct < MiddleRightProduct)
                    MiddleRightProduct = TempRightProduct;
            }
            MiddleProduct = MiddleLeftProduct * MiddleRightProduct;
            return Math.Min(Math.Min(LeftProduct, MiddleProduct), RightProduct);
        }
开发者ID:MadRubicant,项目名称:Project-Euler,代码行数:27,代码来源:Subsequence.cs


示例5: SettingsPair

 // Outgoing
 public SettingsPair(SettingsFlags flags, SettingsIds id, int value)
 {
     _bufferSegment = new ArraySegment<byte>(new byte[PairSize], 0, PairSize);
     Flags = flags;
     Id = id;
     Value = value;
 }
开发者ID:TrickyCat,项目名称:http2-katana,代码行数:8,代码来源:SettingsPair.cs


示例6: ReadMessage

        /// <inheritdoc />
        public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
        {
            // Treat the alternate as native
            if (IsAlternateContent(contentType))
            {
                // HACK: Should see if we have a declr or some xml
               contentType = this.contentType;
            }

            var msgContents = new byte[buffer.Count];
            Array.Copy(buffer.Array, buffer.Offset, msgContents, 0, msgContents.Length);
            bufferManager.ReturnBuffer(buffer.Array);

            // Most interoperable to include the xml declaration
            writerSettings.OmitXmlDeclaration = false;

            // Save the encoding for when we write the response
            writerSettings.Encoding = msgContents.GetEncoding(contentType);
            var xmlDeclEncoding = msgContents.GetXmlDeclEncoding(writerSettings.Encoding);

            // Check if the two encodings align
            if (xmlDeclEncoding != null && xmlDeclEncoding.WebName == writerSettings.Encoding.WebName)
            {
                // Need to recode
                msgContents = Encoding.Convert(writerSettings.Encoding, xmlDeclEncoding, msgContents);
            }

            var stream = new MemoryStream(msgContents);
            return ReadMessage(stream, int.MaxValue);
        }
开发者ID:RustyF,项目名称:EnergyTrading-Core,代码行数:31,代码来源:CustomTextMessageEncoder.cs


示例7: Handshake

        public static byte[] Handshake(WebSocketHttpRequest request)
        {
            FleckLog.Debug("Building Draft76 Response");

            var builder = new StringBuilder();
            builder.Append("HTTP/1.1 101 WebSocket Protocol Handshake\r\n");
            builder.Append("Upgrade: WebSocket\r\n");
            builder.Append("Connection: Upgrade\r\n");
            builder.AppendFormat("Sec-WebSocket-Origin: {0}\r\n",  request["Origin"]);
            builder.AppendFormat("Sec-WebSocket-Location: {0}://{1}{2}\r\n", request.Scheme, request["Host"], request.Path);

            if (request.Headers.ContainsKey("Sec-WebSocket-Protocol"))
                builder.AppendFormat("Sec-WebSocket-Protocol: {0}\r\n", request["Sec-WebSocket-Protocol"]);

            builder.Append("\r\n");

            var key1 = request["Sec-WebSocket-Key1"];
            var key2 = request["Sec-WebSocket-Key2"];
            var challenge = new ArraySegment<byte>(request.Bytes, request.Bytes.Length - 8, 8);

            var answerBytes = CalculateAnswerBytes(key1, key2, challenge);

            byte[] byteResponse = Encoding.ASCII.GetBytes(builder.ToString());
            int byteResponseLength = byteResponse.Length;
            Array.Resize(ref byteResponse, byteResponseLength + answerBytes.Length);
            Array.Copy(answerBytes, 0, byteResponse, byteResponseLength, answerBytes.Length);

            return byteResponse;
        }
开发者ID:smerrell,项目名称:Fleck,代码行数:29,代码来源:Draft76Handler.cs


示例8: DeserializeObject

        protected override object DeserializeObject(ArraySegment<byte> value) {
            Byte[] buffer;
            if (value.Offset != 0) {
                buffer = new Byte[value.Count];
                Array.Copy(value.Array, value.Offset, buffer, 0, value.Count);
            }
            else {
                buffer = value.Array;
            }

            Boolean isJson = false;
            if (buffer[0] == 123 && buffer[buffer.Length - 1] == 125) {
                isJson = true;
            }
            if (!isJson) {
                var isOrignalObjectByte = buffer.Take(10).Distinct().All(_donetBytes.Contains);
                isJson = !isOrignalObjectByte;
            }

            if (isJson) {
                return JsonDeserialize(buffer);
            }
            else {
                try {
                    return base.DeserializeObject(value);
                }
                catch (SerializationException) {
                    // Log or something
                    return JsonDeserialize(buffer);
                }
            }
        }
开发者ID:wxr524720,项目名称:Jusfr.Caching,代码行数:32,代码来源:NewtonsoftJsonTranscoder.cs


示例9: GetMessage

 private static void GetMessage(Tuple<int, WebSocket> connection, WebSocketReceiveResult result, ArraySegment<byte> bytes)
 {
     var connectionId = connection.Item1;
     var webSocket = connection.Item2;
     var message = Encoding.UTF8.GetString(bytes.Array, 0, result.Count);
     Broadcast(message, connectionId, result.EndOfMessage);
 }
开发者ID:streamcode9,项目名称:chat,代码行数:7,代码来源:WebSocketsHelper.cs


示例10: Listen

        private static async Task Listen(Tuple<int, WebSocket> connection)
        {            
            const int maxMsgSize = 1024;
            var webSocket = connection.Item2;
            var buffer = new ArraySegment<byte>(new byte[maxMsgSize]);
            WebSocketReceiveResult result = null;

            do
            {
                logger.LogVerbose("Listen");

                try {
                    result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
                }
                catch(Exception ex)
                {
                    logger.LogVerbose("ReceiveAsync error: {0}", ex.Message);
                    await webSocket.CloseAsync(WebSocketCloseStatus.ProtocolError, "webSocket.ReceiveAsync error", CancellationToken.None);
                    return;
                }                

                GetMessage(connection, result, buffer);
            } while (!result.CloseStatus.HasValue);

            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
开发者ID:streamcode9,项目名称:chat,代码行数:26,代码来源:WebSocketsHelper.cs


示例11: ConcateOperation

		internal ConcateOperation(ConcatenationMode mode, string key, ArraySegment<byte> data)
			: base(mode == ConcatenationMode.Append
					? StoreCommand.Append
					: StoreCommand.Prepend, key, new CacheItem() { Data = data, Flags = 0 }, 0, 0)
		{
			this.mode = mode;
		}
开发者ID:xianrendzw,项目名称:LightFramework.Net,代码行数:7,代码来源:ConcateOperation.cs


示例12: Send

        public void Send(ArraySegment<byte> segment)
        {
            if (!m_Connected || m_Session == null)
                throw new Exception("The socket is not connected.");

            m_Session.Send(segment);
        }
开发者ID:wujun4code,项目名称:SuperSocket.ClientEngine,代码行数:7,代码来源:EasyClientBase.Net20.cs


示例13: WebSocketBuffer

        private WebSocketBuffer(ArraySegment<byte> internalBuffer, int receiveBufferSize, int sendBufferSize)
        {
            Contract.Assert(internalBuffer != null, "'internalBuffer' MUST NOT be NULL.");
            Contract.Assert(receiveBufferSize >= MinReceiveBufferSize,
                "'receiveBufferSize' MUST be at least " + MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");
            Contract.Assert(sendBufferSize >= MinSendBufferSize,
                "'sendBufferSize' MUST be at least " + MinSendBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");
            Contract.Assert(receiveBufferSize <= MaxBufferSize,
                "'receiveBufferSize' MUST NOT exceed " + MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");
            Contract.Assert(sendBufferSize <= MaxBufferSize,
                "'sendBufferSize' MUST NOT exceed  " + MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");

            m_ReceiveBufferSize = receiveBufferSize;
            m_SendBufferSize = sendBufferSize;
            m_InternalBuffer = internalBuffer;
            m_GCHandle = GCHandle.Alloc(internalBuffer.Array, GCHandleType.Pinned);
            // Size of the internal buffer owned exclusively by the WSPC.
            int nativeBufferSize = m_ReceiveBufferSize + m_SendBufferSize + NativeOverheadBufferSize;
            m_StartAddress = Marshal.UnsafeAddrOfPinnedArrayElement(internalBuffer.Array, internalBuffer.Offset).ToInt64();
            m_EndAddress = m_StartAddress + nativeBufferSize;
            m_NativeBuffer = new ArraySegment<byte>(internalBuffer.Array, internalBuffer.Offset, nativeBufferSize);
            m_PayloadBuffer = new ArraySegment<byte>(internalBuffer.Array,
                m_NativeBuffer.Offset + m_NativeBuffer.Count, 
                m_ReceiveBufferSize);
            m_PropertyBuffer = new ArraySegment<byte>(internalBuffer.Array,
                m_PayloadBuffer.Offset + m_PayloadBuffer.Count,
                s_PropertyBufferSize);
            m_SendBufferState = SendBufferState.None;
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:29,代码来源:WebSocketBuffer.cs


示例14: DeriveKeysWithContextHeader

 public static void DeriveKeysWithContextHeader(byte[] kdk, ArraySegment<byte> label, byte[] contextHeader, ArraySegment<byte> context, Func<byte[], HashAlgorithm> prfFactory, ArraySegment<byte> output)
 {
     byte[] combinedContext = new byte[checked(contextHeader.Length + context.Count)];
     Buffer.BlockCopy(contextHeader, 0, combinedContext, 0, contextHeader.Length);
     Buffer.BlockCopy(context.Array, context.Offset, combinedContext, contextHeader.Length, context.Count);
     DeriveKeys(kdk, label, new ArraySegment<byte>(combinedContext), prfFactory, output);
 }
开发者ID:leloulight,项目名称:DataProtection,代码行数:7,代码来源:ManagedSP800_108_CTR_HMACSHA512.cs


示例15: GetPublicKey

        public static void GetPublicKey(ArraySegment<byte> publicKey, ArraySegment<byte> privateKey)
        {
            if (publicKey.Array == null)
                throw new ArgumentNullException("publicKey.Array");
            if (privateKey.Array == null)
                throw new ArgumentNullException("privateKey.Array");
            if (publicKey.Count != PublicKeySizeInBytes)
                throw new ArgumentException("privateKey.Count must be 32");
            if (privateKey.Count != PrivateKeySizeInBytes)
                throw new ArgumentException("privateKey.Count must be 32");

            // hack: abusing publicKey as temporary storage
            // todo: remove hack
            for (int i = 0; i < 32; i++)
            {
                publicKey.Array[publicKey.Offset + i] = privateKey.Array[privateKey.Offset + i];
            }
            ScalarOperations.sc_clamp(publicKey.Array, publicKey.Offset);

            GroupElementP3 A;
            GroupOperations.ge_scalarmult_base(out A, publicKey.Array, publicKey.Offset);
            FieldElement publicKeyFE;
            EdwardsToMontgomeryX(out publicKeyFE, ref A.Y, ref A.Z);
            FieldOperations.fe_tobytes(publicKey.Array, publicKey.Offset, ref publicKeyFE);
        }
开发者ID:FihlaTV,项目名称:csharp-stellar-base,代码行数:25,代码来源:MontgomeryCurve25519.cs


示例16: FromSegment

        public static ReliableDataHeader FromSegment(ArraySegment<byte> segment)
        {
            ushort sequenceNumber = segment.ReadSequenceNumber(SystemHeader.Size);
            ushort payloadSize = (ushort)BitConverter.ToInt16(segment.Array, segment.Offset + SystemHeader.Size + 2);

            return new ReliableDataHeader(sequenceNumber, payloadSize);
        }
开发者ID:dmirmilshteyn,项目名称:Interchange,代码行数:7,代码来源:ReliableDataHeader.cs


示例17: Encrypt

        public byte[] Encrypt(ArraySegment<byte> plaintext, ArraySegment<byte> additionalAuthenticatedData, uint preBufferSize, uint postBufferSize)
        {
            // This wrapper simply converts ArraySegment<byte> to byte* and calls the impl method.

            // Input validation
            plaintext.Validate();
            additionalAuthenticatedData.Validate();

            byte dummy; // used only if plaintext or AAD is empty, since otherwise 'fixed' returns null pointer
            fixed (byte* pbPlaintextArray = plaintext.Array)
            {
                fixed (byte* pbAdditionalAuthenticatedDataArray = additionalAuthenticatedData.Array)
                {
                    try
                    {
                        return EncryptImpl(
                            pbPlaintext: (pbPlaintextArray != null) ? &pbPlaintextArray[plaintext.Offset] : &dummy,
                            cbPlaintext: (uint)plaintext.Count,
                            pbAdditionalAuthenticatedData: (pbAdditionalAuthenticatedDataArray != null) ? &pbAdditionalAuthenticatedDataArray[additionalAuthenticatedData.Offset] : &dummy,
                            cbAdditionalAuthenticatedData: (uint)additionalAuthenticatedData.Count,
                            cbPreBuffer: preBufferSize,
                            cbPostBuffer: postBufferSize);
                    }
                    catch (Exception ex) when (ex.RequiresHomogenization())
                    {
                        // Homogenize to CryptographicException.
                        throw Error.CryptCommon_GenericError(ex);
                    }
                }
            }
        }
开发者ID:yonglehou,项目名称:DataProtection,代码行数:31,代码来源:CngAuthenticatedEncryptorBase.cs


示例18: SetUnmanagedStructures

        internal void SetUnmanagedStructures(IList<ArraySegment<byte>> buffers)
        {
            // Fill in Buffer Array structure that will be used for our send/recv Buffer.
            // Make sure we don't let the app mess up the buffer array enough to cause
            // corruption.
            int count = buffers.Count;
            ArraySegment<byte>[] buffersCopy = new ArraySegment<byte>[count];

            for (int i = 0; i < count; i++)
            {
                buffersCopy[i] = buffers[i];
                RangeValidationHelpers.ValidateSegment(buffersCopy[i]);
            }

            _wsaBuffers = new WSABuffer[count];

            object[] objectsToPin = new object[count];
            for (int i = 0; i < count; i++)
            {
                objectsToPin[i] = buffersCopy[i].Array;
            }

            base.SetUnmanagedStructures(objectsToPin);

            for (int i = 0; i < count; i++)
            {
                _wsaBuffers[i].Length = buffersCopy[i].Count;
                _wsaBuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffersCopy[i].Array, buffersCopy[i].Offset);
            }
        }
开发者ID:neris,项目名称:corefx,代码行数:30,代码来源:OverlappedAsyncResult.Windows.cs


示例19: Read

        public unsafe bool Read(PooledSocket socket)
        {
            this.StatusCode = -1;

            if (!socket.IsAlive)
                return false;

            var header = new byte[HeaderLength];
            socket.Read(header, 0, header.Length);

            int dataLength, extraLength;

            DeserializeHeader(header, out dataLength, out extraLength);

            if (dataLength > 0)
            {
                var data = new byte[dataLength];
                socket.Read(data, 0, dataLength);

                this.Extra = new ArraySegment<byte>(data, 0, extraLength);
                this.Data = new ArraySegment<byte>(data, extraLength, data.Length - extraLength);
            }

            return this.StatusCode == 0;
        }
开发者ID:yorkart,项目名称:CachingClient,代码行数:25,代码来源:BinaryResponse.cs


示例20: HandleWebSocketsAsync

        private static async Task HandleWebSocketsAsync(HttpContext context, Func<Task> next)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await next();
                return;
            }

            var hub = context.RequestServices.GetRequiredService<MessageHub>();

            using (var webSocket = await context.WebSockets.AcceptWebSocketAsync())
            {
                try
                {
                    await hub.SubscribeAsync(webSocket);

                    var buffer = new ArraySegment<byte>(new byte[4096]);

                    while (webSocket?.State == WebSocketState.Open)
                    {
                        await webSocket.ReceiveAsync(buffer, CancellationToken.None);
                    }
                }
                finally
                {
                    await hub.UnsubscribeAsync(webSocket);
                }
            }
        }
开发者ID:tuespetre,项目名称:Sleeper,代码行数:29,代码来源:Startup.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ArraySpecifier类代码示例发布时间:2022-05-24
下一篇:
C# ArrayList类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap