System.Buffer.BlockCopy(System.Array, int, System.Array, int, int)

Here are the examples of the csharp api System.Buffer.BlockCopy(System.Array, int, System.Array, int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3887 Examples 7

19 View Source File : SliceStream.cs
License : MIT License
Project Creator : abdullin

public override int Read(byte[] buffer, int offset, int count)
		{
			ValidateBuffer(buffer, offset, count);

			if (!m_slice.HasValue) StreamIsClosed();

			Contract.Ensures(m_position >= 0 && m_position <= m_slice.Count);

			int remaining = Math.Min(m_slice.Count - m_position, count);
			if (remaining <= 0) return 0;

			int pos = m_position;
			int start = m_slice.Offset + pos;

			if (remaining <= 8)
			{ // too small, copy it ourselves
				int n = remaining;
				while (n-- > 0)
				{
					buffer[offset + n] = m_slice.Array[start + n];
				}
			}
			else
			{ // large enough
				Buffer.BlockCopy(m_slice.Array, start, buffer, offset, remaining);
			}

			m_position += remaining;
			Contract.Ensures(m_position >= 0 && m_position <= m_slice.Count);
			return remaining;
		}

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

void PackUint32(uint value, byte[] buf, ref int offset)
		{
			Buffer.BlockCopy(BitConverter.GetBytes(value), 0, buf, offset, 4);
			offset = offset + 4;
		}

19 View Source File : ByteArray.cs
License : MIT License
Project Creator : 404Lcc

internal static void Copy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count)
        {
            if (count > CopyThreshold)
            {
                Buffer.BlockCopy(src, srcOffset, dst, dstOffset, count);
            }
            else
            {
                int stop = srcOffset + count;
                for (int i = srcOffset; i < stop; i++)
                {
                    dst[dstOffset++] = src[i];
                }
            }
        }

19 View Source File : ClientMessageParser.cs
License : MIT License
Project Creator : Abaudat

public void ParseMessage(byte[] message)
    {
        byte[] size = new byte[sizeof(int)];
        Buffer.BlockCopy(message, 0, size, 0, sizeof(int));
        byte[] data = new byte[BitConverter.ToInt32(size, 0)];
        Buffer.BlockCopy(message, sizeof(int) + 1, data, 0, data.Length);
        switch (message[sizeof(int)]) // Add cases to this switch for all different types of message the client can receive.
        {
            case (byte)NetworkingFlags.Flags.DEBUG_MESSAGE:
                OnDebugMessage(data);
                break;
            default:
                Debug.LogWarning("WARNING: Unknown byte flag " + message[sizeof(int)] + " .");
                break;
        }
    }

19 View Source File : QQTea.cs
License : MIT License
Project Creator : 499116344

public static byte[] Encrypt(byte[] In, int offset, int len, byte[] key)
        {
            var temp = new byte[In.Length];
            Buffer.BlockCopy(In, 0, temp, 0, In.Length);
            var random = new Random();
            var num = (len + 10) % 8;
            if (num != 0)
            {
                num = 8 - num;
            }

            var array = new byte[len + num + 10];
            array[0] = (byte) ((random.Next() & 248) | num);
            for (var i = 1; i < num + 3; i++)
            {
                array[i] = (byte) (random.Next() & 255);
            }

            Array.Copy(temp, 0, array, num + 3, len);
            for (var j = num + 3 + len; j < array.Length; j++)
            {
                array[j] = 0;
            }

            var array2 = new byte[len + num + 10];
            for (var k = 0; k < array2.Length; k += 8)
            {
                Code(array, 0, k, array2, 0, k, key);
            }

            return array2;
        }

19 View Source File : SequentialGuidGenerator.cs
License : MIT License
Project Creator : 17MKH

public Guid Create(SequentialGuidType guidType)
    {
        lock (_lock)
        {
            var randomBytes = new byte[10];
            _rng.GetBytes(randomBytes);

            var timestamp = DateTime.UtcNow.Ticks / 10000L;
            var timestampBytes = BitConverter.GetBytes(timestamp);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(timestampBytes);
            }

            var guidBytes = new byte[16];

            switch (guidType)
            {
                case SequentialGuidType.Sequentialreplacedtring:
                case SequentialGuidType.SequentialAsBinary:
                    Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6);
                    Buffer.BlockCopy(randomBytes, 0, guidBytes, 6, 10);

                    // If formatting as a string, we have to reverse the order
                    // of the Data1 and Data2 blocks on little-endian systems.
                    if (guidType == SequentialGuidType.Sequentialreplacedtring && BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(guidBytes, 0, 4);
                        Array.Reverse(guidBytes, 4, 2);
                    }
                    break;

                case SequentialGuidType.SequentialAtEnd:
                    Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10);
                    Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6);
                    break;
            }

            return new Guid(guidBytes);
        }
    }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

void PackULong(ulong u, byte[] buf, ref int offset)
    {
        Buffer.BlockCopy(BitConverter.GetBytes(u), 0, buf, offset, sizeof(ulong));
        offset += sizeof(ulong);
    }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

public int Read(byte[] bytes, int offset, int count)
        {
            if (bytes is null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
            VerifyNotDisposed();

            if (count == 0)
            {
                return 0;
            }

            if ((readOffset + count) <= readLength)
            {
                Buffer.BlockCopy(buffer, readOffset, bytes, offset, count);
                readOffset += count;

                return count;
            }
            else
            {
                // Ensure that any bytes at the end of the current buffer are included.
                int bytesUnread = readLength - readOffset;

                if (bytesUnread > 0)
                {
                    Buffer.BlockCopy(buffer, readOffset, bytes, offset, bytesUnread);
                }

                // Invalidate the existing buffer.
                readOffset = 0;
                readLength = 0;

                int totalBytesRead = bytesUnread;

                totalBytesRead += stream.Read(bytes, offset + bytesUnread, count - bytesUnread);

                return totalBytesRead;
            }
        }

19 View Source File : ServerPacket.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void CreateReadyToSendPacket(byte[] buffer, out int size)
        {
            uint payloadChecksum = 0u;

            int offset = PacketHeader.HeaderSize;

            if (Data != null && Data.Length > 0)
            {
                var body = Data.GetBuffer();
                Buffer.BlockCopy(body, 0, buffer, offset, (int)Data.Length);
                offset += (int)Data.Length;

                payloadChecksum += Hash32.Calculate(body, (int)Data.Length);
            }

            foreach (ServerPacketFragment fragment in Fragments)
                payloadChecksum += fragment.PackAndReturnHash32(buffer, ref offset);

            size = offset;

            Header.Size = (ushort)(size - PacketHeader.HeaderSize);

            var headerChecksum = Header.CalculateHash32();
            finalChecksum = headerChecksum + payloadChecksum;
            Header.Checksum = headerChecksum + (payloadChecksum ^ issacXor);
            Header.Pack(buffer);
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

public int Read(byte[] bytes, int offset, int count)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
            VerifyNotDisposed();

            if (count == 0)
            {
                return 0;
            }

            if ((readOffset + count) <= readLength)
            {
                Buffer.BlockCopy(buffer, readOffset, bytes, offset, count);
                readOffset += count;

                return count;
            }
            else
            {
                // Ensure that any bytes at the end of the current buffer are included.
                int bytesUnread = readLength - readOffset;

                if (bytesUnread > 0)
                {
                    Buffer.BlockCopy(buffer, readOffset, bytes, offset, bytesUnread);
                }

                // Invalidate the existing buffer.
                readOffset = 0;
                readLength = 0;

                int totalBytesRead = bytesUnread;

                totalBytesRead += stream.Read(bytes, offset + bytesUnread, count - bytesUnread);

                return totalBytesRead;
            }
        }

19 View Source File : ConnectClient.cs
License : Apache License 2.0
Project Creator : AantCoder

private byte[] ReceiveBytes(int countByte)
        {
            //if (!Loger.IsServer) Loger.Log("Client ReceiveBytes " + countByte.ToString() + ", " + Client.ReceiveBufferSize);
            //результат
            byte[] msg = new byte[countByte];
            //сколько уже считано
            int offset = 0;
            //буфер результата
            byte[] receiveBuffer = new byte[Client.ReceiveBufferSize];
            //кол-во считано байт последний раз
            int numberOfBytesRead = 0;
            //длина передаваемого сообщения (принимается в первых 4 байтах (константа Int32Length))
            int lenghtAllMessageByte = countByte;
            var timeOut = DateTime.UtcNow.AddMilliseconds(SilenceTime);

            while (lenghtAllMessageByte > 0)
            {
                int maxCountRead = receiveBuffer.Length;
                if (maxCountRead > lenghtAllMessageByte) maxCountRead = lenghtAllMessageByte;


                //numberOfBytesRead = ClientStream.Read(receiveBuffer, 0, maxCountRead);

                var receiveId = Interlocked.Increment(ref ReceiveId);
                ClientStream.BeginRead(receiveBuffer, 0, maxCountRead, ReceiveBytescallback, receiveId);

                while (!ReceiveReady.ContainsKey(receiveId)
                    && timeOut > DateTime.UtcNow)
                    Thread.Sleep(1);

                lock (ReceiveReady)
                {
                    if (ReceiveReady.ContainsKey(receiveId))
                    {
                        var objRes = ReceiveReady[receiveId];
                        if (objRes is Exception) throw (Exception)objRes;
                        numberOfBytesRead = (int)ReceiveReady[receiveId];
                        ReceiveReady.Remove(receiveId);
                    }
                    else
                        throw new ConnectSilenceTimeOutException();
                }

                if (!Client.Client.Connected)
                {
                    throw new ConnectNotConnectedException();
                }


                if (numberOfBytesRead == 0)
                {
                    if (timeOut < DateTime.UtcNow)
                        throw new ConnectSilenceTimeOutException();
                    Thread.Sleep(1);
                }
                else
                {
                    timeOut = DateTime.UtcNow.AddMilliseconds(SilenceTime);
                    Buffer.BlockCopy(receiveBuffer, 0, msg, offset, numberOfBytesRead);
                    offset += numberOfBytesRead;
                    lenghtAllMessageByte -= numberOfBytesRead;
                }
            };

            return msg;
        }

19 View Source File : Lz4DecoderStream.cs
License : MIT License
Project Creator : 91Act

public override int Read(byte[] buffer, int offset, int count)
        {
#if CHECK_ARGS
            if (buffer == null)
                throw new ArgumentNullException("buffer");
            if (offset < 0 || count < 0 || buffer.Length - count < offset)
                throw new ArgumentOutOfRangeException();

            if (input == null)
                throw new InvalidOperationException();
#endif
            int nRead, nToRead = count;

            var decBuf = decodeBuffer;

            //the stringy gotos are obnoxious, but their purpose is to
            //make it *blindingly* obvious how the state machine transitions
            //back and forth as it reads - remember, we can yield out of
            //this routine in several places, and we must be able to re-enter
            //and pick up where we left off!

#if LOCAL_SHADOW
			var phase = this.phase;
			var inBufPos = this.inBufPos;
			var inBufEnd = this.inBufEnd;
#endif
            switch (phase)
            {
                case DecodePhase.ReadToken:
                    goto readToken;

                case DecodePhase.ReadExLiteralLength:
                    goto readExLiteralLength;

                case DecodePhase.CopyLiteral:
                    goto copyLiteral;

                case DecodePhase.ReadOffset:
                    goto readOffset;

                case DecodePhase.ReadExMatchLength:
                    goto readExMatchLength;

                case DecodePhase.CopyMatch:
                    goto copyMatch;
            }

            readToken:
            int tok;
            if (inBufPos < inBufEnd)
            {
                tok = decBuf[inBufPos++];
            }
            else
            {
#if LOCAL_SHADOW
				this.inBufPos = inBufPos;
#endif

                tok = ReadByteCore();
#if LOCAL_SHADOW
				inBufPos = this.inBufPos;
				inBufEnd = this.inBufEnd;
#endif
#if CHECK_EOF
                if (tok == -1)
                    goto finish;
#endif
            }

            litLen = tok >> 4;
            matLen = (tok & 0xF) + 4;

            switch (litLen)
            {
                case 0:
                    phase = DecodePhase.ReadOffset;
                    goto readOffset;

                case 0xF:
                    phase = DecodePhase.ReadExLiteralLength;
                    goto readExLiteralLength;

                default:
                    phase = DecodePhase.CopyLiteral;
                    goto copyLiteral;
            }

            readExLiteralLength:
            int exLitLen;
            if (inBufPos < inBufEnd)
            {
                exLitLen = decBuf[inBufPos++];
            }
            else
            {
#if LOCAL_SHADOW
				this.inBufPos = inBufPos;
#endif
                exLitLen = ReadByteCore();
#if LOCAL_SHADOW
				inBufPos = this.inBufPos;
				inBufEnd = this.inBufEnd;
#endif

#if CHECK_EOF
                if (exLitLen == -1)
                    goto finish;
#endif
            }

            litLen += exLitLen;
            if (exLitLen == 255)
                goto readExLiteralLength;

            phase = DecodePhase.CopyLiteral;
            goto copyLiteral;

            copyLiteral:
            int nReadLit = litLen < nToRead ? litLen : nToRead;
            if (nReadLit != 0)
            {
                if (inBufPos + nReadLit <= inBufEnd)
                {
                    int ofs = offset;

                    for (int c = nReadLit; c-- != 0;)
                        buffer[ofs++] = decBuf[inBufPos++];

                    nRead = nReadLit;
                }
                else
                {
#if LOCAL_SHADOW
					this.inBufPos = inBufPos;
#endif
                    nRead = ReadCore(buffer, offset, nReadLit);
#if LOCAL_SHADOW
					inBufPos = this.inBufPos;
					inBufEnd = this.inBufEnd;
#endif
#if CHECK_EOF
                    if (nRead == 0)
                        goto finish;
#endif
                }

                offset += nRead;
                nToRead -= nRead;

                litLen -= nRead;

                if (litLen != 0)
                    goto copyLiteral;
            }

            if (nToRead == 0)
                goto finish;

            phase = DecodePhase.ReadOffset;
            goto readOffset;

            readOffset:
            if (inBufPos + 1 < inBufEnd)
            {
                matDst = (decBuf[inBufPos + 1] << 8) | decBuf[inBufPos];
                inBufPos += 2;
            }
            else
            {
#if LOCAL_SHADOW
				this.inBufPos = inBufPos;
#endif
                matDst = ReadOffsetCore();
#if LOCAL_SHADOW
				inBufPos = this.inBufPos;
				inBufEnd = this.inBufEnd;
#endif
#if CHECK_EOF
                if (matDst == -1)
                    goto finish;
#endif
            }

            if (matLen == 15 + 4)
            {
                phase = DecodePhase.ReadExMatchLength;
                goto readExMatchLength;
            }
            else
            {
                phase = DecodePhase.CopyMatch;
                goto copyMatch;
            }

            readExMatchLength:
            int exMatLen;
            if (inBufPos < inBufEnd)
            {
                exMatLen = decBuf[inBufPos++];
            }
            else
            {
#if LOCAL_SHADOW
				this.inBufPos = inBufPos;
#endif
                exMatLen = ReadByteCore();
#if LOCAL_SHADOW
				inBufPos = this.inBufPos;
				inBufEnd = this.inBufEnd;
#endif
#if CHECK_EOF
                if (exMatLen == -1)
                    goto finish;
#endif
            }

            matLen += exMatLen;
            if (exMatLen == 255)
                goto readExMatchLength;

            phase = DecodePhase.CopyMatch;
            goto copyMatch;

            copyMatch:
            int nCpyMat = matLen < nToRead ? matLen : nToRead;
            if (nCpyMat != 0)
            {
                nRead = count - nToRead;

                int bufDst = matDst - nRead;
                if (bufDst > 0)
                {
                    //offset is fairly far back, we need to pull from the buffer

                    int bufSrc = decodeBufferPos - bufDst;
                    if (bufSrc < 0)
                        bufSrc += DecBufLen;
                    int bufCnt = bufDst < nCpyMat ? bufDst : nCpyMat;

                    for (int c = bufCnt; c-- != 0;)
                        buffer[offset++] = decBuf[bufSrc++ & DecBufMask];
                }
                else
                {
                    bufDst = 0;
                }

                int sOfs = offset - matDst;
                for (int i = bufDst; i < nCpyMat; i++)
                    buffer[offset++] = buffer[sOfs++];

                nToRead -= nCpyMat;
                matLen -= nCpyMat;
            }

            if (nToRead == 0)
                goto finish;

            phase = DecodePhase.ReadToken;
            goto readToken;

            finish:
            nRead = count - nToRead;

            int nToBuf = nRead < DecBufLen ? nRead : DecBufLen;
            int repPos = offset - nToBuf;

            if (nToBuf == DecBufLen)
            {
                Buffer.BlockCopy(buffer, repPos, decBuf, 0, DecBufLen);
                decodeBufferPos = 0;
            }
            else
            {
                int decPos = decodeBufferPos;

                while (nToBuf-- != 0)
                    decBuf[decPos++ & DecBufMask] = buffer[repPos++];

                decodeBufferPos = decPos & DecBufMask;
            }

#if LOCAL_SHADOW
			this.phase = phase;
			this.inBufPos = inBufPos;
#endif
            return nRead;
        }

19 View Source File : PkgChecker.cs
License : MIT License
Project Creator : 13xforever

private static byte[] GetPs3Hmac(Span<byte> data)
        {
            byte[] sha;
            using (var sha1 = SHA1.Create())
                sha = sha1.ComputeHash(data.ToArray());
            var buf = new byte[0x40];
            Buffer.BlockCopy(sha, 4, buf, 0, 8);
            Buffer.BlockCopy(sha, 4, buf, 8, 8);
            Buffer.BlockCopy(sha, 12, buf, 16, 4);
            buf[20] = sha[16];
            buf[21] = sha[1];
            buf[22] = sha[2];
            buf[23] = sha[3];
            Buffer.BlockCopy(buf, 16, buf, 24, 8);
            using (var sha1 = SHA1.Create())
                sha = sha1.ComputeHash(buf);
            return sha.replacedpan(0, 0x10).ToArray();
        }

19 View Source File : MessageBuilder.cs
License : MIT License
Project Creator : Abaudat

static byte[] Vector3ToByteArray(Vector3 vector)
    {
        byte[] bytes = new byte[sizeof(float) * 3];

        Buffer.BlockCopy(BitConverter.GetBytes(vector.x), 0, bytes, 0 * sizeof(float), sizeof(float));
        Buffer.BlockCopy(BitConverter.GetBytes(vector.y), 0, bytes, 1 * sizeof(float), sizeof(float));
        Buffer.BlockCopy(BitConverter.GetBytes(vector.z), 0, bytes, 2 * sizeof(float), sizeof(float));

        return bytes;
    }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

private void FillBuffer(int minBytes)
        {
            int bytesUnread = this.readLength - this.readOffset;

            if (bytesUnread > 0)
            {
                Buffer.BlockCopy(this.buffer, this.readOffset, this.buffer, 0, bytesUnread);
            }

            int numBytesToRead = this.bufferSize - bytesUnread;
            int numBytesRead = bytesUnread;
            do
            {
                int n = this.stream.Read(this.buffer, numBytesRead, numBytesToRead);

                if (n == 0)
                {
                    throw new EndOfStreamException();
                }

                numBytesRead += n;
                numBytesToRead -= n;

            } while (numBytesRead < minBytes);

            this.readOffset = 0;
            this.readLength = numBytesRead;
        }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

public void processAvatarPacket(RemotePlayer remote, ref byte[] packet, ref int offset)
    {
        if (remote == null)
            return;

        remote.receivedRootPositionPrior = remote.receivedRootPosition;
        remote.receivedRootPosition.x = ReadFloat(packet, ref offset);
        remote.receivedRootPosition.y = ReadFloat(packet, ref offset);
        remote.receivedRootPosition.z = ReadFloat(packet, ref offset);

        remote.receivedRootRotationPrior = remote.receivedRootRotation;
        remote.receivedRootRotation.x = ReadFloat(packet, ref offset);
        remote.receivedRootRotation.y = ReadFloat(packet, ref offset);
        remote.receivedRootRotation.z = ReadFloat(packet, ref offset);
        remote.receivedRootRotation.w = ReadFloat(packet, ref offset);
        
        remote.RemoteAvatar.transform.position = remote.receivedRootPosition;
        remote.RemoteAvatar.transform.rotation = remote.receivedRootRotation;

        // forward the remaining data to the avatar system
        int sequence = (int)ReadUInt32(packet, ref offset);

        byte[] remainingAvatarBuffer = new byte[packet.Length - offset];
        Buffer.BlockCopy(packet, offset, remainingAvatarBuffer, 0, remainingAvatarBuffer.Length);

        IntPtr avatarPacket = Oculus.Avatar.CAPI.ovrAvatarPacket_Read((UInt32)remainingAvatarBuffer.Length, remainingAvatarBuffer);

        var ovravatarPacket = new OvrAvatarPacket { ovrNativePacket = avatarPacket };
        remote.RemoteAvatar.GetComponent<OvrAvatarRemoteDriver>().QueuePacket(sequence, ovravatarPacket);
    }

19 View Source File : MD4Managed.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

protected override void HashCore(byte[] array, int ibStart, int cbSize)
        {
            int dstOffset = ((int)(this.count[0] >> 3)) & 0x3f;
            this.count[0] += (uint)(cbSize << 3);

            if (this.count[0] < (cbSize << 3))
            {
                this.count[1]++;
            }

            this.count[1] += (uint)(cbSize >> 0x1d);
            int count = 0x40 - dstOffset;
            int index = 0;

            if (cbSize >= count)
            {
                Buffer.BlockCopy(array, ibStart, this.buffer, dstOffset, count);
                this.MD4Transform(this.state, this.buffer, 0);
                index = count;

                while ((index + 0x3f) < cbSize)
                {
                    this.MD4Transform(this.state, array, index);
                    index += 0x40;
                }

                dstOffset = 0;
            }

            Buffer.BlockCopy(array, ibStart + index, this.buffer, dstOffset, cbSize - index);
        }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

void PackFloat(float value, byte[] buf, ref int offset)
		{
			Buffer.BlockCopy(BitConverter.GetBytes(value), 0, buf, offset, 4);
			offset = offset + 4;
		}

19 View Source File : Protocol16Serializer.cs
License : MIT License
Project Creator : 0blu

private static void SerializeFloat(Protocol16Stream output, float value, bool writeTypeCode)
        {
            output.WriteTypeCodeIfTrue(Protocol16Type.Float, writeTypeCode);
            var floatBuffer = _floatBuffer.Value;
            floatBuffer[0] = value;
            var buffer = _byteBuffer.Value;
            Buffer.BlockCopy(floatBuffer, 0, buffer, 0, sizeof(float));
            if (BitConverter.IsLittleEndian)
            {
                byte b0 = buffer[0];
                byte b1 = buffer[1];
                buffer[0] = buffer[3];
                buffer[1] = buffer[2];
                buffer[2] = b1;
                buffer[3] = b0;
            }
            output.Write(buffer, 0, sizeof(float));
        }

19 View Source File : ConnectionListener.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private void OnDataReceive(IAsyncResult result)
        {
            EndPoint clientEndPoint = null;

            try
            {
                clientEndPoint = new IPEndPoint(listeningHost, 0);
                int dataSize = Socket.EndReceiveFrom(result, ref clientEndPoint);

                IPEndPoint ipEndpoint = (IPEndPoint)clientEndPoint;

                // TO-DO: generate ban entries here based on packet rates of endPoint, IP Address, and IP Address Range

                if (packetLog.IsDebugEnabled)
                {
                    byte[] data = new byte[dataSize];
                    Buffer.BlockCopy(buffer, 0, data, 0, dataSize);

                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine($"Received Packet (Len: {data.Length}) [{ipEndpoint.Address}:{ipEndpoint.Port}=>{ListenerEndpoint.Address}:{ListenerEndpoint.Port}]");
                    sb.AppendLine(data.BuildPacketString());
                    packetLog.Debug(sb.ToString());
                }

                var packet = new ClientPacket();

                if (packet.Unpack(buffer, dataSize))
                    NetworkManager.ProcessPacket(this, packet, ipEndpoint);

                packet.ReleaseBuffer();
            }
            catch (SocketException socketException)
            {
                // If we get "Connection has been forcibly closed..." error, just eat the exception and continue on
                // This gets sent when the remote host terminates the connection (on UDP? interesting...)
                // TODO: There might be more, should keep an eye out. Logged message will help here.
                if (socketException.SocketErrorCode == SocketError.MessageSize ||
                    socketException.SocketErrorCode == SocketError.NetworkReset ||
                    socketException.SocketErrorCode == SocketError.ConnectionReset)
                {
                    log.DebugFormat("ConnectionListener.OnDataReceieve() has thrown {0}: {1} from client {2}", socketException.SocketErrorCode, socketException.Message, clientEndPoint != null ? clientEndPoint.ToString() : "Unknown");
                }
                else
                {
                    log.FatalFormat("ConnectionListener.OnDataReceieve() has thrown {0}: {1} from client {2}", socketException.SocketErrorCode, socketException.Message, clientEndPoint != null ? clientEndPoint.ToString() : "Unknown");
                    return;
                }
            }

            Listen();
        }

19 View Source File : ClientNetworkManager.cs
License : MIT License
Project Creator : 404Lcc

public void ReceiveCompleted(IAsyncResult result)
        {
            int length = socket.EndReceive(result);
            byte[] bytes = new byte[length];
            Buffer.BlockCopy(this.bytes, 0, bytes, 0, length);
            cacheList.AddRange(bytes);
            if (!receive)
            {
                receive = true;
                ReceiveHandle();
            }
            Receive();
        }

19 View Source File : QQTea.cs
License : MIT License
Project Creator : 499116344

public static byte[] Decrypt(byte[] In, int offset, int len, byte[] key)
        {
            var temp = new byte[In.Length];
            Buffer.BlockCopy(In, 0, temp, 0, In.Length);
            if (len % 8 != 0 || len < 16)
            {
                return null;
            }

            var array = new byte[len];
            for (var i = 0; i < len; i += 8)
            {
                Decode(temp, offset, i, array, 0, i, key);
            }

            for (var j = 8; j < len; j++)
            {
                array[j] ^= temp[offset + j - 8];
            }

            var num = array[0] & 7;
            len = len - num - 10;
            var array2 = new byte[len];
            Array.Copy(array, num + 3, array2, 0, len);
            return array2;
        }

19 View Source File : Protocol16Serializer.cs
License : MIT License
Project Creator : 0blu

private static void SerializeDouble(Protocol16Stream output, double value, bool writeTypeCode)
        {
            output.WriteTypeCodeIfTrue(Protocol16Type.Double, writeTypeCode);
            var doubleBuffer = _doubleBuffer.Value;
            doubleBuffer[0] = value;
            var buffer = _byteBuffer.Value;
            Buffer.BlockCopy(doubleBuffer, 0, buffer, 0, sizeof(double));
            if (BitConverter.IsLittleEndian)
            {
                byte b0 = buffer[0];
                byte b1 = buffer[1];
                byte b2 = buffer[2];
                byte b3 = buffer[3];
                buffer[0] = buffer[7];
                buffer[1] = buffer[6];
                buffer[2] = buffer[5];
                buffer[3] = buffer[4];
                buffer[4] = b3;
                buffer[5] = b2;
                buffer[6] = b1;
                buffer[7] = b0;
            }
            output.Write(buffer, 0, sizeof(double));
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 404Lcc

public static void BlockCopy(byte[] from, int fromIndex, byte[] to, int toIndex, int count)
        {
#if MF || WINRT
            Array.Copy(from, fromIndex, to, toIndex, count);
#else
            Buffer.BlockCopy(from, fromIndex, to, toIndex, count);
#endif
        }

19 View Source File : AesGcm.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3

public byte[] Concat(params byte[][] arrays)
        {
            int len = 0;

            foreach (byte[] array in arrays)
            {
                if (array == null)
                    continue;
                len += array.Length;
            }

            byte[] result = new byte[len - 1 + 1];
            int offset = 0;

            foreach (byte[] array in arrays)
            {
                if (array == null)
                    continue;
                Buffer.BlockCopy(array, 0, result, offset, array.Length);
                offset += array.Length;
            }

            return result;
        }

19 View Source File : EncryptionUtility.cs
License : Apache License 2.0
Project Creator : A7ocin

public static byte[] Combine(byte[] first, byte[] second)
		{
			byte[] ret = new byte[first.Length + second.Length];
			Buffer.BlockCopy(first, 0, ret, 0, first.Length);
			Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
			return ret;
		}

19 View Source File : Mesh.cs
License : MIT License
Project Creator : 91Act

public uint[] UnpackBitVector (PackedBitVector pakData)
		{
			uint[] unpackedVectors = new uint[pakData.m_NumItems];
			//int bitmax = 0;//used to convert int value to float
			//for (int b = 0; b < pakData.m_BitSize; b++) { bitmax |= (1 << b); }
			
			//the lazy way
			//split data into groups of "aligned" bytes i.e. 8 packed values per group
			//I could calculate optimized group size based on BitSize, but this is the lazy way
			
			if (pakData.m_BitSize == 0)
			{
				pakData.m_BitSize = (byte)((pakData.m_Data.Length * 8) / pakData.m_NumItems);
				//don't know, don't care
			}
			int groupSize = pakData.m_BitSize; //bitSize * 8 values / 8 bits
			byte[] group = new byte[groupSize];
			int groupCount = pakData.m_NumItems / 8;

			for (int g = 0; g < groupCount; g++)
			{
				Buffer.BlockCopy(pakData.m_Data, g * groupSize, group, 0, groupSize);
				BitArray groupBits = new BitArray(group);

				for (int v = 0; v < 8; v++)
				{
					BitArray valueBits = new BitArray(new Boolean[pakData.m_BitSize]);
					for (int b = 0; b < pakData.m_BitSize; b++)
					{
						valueBits.Set(b, groupBits.Get(b + v * pakData.m_BitSize));
					}

					var valueArr = new int[1];
					valueBits.CopyTo(valueArr, 0);
					//unpackedVectors[v + g * 8] = (float)(valueArr[0] / bitmax) * pakData.m_Range + pakData.m_Start;
					//valueBits.CopyTo(unpackedVectors, v + g * 8);//doesn't work with uint[]
					unpackedVectors[v + g * 8] = (uint)valueArr[0];
				}
			}

			//m_NumItems is not necessarily a multiple of 8, so there can be one extra group with fewer values
			int endBytes = pakData.m_Data.Length - groupCount * groupSize;
			int endVal = pakData.m_NumItems - groupCount * 8;

			if (endBytes > 0)
			{
				Buffer.BlockCopy(pakData.m_Data, groupCount * groupSize, group, 0, endBytes);
				BitArray groupBits = new BitArray(group);

				for (int v = 0; v < endVal; v++)
				{
					BitArray valueBits = new BitArray(new Boolean[pakData.m_BitSize]);
					for (int b = 0; b < pakData.m_BitSize; b++)
					{
						valueBits.Set(b, groupBits.Get(b + v * pakData.m_BitSize));
					}

					var valueArr = new int[1];
					valueBits.CopyTo(valueArr, 0);
					//unpackedVectors[v + groupCount * 8] = (float)(valueArr[0] / bitmax) * pakData.m_Range + pakData.m_Start;
					//valueBits.CopyTo(unpackedVectors, v + groupCount * 8);
					unpackedVectors[v + groupCount * 8] = (uint)valueArr[0];
				}
			}


			//the hard way
			//compute bit position in m_Data for each value
			/*byte[] value = new byte[4] { 0, 0, 0, 0 };

			int byteCount = pakData.m_BitSize / 8;//bytes in single value
			int bitCount = pakData.m_BitSize % 8;

			for (int v = 0; v < pakData.m_NumItems; v++)
			{
				if ((bitCount * v) % 8 == 0) //bitstream is "aligned"
				{//does this make sense if I'm gonna compute unaligned anywhay?
					for (int b = 0; b < byteCount; b++)
					{
						value[b] = pakData.m_Data[b + v * (byteCount+1)];
					}

					if (byteCount < 4) //shouldn't it be always?
					{
						byte lastByte = pakData.m_Data[bitCount * v / 8];

						for (int b = 0; b < bitCount; b++)//no
						{
							//set bit in val[byteCount+1]
						}
					}
				}
				else
				{
					//god knows
				}

				unpackedVectors[v] = BitConverter.ToSingle(value, 0);
			}*/


			//first I split the data into byte-aligned arrays
			//too complicated to calculate group size each time
			//then no point in dividing?
			/*int groupSize = byteCount + (bitCount + 7)/8;

			int groups = pakData.m_Data.Length / groupSize;
			int valPerGr = (int)(pakData.m_NumItems / groups);
			byte[] group = new byte[groupSize];

			for (int g = 0; g < groups; g++)
			{
				Buffer.BlockCopy(pakData.m_Data, g * groupSize, group, 0, groupSize);

				for (int v = 0; v < valPerGr; v++)
				{

					unpackedVectors[v + g * valPerGr] = BitConverter.ToSingle(value, 0);
				}
			}

			//m_Data size is not necessarily a multiple of align, so there can be one extra group with fewer values
			int lastBytes = pakData.m_Data.Length % groupSize;
			int lastVal = (int)(pakData.m_NumItems - groups * valPerGr);

			if (lastBytes > 0)
			{
				Buffer.BlockCopy(pakData.m_Data, groups * groupSize, group, 0, lastBytes);

				for (int v = 0; v < lastVal; v++)
				{

					unpackedVectors[v + groups * valPerGr] = BitConverter.ToSingle(value, 0);
				}
			}*/

			return unpackedVectors;
		}

19 View Source File : PkgChecker.cs
License : MIT License
Project Creator : 13xforever

private static byte[] GetCmac(Span<byte> data, byte[] omacKey, bool truncate = true)
        {
            if (omacKey?.Length != 0x10)
                throw new ArgumentException(nameof(omacKey));

            static byte[] AESEncrypt(byte[] key, byte[] iv, Span<byte> dataToEncrypt)
            {
                using var result = new MemoryStream();
                using var aes = Aes.Create();
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.None;
                using var cs = new CryptoStream(result, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write);
                cs.Write(dataToEncrypt);
                cs.FlushFinalBlock();
                return result.ToArray();
            }

            static byte[] Rol(byte[] b)
            {
                var r = new byte[b.Length];
                byte carry = 0;
                for (var i = b.Length - 1; i >= 0; i--)
                {
                    ushort u = (ushort)(b[i] << 1);
                    r[i] = (byte)((u & 0xff) + carry);
                    carry = (byte)((u & 0xff00) >> 8);
                }
                return r;
            }

            // SubKey generation
            // step 1, AES-128 with key K is applied to an all-zero input block.
            byte[] derivedKey = AESEncrypt(omacKey, new byte[16], new byte[16]);

            // step 2, K1 is derived through the following operation:
            byte[] subKey1 = Rol(derivedKey); //If the most significant bit of L is equal to 0, K1 is the left-shift of L by 1 bit.
            if ((derivedKey[0] & 0x80) == 0x80)
                subKey1[15] ^= 0x87; // Otherwise, K1 is the exclusive-OR of const_Rb and the left-shift of L by 1 bit.

            // step 3, K2 is derived through the following operation:
            byte[] subKey2 = Rol(subKey1); // If the most significant bit of K1 is equal to 0, K2 is the left-shift of K1 by 1 bit.
            if ((subKey1[0] & 0x80) == 0x80)
                subKey2[15] ^= 0x87; // Otherwise, K2 is the exclusive-OR of const_Rb and the left-shift of K1 by 1 bit.

            // MAC computing
            byte[] buf;
            if ((data.Length != 0) && (data.Length % 16 == 0))
            {
                // If the size of the input message block is equal to a positive multiple of the block size (namely, 128 bits),
                // the last block shall be exclusive-OR'ed with K1 before processing
                buf = new byte[data.Length];
                Buffer.BlockCopy(data.ToArray(), 0, buf, 0, data.Length-16);
                for (var j = 0; j < subKey1.Length; j++)
                {
                    var idx = data.Length - 16 + j;
                    buf[idx] = (byte)(data[idx] ^ subKey1[j]);
                }
            }
            else
            {
                // Otherwise, the last block shall be padded with 10^i
                var paddingLength = 16 - data.Length % 16;
                buf = new byte[data.Length + paddingLength];
                Buffer.BlockCopy(data.ToArray(), 0, buf, 0, data.Length);
                buf[data.Length] = 0x80;
                // and exclusive-OR'ed with K2
                for (int j = 0; j < subKey2.Length; j++)
                    buf[buf.Length - 16 + j] ^= subKey2[j];
            }

            // The result of the previous process will be the input of the last encryption.
            byte[] encResult = AESEncrypt(omacKey, new byte[16], buf);
            if (truncate)
                return encResult.replacedpan(encResult.Length - 16, 16).ToArray();
            else
                return encResult.replacedpan(encResult.Length - 0x14, 0x14).ToArray();
        }

19 View Source File : DellSmbiosSmi.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public static bool ExecuteCommand(ref SmiObject message)
        {
            byte[] bytes = StructToByteArray(message);
            byte[] buffer = new byte[BufferLength];
            Buffer.BlockCopy(bytes, 0, buffer, 0, bytes.Length);
            bool result = ExecuteCommand(ref buffer);
            message = ByteArrayToStruct(buffer);

            return result;
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

private void FillBuffer(int minBytes)
        {
            int bytesUnread = readLength - readOffset;

            if (bytesUnread > 0)
            {
                Buffer.BlockCopy(buffer, readOffset, buffer, 0, bytesUnread);
            }

            int numBytesToRead = bufferSize - bytesUnread;
            int numBytesRead = bytesUnread;
            do
            {
                int n = stream.Read(buffer, numBytesRead, numBytesToRead);

                if (n == 0)
                {
                    throw new EndOfStreamException();
                }

                numBytesRead += n;
                numBytesToRead -= n;

            } while (numBytesRead < minBytes);

            readOffset = 0;
            readLength = numBytesRead;
        }

19 View Source File : MessageBuilder.cs
License : MIT License
Project Creator : Abaudat

static byte[] FlagMessage(byte[] data, NetworkingFlags.Flags flag)
    {
        byte[] flaggedData = new byte[data.Length + sizeof(int) + 1];

        Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, flaggedData, 0, sizeof(int));
        flaggedData[sizeof(int)] = (byte)flag;
        Buffer.BlockCopy(data, 0, flaggedData, sizeof(int) + 1, data.Length);

        return flaggedData;
    }

19 View Source File : PkgChecker.cs
License : MIT License
Project Creator : 13xforever

private static byte[] GetSha1Hmac(Span<byte> data, Span<byte> key)
        {
            if (key.Length != 0x40)
                throw new ArgumentException(nameof(key));

            var ipad = new byte[0x40];
            var tmp = new byte[0x40 + 0x14]; // opad + hash(ipad + message)

            for (var i = 0; i < ipad.Length; i++)
            {
                tmp[i] = (byte)(key[i] ^ 0x5c); // opad
                ipad[i] = (byte)(key[i] ^ 0x36);
            }

            using (var sha1 = SHA1.Create())
            {
                sha1.TransformBlock(ipad.ToArray(), 0, ipad.Length, null, 0);
                sha1.TransformFinalBlock(data.ToArray(), 0, data.Length);
                Buffer.BlockCopy(sha1.Hash, 0, tmp, 0x40, 0x14);
            }
            using (var sha1 = SHA1.Create())
                return sha1.ComputeHash(tmp);
        }

19 View Source File : ServerMessageParser.cs
License : MIT License
Project Creator : Abaudat

public void ParseMessage(byte[] message, int connectionId)
    {
        byte[] size = new byte[sizeof(int)];
        Buffer.BlockCopy(message, 0, size, 0, sizeof(int));
        byte[] data = new byte[BitConverter.ToInt32(size, 0)];
        Buffer.BlockCopy(message, sizeof(int) + 1, data, 0, data.Length);
        switch (message[sizeof(int)]) // Add cases to this switch for all different types of message the server can receive.
        {
            case (byte)NetworkingFlags.Flags.DEBUG_MESSAGE:
                OnDebugMessage(data, connectionId);
                break;
            default:
                Debug.LogWarning("WARNING: Unknown byte flag " + message[sizeof(int)] + " .");
                break;
        }
    }

19 View Source File : Protocol16Serializer.cs
License : MIT License
Project Creator : 0blu

private static void SerializeLong(Protocol16Stream output, long value, bool writeTypeCode)
        {
            output.WriteTypeCodeIfTrue(Protocol16Type.Long, writeTypeCode);
            var longBuffer = _longBuffer.Value;
            longBuffer[0] = value;
            var buffer = _byteBuffer.Value;
            Buffer.BlockCopy(longBuffer, 0, buffer, 0, sizeof(long));
            if (BitConverter.IsLittleEndian)
            {
                byte b0 = buffer[0];
                byte b1 = buffer[1];
                byte b2 = buffer[2];
                byte b3 = buffer[3];
                buffer[0] = buffer[7];
                buffer[1] = buffer[6];
                buffer[2] = buffer[5];
                buffer[3] = buffer[4];
                buffer[4] = b3;
                buffer[5] = b2;
                buffer[6] = b1;
                buffer[7] = b0;
            }
            output.Write(buffer, 0, sizeof(long));
        }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

public void SendAvatarUpdate(ulong userID, Transform rootTransform, UInt32 sequence, byte[] avatarPacket)
    {
        const int UPDATE_DATA_LENGTH = 41;
        byte[] sendBuffer = new byte[avatarPacket.Length + UPDATE_DATA_LENGTH];

        int offset = 0;
        PackByte((byte)MessageType.Update, sendBuffer, ref offset);

        PackULong(SocialPlatformManager.MyID, sendBuffer, ref offset);

        PackFloat(rootTransform.position.x, sendBuffer, ref offset);
        // Lock to floor height
        PackFloat(0f, sendBuffer, ref offset);
        PackFloat(rootTransform.position.z, sendBuffer, ref offset);
        PackFloat(rootTransform.rotation.x, sendBuffer, ref offset);
        PackFloat(rootTransform.rotation.y, sendBuffer, ref offset);
        PackFloat(rootTransform.rotation.z, sendBuffer, ref offset);
        PackFloat(rootTransform.rotation.w, sendBuffer, ref offset);

        PackUInt32(sequence, sendBuffer, ref offset);

        Debug.replacedert(offset == UPDATE_DATA_LENGTH);

        Buffer.BlockCopy(avatarPacket, 0, sendBuffer, offset, avatarPacket.Length);
        Net.SendPacket(userID, sendBuffer, SendPolicy.Unreliable);
    }

19 View Source File : Inline_Hook.cs
License : Apache License 2.0
Project Creator : 1694439208

public byte[] ReplaceBytes(byte[] src, byte[] search, byte[] repl)
        {
            byte[] dst = null;
            int index = FindBytes(src, search);
            if (index >= 0)
            {
                dst = new byte[src.Length - search.Length + repl.Length];
                // before found array
                Buffer.BlockCopy(src, 0, dst, 0, index);
                // repl copy
                Buffer.BlockCopy(repl, 0, dst, index, repl.Length);
                // rest of src array
                Buffer.BlockCopy(
                    src,
                    index + search.Length,
                    dst,
                    index + repl.Length,
                    src.Length - (index + search.Length));
            }
            return dst;
        }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

void PackFloat(float f, byte[] buf, ref int offset)
    {
        Buffer.BlockCopy(BitConverter.GetBytes(f), 0, buf, offset, sizeof(float));
        offset += sizeof(float);
    }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

private int ReadInternal(byte[] bytes, int offset, int count)
        {
            if (count == 0)
            {
                return 0;
            }

            if ((this.readOffset + count) <= this.readLength)
            {
                if (count <= 8)
                {
                    // Use a for loop when copying a small number of bytes.
                    for (int i = 0; i < count; i++)
                    {
                        bytes[offset + i] = this.buffer[this.readOffset + i];
                    }
                }
                else
                {
                    Buffer.BlockCopy(this.buffer, this.readOffset, bytes, offset, count);
                }
                this.readOffset += count;

                return count;
            }
            else
            {
                // Ensure that any bytes at the end of the current buffer are included.
                int bytesUnread = this.readLength - this.readOffset;

                if (bytesUnread > 0)
                {
                    Buffer.BlockCopy(this.buffer, this.readOffset, bytes, offset, bytesUnread);
                }

                // Invalidate the existing buffer.
                this.readOffset = 0;
                this.readLength = 0;

                int totalBytesRead = bytesUnread;

                totalBytesRead += this.stream.Read(bytes, offset + bytesUnread, count - bytesUnread);

                return totalBytesRead;
            }
        }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

void PackUInt32(UInt32 u, byte[] buf, ref int offset)
    {
        Buffer.BlockCopy(BitConverter.GetBytes(u), 0, buf, offset, sizeof(UInt32));
        offset += sizeof(UInt32);
    }

19 View Source File : MP3FileWriter.cs
License : MIT License
Project Creator : 3wz

public override void Write(byte[] buffer, int offset, int count)
        {
            while (count > 0)
            {
                int blockSize = Math.Min(inBuffer.nBytes - inPosition, count);
                Buffer.BlockCopy(buffer, offset, inBuffer.bytes, inPosition, blockSize);

                inPosition += blockSize;
                count -= blockSize;
                offset += blockSize;

                if (inPosition >= inBuffer.nBytes)
                    Encode();
            }
        }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

void PackInt32(int value, byte[] buf, ref int offset)
		{
			Buffer.BlockCopy(BitConverter.GetBytes(value), 0, buf, offset, 4);
			offset = offset + 4;
		}

19 View Source File : Protocol16Stream.cs
License : MIT License
Project Creator : 0blu

public override int Read(byte[] buffer, int offset, int count)
        {
            int dif = _length - _position;
            if (dif <= 0)
            {
                return 0;
            }
            if (count > dif)
            {
                count = dif;
            }
            Buffer.BlockCopy(_buffer, _position, buffer, offset, count);
            _position += count;

            return count;
        }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

void PackFloat(float f, byte[] buf, ref int offset)
		{
			Buffer.BlockCopy(BitConverter.GetBytes(f), 0, buf, offset, 4);
			offset = offset + 4;
		}

19 View Source File : CodedInputStream.cs
License : MIT License
Project Creator : 404Lcc

internal byte[] ReadRawBytes(int size)
        {
            if (size < 0)
            {
                throw InvalidProtocolBufferException.NegativeSize();
            }

            if (totalBytesRetired + bufferPos + size > currentLimit)
            {
                // Read to the end of the stream (up to the current limit) anyway.
                SkipRawBytes(currentLimit - totalBytesRetired - bufferPos);
                // Then fail.
                throw InvalidProtocolBufferException.TruncatedMessage();
            }

            if (size <= bufferSize - bufferPos)
            {
                // We have all the bytes we need already.
                byte[] bytes = new byte[size];
                ByteArray.Copy(buffer, bufferPos, bytes, 0, size);
                bufferPos += size;
                return bytes;
            }
            else if (size < buffer.Length)
            {
                // Reading more bytes than are in the buffer, but not an excessive number
                // of bytes.  We can safely allocate the resulting array ahead of time.

                // First copy what we have.
                byte[] bytes = new byte[size];
                int pos = bufferSize - bufferPos;
                ByteArray.Copy(buffer, bufferPos, bytes, 0, pos);
                bufferPos = bufferSize;

                // We want to use RefillBuffer() and then copy from the buffer into our
                // byte array rather than reading directly into our byte array because
                // the input may be unbuffered.
                RefillBuffer(true);

                while (size - pos > bufferSize)
                {
                    Buffer.BlockCopy(buffer, 0, bytes, pos, bufferSize);
                    pos += bufferSize;
                    bufferPos = bufferSize;
                    RefillBuffer(true);
                }

                ByteArray.Copy(buffer, 0, bytes, pos, size - pos);
                bufferPos = size - pos;

                return bytes;
            }
            else
            {
                // The size is very large.  For security reasons, we can't allocate the
                // entire byte array yet.  The size comes directly from the input, so a
                // maliciously-crafted message could provide a bogus very large size in
                // order to trick the app into allocating a lot of memory.  We avoid this
                // by allocating and reading only a small chunk at a time, so that the
                // malicious message must actually *be* extremely large to cause
                // problems.  Meanwhile, we limit the allowed size of a message elsewhere.

                // Remember the buffer markers since we'll have to copy the bytes out of
                // it later.
                int originalBufferPos = bufferPos;
                int originalBufferSize = bufferSize;

                // Mark the current buffer consumed.
                totalBytesRetired += bufferSize;
                bufferPos = 0;
                bufferSize = 0;

                // Read all the rest of the bytes we need.
                int sizeLeft = size - (originalBufferSize - originalBufferPos);
                List<byte[]> chunks = new List<byte[]>();

                while (sizeLeft > 0)
                {
                    byte[] chunk = new byte[Math.Min(sizeLeft, buffer.Length)];
                    int pos = 0;
                    while (pos < chunk.Length)
                    {
                        int n = (input == null) ? -1 : input.Read(chunk, pos, chunk.Length - pos);
                        if (n <= 0)
                        {
                            throw InvalidProtocolBufferException.TruncatedMessage();
                        }
                        totalBytesRetired += n;
                        pos += n;
                    }
                    sizeLeft -= chunk.Length;
                    chunks.Add(chunk);
                }

                // OK, got everything.  Now concatenate it all into one buffer.
                byte[] bytes = new byte[size];

                // Start by copying the leftover bytes from this.buffer.
                int newPos = originalBufferSize - originalBufferPos;
                ByteArray.Copy(buffer, originalBufferPos, bytes, 0, newPos);

                // And now all the chunks.
                foreach (byte[] chunk in chunks)
                {
                    Buffer.BlockCopy(chunk, 0, bytes, newPos, chunk.Length);
                    newPos += chunk.Length;
                }

                // Done.
                return bytes;
            }
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

public byte[] ReadBytes(int count)
        {
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
            VerifyNotDisposed();

            if (count == 0)
            {
                return EmptyArray<byte>.Value;
            }

            byte[] bytes = new byte[count];

            if ((readOffset + count) <= readLength)
            {
                Buffer.BlockCopy(buffer, readOffset, bytes, 0, count);
                readOffset += count;
            }
            else
            {
                // Ensure that any bytes at the end of the current buffer are included.
                int bytesUnread = readLength - readOffset;

                if (bytesUnread > 0)
                {
                    Buffer.BlockCopy(buffer, readOffset, bytes, 0, bytesUnread);
                }

                int numBytesToRead = count - bytesUnread;
                int numBytesRead = bytesUnread;
                do
                {
                    int n = stream.Read(bytes, numBytesRead, numBytesToRead);

                    if (n == 0)
                    {
                        throw new EndOfStreamException();
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;

                } while (numBytesToRead > 0);

                // Invalidate the existing buffer.
                readOffset = 0;
                readLength = 0;
            }

            return bytes;
        }

19 View Source File : PhotonParser.cs
License : MIT License
Project Creator : 0blu

private void HandleSegmentedPayload(int startSequenceNumber, int totalLength, int fragmentLength, int fragmentOffset, byte[] source, ref int offset)
        {
            SegmentedPackage segmentedPackage = GetSegmentedPackage(startSequenceNumber, totalLength);

            Buffer.BlockCopy(source, offset, segmentedPackage.TotalPayload, fragmentOffset, fragmentLength);
            offset += fragmentLength;
            segmentedPackage.BytesWritten += fragmentLength;

            if (segmentedPackage.BytesWritten >= segmentedPackage.TotalLength)
            {
                _pendingSegments.Remove(startSequenceNumber);
                HandleFinishedSegmentedPackage(segmentedPackage.TotalPayload);
            }
        }

19 View Source File : Protocol16Stream.cs
License : MIT License
Project Creator : 0blu

public override void Write(byte[] buffer, int offset, int count)
        {
            int sum = _position + count;
            ExpandIfNeeded(sum);
            if (sum > _length)
            {
                _length = sum;
            }
            Buffer.BlockCopy(buffer, offset, _buffer, _position, count);
            _position = sum;
        }

19 View Source File : AvifWriter.AvifWriterItem.cs
License : MIT License
Project Creator : 0xC0000054

public static AvifWriterItem CreateFromExif(uint itemId, byte[] exif)
            {
                // The AVIF format includes the offset to the start of the TIFF header
                // before the EXIF data.
                // The EXIF blob that this plug-in creates will always have the TIFF header
                // at offset 0, so we only need to copy the EXIF data to a new byte array.

                byte[] contentBytes = new byte[sizeof(uint) + exif.Length];
                Buffer.BlockCopy(exif, 0, contentBytes, 4, exif.Length);

                ExifItemInfoEntry exifItemInfo = new ExifItemInfoEntry(itemId);

                return new AvifWriterItem(itemId, "Exif", contentBytes, exifItemInfo);
            }

19 View Source File : Decrypter.cs
License : MIT License
Project Creator : 13xforever

public override int Read( byte[] buffer, int offset, int count)
        {
            if (Position == inputStream.Length)
                return 0;

            var positionInSector = Position % sectorSize;
            var resultCount = 0;
            if (positionInSector > 0)
            {
                var len = (int)Math.Min(Math.Min(count, sectorSize - positionInSector), inputStream.Position - Position);
                md5.TransformBlock(bufferedSector, (int)positionInSector, len, buffer, offset);
                sha1.TransformBlock(bufferedSector, (int)positionInSector, len, buffer, offset);
                sha256.TransformBlock(bufferedSector, (int)positionInSector, len, buffer, offset);
                offset += len;
                count -= len;
                resultCount += len;
                Position += len;
                if (Position % sectorSize == 0)
                    SectorPosition++;
            }
            if (Position == inputStream.Length)
                return resultCount;

            int readCount;
            do
            {
                readCount = inputStream.ReadExact(tmpSector, 0, sectorSize);
                if (readCount < sectorSize)
                    Array.Clear(tmpSector, readCount, sectorSize - readCount);
                var decryptedSector = tmpSector;
                if (IsEncrypted(SectorPosition))
                {
                    WasEncrypted = true;
                    if (readCount % 16 != 0)
                    {
                        Log.Debug($"Block has only {(readCount % 16) * 8} bits of data, reading raw sector...");
                        discStream.Seek(SectorPosition * sectorSize, SeekOrigin.Begin);
                        var newTmpSector = new byte[sectorSize];
                        discStream.ReadExact(newTmpSector, 0, sectorSize);
                        if (!newTmpSector.Take(readCount).SequenceEqual(tmpSector.Take(readCount)))
                            Log.Warn($"Filesystem data and raw data do not match for sector 0x{SectorPosition:x8}");
                        tmpSector = newTmpSector;
                    }
                    using var aesTransform = aes.CreateDecryptor(decryptionKey, GetSectorIV(SectorPosition));
                    decryptedSector = aesTransform.TransformFinalBlock(tmpSector, 0, sectorSize);
                }
                else
                    WasUnprotected = true;
                if (count >= readCount)
                {
                    md5.TransformBlock(decryptedSector, 0, readCount, buffer, offset);
                    sha1.TransformBlock(decryptedSector, 0, readCount, buffer, offset);
                    sha256.TransformBlock(decryptedSector, 0, readCount, buffer, offset);
                    offset += readCount;
                    count -= readCount;
                    resultCount += readCount;
                    Position += readCount;
                    SectorPosition++;
                }
                else // partial sector read
                {
                    Buffer.BlockCopy(decryptedSector, 0, bufferedSector, 0, sectorSize);
                    md5.TransformBlock(decryptedSector, 0, count, buffer, offset);
                    sha1.TransformBlock(decryptedSector, 0, count, buffer, offset);
                    sha256.TransformBlock(decryptedSector, 0, count, buffer, offset);
                    offset += count;
                    count = 0;
                    resultCount += count;
                    Position += count;
                }
            } while (count > 0 && readCount == sectorSize);
            return resultCount;
        }

19 View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802

private static float[] Convert24BitByteArrayToAudioClipData(byte[] source, int headerOffset, int dataSize)
		{
			int wavSize = BitConverter.ToInt32(source, headerOffset);
			headerOffset += sizeof(int);
			Debug.replacedertFormat(wavSize > 0 && wavSize == dataSize, "Failed to get valid 24-bit wav size: {0} from data bytes: {1} at offset: {2}", wavSize, dataSize, headerOffset);

			int x = 3; // block size = 3
			int convertedSize = wavSize / x;

			int maxValue = Int32.MaxValue;

			float[] data = new float[convertedSize];

			byte[] block = new byte[sizeof(int)]; // using a 4 byte block for copying 3 bytes, then copy bytes with 1 offset

			int offset = 0;
			int i = 0;
			while (i < convertedSize)
			{
				offset = i * x + headerOffset;
				Buffer.BlockCopy(source, offset, block, 1, x);
				data[i] = (float)BitConverter.ToInt32(block, 0) / maxValue;
				++i;
			}

			Debug.replacedertFormat(data.Length == convertedSize, "AudioClip .wav data is wrong size: {0} == {1}", data.Length, convertedSize);

			return data;
		}

See More Examples