Ejemplo n.º 1
0
        internal HeaderTable SetMaxLength(int maxLength, IBufferPool pool)
        {
            if (checked ((int)maxLength) == MaxLength)
            {
                return(this);
            }

            if (maxLength == 0 || Count == 0)
            {
                _buffer?.Dispose();
                return(new HeaderTable(maxLength ^ DefaultMaxLength, 0, null));
            }

            int bytesToKeep = 0, headersToKeep = 0, totalBytes = 0;
            var span = _buffer.Data.Span;

            for (int i = 0; i < Count; i++)
            {
                long lengths = span.Slice(bytesToKeep).Read <long>();
                int  itemLen = ItemLength(lengths);
                totalBytes += itemLen;
                if (totalBytes > MaxLength)
                {
                    break;
                }
                bytesToKeep += itemLen;
                headersToKeep++;
            }

            var newBuffer = pool.Lease(maxLength);

            _buffer.Data.Span.Slice(0, bytesToKeep).CopyTo(newBuffer.Data.Span.Slice(bytesToKeep));
            _buffer.Dispose();
            return(new HeaderTable(maxLength ^ DefaultMaxLength, headersToKeep, newBuffer));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Completes an asynchronous send
        /// </summary>
        /// <param name="ar">AsyncResul obtained from BeginSend</param>
        private void CompleteSend(IAsyncResult ar)
        {
            // Complete asynchronous send
            IBuffer sendBuffer = (IBuffer)ar.AsyncState;

            try
            {
                if (!socket.Connected)
                {
                    return;
                }
                lock (syncSocket)
                {
                    socket.EndSend(ar);
                }
                sendBuffer.Dispose();
                sendBuffer = null;
            }
            catch (Exception ex)
            {
                Diags.LogSocketException(ex);
                if (sendBuffer != null)
                {
                    sendBuffer.Dispose();
                    sendBuffer = null;
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Begins an asynchronous receive
        /// </summary>
        /// <param name="Buffer">Buffer to store received data</param>
        /// <param name="ReadCallBack">Method to call on receiving data</param>
        /// <param name="StateObject">State object to be passed to ReadCallBack</param>
        /// <returns>AsyncResult for the asynchronous operation</returns>
        public IAsyncResult BeginReceive(int BufferLength, AsyncCallback ReadCallBack, object StateObject)
        {
            try
            {
                if (recvBuffer == null || recvBuffer.IsDisposed)
                {
                    recvBuffer = bufferPool.GetBuffer(BufferLength);
                }
                else if (recvBuffer.Size < BufferLength)
                {
                    recvBuffer.Dispose();
                    recvBuffer = bufferPool.GetBuffer(BufferLength);
                }

                lock (syncSocket)
                {
                    return(socket.BeginReceive(recvBuffer.GetSegments(), SocketFlags.None, ReadCallBack, StateObject));
                }
            }
            catch (Exception ex)
            {
                Diags.LogSocketException(ex);
                return(null);
            }
        }
Ejemplo n.º 4
0
        private IBuffer GetGlBuffer(ref IBuffer glBuffer, BufferTarget target, int offset)
        {
            if (!dirty)
            {
                return(glBuffer);
            }
            var nonDynamic        = rawDataResource.Volatility != ResourceVolatility.Volatile;
            var resourcePtr       = rawDataResource.Map();
            var resourceOffsetPtr = resourcePtr + offset;
            var glBufferSize      = rawDataResource.Size - offset;

            if (glBuffer == null || glBuffer.SizeInBytes != glBufferSize)
            {
                glBuffer?.Dispose();
                var usage = nonDynamic
                    ? BufferUsageHint.StaticDraw
                    : BufferUsageHint.DynamicDraw;
                // todo: target for index buffer
                glBuffer = infra.GlContext.Create.Buffer(target, glBufferSize, usage, resourceOffsetPtr);
            }
            else if (nonDynamic)
            {
                glBuffer.SetData(resourceOffsetPtr);
            }
            else
            {
                var bufferPtr = glBuffer.Map(0, glBufferSize, MapAccess.Write | MapAccess.InvalidateBuffer);
                PtrHelper.CopyBulk((byte *)bufferPtr, (byte *)resourceOffsetPtr, glBufferSize);
                glBuffer.Unmap();
            }
            rawDataResource.Unmap(false);
            dirty = false;
            return(glBuffer);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Sends data via the socket asynchronously
        /// </summary>
        /// <param name="Message">Data to transmit</param>
        public void Send(ResponseData Message)
        {
            IBuffer sendBuffer = null;

            //TODO: ENHANCEMENT: Log consecutive bad request response types and use that information to disconnect socket after 3
            try
            {
                lock (syncSocket)
                {
                    if (sentMsgs.Count > 1)
                    {
                        sentMsgs.Dequeue();
                    }
                    sentMsgs.Enqueue(Message);

                    //Log error if .Data is null -- this will help raise a flag if the message is being resent after .ClearData was called
                    Diags.Assert(Message.Data != null, "ASSERTION FAILED: Message Data is null", new System.Diagnostics.StackTrace().ToString());

                    sendBuffer = bufferPool.GetBuffer(Message.Data.LongLength);
                    sendBuffer.CopyFrom(Message.Data);
                    socket.BeginSend(sendBuffer.GetSegments(), SocketFlags.None, CompleteSend, sendBuffer);

                    Message.ClearData(); //free some memory
                }
            }
            catch (Exception ex)
            {
                Diags.LogSocketException(ex);
                if (sendBuffer != null)
                {
                    sendBuffer.Dispose();
                    sendBuffer = null;
                }
            }
        }
Ejemplo n.º 6
0
 void IDisposable.Dispose()
 {
     textureVariable?.Dispose();
     bindings?.Dispose();
     pipelineState?.Dispose();
     constantBuffer?.Dispose();
 }
        public void TestWrite()
        {
            LosgapSystem.InvokeOnMaster(() => {
                // Define variables and constants
                IBuffer res = BufferFactory.NewBuffer <int>()
                              .WithUsage(ResourceUsage.Write)
                              .WithLength(100)
                              .Create();

                IBuffer copyDest = (res as Buffer <int>).Clone()
                                   .WithUsage(ResourceUsage.StagingRead)
                                   .WithPermittedBindings(GPUBindings.None)
                                   .Create();

                // Set up context


                // Execute
                Assert.IsTrue(res.CanWrite);
                res.Write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 10U);
                res.CopyTo(copyDest);

                // Assert outcome
                byte[] readData = copyDest.Read();
                for (int i = 10; i < 20; ++i)
                {
                    Assert.AreEqual(i - 9, readData[i]);
                }

                res.Dispose();
                copyDest.Dispose();
            });
        }
Ejemplo n.º 8
0
        internal static void Share()
        {
            IEnumerable <int> sequence             = Enumerable.Range(0, 5);
            IEnumerator <int> independentIterator1 = sequence.GetEnumerator();
            IEnumerator <int> independentIterator2 = sequence.GetEnumerator();

            independentIterator1.MoveNext(); independentIterator1.Current.WriteLine(); // 0| |
            independentIterator2.MoveNext(); independentIterator2.Current.WriteLine(); //  |0|
            independentIterator1.MoveNext(); independentIterator1.Current.WriteLine(); // 1| |
            IEnumerator <int> independentIterator3 = sequence.GetEnumerator();         //  | |

            independentIterator3.MoveNext(); independentIterator3.Current.WriteLine(); //  | |0
            independentIterator1.MoveNext(); independentIterator1.Current.WriteLine(); // 2| |
            independentIterator2.MoveNext(); independentIterator2.Current.WriteLine(); //  |1|
            // ...

            IBuffer <int>     share           = Enumerable.Range(0, 5).Share();
            IEnumerator <int> sharedIterator1 = share.GetEnumerator();
            IEnumerator <int> sharedIterator2 = share.GetEnumerator();

            sharedIterator1.MoveNext(); sharedIterator1.Current.WriteLine(); // 0| |
            sharedIterator2.MoveNext(); sharedIterator2.Current.WriteLine(); //  |1|
            sharedIterator1.MoveNext(); sharedIterator1.Current.WriteLine(); // 2| |
            IEnumerator <int> sharedIterator3 = share.GetEnumerator();       //  | |

            sharedIterator3.MoveNext(); sharedIterator3.Current.WriteLine(); //  | |3

            share.Dispose();
            sharedIterator1.MoveNext(); // ObjectDisposedException.
            sharedIterator2.MoveNext(); // ObjectDisposedException.
            sharedIterator3.MoveNext(); // ObjectDisposedException.
        }
        public void BufferIsReusedAfterDispose()
        {
            subject = new CachingBufferManager(options);

            IBuffer buffer1 = subject.GetBuffer(2049);

            buffer1.Dispose();
            IBuffer buffer2 = subject.GetBuffer(2050);

            Assert.AreSame(buffer1, buffer2);
        }
Ejemplo n.º 10
0
        void IDisposable.Dispose()
        {
            textureVariableRgb?.Dispose();
            bindingsRgb?.Dispose();
            psoRgb?.Dispose();

            textureVariableInvert?.Dispose();
            bindingsInvert?.Dispose();
            psoInvert?.Dispose();

            constantBuffer?.Dispose();
        }
Ejemplo n.º 11
0
 public void Push(IBuffer item)
 {
     if (_availableCount > _initialCount)
     {
         Interlocked.Decrement(ref _totalCount);
         item.Dispose();
     }
     else
     {
         PushBuffer(item);
     }
 }
Ejemplo n.º 12
0
        public void TryFreeSlabTest()
        {
            long       SlabSize        = BufferPool.MinimumSlabSize;
            int        InitialSlabs    = 1;
            int        SubsequentSlabs = 3;
            BufferPool target          = new BufferPool(SlabSize, InitialSlabs, SubsequentSlabs);

            Assert.AreEqual <long>(InitialSlabs, target.SlabCount);

            //GetBuffer of slab size
            IBuffer buff1 = target.GetBuffer(SlabSize);

            //confirm that slabcount is 1
            Assert.AreEqual <long>(InitialSlabs, target.SlabCount);

            //Try to free a slab and do a recount -- slabcount should remain 1
            target.TryFreeSlab();
            Assert.AreEqual <long>(InitialSlabs, target.SlabCount);

            //Get it again to force construction of 3 new slabs
            IBuffer buff2 = target.GetBuffer(SlabSize);

            Assert.AreEqual <long>(SubsequentSlabs + InitialSlabs, target.SlabCount);

            //Free a slab and do a recount
            target.TryFreeSlab();
            Assert.AreEqual <long>(SubsequentSlabs + InitialSlabs - 1, target.SlabCount);

            //Free a slab and do a recount -- slabcount should not budge since only one slab is free
            target.TryFreeSlab();
            Assert.AreEqual <long>(SubsequentSlabs + InitialSlabs - 1, target.SlabCount);

            //Try to free a slab and do a recount
            //Free 1st buffer
            buff1.Dispose();
            target.TryFreeSlab();
            Assert.AreEqual <long>(SubsequentSlabs + InitialSlabs - 2, target.SlabCount);

            //Try to free a slab and do a recount -- slabcount shouldn't go below two
            target.TryFreeSlab();
            Assert.AreEqual <long>(SubsequentSlabs + InitialSlabs - 2, target.SlabCount);

            //Free buffer, try to free a slab and do a recount -- slabcount should now be back to 1
            buff2.Dispose();
            target.TryFreeSlab();
            Assert.AreEqual <long>(SubsequentSlabs + InitialSlabs - 3, target.SlabCount);
        }
Ejemplo n.º 13
0
        public unsafe IVertexArray GetVao()
        {
            if (!isDirty && NumPoints == lastPointCount)
            {
                return(vao);
            }

            if (aspect.VisualBorderCurve == null || aspect.VisualBorderCurve.Count == 0)
            {
                return(null);
            }

            if (vao == null)
            {
                vao = glContext.Create.VertexArray();
            }

            var newPointCount = NumPoints;

            if (vertexBuffer == null || bufferPointCapacity < newPointCount)
            {
                vertexBuffer?.Dispose();
                while (bufferPointCapacity < newPointCount)
                {
                    bufferPointCapacity *= 2;
                }
                vertexBuffer = glContext.Create.Buffer(BufferTarget.Array, bufferPointCapacity * sizeof(Vector4), BufferUsageHint.DynamicDraw);
                vao.SetVertexAttributeF(0, vertexBuffer, VertexAttributeDimension.Four, VertexAttribPointerType.Float, false, sizeof(Vector4), 0);
            }

            var rawData = aspect.BorderComplete
                ? aspect.VisualBorderCurve.Concat(aspect.VisualBorderCurve.First().EnumSelf()).Select(xy => new Vector4(xy, 0, 1)).ToArray()
                : aspect.VisualBorderCurve.Select(xy => new Vector4(xy, 0, 1)).ToArray();

            var sizeInBytes = rawData.Length * sizeof(Vector4);
            var dst         = vertexBuffer.Map(0, vertexBuffer.SizeInBytes, MapAccess.Write | MapAccess.InvalidateBuffer);

            fixed(Vector4 *src = rawData)
            PtrHelper.CopyBulk((byte *)dst, (byte *)src, sizeInBytes);

            vertexBuffer.Unmap();

            lastPointCount = newPointCount;
            isDirty        = false;
            return(vao);
        }
Ejemplo n.º 14
0
            private async Task <ReadFileResult> ReadFile(int length)
            {
                IBuffer          content   = bufferAllocator.Allocate(length);
                Stream           dest      = content.GetStream();
                IMD5HashProvider chunkHash = MD5HashProviderFactory.GetHashProvider().CreateHash();

                byte[] b = ArrayPool <byte> .Shared.Rent(Configuration.BufferSize);

                try
                {
                    int read   = 0;
                    int toRead = length;
                    do
                    {
                        read = await fileStream.ReadAsync(b, offset : 0, count : Math.Min(b.Length, toRead)).ConfigureAwait(false);

                        toRead -= read;

                        await dest.WriteAsync(b, offset : 0, count : read).ConfigureAwait(false);

                        chunkHash.Append(b, offset: 0, size: read);
                        fileHash.Append(b, offset: 0, size: read);
                    } while (read > 0 && toRead > 0);
                    if (toRead > 0)
                    {
                        throw new Exception($"Expected to read {length} bytes, actual read {length - toRead} bytes");
                    }

                    chunkHash.Finalize(ArrayPool <byte> .Shared.Rent(0), 0, 0);
                    return(new ReadFileResult {
                        Content = content, Hash = chunkHash.GetComputedHashAsString()
                    });
                }
                catch
                {
                    content.Dispose();
                    throw;
                }
                finally
                {
                    ArrayPool <byte> .Shared.Return(b);

                    dest.Dispose();
                }
            }
        public void UseBiggerActionReusingExisting()
        {
            options.MaxBuffersPerSizeBand     = 2;
            options.ActionOnBufferUnavailable = CachingBufferManager.Options.BufferUnavailableAction.UseBigger;
            subject = new CachingBufferManager(options);

            // This buffer will be used later on
            IBuffer bigger = subject.GetBuffer(4098);

            bigger.Dispose();

            IBuffer buffer1 = subject.GetBuffer(3000);
            IBuffer buffer2 = subject.GetBuffer(3000);

            IBuffer buffer3 = subject.GetBuffer(3000);

            Assert.AreSame(bigger, buffer3);
        }
Ejemplo n.º 16
0
        internal static void Publish2()
        {
            IBuffer <int>     publish   = Enumerable.Range(0, 5).Publish();
            IEnumerator <int> iterator1 = publish.GetEnumerator();
            // iterator1: 0 1 2 3 4
            IEnumerator <int> iterator2 = publish.GetEnumerator();

            // iterator1: 0 1 2 3 4
            iterator1.MoveNext(); iterator1.Current.WriteLine(); // 0| |Trace: 0
            iterator1.MoveNext(); iterator1.Current.WriteLine(); // 1| |Trace: 1
            iterator1.MoveNext(); iterator1.Current.WriteLine(); // 2| |Trace: 2
            iterator2.MoveNext(); iterator2.Current.WriteLine(); //  |0|
            iterator1.MoveNext(); iterator1.Current.WriteLine(); // 3| |Trace: 3
            iterator2.MoveNext(); iterator2.Current.WriteLine(); //  |1|
            iterator1.MoveNext(); iterator1.Current.WriteLine(); // 4| |Trace: 4

            publish.Dispose();
            iterator1.MoveNext(); // ObjectDisposedException.
            iterator2.MoveNext(); // ObjectDisposedException.
        }
        internal static void Publish()
        {
            IBuffer <int>     publish   = TracedRange(0, 5).Publish();
            IEnumerator <int> iterator1 = publish.GetEnumerator();

            // iterator1: 0 1 2 3 4
            iterator1.MoveNext(); Trace.WriteLine(iterator1.Current); // 0| |Trace: 0
            iterator1.MoveNext(); Trace.WriteLine(iterator1.Current); // 1| |Trace: 1
            iterator1.MoveNext(); Trace.WriteLine(iterator1.Current); // 2| |Trace: 2
            IEnumerator <int> iterator2 = publish.GetEnumerator();    //  | |

            // iterator2: 3 4                                               | |
            iterator2.MoveNext(); Trace.WriteLine(iterator2.Current); //  |3|Trace: 3
            iterator1.MoveNext(); Trace.WriteLine(iterator1.Current); // 3| |
            iterator2.MoveNext(); Trace.WriteLine(iterator2.Current); //  |4|Trace: 4
            iterator1.MoveNext(); Trace.WriteLine(iterator1.Current); // 4| |
                                                                      // Trace: 0 1 2 3 4.

            publish.Dispose();
            iterator1.MoveNext(); // ObjectDisposedException.
            iterator2.MoveNext(); // ObjectDisposedException.
        }
Ejemplo n.º 18
0
 public void Dispose()
 {
     Buffer.Dispose();
 }
Ejemplo n.º 19
0
 public void Dealloc(IBuffer buffer)
 {
     // Deallocate the buffer, since we're an unpooled allocator we don't really need to do much,
     // other than to dispose the buffer
     buffer.Dispose(this);
 }
Ejemplo n.º 20
0
 public void Dispose()
 {
     buffer.Dispose();
     GC.SuppressFinalize(this);
 }
Ejemplo n.º 21
0
        public void Draw()
        {
            var sketches        = sketchService.GetSketches();
            var totalPointCount = sketches.Sum(x => x.Count);

            if (totalPointCount == 0)
            {
                return;
            }

            if (data == null || totalPointCount > data.Length)
            {
                vertexBuffer?.Dispose();
                var size = data?.Length ?? 1024;
                while (size < totalPointCount)
                {
                    size *= 2;
                }

                data         = new Vector2[size];
                vertexBuffer = glContext.Create.Buffer(BufferTarget.Array, data.Length * sizeof(Vector2), BufferUsageHint.DynamicDraw);
                vao.SetVertexAttributeF(0, vertexBuffer, VertexAttributeDimension.Two, VertexAttribPointerType.Float, false, sizeof(Vector2), 0);
            }

            int offset = 0;

            foreach (var sketch in sketches)
            {
                foreach (var point in sketch)
                {
                    data[offset++] = point;
                }
            }

            var sketchSize = totalPointCount * sizeof(Vector2);
            var map        = vertexBuffer.Map(0, sketchSize, MapAccess.Write | MapAccess.InvalidateRange);

            fixed(Vector2 *pData = data)
            PtrHelper.CopyBulk((byte *)map, (byte *)pData, sketchSize);

            vertexBuffer.Unmap();

            glContext.Bindings.Program.Set(shaderProgram);
            glContext.Bindings.VertexArray.Set(vao);

            glContext.States.DepthStencil.DepthTestEnable.Set(false);
            glContext.States.DepthStencil.DepthMask.Set(false);

            OpenTK.Graphics.OpenGL4.GL.LineWidth(6f);

            offset = 0;
            foreach (var sketch in sketches)
            {
                glContext.Actions.Draw.Arrays(BeginMode.LineStrip, offset, sketch.Count);
                offset += sketch.Count;
            }

            OpenTK.Graphics.OpenGL4.GL.LineWidth(1f);

            glContext.States.DepthStencil.DepthTestEnable.Set(true);
            glContext.States.DepthStencil.DepthMask.Set(true);
        }
Ejemplo n.º 22
0
        public void Dealloc(IBuffer buffer)
        {
            this._bufferIndexPool.Push((buffer as DefaultBuffer).Offset);

            buffer.Dispose(this);
        }
Ejemplo n.º 23
0
 public void Dispose()
 {
     _buffer.Dispose();
 }
Ejemplo n.º 24
0
 public void Dispose() => _buffer.Dispose();