예제 #1
0
        /// <inheritdoc/>
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (count < 0 || offset + count > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("count");
            }
            ThrowIfDisposed();

            if (_position >= _length)
            {
                return(0);
            }

            var available = _length - _position;

            if (count > available)
            {
                count = available;
            }

            _buffer.GetBytes(_position, buffer, offset, count);
            _position += count;

            return(count);
        }
예제 #2
0
        public void TestCopyingToOutputStream()
        {
            IByteBuffer buf1 = Unpooled.DirectBuffer(10);
            IByteBuffer buf2 = Unpooled.Buffer(10);
            IByteBuffer buf3 = Unpooled.DirectBuffer(10);

            buf1.WriteBytes(Encoding.ASCII.GetBytes("a"));
            buf2.WriteBytes(Encoding.ASCII.GetBytes("b"));
            buf3.WriteBytes(Encoding.ASCII.GetBytes("c"));
            IByteBuffer composite   = Unpooled.WrappedUnmodifiableBuffer(buf1, buf2, buf3);
            IByteBuffer copy        = Unpooled.DirectBuffer(3);
            IByteBuffer copy2       = Unpooled.Buffer(3);
            var         copyStream  = new ByteBufferStream(copy);
            var         copy2Stream = new ByteBufferStream(copy2);

            try
            {
                composite.GetBytes(0, copyStream, 3);
                composite.GetBytes(0, copy2Stream, 3);
                Assert.Equal(0, ByteBufferUtil.Compare(copy, composite));
                Assert.Equal(0, ByteBufferUtil.Compare(copy2, composite));
                Assert.Equal(0, ByteBufferUtil.Compare(copy, copy2));
            }
            finally
            {
                copy.Release();
                copy2.Release();
                copyStream.Close();
                copy2Stream.Close();
                composite.Release();
            }
        }
예제 #3
0
        public override byte[] GetBytes()
        {
            if (_byteBuf is null)
            {
                return(Unpooled.Empty.Array);
            }

            var array = new byte[_byteBuf.ReadableBytes];

            _ = _byteBuf.GetBytes(_byteBuf.ReaderIndex, array);
            return(array);
        }
예제 #4
0
        public static byte[] Split(IByteBuffer buffer)
        {
            var rdx      = 0;
            var crcBytes = new byte[2];
            var crc      = 0;
            var length   = 0;
            var valid    = false;

            while (true)
            {
                // 可读字节数小于最小报文长度
                if (buffer.ReadableBytes < LoraConst.MinLength)
                {
                    return(null);
                }
                // 确定帧头的位置
                if (LoraConst.StartSign != buffer.GetByte(rdx))
                {
                    rdx = GetStartIndex(buffer, LoraConst.StartSign);
                }

                // 没有找到帧头
                if (rdx == -1)
                {
                    return(null);
                }
                buffer.SetReaderIndex(rdx);
                var lengthBytes = new byte[2];
                buffer.GetBytes(rdx + 23, lengthBytes);
                length = BytesUtil.Bytes2Int16(lengthBytes);
                if (buffer.ReadableBytes < LoraConst.MinLength + length)
                {
                    rdx++;
                    buffer.SetReaderIndex(rdx);
                    continue;
                }
                var content = new byte[25 + length];
                buffer.GetBytes(rdx, content);
                buffer.GetBytes(rdx + 25 + length, crcBytes);
                crc   = CRC16.calcCrc16(content);
                valid = BytesUtil.ByteArrayEquals(crcBytes, BytesUtil.Int16ToBytes((Int16)crc));
                if (!valid)
                {
                    rdx++;
                    buffer.SetReaderIndex(rdx);
                    continue;
                }
                var msg = new byte[LoraConst.MinLength + length];
                buffer.ReadBytes(msg);
                return(msg);
            }
        }
예제 #5
0
        /// <summary>
        /// Return an array of the underlying storage from <paramref name="buf"/> into a byte array.
        /// The copy will start at {@code start} and copy {@code length} bytes.
        /// If <paramref name="copy"/> is true a copy will be made of the memory.
        /// If <paramref name="copy"/> is false the underlying storage will be shared, if possible.
        /// </summary>
        /// <param name="buf"></param>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="copy"></param>
        /// <returns></returns>
        public static byte[] GetBytes(IByteBuffer buf, int start, int length, bool copy)
        {
            var capacity = buf.Capacity;

            if (MathUtil.IsOutOfBounds(start, length, capacity))
            {
                ThrowHelper.ThrowIndexOutOfRangeException_Expected(start, length, capacity);
            }

            if (buf.HasArray)
            {
                if (copy || start != 0 || length != capacity)
                {
                    int baseOffset = buf.ArrayOffset + start;
                    var bytes      = new byte[length];
                    PlatformDependent.CopyMemory(buf.Array, baseOffset, bytes, 0, length);
                    return(bytes);
                }
                else
                {
                    return(buf.Array);
                }
            }

            byte[] v = new byte[length];
            _ = buf.GetBytes(start, v);
            return(v);
        }
예제 #6
0
        public override void SetContent(IByteBuffer buffer)
        {
            Contract.Requires(buffer != null);
            try
            {
                this.Size = buffer.ReadableBytes;
                this.CheckSize(this.Size);
                if (this.DefinedSize > 0 && this.DefinedSize < this.Size)
                {
                    throw new IOException($"Out of size: {this.Size} > {this.DefinedSize}");
                }
                if (this.fileStream == null)
                {
                    this.fileStream = this.TempFile();
                }
                if (buffer.ReadableBytes == 0)
                {
                    // empty file
                    return;
                }

                buffer.GetBytes(buffer.ReaderIndex, this.fileStream, buffer.ReadableBytes);
                buffer.SetReaderIndex(buffer.ReaderIndex + buffer.ReadableBytes);
                this.fileStream.Flush();
                this.SetCompleted();
            }
            finally
            {
                // Release the buffer as it was retained before and we not need a reference to it at all
                // See https://github.com/netty/netty/issues/1516
                buffer.Release();
            }
        }
예제 #7
0
        internal static void SetBytes(AbstractByteBuffer buf, byte *addr, int index, IByteBuffer src, int srcIndex, int length)
        {
            if (MathUtil.IsOutOfBounds(srcIndex, length, src.Capacity))
            {
                throw new IndexOutOfRangeException($"srcIndex: {srcIndex}");
            }

            if (length != 0)
            {
                if (src.HasMemoryAddress)
                {
                    IntPtr ptr = src.AddressOfPinnedMemory();
                    if (ptr != IntPtr.Zero)
                    {
                        PlatformDependent.CopyMemory((byte *)(ptr + srcIndex), addr, length);
                    }
                    else
                    {
                        fixed(byte *source = &src.GetPinnableMemoryAddress())
                        {
                            PlatformDependent.CopyMemory(source + srcIndex, addr, length);
                        }
                    }
                }
                else if (src.HasArray)
                {
                    PlatformDependent.CopyMemory(src.Array, src.ArrayOffset + srcIndex, addr, length);
                }
                else
                {
                    src.GetBytes(srcIndex, buf, index, length);
                }
            }
        }
예제 #8
0
        private byte[] GetBytes(int length)
        {
            byte[] dest = new byte[length];
            buffer.GetBytes(buffer.ReaderIndex, dest);

            return(dest);
        }
예제 #9
0
        private byte[] ToByteArray(IByteBuffer buffer)
        {
            var bytes = new byte[buffer.Length];

            buffer.GetBytes(0, bytes, 0, buffer.Length);
            return(bytes);
        }
예제 #10
0
        /// <inheritdoc/>
        public void GetBytes(int position, byte[] destination, int offset, int count)
        {
            EnsureValidPositionAndCount(position, count);
            ThrowIfDisposed();

            _buffer.GetBytes(position + _offset, destination, offset, count);
        }
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            IByteBuffer buffer = (IByteBuffer)message;

            try
            {
                byte[] data = new byte[buffer.ReadableBytes];
                buffer.GetBytes(buffer.ReaderIndex, data);

                string datajson     = LZ4MessagePackSerializer.ToJson(data);
                var    convertedMsg = _serializer.Deserialize <string, TransportMsg>(datajson);

                if (convertedMsg.ContentType == typeof(RemoteCallData).FullName)
                {
                    convertedMsg.Content = _serializer.Deserialize <object, RemoteCallData>(convertedMsg.Content);
                }
                else if (convertedMsg.ContentType == typeof(RemoteCallBackData).FullName)
                {
                    convertedMsg.Content = _serializer.Deserialize <object, RemoteCallBackData>(convertedMsg.Content);
                }
                context.FireChannelRead(convertedMsg);
            }
            finally
            {
                buffer.Release();
            }
        }
        public void SetContentFromStream()
        {
            var random = new Random();

            for (int i = 0; i < 20; i++)
            {
                // Generate input data bytes.
                int size  = random.Next(short.MaxValue);
                var bytes = new byte[size];

                random.NextBytes(bytes);

                // Generate parsed HTTP data block.
                var httpData = new TestHttpData("name", Encoding.UTF8, 0);

                httpData.SetContent(new MemoryStream(bytes));

                // Validate stored data.
                IByteBuffer buffer = httpData.GetByteBuffer();

                Assert.Equal(0, buffer.ReaderIndex);
                Assert.Equal(bytes.Length, buffer.WriterIndex);

                var data = new byte[bytes.Length];
                buffer.GetBytes(buffer.ReaderIndex, data);

                Assert.True(data.SequenceEqual(bytes));
            }
        }
예제 #13
0
        public static IByteBuffer GetBytes(this IByteBuffer buf, int index, IByteBuffer destination, int length)
        {
            var writerIdx = destination.WriterIndex;

            _ = buf.GetBytes(index, destination, writerIdx, length);
            _ = destination.SetWriterIndex(writerIdx + length);
            return(buf);
        }
예제 #14
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer message, List <object> output)
        {
            var len   = message.ReadableBytes;
            var array = new byte[len];

            message.GetBytes(message.ReaderIndex, array, 0, len);
            output.Add(_serialize.Deserializes <T>(array));
        }
예제 #15
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer message, List <object> output)
        {
            var len   = message.ReadableBytes;
            var array = new byte[len];

            message.GetBytes(message.ReaderIndex, array, 0, len);
            //output.Add(SerializerHelper.Deserialize<TransportMessage<T>>(array));
            output.Add(Codec.Deserialize(array, typeof(T)));
        }
예제 #16
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            byte[] array = new byte[input.ReadableBytes];
            input.GetBytes(input.ReaderIndex, array, 0, input.ReadableBytes);
            input.Clear();

            var msg = new Message();

            output.Add(msg.Prase(array));
        }
예제 #17
0
 private static void SetBytes0(AbstractByteBuffer buf, byte *addr, int index, IByteBuffer src, int srcIndex, int length)
 {
     if (src.HasArray)
     {
         PlatformDependent.CopyMemory(src.Array, src.ArrayOffset + srcIndex, addr, length);
     }
     else
     {
         _ = src.GetBytes(srcIndex, buf, index, length);
     }
 }
 /// <summary>
 /// Copies a slice of a frame representing a part of a bigger string in a temporary buffer to be reassembled. </summary>
 /// <param name="startIndex"> starting index (inclusive) </param>
 /// <param name="endIndex"> ending index (exclusive) </param>
 private void copyLinePart(IByteBuffer buf, int startIndex, int endIndex)
 {
     try
     {
         buf.GetBytes(startIndex, linePart, endIndex - startIndex);
     }
     catch (IOException e)
     {
         log.Error("Unexpected exception", e); // should not happen
     }
 }
예제 #19
0
        public static IByteBuffer DecompressGzip(this IByteBuffer buffer)
        {
            var data = buffer.GetBytes();

            using (var compressedStream = new MemoryStream(data))
                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                    using (var resultStream = new MemoryStream())
                    {
                        zipStream.CopyTo(resultStream);
                        return(Unpooled.WrappedBuffer(resultStream.ToArray()));
                    }
        }
예제 #20
0
        public static IByteBuffer CompressGzip(this IByteBuffer buffer)
        {
            var data = buffer.GetBytes();

            using (var compressedStream = new MemoryStream(data))
                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
                {
                    zipStream.Write(data, 0, data.Length);
                    zipStream.Close();
                    return(Unpooled.WrappedBuffer(compressedStream.ToArray()));
                }
        }
예제 #21
0
 public override IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length)
 {
     this.CheckSrcIndex(index, length, srcIndex, src.Capacity);
     if (src.HasArray)
     {
         this.SetBytes(index, src.Array, src.ArrayOffset + srcIndex, length);
     }
     else
     {
         src.GetBytes(srcIndex, this.Memory, this.Idx(index), length);
     }
     return(this);
 }
예제 #22
0
        public void SetContentFromStream()
        {
            // definedSize=0
            TestHttpData test       = new TestHttpData("test", Encoding.UTF8, 0);
            string       contentStr = "foo_test";
            var          buf        = Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(contentStr));

            buf.MarkReaderIndex();
            var bs = new ByteBufferStream(buf);

            try
            {
                test.SetContent(bs);
                Assert.False(buf.IsReadable());
                Assert.Equal(test.GetString(Encoding.UTF8), contentStr);
                buf.ResetReaderIndex();
                Assert.True(ByteBufferUtil.Equals(buf, test.GetByteBuffer()));
            }
            finally
            {
                bs.Close();
            }

            var random = new Random();

            for (int i = 0; i < 20; i++)
            {
                // Generate input data bytes.
                int size  = random.Next(short.MaxValue);
                var bytes = new byte[size];

                random.NextBytes(bytes);

                // Generate parsed HTTP data block.
                var httpData = new TestHttpData("name", Encoding.UTF8, 0);

                httpData.SetContent(new MemoryStream(bytes));

                // Validate stored data.
                IByteBuffer buffer = httpData.GetByteBuffer();

                Assert.Equal(0, buffer.ReaderIndex);
                Assert.Equal(bytes.Length, buffer.WriterIndex);

                var data = new byte[bytes.Length];
                buffer.GetBytes(buffer.ReaderIndex, data);

                Assert.True(data.AsSpan().SequenceEqual(bytes));
            }
        }
예제 #23
0
 public bool IsAndroidQQProtocol(IByteBuffer buffer)
 {
     if (buffer.ReadableBytes < 9)
     {
         return(false);
     }
     byte[] tag = new byte[5];
     buffer.GetBytes(buffer.ReaderIndex + 4, tag, 0, 5);
     return(((IStructuralEquatable)tag).Equals(ANDROIDQQ_PROTOCOL_MARK1, StructuralEqualityComparer) ||
            ((IStructuralEquatable)tag).Equals(ANDROIDQQ_PROTOCOL_MARK2, StructuralEqualityComparer) ||
            ((IStructuralEquatable)tag).Equals(ANDROIDQQ_PROTOCOL_MARK3, StructuralEqualityComparer) ||
            ((IStructuralEquatable)tag).Equals(ANDROIDQQ_PROTOCOL_MARK4, StructuralEqualityComparer) ||
            ((IStructuralEquatable)tag).Equals(ANDROIDQQ_PROTOCOL_MARK5, StructuralEqualityComparer) ||
            ((IStructuralEquatable)tag).Equals(ANDROIDQQ_PROTOCOL_MARK6, StructuralEqualityComparer));
 }
        private void checkCRC(IByteBuffer @in, int startIndex)
        {
            int endIndex    = @in.ReaderIndex;
            int expectedCrc = @in.ReadInt();

            byte[] frame = new byte[endIndex - startIndex];
            @in.GetBytes(startIndex, frame, 0, endIndex - startIndex);
            int actualCrc = CrcUtil.crc32(frame);

            if (expectedCrc != actualCrc)
            {
                string err = "CRC check failed!";
                logger.LogError(err);
                throw new Exception(err);
            }
        }
예제 #25
0
        /// <summary>
        ///     Creates a new big-endian buffer whose content is a copy of the specified <see cref="Array" />.
        ///     The new buffer's <see cref="IByteBuffer.ReaderIndex" /> and <see cref="IByteBuffer.WriterIndex" />
        ///     are <c>0</c> and <see cref="IByteBuffer.Capacity" /> respectively.
        /// </summary>
        /// <param name="buffer">A buffer we're going to copy.</param>
        /// <returns>The new buffer that copies the contents of <see cref="buffer" />.</returns>
        public static IByteBuffer CopiedBuffer(IByteBuffer buffer)
        {
            Contract.Requires(buffer != null);
            int length = buffer.ReadableBytes;

            if (length == 0)
            {
                return(Empty);
            }
            var copy = new byte[length];

            // Duplicate the buffer so we do not adjust our position during our get operation
            IByteBuffer duplicate = buffer.Duplicate();

            duplicate.GetBytes(0, copy);
            return(WrappedBuffer(copy).WithOrder(duplicate.Order));
        }
예제 #26
0
 public sealed override IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length)
 {
     if (src is null)
     {
         ThrowHelper.ThrowArgumentNullException(ExceptionArgument.src);
     }
     CheckSrcIndex(index, length, srcIndex, src.Capacity);
     if (src.HasArray)
     {
         _ = SetBytes(index, src.Array, src.ArrayOffset + srcIndex, length);
     }
     else
     {
         _ = src.GetBytes(srcIndex, Memory, Idx(index), length);
     }
     return(this);
 }
예제 #27
0
        /// <summary>
        ///     Creates a new big-endian buffer whose content  is a merged copy of the specified <see cref="Array" />.
        ///     The new buffer's <see cref="IByteBuffer.ReaderIndex" /> and <see cref="IByteBuffer.WriterIndex" />
        ///     are <c>0</c> and <see cref="IByteBuffer.Capacity" /> respectively.
        /// </summary>
        /// <param name="buffers">Buffers we're going to copy.</param>
        /// <returns>The new buffer that copies the contents of buffers.</returns>
        public static IByteBuffer CopiedBuffer(params IByteBuffer[] buffers)
        {
            switch (buffers.Length)
            {
            case 0:
                return(Empty);

            case 1:
                return(CopiedBuffer(buffers[0]));
            }

            // Merge the specified buffers into one buffer.
            int length = 0;

            foreach (IByteBuffer b in buffers)
            {
                int bLen = b.ReadableBytes;
                if (bLen <= 0)
                {
                    continue;
                }
                if (int.MaxValue - length < bLen)
                {
                    throw new ArgumentException("The total length of the specified buffers is too big.");
                }

                length += bLen;
            }

            if (length == 0)
            {
                return(Empty);
            }

            var mergedArray = new byte[length];

            for (int i = 0, j = 0; i < buffers.Length; i++)
            {
                IByteBuffer b    = buffers[i];
                int         bLen = b.ReadableBytes;
                b.GetBytes(b.ReaderIndex, mergedArray, j, bLen);
                j += bLen;
            }

            return(WrappedBuffer(mergedArray));
        }
예제 #28
0
        /// <summary>
        /// 获取IByteBuffer中的byte[]
        /// </summary>
        /// <param name="byteBuffer">IByteBuffer</param>
        /// <returns></returns>
        public static byte[] ToArray(this IByteBuffer byteBuffer)
        {
            int readableBytes = byteBuffer.ReadableBytes;
            if (readableBytes == 0)
            {
                return ArrayExtensions.ZeroBytes;
            }

            if (byteBuffer.HasArray)
            {
                return byteBuffer.Array.Slice(byteBuffer.ArrayOffset + byteBuffer.ReaderIndex, readableBytes);
            }

            var bytes = new byte[readableBytes];
            byteBuffer.GetBytes(byteBuffer.ReaderIndex, bytes);
            return bytes;
        }
예제 #29
0
파일: Unpooled.cs 프로젝트: ywscr/SpanNetty
        /// <summary>
        ///     Creates a new big-endian buffer whose content  is a merged copy of the specified <see cref="Array" />.
        ///     The new buffer's <see cref="IByteBuffer.ReaderIndex" /> and <see cref="IByteBuffer.WriterIndex" />
        ///     are <c>0</c> and <see cref="IByteBuffer.Capacity" /> respectively.
        /// </summary>
        /// <param name="buffers">Buffers we're going to copy.</param>
        /// <returns>The new buffer that copies the contents of buffers.</returns>
        public static IByteBuffer CopiedBuffer(params IByteBuffer[] buffers)
        {
            switch (buffers.Length)
            {
            case 0:
                return(Empty);

            case 1:
                return(CopiedBuffer(buffers[0]));
            }

            // Merge the specified buffers into one buffer.
            int length = 0;

            foreach (IByteBuffer b in buffers)
            {
                int bLen = b.ReadableBytes;
                if ((uint)(bLen - 1) > SharedConstants.TooBigOrNegative) // bLen <= 0
                {
                    continue;
                }
                if (int.MaxValue - length < bLen)
                {
                    ThrowHelper.ThrowArgumentException_CopyBuffer();
                }

                length += bLen;
            }

            if (0u >= (uint)length)
            {
                return(Empty);
            }

            var mergedArray = new byte[length];

            for (int i = 0, j = 0; i < buffers.Length; i++)
            {
                IByteBuffer b    = buffers[i];
                int         bLen = b.ReadableBytes;
                _  = b.GetBytes(b.ReaderIndex, mergedArray, j, bLen);
                j += bLen;
            }

            return(WrappedBuffer(mergedArray));
        }
예제 #30
0
        public override void AddContent(IByteBuffer buffer, bool last)
        {
            if (buffer is object)
            {
                try
                {
                    int localsize = buffer.ReadableBytes;
                    CheckSize(Size + localsize, MaxSize);
                    if (DefinedSize > 0 && DefinedSize < Size + localsize)
                    {
                        ThrowHelper.ThrowIOException_OutOfSize(Size, DefinedSize);
                    }
                    if (_fileStream is null)
                    {
                        _fileStream = TempFile();
                    }
                    _ = buffer.GetBytes(buffer.ReaderIndex, _fileStream, buffer.ReadableBytes);
                    _ = buffer.SetReaderIndex(buffer.ReaderIndex + localsize);
                    _fileStream.Flush();

                    Size += buffer.ReadableBytes;
                }
                finally
                {
                    // Release the buffer as it was retained before and we not need a reference to it at all
                    // See https://github.com/netty/netty/issues/1516
                    _ = buffer.Release();
                }
            }
            if (last)
            {
                if (_fileStream is null)
                {
                    _fileStream = TempFile();
                }
                SetCompleted();
            }
            else
            {
                if (buffer is null)
                {
                    ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer);
                }
            }
        }
예제 #31
0
 private byte[] ToByteArray(IByteBuffer buffer)
 {
     var bytes = new byte[buffer.Length];
     buffer.GetBytes(0, bytes, 0, buffer.Length);
     return bytes;
 }
예제 #32
0
 public override IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length)
 {
     this.CheckSrcIndex(index, length, srcIndex, src.Capacity);
     if (src.HasArray)
     {
         this.SetBytes(index, src.Array, src.ArrayOffset + srcIndex, length);
     }
     else
     {
         src.GetBytes(srcIndex, this.array, index, length);
     }
     return this;
 }