예제 #1
0
        public void EnumerateEvents()
        {
            var array = new byte[22];
            var spanToRead = array.AsSpan();
            var payloadLength = 2;
            BitConverter.TryWriteBytes(spanToRead.Slice(sizeof(ulong)), payloadLength);

            BitConverter.TryWriteBytes(spanToRead.Slice(sizeof(ulong) + sizeof(int) + payloadLength), 100);
            var consumption = 1 << 31 | 200;
            BitConverter.TryWriteBytes(spanToRead.Slice(sizeof(ulong) + sizeof(int) + payloadLength 
                                                         + BlockEvent.SizeInBytes), consumption);


            var iterator = PayloadReader.GetEvents(spanToRead);
            Assert.Equal(new BlockAlias(100), iterator.Current.BlockAlias);
            Assert.Equal(BlockEventType.Production, iterator.Current.Type);
            iterator.MoveNext();
            Assert.Equal(new BlockAlias(200), iterator.Current.BlockAlias);
            Assert.Equal(BlockEventType.Consumption, iterator.Current.Type);
            iterator.MoveNext();
            Assert.False(iterator.EndNotReached);
        }
예제 #2
0
        private static void EnsureKeys(TimeParameters timeParameters)
        {
            var keysRequired = (int)(ulong)timeParameters.SlotsPerEpoch * 16;

            if (_testKeys.Count == keysRequired)
            {
                return;
            }

            _testKeys.Clear();
            _privateKeys.Clear();
            _publicKeys.Clear();
            // Private key is ~255 bits (32 bytes) long
            for (var keyNumber = 0; keyNumber < keysRequired; keyNumber++)
            {
                var privateKeySpan = new Span <byte>(new byte[32]);
                // Key is big endian number, so write Int32 to last 4 bytes.
                BitConverter.TryWriteBytes(privateKeySpan.Slice(28), keyNumber + 1);
                if (BitConverter.IsLittleEndian)
                {
                    // And reverse if necessary
                    privateKeySpan.Slice(28).Reverse();
                }
                var privateKey = privateKeySpan.ToArray();

                var blsParameters = new BLSParameters()
                {
                    PrivateKey = privateKey
                };
                using var bls = BLS.Create(blsParameters);
                var publicKeyBytes = new byte[BlsPublicKey.Length];
                bls.TryExportBlsPublicKey(publicKeyBytes, out var bytesWritten);
                var publicKey = new BlsPublicKey(publicKeyBytes);

                _privateKeys.Add(privateKey);
                _publicKeys.Add(publicKey);
                _testKeys[publicKey] = privateKey;
            }
        }
예제 #3
0
        /// <summary>
        /// Serialize IPEndPoint to 24 byte array [4 bytes endpoint type, 16 bytes ip address, 4 bytes port]
        /// </summary>
        /// <param name="endPoint">Serialized endpoint</param>
        /// <returns></returns>
        public static byte[] Raw(this IPEndPoint endPoint)
        {
            var array = new byte[sizeof(uint) + sizeof(byte) * 16 + sizeof(ushort) + 2]; // 0 type, 4 ip, 20 port, padding 2 bytes
            var bytes = new Span <byte>(array);
            var type  = TypeInvalid;

            switch (endPoint.AddressFamily)
            {
            case AddressFamily.InterNetwork:
                type = TypeIPv4;
                break;

            case AddressFamily.InterNetworkV6:
                type = TypeIPv6;
                break;
            }

            BitConverter.TryWriteBytes(bytes, (uint)type);                          // type
            endPoint.Address.GetAddressBytes().AsSpan().CopyTo(bytes.Slice(4));     // address bytes
            BitConverter.TryWriteBytes(bytes.Slice(20), (ushort)endPoint.Port);     // port
            return(array);
        }
예제 #4
0
    public ArraySegment <byte> Write()
    {
        ArraySegment <byte> segment = SendBufferHelper.Open(4096);
        ushort      count           = 0;
        bool        success         = true;
        Span <byte> s = new Span <byte>(segment.Array, segment.Offset, segment.Count);

        count   += sizeof(ushort);
        success &= BitConverter.TryWriteBytes(s.Slice(count, s.Length - count), (ushort)PacketID.C_Chat);
        count   += sizeof(ushort);
        ushort chatLen = (ushort)Encoding.Unicode.GetBytes(this.chat, 0, this.chat.Length, segment.Array, segment.Offset + count + sizeof(ushort));

        success &= BitConverter.TryWriteBytes(s.Slice(count, s.Length - count), chatLen);
        count   += sizeof(ushort);
        count   += chatLen;
        success &= BitConverter.TryWriteBytes(s, count);
        if (success == false)
        {
            return(null);
        }
        return(SendBufferHelper.Close(count));
    }
        public override ArraySegment <byte> Serialize()
        {
            ArraySegment <byte> arr = SendBufferHelper.Open(4096);

            ushort count   = 0;
            bool   success = true;

            count   += 2;
            success &= BitConverter.TryWriteBytes(new Span <byte>(arr.Array, arr.Offset + count, arr.Count - count), packetId);
            count   += 2;
            success &= BitConverter.TryWriteBytes(new Span <byte>(arr.Array, arr.Offset + count, arr.Count - count), playerId);
            count   += 8;

            success &= BitConverter.TryWriteBytes(new Span <byte>(arr.Array, arr.Offset, arr.Count), count);

            if (!success)
            {
                return(null);
            }

            return(SendBufferHelper.Close(count));
        }
        private static async Task FillPipeAsync(int iterations, PipeWriter writer)
        {
            const int minimumBufferSize = 4;
            var       random            = new Random();

            for (int i = 0; i < iterations; i++)
            {
                Memory <byte> memory        = writer.GetMemory(minimumBufferSize);
                var           numberToWrite = random.Next(int.MaxValue / 2, int.MaxValue);
                Console.WriteLine("Writing...");
                BitConverter.TryWriteBytes(memory.Span, numberToWrite);
                writer.Advance(minimumBufferSize);
                // Make the data available to the PipeReader.
                FlushResult result = await writer.FlushAsync();

                if (result.IsCompleted)
                {
                    break;
                }
            }
            await writer.CompleteAsync();
        }
예제 #7
0
        public void WriteSector()
        {
            // Writing to the stream and verify that the written data is correct.
            _sector.Write(_stream, _key);
            var actual = _stream.ToArray();

            var expected = new byte[SectorSize];

            BitConverter.TryWriteBytes(new Span <byte>(expected, 0, sizeof(long)), _key);
            for (int i = 0; i < _contentBytes.Length; i++)
            {
                expected[i + sizeof(long)] = _contentBytes[i];
            }

            var hashValue =
                new MurmurHash3().ComputeHash(new Span <byte>(expected, 0, expected.Length - Hash128.SizeInBytes));

            hashValue.WriteTo(new Span <byte>(expected).Slice(expected.Length - Hash128.SizeInBytes));
            Console.WriteLine(BitConverter.ToString(expected));
            Console.WriteLine(BitConverter.ToString(actual));
            Assert.Equal(expected, actual);
        }
예제 #8
0
        private protected override Task <DeltaBackendSession> OnListenForInjectorConnection(CancellationToken ct = default)
        {
            if (created)
            {
                var tcs = new TaskCompletionSource <DeltaBackendSession>();
                return(tcs.Task); // return a Task that never completes
            }

            var       s        = "Hello World!";
            var       enc      = System.Text.Encoding.UTF8;
            const int lenCount = 4;
            var       count    = enc.GetByteCount(s);
            var       buf      = new byte[lenCount + count];

            BitConverter.TryWriteBytes(new Span <byte>(buf, 0, lenCount), System.Net.IPAddress.HostToNetworkOrder(count));
            enc.GetBytes(s, new Span <byte>(buf, lenCount, buf.Length - lenCount));
            _log.LogTrace("creating memory stream");
            var t = Task.FromResult <DeltaBackendSession>(new SingleStreamDeltaBackendSession(new MemoryStream(buf), _log));

            created = true;
            return(t);
        }
예제 #9
0
        public int ToBytes(byte[] buffer)
        {
            buffer[0] = (byte)MessageType;
            buffer[1] = (byte)Players.Count;

            int index = 2;

            foreach (var player in Players)
            {
                buffer[index] = (byte)player.PlayerId;

                BitConverter.TryWriteBytes(new Span <byte>(buffer, index + 1, 4), player.Position.X);
                BitConverter.TryWriteBytes(new Span <byte>(buffer, index + 5, 4), player.Position.Y);
                BitConverter.TryWriteBytes(new Span <byte>(buffer, index + 9, 4), player.Velocity.X);
                BitConverter.TryWriteBytes(new Span <byte>(buffer, index + 13, 4), player.Velocity.Y);
                BitConverter.TryWriteBytes(new Span <byte>(buffer, index + 17, 4), player.LastSequence);

                index += 21;
            }

            return((Players.Count * 21) + 2);
        }
예제 #10
0
        public override int GetHashCode()
        {
            if (_hashCode != 0)
            {
                return(_hashCode);
            }

            // For IPv6 addresses, we calculate the hashcode by using Marvin
            // on a stack-allocated array containing the Address bytes and ScopeId.
            int hashCode;

            if (IsIPv6)
            {
                const int   addressAndScopeIdLength = IPAddressParserStatics.IPv6AddressBytes + sizeof(uint);
                Span <byte> addressAndScopeIdSpan   = stackalloc byte[addressAndScopeIdLength];

                MemoryMarshal.AsBytes(new ReadOnlySpan <ushort>(_numbers)).CopyTo(addressAndScopeIdSpan);
                Span <byte> scopeIdSpan  = addressAndScopeIdSpan.Slice(IPAddressParserStatics.IPv6AddressBytes);
                bool        scopeWritten = BitConverter.TryWriteBytes(scopeIdSpan, _addressOrScopeId);
                Debug.Assert(scopeWritten);

                hashCode = Marvin.ComputeHash32(
                    addressAndScopeIdSpan,
                    Marvin.DefaultSeed);
            }
            else
            {
                Span <uint> addressOrScopeIdSpan = stackalloc uint[1];
                addressOrScopeIdSpan[0] = _addressOrScopeId;

                // For IPv4 addresses, we use Marvin on the integer representation of the Address.
                hashCode = Marvin.ComputeHash32(
                    MemoryMarshal.AsBytes(addressOrScopeIdSpan),
                    Marvin.DefaultSeed);
            }

            _hashCode = hashCode;
            return(_hashCode);
        }
예제 #11
0
        public void TestRequestTypes()
        {
            BitConverter.TryWriteBytes(new Span <byte>(_bytes, ClientServerMessage.MessageTypeStart, sizeof(int)), (int)MessageType.OpenBlock);
            Assert.Equal(MessageType.OpenBlock, ClientServerMessage.GetMessageType(_bytes));

            BitConverter.TryWriteBytes(new Span <byte>(_bytes, ClientServerMessage.MessageTypeStart, sizeof(int)), (int)MessageType.CommitBlock);
            Assert.Equal(MessageType.CommitBlock, ClientServerMessage.GetMessageType(_bytes));

            BitConverter.TryWriteBytes(new Span <byte>(_bytes, ClientServerMessage.MessageTypeStart, sizeof(int)), (int)MessageType.Authenticate);
            Assert.Equal(MessageType.Authenticate, ClientServerMessage.GetMessageType(_bytes));

            BitConverter.TryWriteBytes(new Span <byte>(_bytes, ClientServerMessage.MessageTypeStart, sizeof(int)), (int)MessageType.GetBlockHandle);
            Assert.Equal(MessageType.GetBlockHandle, ClientServerMessage.GetMessageType(_bytes));

            BitConverter.TryWriteBytes(new Span <byte>(_bytes, ClientServerMessage.MessageTypeStart, sizeof(int)), (int)MessageType.IsAncestor);
            Assert.Equal(MessageType.IsAncestor, ClientServerMessage.GetMessageType(_bytes));

            BitConverter.TryWriteBytes(new Span <byte>(_bytes, ClientServerMessage.MessageTypeStart, sizeof(int)), (int)MessageType.IsPruneable);
            Assert.Equal(MessageType.IsPruneable, ClientServerMessage.GetMessageType(_bytes));

            Assert.Throws <ArgumentException>(() => ClientServerMessage.GetMessageType(new Span <byte>(_bytes, 0, ClientServerMessage.PayloadStart - 1)));
        }
예제 #12
0
        public async Task SendDataAsync(ReadOnlyMemory <byte> data, CancellationToken cancellationToken)
        {
            if (State == ConnectionState.Connected && IsStreamConnected)
            {
                _sendKeepAliveResetEvent?.Set();

                try
                {
                    using var memoryBufferOwner = MemoryPool <byte> .Shared.Rent(4);

                    if (!BitConverter.TryWriteBytes(memoryBufferOwner.Memory.Span, data.Length))
                    {
                        throw new InvalidOperationException();
                    }

                    if (_messageFramingEnabled)
                    {
                        await _sendingStream.WriteAsync(memoryBufferOwner.Memory.Slice(0, 4), cancellationToken).AsTask().ConfigureAwait(false);
                    }

                    await _sendingStream.WriteAsync(data, cancellationToken).AsTask().ConfigureAwait(false);

                    await _sendingStream.FlushAsync().ConfigureAwait(false);

                    //}
                }
#if DEBUG
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"{GetType()}{Environment.NewLine}{ex}");
#else
                catch (Exception)
                {
#endif
                    SetState(ConnectionTrigger.LinkError);
                }
            }
        }
예제 #13
0
        private void FindExpectedHashWithVector()
        {
            using var mySHA256 = SHA256.Create();

            Span <byte> maskBytes = stackalloc byte[32];

            var hardLevel = (byte)25;

            for (int j = 0; j < maskBytes.Length && hardLevel != 0; j++)
            {
                var delta = hardLevel > 8 ? (byte)8 : hardLevel;

                maskBytes[j] |= (byte)((1 << delta) - 1);

                hardLevel -= delta;
            }

            var maskVector = new Vector <byte>(maskBytes);

            var buffer = new byte[4];

            for (int i = 0; i < int.MaxValue; i++)
            {
                BitConverter.TryWriteBytes(buffer, i);

                var hash = mySHA256.ComputeHash(buffer);

                var hashVector = new Vector <byte>(hash);

                if ((hashVector & maskVector) == Vector <byte> .Zero)
                {
                    TextBox1.Text = i.ToString();
                    return;
                }
            }

            TextBox1.Text = "I can't do it";
        }
예제 #14
0
        // 참고: unsafe를 이용하여 C++의 포인터 조작과 유사한 동작을 실행할 수 있다.
        //		 이는 추후 다룰 예정.

        /*
         * static unsafe void ToBytes(byte[] array, int offset, ulong value)
         * {
         *      fixed (byte* ptr = &array[offset])
         *(ulong*)ptr = value;
         * }
         */

        public override void OnConnected(EndPoint endPoint)
        {
            Console.WriteLine($"{endPoint}에 연결되었습니다.");

            PlayerInfoReq packet = new PlayerInfoReq()
            {
                packetId = (ushort)PacketID.PlayerInfoReq,
                playerId = 1001
            };

            for (int i = 0; i < 5; i++)
            {
                ArraySegment <byte> arr = SendBufferHelper.Open(4096);

                // * 수정된 부분
                // TryWriteBytes를 이용하여, GetByte로 변환 후 복사하는 과정을 한 번에 실행한다.
                // success에 비트 연산을 통해 한 번이라도 실패했다면 false로 바뀌게 한다.
                ushort count   = 0;
                bool   success = true;

                // 패킷 크기가 들어갈 부분은 2바이트 비워준다.
                count   += 2;
                success &= BitConverter.TryWriteBytes(new Span <byte>(arr.Array, arr.Offset + count, arr.Count - count), packet.packetId);
                count   += 2;
                success &= BitConverter.TryWriteBytes(new Span <byte>(arr.Array, arr.Offset + count, arr.Count - count), packet.playerId);
                count   += 8;

                // 패킷의 크기는 미리 패킷에 정의해두지 않고, 보낼 때 크기를 센 다음 마지막에 count로 입력해준다.
                success &= BitConverter.TryWriteBytes(new Span <byte>(arr.Array, arr.Offset, arr.Count), count);

                ArraySegment <byte> sendBuff = SendBufferHelper.Close(count);

                if (success)
                {
                    Send(sendBuff);
                }
            }
        }
예제 #15
0
        public static (int nonce, string hash) FindExpectedHash(byte[] sourceData, int hardLevel, int checkFrom, int checkTo)
        {
            using var mySHA256 = SHA256.Create();

            var buffer = new byte[sizeof(int) + sourceData.Length];

            Array.Copy(sourceData, 0, buffer, sizeof(int), sourceData.Length);

            for (int i = checkFrom; i < checkTo; i++)
            {
                BitConverter.TryWriteBytes(buffer, i);

                var hash = mySHA256.ComputeHash(buffer);

                if (CheckHash(hash, hardLevel))
                {
                    var hashString = PrintByteArray(hash);
                    return(i, hashString);
                }
            }

            return(0, string.Empty);
        }
        private async ValueTask WritePagePositionAllocationToc(int tocIndex, long position, long length)
        {
            if (_tocPage == null)
            {
                await InitIndexPageAsync(true);
            }

            CheckRange(tocIndex);

            var offsetIndex = tocIndex * TocIndexSize;

            BitConverter.TryWriteBytes(_tocPage.AsSpan(offsetIndex), position);
            BitConverter.TryWriteBytes(_tocPage.AsSpan(offsetIndex + sizeof(int)), length);

            if (tocIndex < 64)
            {
                await AzurePageBlob.WriteBytesAsync(new ReadOnlyMemory <byte>(_tocPage, 0, MyAzurePageBlobUtils.PageSize), 0);
            }
            else
            {
                await AzurePageBlob.WriteBytesAsync(new ReadOnlyMemory <byte>(_tocPage, MyAzurePageBlobUtils.PageSize, MyAzurePageBlobUtils.PageSize), 1);
            }
        }
예제 #17
0
    public ArraySegment <byte> Write()
    {
        ushort count   = 0;
        bool   success = true;

        ArraySegment <byte> sg   = SendBufferHelper.Open(4096);
        Span <byte>         span = new Span <byte>(sg.Array, sg.Offset, sg.Count); // span을 만든 이유는 어차피 spawn을 인자로 써야하기때문에

        count   += sizeof(ushort);
        success &= BitConverter.TryWriteBytes(span.Slice(count, span.Length - count), (ushort)PacketID.C_Chat); // 시작범위부터 남은공간까지 오른쪽에 인자 값을 넣어라
        count   += sizeof(ushort);
        ushort chatLen = (ushort)Encoding.Unicode.GetBytes(this.chat, 0, this.chat.Length, sg.Array, sg.Offset + count + sizeof(ushort));

        success &= BitConverter.TryWriteBytes(span.Slice(count, span.Length - count), chatLen);
        count   += sizeof(ushort);
        count   += chatLen;
        success &= BitConverter.TryWriteBytes(span, count);
        if (success == false)
        {
            return(null);
        }
        return(SendBufferHelper.Close(count));
    }
        public static bool TryGetUInt24Bytes(uint value, Span <byte> buffer, bool littleEndian = false)
        {
            if (buffer.Length < 3)
            {
                return(false);
            }
            using (var owner = _memoryPool.Rent(4))
            {
                if (!BitConverter.TryWriteBytes(owner.Memory.Span, value))
                {
                    return(false);
                }

                var valueSpan = owner.Memory.Span.Slice(0, 3);

                if (!littleEndian)
                {
                    valueSpan.Reverse();
                }
                valueSpan.CopyTo(buffer);
            }
            return(true);
        }
예제 #19
0
    public ArraySegment <byte> Write()
    {
        ArraySegment <byte> segment = SendBufferHelper.Open(4096);
        ushort pos     = 0;
        bool   success = true;

        Span <byte> s = new Span <byte>(segment.Array, segment.Offset, segment.Count);

        pos     += sizeof(ushort);
        success &= BitConverter.TryWriteBytes(s.Slice(pos, s.Length - pos), (ushort)PacketID.Test);
        pos     += sizeof(ushort);
        success &= BitConverter.TryWriteBytes(s.Slice(pos, s.Length - pos), this.testint);
        pos     += sizeof(int);

        success &= BitConverter.TryWriteBytes(s, pos);

        if (success == false)
        {
            return(null);
        }

        return(SendBufferHelper.Close(pos));
    }
예제 #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        unsafe public uint WriteString(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                var span2 = Advance(4);
                BitConverter.TryWriteBytes(span2, 0);
                return(4);
            }
            var l    = Encoding.GetByteCount(value);
            var span = Advance(4);

            BitConverter.TryWriteBytes(span, l);
            span = Advance(l);
            fixed(char *cPtr = value)
            {
                fixed(byte *bPtr = &MemoryMarshal.GetReference(span))
                {
                    var a = Encoding.GetBytes(cPtr, value.Length, bPtr, l);
                }
            }

            return((uint)l + 4);
        }
        public DeviceClientScenario(PerfScenarioConfig config) : base(config)
        {
            _m.Id = _id;

            _mRecv.Id            = _id;
            _mRecv.OperationType = TelemetryMetrics.DeviceOperationReceive;

            _mMethod.Id = _id;

            _mConnectionStatus.Id           = _id;
            _mConnectionStatus.ExecuteTime  = null;
            _mConnectionStatus.ScheduleTime = null;

            _messageBytes = new byte[_sizeBytes];

            _pooled = config.PoolSize > 0;
            if (_pooled)
            {
                _poolSize = config.PoolSize;
            }

            BitConverter.TryWriteBytes(_messageBytes, _id);
        }
예제 #22
0
        public override Task WriteAsync(ArraySegment <byte> buffer, CancellationToken cancellationToken = new CancellationToken())
        {
            var buf = ArrayPool <byte> .Shared.Rent(buffer.Count + 20);

            var ctext = new ArraySegment <byte>(buf, 20, buffer.Count);
            var tag   = new ArraySegment <byte>(buf, 4, 16);

            BitConverter.TryWriteBytes(new ArraySegment <byte>(buf, 0, 4), buffer.Count);
            lock (_writeNonce)
            {
                _aes.Encrypt(_writeNonce, buffer, ctext, tag);
                IncrementNonce(_writeNonce);
            }

            async Task Send()
            {
                await WrappedSocket.WriteAsync(new ArraySegment <byte>(buf, 0, buffer.Count + 20), cancellationToken);

                ArrayPool <byte> .Shared.Return(buf);
            }

            return(Send());
        }
예제 #23
0
        /// <summary>
        /// Return from ``indices`` a random index sampled by effective balance.
        /// </summary>
        public ValidatorIndex ComputeProposerIndex(BeaconState state, IList <ValidatorIndex> indices, Hash32 seed)
        {
            if (!indices.Any())
            {
                throw new ArgumentException("Indices can not be empty", nameof(indices));
            }

            ulong          indexCount = (ulong)indices.Count;
            ValidatorIndex index      = 0UL;

            while (true)
            {
                ValidatorIndex initialValidatorIndex = (ValidatorIndex)(index % indexCount);
                ValidatorIndex shuffledIndex         = ComputeShuffledIndex(initialValidatorIndex, indexCount, seed);
                ValidatorIndex candidateIndex        = indices[(int)shuffledIndex];

                Span <byte> randomInputBytes = new Span <byte>(new byte[40]);
                seed.AsSpan().CopyTo(randomInputBytes);
                BitConverter.TryWriteBytes(randomInputBytes.Slice(32), index / 32);
                if (!BitConverter.IsLittleEndian)
                {
                    randomInputBytes.Slice(32).Reverse();
                }

                Hash32 randomHash = _cryptographyService.Hash(randomInputBytes);
                byte   random     = randomHash.AsSpan()[(int)(index % 32)];

                Gwei effectiveBalance = state.Validators[(int)candidateIndex].EffectiveBalance;
                if ((effectiveBalance * byte.MaxValue) >=
                    (_gweiValueOptions.CurrentValue.MaximumEffectiveBalance * random))
                {
                    return(candidateIndex);
                }

                index++;
            }
        }
예제 #24
0
        /// <summary>
        /// Return a random outpoint and a random payload.
        /// </summary>
        private (Outpoint, Memory <byte>) MakeRandomRawTxo(int lowLimit, int upLimit)
        {
            var content = new byte[Outpoint.TotalSizeInBytes].AsMemory();
            var temp    = new byte[Outpoint.KeySizeInBytes - 4];

            _rand.NextBytes(temp);
            temp.CopyTo(content);

            var index = _rand.Next(0, 20);

            BitConverter.GetBytes(index).CopyTo(content.Slice(Outpoint.KeySizeInBytes - 4, 4));

            var payloadLength = _rand.Next(lowLimit, upLimit);

            BitConverter.GetBytes(payloadLength).CopyTo(content.Slice(Outpoint.KeySizeInBytes, 4));

            var payload = new byte[payloadLength];

            _rand.NextBytes(payload);

            var numberOfEvents = _rand.Next(1, 5);

            // write data length inside payload

            BitConverter.TryWriteBytes(payload.AsSpan(sizeof(ulong), sizeof(int)),
                                       payloadLength - sizeof(ulong) - sizeof(int) - BlockEvent.SizeInBytes * numberOfEvents);

            var writer = new PayloadWriter(payload.AsSpan(payloadLength - BlockEvent.SizeInBytes * numberOfEvents));

            for (var i = 0; i < numberOfEvents; ++i)
            {
                var ev = new BlockEvent((uint)_rand.Next(0, 1_000_000));
                writer.Write(ev);
            }

            return(Outpoint.Create(content.Span), payload);
        }
예제 #25
0
    public ArraySegment <byte> Serialize()
    {
        ArraySegment <byte> arr  = SendBufferHelper.Open(4096);
        Span <byte>         span = new Span <byte>(arr.Array, arr.Offset, arr.Count);

        ushort count   = 0;
        bool   success = true;

        count   += sizeof(ushort);
        success &= BitConverter.TryWriteBytes(span.Slice(count, span.Length - count), (ushort)PacketID.C_PlayerInfoReq);
        count   += sizeof(ushort);

        arr.Array[arr.Offset + count] = (byte)this.testByte;
        count   += sizeof(byte);
        success &= BitConverter.TryWriteBytes(span.Slice(count, span.Length - count), playerId);
        count   += sizeof(long);
        ushort playerNameLen = (ushort)Encoding.Unicode.GetBytes(playerName, 0, playerName.Length, arr.Array, arr.Offset + count + sizeof(ushort));

        success &= BitConverter.TryWriteBytes(span.Slice(count, span.Length - count), playerNameLen);
        count   += sizeof(ushort);
        count   += playerNameLen;
        success &= BitConverter.TryWriteBytes(span.Slice(count, span.Length - count), (ushort)skills.Count);
        count   += sizeof(ushort);
        foreach (Skill skill in skills)
        {
            success &= skill.Serialize(span, ref count);
        }

        success &= BitConverter.TryWriteBytes(span, count);

        if (!success)
        {
            return(null);
        }

        return(SendBufferHelper.Close(count));
    }
예제 #26
0
        static async Task Main(string[] args)
        {
            UdpClient client1 = new UdpClient(9999);
            UdpClient client2 = new UdpClient(1000);


            Socket client1Socket = client1.Client;
            Socket client2Socket = client2.Client;

            List <Socket> readSockets = new List <Socket>();

            while (true)
            {
                readSockets.Clear();
                readSockets.Add(client1Socket);
                readSockets.Add(client2Socket);

                client1Socket.Poll(50, SelectMode.SelectRead);

                Socket.Select(readSockets, null, null, 1000);
            }



            byte[] data = new byte[20];
            {
                BitConverter.TryWriteBytes(data.AsSpan(), 42);
                BitConverter.TryWriteBytes(data.AsSpan().Slice(4), 56);
                BitConverter.TryWriteBytes(data.AsSpan().Slice(8), 94);
                BitConverter.TryWriteBytes(data.AsSpan().Slice(12), 78);
                BitConverter.TryWriteBytes(data.AsSpan().Slice(16), 0);
            }

            MemoryStream memStream = new MemoryStream(data);

            int[] arr = new int[42];
            await arr[1..5].ToAsyncEnumerable().SelectAwait(async x =>
예제 #27
0
        public bool Wrtie(Span <byte> s, ref ushort pos)
        {
            bool success = true;

            success &= BitConverter.TryWriteBytes(s.Slice(pos, s.Length - pos), this.id);
            pos     += sizeof(int);

            success &= BitConverter.TryWriteBytes(s.Slice(pos, s.Length - pos), this.level);
            pos     += sizeof(short);

            success &= BitConverter.TryWriteBytes(s.Slice(pos, s.Length - pos), this.duration);
            pos     += sizeof(float);

            success &= BitConverter.TryWriteBytes(s.Slice(pos, s.Length - pos), (ushort)this.attributes.Count);
            pos     += sizeof(ushort);

            foreach (Attribute attribute in this.attributes)
            {
                success &= attribute.Wrtie(s, ref pos);
            }


            return(success);
        }
예제 #28
0
    public ArraySegment <byte> Serialize()
    {
        ArraySegment <byte> arr  = SendBufferHelper.Open(4096);
        Span <byte>         span = new Span <byte>(arr.Array, arr.Offset, arr.Count);

        ushort count   = 0;
        bool   success = true;

        count   += sizeof(ushort);
        success &= BitConverter.TryWriteBytes(span.Slice(count, span.Length - count), (ushort)PacketID.S_Test);
        count   += sizeof(ushort);

        success &= BitConverter.TryWriteBytes(span.Slice(count, span.Length - count), testInt);
        count   += sizeof(int);

        success &= BitConverter.TryWriteBytes(span, count);

        if (!success)
        {
            return(null);
        }

        return(SendBufferHelper.Close(count));
    }
예제 #29
0
        /// <summary>
        /// 注意要和SystemLib中的String的对象格式相同
        /// </summary>
        /// <param name="value"></param>
        /// <returns>绝对地址</returns>
        public uint AddConstantString(string value)
        {
            if (!StringPool.TryGetValue(value, out HeapData data))
            {
                // 分配byte数组
                HeapData stringData = MallocCharArray(Encoding.UTF8.GetByteCount(value));
                Encoding.UTF8.GetBytes(value, new Span <byte>(stringData.Data, HeapData.ArrayLengthSize + HeapData.MiscDataSize,
                                                              stringData.Data.Length - HeapData.ArrayLengthSize - HeapData.MiscDataSize));

                // String对象
                byte[] vs = new byte[HeapData.MiscDataSize + HeapData.StringLengthSize + HeapData.StringDataSize];
                // 头部信息可以不填,因为MethodArea是内存的边界,GC不会继续walk
                // 长度信息
                BitConverter.TryWriteBytes(new Span <byte>(vs, HeapData.MiscDataSize, HeapData.StringLengthSize), value.Length);
                // Data信息
                BitConverter.TryWriteBytes(new Span <byte>(vs, HeapData.MiscDataSize + HeapData.StringLengthSize, HeapData.StringDataSize),
                                           MemoryMap.MapToAbsolute(stringData.Offset, MemoryTag.METHOD));

                // 字符串
                data = Malloc(vs);
                StringPool.Add(value, data);
            }
            return(MemoryMap.MapToAbsolute(data.Offset, MemoryTag.METHOD));
        }
예제 #30
0
        private static async Task FillPipeAsync(PipeWriter writer)
        {
            // result file format:
            // | flag (1byte) | data (8 bytes) |
            // flag: none = 0x00, fizz = 0x01, buzz = 0x02, fizzbuzz = 0x03
            const int blockSize = 9;
            var       block     = new byte[blockSize];

            void WriteFizzBuzz(ulong x)
            {
                block[0] = (byte)x.GetFizzBuzz();
                if (!BitConverter.TryWriteBytes(block.AsSpan(1), x))
                {
                    throw new Exception();
                }
                block.CopyTo(writer.GetSpan(blockSize));
                writer.Advance(blockSize);
            }

            for (ulong i = 0; i < ulong.MaxValue; i++)
            {
                WriteFizzBuzz(i);
                if (i % 128 == 0)
                {
                    await writer.FlushAsync();
                }
                if (i % 1000000 == 0)
                {
                    Console.WriteLine(i);
                }
            }

            await writer.FlushAsync();

            writer.Complete();
        }