BlockCopy() 개인적인 메소드

private BlockCopy ( Array src, int srcOffset, Array dst, int dstOffset, int count ) : void
src Array
srcOffset int
dst Array
dstOffset int
count int
리턴 void
예제 #1
0
        public void UpdateBufferForBlock(int program, string nameBlock)
        {
            int index_SLI = GL.GetUniformBlockIndex(program, nameBlock);

            if (index_SLI != -1)
            {
                GL.GetActiveUniformBlock(program, index_SLI, ActiveUniformBlockParameter.UniformBlockDataSize, out blockSizeLightInfo);
                byte[]   blockBuffer = new byte[blockSizeLightInfo];
                string[] names       = { nameBlock + ".position_lgh", nameBlock + ".intensity_lgh", nameBlock + ".direction_lgh", nameBlock + ".exponent_lgh", nameBlock + ".cutoff_lgh" };
                int[]    indices     = new int[5];
                GL.GetUniformIndices(program, 5, names, indices);
                int[] offset = new int[5];
                GL.GetActiveUniforms(program, 5, indices, ActiveUniformParameter.UniformOffset, offset);

                float[] position_lgh  = { Position.X, Position.Y, Position.Z, 0.0f };
                float[] intensity_lgh = { DiffusionIntensity.X, DiffusionIntensity.Y, DiffusionIntensity.Z }; //интенсивность света
                float[] direction_lgh = { LightVecNormalized.X, LightVecNormalized.Y, LightVecNormalized.Z }; //направление света
                float[] exponent      = { 1.0f };                                                             // Экспанента углового ослабления света
                float[] cutoff        = { 30f };                                                              //угол отсечения

                Buffer.BlockCopy(position_lgh, 0, blockBuffer, offset[0], position_lgh.Length * sizeof(float));
                Buffer.BlockCopy(intensity_lgh, 0, blockBuffer, offset[1], intensity_lgh.Length * sizeof(float));
                Buffer.BlockCopy(direction_lgh, 0, blockBuffer, offset[2], direction_lgh.Length * sizeof(float));
                Buffer.BlockCopy(exponent, 0, blockBuffer, offset[3], exponent.Length * sizeof(float));
                Buffer.BlockCopy(cutoff, 0, blockBuffer, offset[4], cutoff.Length * sizeof(float));

                GL.BindBuffer(BufferTarget.UniformBuffer, uboLightInfo);
                GL.BufferSubData(BufferTarget.UniformBuffer, (IntPtr)0, blockSizeLightInfo, blockBuffer);
            }
        }
예제 #2
0
        /// <summary>
        /// Reads a sequence of bytes from the stream and advances the position
        /// within the stream by the number of bytes read.
        /// </summary>
        /// <remarks>
        /// Reads a sequence of bytes from the stream and advances the position
        /// within the stream by the number of bytes read.
        /// </remarks>
        /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many
        /// bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
        /// <param name="buffer">The buffer.</param>
        /// <param name="offset">The buffer offset.</param>
        /// <param name="count">The number of bytes to read.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="buffer"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
        /// <para>-or-</para>
        /// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
        /// at the specified <paramref name="offset"/>.</para>
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">
        /// The stream has been disposed.
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public int Read(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
#if false // Note: this code will never get called as we always use ReadResponse() instead.
            CheckDisposed();

            ValidateArguments(buffer, offset, count);

            int length = inputEnd - inputIndex;
            int n;

            if (length < count && length <= ReadAheadSize)
            {
                ReadAhead(cancellationToken);
            }

            length = inputEnd - inputIndex;
            n      = Math.Min(count, length);

            Buffer.BlockCopy(input, inputIndex, buffer, offset, n);
            inputIndex += n;

            return(n);
#else
            throw new NotImplementedException();
#endif
        }
        public void WriteBytes(byte[] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            int additionalCapacity = sizeof(int) + value.Length;

            if (this.position + additionalCapacity >= this.buffer.Length)
            {
                int curLength = this.buffer.Length;
                int newLength = curLength * 2;
                while (newLength <= curLength + additionalCapacity)
                {
                    newLength *= 2;
                }

                byte[] newbuffer = new byte[newLength];
                Buff.BlockCopy(this.buffer, 0, newbuffer, 0, this.Length);
                this.buffer = newbuffer;
            }

            Buff.BlockCopy(BitConverter.GetBytes(value.Length), 0, this.buffer, this.position, sizeof(int));
            this.position += sizeof(int);
            Buff.BlockCopy(value, 0, this.buffer, this.position, value.Length);
            this.position += value.Length;
        }
예제 #4
0
        public void InsertBytes(int offset, byte[] value, int valueOffset, int length)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (valueOffset < 0 || valueOffset >= value.Length)
            {
                throw new ArgumentOutOfRangeException("offset", "offset can not negative or >=data.Length");
            }
            if (length < 0 || valueOffset + length > value.Length)
            {
                throw new ArgumentOutOfRangeException("length", "length can not be negative or combined with offset longer than the array");
            }

            EnsureAdditionalCapacity(length);

            if (offset != this.position)
            {
                Buff.BlockCopy(this.buffer, offset, this.buffer, offset + length, this.position - offset);
            }

            Buff.BlockCopy(value, valueOffset, this.buffer, offset, length);
            this.position += length;
        }
예제 #5
0
        /// <summary>
        /// Reads a sequence of bytes from the stream and advances the position
        /// within the stream by the number of bytes read.
        /// </summary>
        /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many
        /// bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
        /// <param name="buffer">The buffer.</param>
        /// <param name="offset">The buffer offset.</param>
        /// <param name="count">The number of bytes to read.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="buffer"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
        /// <para>-or-</para>
        /// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
        /// at the specified <paramref name="offset"/>.</para>
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">
        /// The stream has been disposed.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// The stream is in token mode (see <see cref="ImapStreamMode.Token"/>).
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public int Read(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            CheckDisposed();

            ValidateArguments(buffer, offset, count);

            if (Mode != ImapStreamMode.Literal)
            {
                return(0);
            }

            count = Math.Min(count, literalDataLeft);

            int length = inputEnd - inputIndex;
            int n;

            if (length < count && length <= ReadAheadSize)
            {
                ReadAhead(BlockSize, cancellationToken);
            }

            length = inputEnd - inputIndex;
            n      = Math.Min(count, length);

            Buffer.BlockCopy(input, inputIndex, buffer, offset, n);
            literalDataLeft -= n;
            inputIndex      += n;

            if (literalDataLeft == 0)
            {
                Mode = ImapStreamMode.Token;
            }

            return(n);
        }
        public byte[] ToArray()
        {
            byte[] value = new byte[Length];
            Buff.BlockCopy(this.buffer, 0, value, 0, Length);

            return(value);
        }
        public override void MakeBinary(string path)
        {
            ReadObj(path, out List <Vector3> outPositions, out List <Vector2> outTexCoords, out List <Vector3> outNormals, out List <VertexReference> outVertices);

            int vertexCount = outPositions.Count;

            byte[] closure = _closures[Name];
            Buffer = new byte[10 + vertexCount * Vertex.ByteCount + vertexCount * sizeof(uint) + closure.Length];

            Buf.BlockCopy(BitConverter.GetBytes((uint)vertexCount), 0, Buffer, 0, sizeof(uint));
            Buf.BlockCopy(BitConverter.GetBytes((uint)vertexCount), 0, Buffer, 4, sizeof(uint));
            Buf.BlockCopy(BitConverter.GetBytes((ushort)288), 0, Buffer, 8, sizeof(ushort));

            for (int i = 0; i < vertexCount; i++)
            {
                Vertex vertex      = new(outPositions[(int)outVertices[i].PositionReference - 1], outTexCoords[(int)outVertices[i].TexCoordReference - 1], outNormals[(int)outVertices[i].NormalReference - 1]);
                byte[] vertexBytes = vertex.ToByteArray();
                Buf.BlockCopy(vertexBytes, 0, Buffer, 10 + i * Vertex.ByteCount, Vertex.ByteCount);
            }

            for (int i = 0; i < vertexCount; i++)
            {
                Buf.BlockCopy(BitConverter.GetBytes(outVertices[i].PositionReference - 1), 0, Buffer, 10 + vertexCount * Vertex.ByteCount + i * sizeof(uint), sizeof(uint));
            }
            Buf.BlockCopy(closure, 0, Buffer, 10 + vertexCount * (Vertex.ByteCount + sizeof(uint)), closure.Length);

            Size = (uint)Buffer.Length;
        }
예제 #8
0
 /// <summary>
 /// Replace current PacketStream with some bytes from provided byte array.
 /// </summary>
 /// <param name="bytes"></param>
 /// <param name="offset"></param>
 /// <param name="count"></param>
 /// <returns></returns>
 public PacketStream Replace(Byte[] bytes, Int32 offset, Int32 count)
 {
     Reserve(count);
     SBuffer.BlockCopy(bytes, offset, Buffer, 0, count);
     Count = count;
     return(this);
 }
예제 #9
0
파일: ImapStream.cs 프로젝트: zamis/MailKit
        async Task <int> ReadAsync(byte[] buffer, int offset, int count, bool doAsync, CancellationToken cancellationToken)
        {
            CheckDisposed();

            ValidateArguments(buffer, offset, count);

            if (Mode != ImapStreamMode.Literal)
            {
                return(0);
            }

            count = Math.Min(count, literalDataLeft);

            int length = inputEnd - inputIndex;
            int n;

            if (length < count && length <= ReadAheadSize)
            {
                await ReadAheadAsync(BlockSize, doAsync, cancellationToken).ConfigureAwait(false);
            }

            length = inputEnd - inputIndex;
            n      = Math.Min(count, length);

            Buffer.BlockCopy(input, inputIndex, buffer, offset, n);
            literalDataLeft -= n;
            inputIndex      += n;

            if (literalDataLeft == 0)
            {
                Mode = ImapStreamMode.Token;
            }

            return(n);
        }
예제 #10
0
        public void WriteString(Encoding encoding, string value)
        {
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            if (value == null)
            {
                Write7BitEncodedInt(-1);
                return;
            }

            byte[] data = encoding.GetBytes(value);
            int    additionalCapacity = sizeof(int) + data.Length;

            if (this.position + additionalCapacity >= this.buffer.Length)
            {
                int curLength = this.buffer.Length;
                int newLength = curLength * 2;
                while (newLength <= curLength + additionalCapacity)
                {
                    newLength *= 2;
                }

                byte[] newbuffer = new byte[newLength];
                Buff.BlockCopy(this.buffer, 0, newbuffer, 0, this.Length);
                this.buffer = newbuffer;
            }

            Write7BitEncodedInt(data.Length);
            Buff.BlockCopy(data, 0, this.buffer, this.position, data.Length);
            this.position += data.Length;
        }
예제 #11
0
        public void WriteDouble(double value)
        {
            if (this.position + sizeof(double) >= this.buffer.Length)
            {
                int curLength = this.buffer.Length;
                int newLength = curLength * 2;
                while (newLength <= curLength + sizeof(double))
                {
                    newLength *= 2;
                }

                byte[] newbuffer = new byte[newLength];
                Buff.BlockCopy(this.buffer, 0, newbuffer, 0, this.Length);
                this.buffer = newbuffer;
            }

                        #if SAFE
            Buff.BlockCopy(BitConverter.GetBytes(value), 0, this.buffer, this.position, sizeof(double));
                        #else
            fixed(byte *ub = this.buffer)
            * ((double *)(ub + this.position)) = value;
                        #endif

            this.position += sizeof(double);
        }
예제 #12
0
파일: draw.cs 프로젝트: MSylvia/SharpQuake
        // Draw_CachePic
        public static glpic_t CachePic(string path)
        {
            for (int i = 0; i < _MenuNumCachePics; i++)
            {
                cachepic_t p = _MenuCachePics[i];
                if (p.name == path) // !strcmp(path, pic->name))
                {
                    return(p.pic);
                }
            }

            if (_MenuNumCachePics == MAX_CACHED_PICS)
            {
                sys.Error("menu_numcachepics == MAX_CACHED_PICS");
            }

            cachepic_t pic = _MenuCachePics[_MenuNumCachePics];

            _MenuNumCachePics++;
            pic.name = path;

            //
            // load the pic from disk
            //
            byte[] data = common.LoadFile(path);
            if (data == null)
            {
                sys.Error("Draw_CachePic: failed to load {0}", path);
            }
            dqpicheader_t header = sys.BytesToStructure <dqpicheader_t>(data, 0);

            wad.SwapPic(header);

            int headerSize = Marshal.SizeOf(typeof(dqpicheader_t));

            // HACK HACK HACK --- we need to keep the bytes for
            // the translatable player picture just for the menu
            // configuration dialog
            if (path == "gfx/menuplyr.lmp")
            {
                Buffer.BlockCopy(data, headerSize, _MenuPlayerPixels, 0, header.width * header.height);
                //memcpy (menuplyr_pixels, dat->data, dat->width*dat->height);
            }

            glpic_t gl = new glpic_t();

            gl.width  = header.width;
            gl.height = header.height;

            //gl = (glpic_t *)pic->pic.data;
            gl.texnum = LoadTexture(gl, new ByteArraySegment(data, headerSize));
            gl.sl     = 0;
            gl.sh     = 1;
            gl.tl     = 0;
            gl.th     = 1;
            pic.pic   = gl;

            return(gl);
        }
예제 #13
0
        //
        // This validation logic is a manual port of StrongNameIsValidPublicKey() in the desktop CLR (see clr\src\StrongName\api\StrongNameInternal.cpp)
        //
        private static bool IsValidPublicKey(byte[] publicKey)
        {
            uint publicKeyLength = (uint)(publicKey.Length);

            // The buffer must be at least as large as the public key structure (for compat with desktop, we actually compare with the size of the header + 4).
            if (publicKeyLength < SizeOfPublicKeyBlob + 4)
            {
                return(false);
            }


            // Poor man's reinterpret_cast into the PublicKeyBlob structure.
            uint[] publicKeyBlob = new uint[3];
            Buffer.BlockCopy(publicKey, 0, publicKeyBlob, 0, (int)SizeOfPublicKeyBlob);
            uint sigAlgID    = publicKeyBlob[0];
            uint hashAlgID   = publicKeyBlob[1];
            uint cbPublicKey = publicKeyBlob[2];

            // The buffer must be the same size as the structure header plus the trailing key data
            if (cbPublicKey != publicKeyLength - SizeOfPublicKeyBlob)
            {
                return(false);
            }

            // The buffer itself looks reasonable, but the public key structure needs to be validated as well

            // The ECMA key doesn't look like a valid key so it will fail the below checks. If we were passed that
            // key, then we can skip them.
            if (ByteArrayEquals(publicKey, s_ecmaKey))
            {
                return(true);
            }

            // If a hash algorithm is specified, it must be a sensible value
            bool fHashAlgorithmValid = GetAlgClass(hashAlgID) == ALG_CLASS_HASH && GetAlgSid(hashAlgID) == ALG_SID_SHA1;

            if (hashAlgID != 0 && !fHashAlgorithmValid)
            {
                return(false);
            }

            // If a signature algorithm is specified, it must be a sensible value
            bool fSignatureAlgorithmValid = GetAlgClass(sigAlgID) == ALG_CLASS_SIGNATURE;

            if (sigAlgID != 0 && !fSignatureAlgorithmValid)
            {
                return(false);
            }

            // The key blob must indicate that it is a PUBLICKEYBLOB
            if (publicKey[SizeOfPublicKeyBlob] != PUBLICKEYBLOB)
            {
                return(false);
            }

            //@todo: Desktop also tries to import the public key blob using the Crypto api as further validation - not clear if there's any non-banned API to do this.

            return(true);
        }
예제 #14
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
            var itemSize = Marshal.SizeOf <T>();
            var bytes    = formatter.ReadBytes(itemSize * rows);

            Data = new T[rows];
            Buffer.BlockCopy(bytes, 0, Data, 0, itemSize * rows);
        }
예제 #15
0
        public static byte[] ArrayConcat(byte[] a, byte[] b)
        {
            byte[] c = new byte[a.Length + b.Length];
            Buffer.BlockCopy(a, 0, c, 0, a.Length);
            Buffer.BlockCopy(b, 0, c, a.Length, b.Length);

            return(c);
        }
예제 #16
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
            var itemSize = Marshal.SizeOf <uint>();
            var bytes    = formatter.ReadBytes(itemSize * rows);
            var xdata    = new uint[rows];

            Buffer.BlockCopy(bytes, 0, xdata, 0, itemSize * rows);
            Data = xdata.Select(x => UnixTimeBase.AddSeconds(x)).ToArray();
        }
예제 #17
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
            var itemSize = Marshal.SizeOf(typeof(Guid));
            var bytes    = formatter.ReadBytes(itemSize * rows);
            var xdata    = new Guid[rows];

            Buffer.BlockCopy(bytes, 0, xdata, 0, itemSize * rows);
            Data = xdata.ToArray();
        }
예제 #18
0
        public override void Write(ProtocolFormatter formatter, int rows)
        {
            Debug.Assert(Rows == rows, "Row count mismatch!");
            var itemSize = Marshal.SizeOf <T>();
            var bytes    = new byte[itemSize * rows];

            Buffer.BlockCopy(Data, 0, bytes, 0, itemSize * rows);
            formatter.WriteBytes(bytes);
        }
        private static void GetByteVertexAndIndexBuffer(out byte[] byteVertexBuffer, out int[] indexBuffer)
        {
            float[] floatVertexBuffer;
            GetFloatVertexAndIndexBuffer(out floatVertexBuffer, out indexBuffer);

            // Copy float array into byte array
            byteVertexBuffer = new byte[floatVertexBuffer.Length * 4];
            Buffer.BlockCopy(floatVertexBuffer, 0, byteVertexBuffer, 0, byteVertexBuffer.Length);
        }
예제 #20
0
        public static long GetRSAFingerprint(string key)
        {
            using (var text = new StringReader(key))
            {
                var reader    = new PemReader(text);
                var parameter = reader.ReadObject() as RsaKeyParameters;
                if (parameter != null)
                {
                    var modulus  = parameter.Modulus.ToByteArray();
                    var exponent = parameter.Exponent.ToByteArray();

                    if (modulus.Length > 256)
                    {
                        var corrected = new byte[256];
                        Buffer.BlockCopy(modulus, modulus.Length - 256, corrected, 0, 256);

                        modulus = corrected;
                    }
                    else if (modulus.Length < 256)
                    {
                        var corrected = new byte[256];
                        Buffer.BlockCopy(modulus, 0, corrected, 256 - modulus.Length, modulus.Length);

                        for (int a = 0; a < 256 - modulus.Length; a++)
                        {
                            modulus[a] = 0;
                        }

                        modulus = corrected;
                    }

                    using (var stream = new MemoryStream())
                    {
                        var modulusString  = TLString.FromBigEndianData(modulus);
                        var exponentString = TLString.FromBigEndianData(exponent);

                        modulusString.ToStream(stream);
                        exponentString.ToStream(stream);

                        var hash = ComputeSHA1(stream.ToArray());

                        var fingerprint = (((ulong)hash[19]) << 56) |
                                          (((ulong)hash[18]) << 48) |
                                          (((ulong)hash[17]) << 40) |
                                          (((ulong)hash[16]) << 32) |
                                          (((ulong)hash[15]) << 24) |
                                          (((ulong)hash[14]) << 16) |
                                          (((ulong)hash[13]) << 8) |
                                          ((ulong)hash[12]);

                        return((long)fingerprint);
                    }
                }
            }

            return(-1);
        }
예제 #21
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
            var itemSize = sizeof(ushort);
            var bytes    = formatter.ReadBytes(itemSize * rows);
            var xdata    = new ushort[rows];

            Buffer.BlockCopy(bytes, 0, xdata, 0, itemSize * rows);
            Data = xdata.Select(x => UnixTimeBase.AddDays(x)).ToArray();
        }
예제 #22
0
 public PacketStream Insert(Int32 offset, Byte[] copyArray, Int32 copyArrayOffset, Int32 count)
 {
     Reserve(Count + count);
     // передвигаем данные с позиции offset до позиции offset + count
     SBuffer.BlockCopy(Buffer, offset, Buffer, offset + count, Count - offset);
     // копируем новый массив данных в позицию offset
     SBuffer.BlockCopy(copyArray, copyArrayOffset, Buffer, offset, count);
     Count += count;
     return(this);
 }
예제 #23
0
        public byte[] ReadBytes()
        {
            int len = ReadInt32();

            byte[] b = new byte[len];
            Buff.BlockCopy(this.buffer, this.Position, b, 0, len);
            this.Position += len;

            return(b);
        }
예제 #24
0
        async Task <int> ReadAheadAsync(bool doAsync, CancellationToken cancellationToken)
        {
            int left = inputEnd - inputIndex;
            int index, nread;

            if (left > 0)
            {
                if (inputIndex > 0)
                {
                    // move all of the remaining input to the beginning of the buffer
                    Buffer.BlockCopy(input, inputIndex, input, 0, left);
                    inputEnd   = left;
                    inputIndex = 0;
                }
            }
            else
            {
                inputIndex = 0;
                inputEnd   = 0;
            }

            left  = input.Length - inputEnd;
            index = inputEnd;

            try {
                var network = Stream as NetworkStream;

                cancellationToken.ThrowIfCancellationRequested();

                if (doAsync)
                {
                    nread = await Stream.ReadAsync(input, index, left, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    network?.Poll(SelectMode.SelectRead, cancellationToken);
                    nread = Stream.Read(input, index, left);
                }

                if (nread > 0)
                {
                    logger.LogServer(input, index, nread);
                    inputEnd += nread;
                }
                else
                {
                    throw new SmtpProtocolException("The SMTP server has unexpectedly disconnected.");
                }
            } catch {
                IsConnected = false;
                throw;
            }

            return(inputEnd - inputIndex);
        }
예제 #25
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
#if FRAMEWORK20 || FRAMEWORK40 || FRAMEWORK45
            var itemSize = Marshal.SizeOf(typeof(T));
#else
            var itemSize = Marshal.SizeOf <T>();
#endif
            var bytes = formatter.ReadBytes(itemSize * rows);
            Data = new T[rows];
            Buffer.BlockCopy(bytes, 0, Data, 0, itemSize * rows);
        }
예제 #26
0
        public Byte[] ReadBytes(Int32 count)
        {
            if (Pos + count > Count)
            {
                throw new MarshalException();
            }

            Byte[] result = new Byte[count];
            SBuffer.BlockCopy(Buffer, Pos, result, 0, count);
            Pos += count;
            return(result);
        }
예제 #27
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
#if FRAMEWORK20 || FRAMEWORK40 || FRAMEWORK45
            var itemSize = sizeof(ushort);
#else
            var itemSize = Marshal.SizeOf <ushort>();
#endif
            var bytes = formatter.ReadBytes(itemSize * rows);
            var xdata = new ushort[rows];
            Buffer.BlockCopy(bytes, 0, xdata, 0, itemSize * rows);
            Data = xdata.Select(x => UnixTimeBase.AddDays(x)).ToArray();
        }
예제 #28
0
        public override void Write(ProtocolFormatter formatter, int rows)
        {
            Debug.Assert(Rows == rows, "Row count mismatch!");
#if FRAMEWORK20 || FRAMEWORK40 || FRAMEWORK45
            var itemSize = Marshal.SizeOf(typeof(T));
#else
            var itemSize = Marshal.SizeOf <T>();
#endif
            var bytes = new byte[itemSize * rows];
            Buffer.BlockCopy(Data, 0, bytes, 0, itemSize * rows);
            formatter.WriteBytes(bytes);
        }
예제 #29
0
        /// <summary>
        /// Writes a sequence of bytes to the stream and advances the current
        /// position within this stream by the number of bytes written.
        /// </summary>
        /// <remarks>
        /// Writes a sequence of bytes to the stream and advances the current
        /// position within this stream by the number of bytes written.
        /// </remarks>
        /// <param name='buffer'>The buffer to write.</param>
        /// <param name='offset'>The offset of the first byte to write.</param>
        /// <param name='count'>The number of bytes to write.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="buffer"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
        /// <para>-or-</para>
        /// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
        /// at the specified <paramref name="offset"/>.</para>
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">
        /// The stream has been disposed.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// The stream does not support writing.
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public void Write(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            CheckDisposed();

            ValidateArguments(buffer, offset, count);

            try {
                int index = offset;
                int left  = count;

                while (left > 0)
                {
                    int n = Math.Min(BlockSize - outputIndex, left);

                    if (outputIndex > 0 || n < BlockSize)
                    {
                        // append the data to the output buffer
                        Buffer.BlockCopy(buffer, index, output, outputIndex, n);
                        outputIndex += n;
                        index       += n;
                        left        -= n;
                    }

                    if (outputIndex == BlockSize)
                    {
                        // flush the output buffer
                        Poll(SelectMode.SelectWrite, cancellationToken);
                        Stream.Write(output, 0, BlockSize);
                        logger.LogClient(output, 0, BlockSize);
                        outputIndex = 0;
                    }

                    if (outputIndex == 0)
                    {
                        // write blocks of data to the stream without buffering
                        while (left >= BlockSize)
                        {
                            Poll(SelectMode.SelectWrite, cancellationToken);
                            Stream.Write(buffer, index, BlockSize);
                            logger.LogClient(buffer, index, BlockSize);
                            index += BlockSize;
                            left  -= BlockSize;
                        }
                    }
                }
            } catch {
                IsConnected = false;
                throw;
            }

            IsEndOfData = false;
        }
예제 #30
0
 /// <summary>
 /// Initializes buffer for this stream with provided minimum size.
 /// </summary>
 /// <param name="count">Minimum buffer size.</param>
 public void Reserve(Int32 count)
 {
     if (Buffer == null)
     {
         Buffer = Roundup(count);
     }
     else if (count > Buffer.Length)
     {
         Byte[] newBuffer = Roundup(count);
         SBuffer.BlockCopy(Buffer, 0, newBuffer, 0, Count);
         Buffer = newBuffer;
     }
 }