public MediaStateChangedEventArgs(BufferState bufferState, NetworkState networkState, PlaybackState playbackState, SeekState seekState)
		{
			this.bufferState = bufferState;
			this.networkState = networkState;
			this.playbackState = playbackState;
			this.seekState = seekState;
		}
 public Tokenizer()
 {
     _operators =
         new HashSet<string>(new[] { "+", "++", "-", "--", "*", "/", "%", "=", "<", ">", "==", ">=", "<=" });
     _keywords = new HashSet<string>(new[] { "if", "else", "for", "while", "module", "return" });
     _specialtokens = new HashSet<char>(new[] { '[', ']', '{', '}', '(', ')' });
     _state = BufferState.EmptyState;
     _buffer = new List<char>();
     _ready = false;
     _escapeNextChar = false;
     _endOfString = false;
 }
 public void Close()
 {
     int num;
     if (this.bufferState != BufferState.Created)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.CreateInvalidStateException());
     }
     this.bufferState = BufferState.Reading;
     this.buffer = this.stream.ToArray(out num);
     this.writer = null;
     this.stream = null;
 }
 public void CloseSection()
 {
     if (this.bufferState != BufferState.Writing)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.CreateInvalidStateException());
     }
     this.writer.Close();
     this.bufferState = BufferState.Created;
     int size = ((int) this.stream.Length) - this.offset;
     this.sections.Add(new Section(this.offset, size, this.quotas));
     this.offset += size;
 }
Example #5
0
 public XmlDictionaryWriter OpenSection(XmlDictionaryReaderQuotas quotas)
 {
     if (bufferState != BufferState.Created)
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidStateException());
     bufferState = BufferState.Writing;
     this.quotas = new XmlDictionaryReaderQuotas();
     quotas.CopyTo(this.quotas);
     if (this.writer == null)
     {
         this.writer = XmlDictionaryWriter.CreateBinaryWriter(stream, XD.Dictionary, null, true);
     }
     else
     {
         ((IXmlBinaryWriterInitializer)this.writer).SetOutput(stream, XD.Dictionary, null, true);
     }
     return this.writer;
 }
Example #6
0
 public XmlDictionaryWriter OpenSection(XmlDictionaryReaderQuotas quotas)
 {
     if (_bufferState != BufferState.Created)
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidStateException());
     _bufferState = BufferState.Writing;
     _quotas = new XmlDictionaryReaderQuotas();
     quotas.CopyTo(_quotas);
     if (_writer != null)
     {
         // We always want to Dispose of the writer now; previously, writers could be reassigned 
         // to a new stream, with a new dictionary and session. 
         var thisWriter = _writer;
         thisWriter.Dispose();
         _writer = null;
     }
     _writer = XmlDictionaryWriter.CreateBinaryWriter(_stream, XD.Dictionary, null, true);
     return _writer;
 }
Example #7
0
 public void OnAuthenticate(IAsyncResult ar)
 {
     lock (this.thisClientLock)
     {
         C c = ar.AsyncState as C;
         try
         {
             Common.WriteLine("    OnAuthenticate done", new string[0]);
             if (!c._sock.Connected)
             {
                 Common.WriteLine("    Socket is down while authenticating", new string[0]);
                 base.AbortOnError(c);
             }
             else
             {
                 c._sslConnected = true;
                 BufferState bufferState = new BufferState();
                 bufferState._ctx    = c;
                 bufferState._buffer = new byte[4096];
                 if (bufferState._buffer != null)
                 {
                     c._sslStream.BeginRead(bufferState._buffer, 0, bufferState._buffer.Length, new AsyncCallback(this.ReadCallback), bufferState);
                     this.OnSayHello();
                 }
             }
         }
         catch (Exception ex)
         {
             Common.WriteLine("    OnAuthenticate: {0}", new string[]
             {
                 ex.Message
             });
             base.AbortOnError(c);
         }
     }
 }
Example #8
0
        public int GetMaxBufferCountLocked(bool async)
        {
            int minMaxBufferCount = GetMinMaxBufferCountLocked(async);

            int maxBufferCount = Math.Max(DefaultMaxBufferCount, minMaxBufferCount);

            if (OverrideMaxBufferCount != 0)
            {
                maxBufferCount = OverrideMaxBufferCount;
            }

            // Preserve all buffers already in control of the producer and the consumer.
            for (int slot = maxBufferCount; slot < Slots.Length; slot++)
            {
                BufferState state = Slots[slot].BufferState;

                if (state == BufferState.Queued || state == BufferState.Dequeued)
                {
                    maxBufferCount = slot + 1;
                }
            }

            return(maxBufferCount);
        }
        public void Insert(char ch)
        {
            bool insert = true;

            switch (_state)
            {
                case BufferState.ErrorState:
                    {
                        // If we are in an error token, switch to ready to
                        // dispense if we encounter a token that is valid to
                        // start an identifier
                        if (CanStartToken(ch))
                        {
                            _ready = true;
                        }
                    }
                    break;
                case BufferState.SpecialTokenState:
                    {
                        _ready = true;
                    }
                    break;
                case BufferState.WhiteSpaceState:
                    {
                        // if we are in a white space token, only something
                        // besides a white space token will end our token
                        if (!IsWhitespace(ch))
                        {
                            _ready = true;
                        }
                    }
                    break;
                case BufferState.VariableOrKeywordState:
                    {
                        // If we are in an identifier, keyword, or condition,
                        // only something besides a valid identifier
                        // character will end the token
                        if (!IsIdentifierCharacter(ch))
                        {
                            _ready = true;
                        }
                    }
                    break;
                case BufferState.IntLiteralState:
                    {
                        if (ch == '.')
                        {
                            _state = BufferState.FloatLiteralState;
                        }
                        else if (_buffer.Last() == '0' && ch == 'x')
                        {
                            // Do nothing, prevent check below from making this terminate early.
                        }
                        else if (!IsDigit(ch))
                        {
                            _ready = true;
                        }
                    }
                    break;
                case BufferState.FloatLiteralState:
                    {
                        if (!IsDigit(ch))
                        {
                            _ready = true;
                        }
                    }
                    break;
                case BufferState.StringLiteralState:
                    {
                        if (_endOfString)
                        {
                            _ready = true;
                            _endOfString = false;
                        }
                        else if (_escapeNextChar)
                        {
                            ch = GetEscapedChar(ch);
                            _escapeNextChar = false;
                        }
                        else if (ch == '\"')
                        {
                            _endOfString = true;
                        }
                        else if (ch == '\\')
                        {
                            _escapeNextChar = true;
                            insert = false;
                        }
                    }
                    break;
                case BufferState.CommentState:
                    {
                        // a comment continues until the new line character
                        if (ch == '\n')
                        {
                            _ready = true;
                        }
                    }
                    break;
                case BufferState.OperatorState:
                    {
                        if (_buffer.Count() == 1 && _buffer[0] == '-' && IsDigit(ch))
                        {
                            // Negative literal special case
                            _state = BufferState.IntLiteralState;
                            break;
                        }

                        bool before = IsOperatorSubstring(_buffer);

                        _buffer.Add(ch);
                        insert = false;
                        bool after = IsOperatorSubstring(_buffer);

                        if (before && !after)
                        {
                            _ready = true;
                        }
                    }
                    break;
                case BufferState.EmptyState:
                    {
                        // make the mBuffer mState appropriate for whatever we
                        // are adding.
                        _state = BufferType(ch);
                    }
                    break;
            }

            if (insert)
            {
                _buffer.Add(ch);
            }
        }
 internal void RestoreState(BufferState state)
 {
     this.pos = state.pos;
     this.bitBuf = state.bitBuf;
     this.bitCount = state.bitCount;
 }
Example #11
0
        private void HandleBuffering(object o)
        {
            while (true)
            {
                byte[] Packet = null;
                lock (BufferQueueLock)
                {
                    if (BufferQueue.Count == 0)
                    {
                        lock (IsBufferingLock)
                        {
                            IsBuffering = false;
                        }
                        break;
                    }
                    Packet = BufferQueue.Dequeue();
                }
                int BytesToProcess = Packet.Length;
                while (BytesToProcess > 0)
                {
                    switch (State)
                    {
                    case BufferState.HEADER:
                        if (BytesToProcess + WriteOffset >= Config.GetHeaderSize())
                        {
                            int ExactLength = (BytesToProcess >= Config.GetHeaderSize()) ? Config.GetHeaderSize() - WriteOffset : BytesToProcess;
                            Buffer.BlockCopy(Packet, ReadOffset, HeaderStore, WriteOffset, ExactLength);

                            WriteOffset     = 0;
                            ReadOffset     += ExactLength;
                            BytesToProcess -= ExactLength;

                            MessageSize = BitConverter.ToInt32(HeaderStore, 0);

                            if (MessageSize <= 0 || MessageSize >= Config.GetMaxMessageSize())
                            {
                                OnClientDisconnected?.Invoke(this, "Corrupted Header Packet");
                                IsActive       = false;
                                BytesToProcess = 0;
                            }
                            State = BufferState.BODY;
                        }
                        else
                        {
                            Buffer.BlockCopy(Packet, ReadOffset, HeaderStore, WriteOffset, BytesToProcess);
                            WriteOffset   += BytesToProcess;
                            BytesToProcess = 0;
                        }
                        break;

                    case BufferState.BODY:
                        if (BodyStore == null)
                        {
                            BodyStore = new byte[MessageSize];
                        }
                        else
                        {
                            if (BodyStore.Length != MessageSize)
                            {
                                BodyStore = new byte[MessageSize];
                            }
                        }
                        int BodyLength = (BytesToProcess + WriteOffset > MessageSize) ? MessageSize - WriteOffset : BytesToProcess;

                        Buffer.BlockCopy(Packet, ReadOffset, BodyStore, WriteOffset, BodyLength);

                        WriteOffset    += BodyLength;
                        ReadOffset     += BodyLength;
                        BytesToProcess -= BodyLength;
                        if (WriteOffset == MessageSize)
                        {
                            Packet Message = PacketManager.GetPacket(BodyStore, 0);
                            if (Message.Code == -1)
                            {
                                OnClientDisconnected?.Invoke(this, "Invalid Packet Message");
                                IsActive       = false;
                                BytesToProcess = 0;
                            }
                            else
                            {
                                SetOnReceiveMessage(Message);
                                State       = BufferState.HEADER;
                                WriteOffset = 0;
                            }
                        }
                        break;
                    }
                    if (BytesToProcess == 0)
                    {
                        ReadOffset = 0;
                    }
                }
            }
        }
Example #12
0
 public void Close()
 {
     if (_bufferState != BufferState.Created)
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidStateException());
     _bufferState = BufferState.Reading;
     int bufferSize;
     _buffer = _stream.ToArray(out bufferSize);
     _writer = null;
     _stream = null;
 }
Example #13
0
 // Puts data in the buffer in the back of the queue.
 internal override void Put(T newdata)
 {
     buffer.Enqueue(newdata);
     state = BufferState.NonFullEmpty;
 }
Example #14
0
 public BufferInfo(BufferState state, TProduct topProduct)
 {
     State      = state;
     TopProduct = topProduct;
 }
Example #15
0
 // Constructor taking the size of the buffer as parameter.
 internal FifoBuffer(int size)
 {
     bufferSize = size;
     buffer     = new Queue <T>(size);
     state      = BufferState.Empty;
 }
Example #16
0
 // Constructor taking the size of the buffer as parameter.
 internal LifoBuffer(int size)
 {
     bufferSize = size;
     buffer     = new Stack <T>(size);
     state      = BufferState.Empty;
 }
        public static IObserver <ByteBuffer> ToClientObserver(this Socket socket, SocketFlags socketFlags, Selector selector, CancellationToken token)
        {
            return(Observer.Create <ByteBuffer>(
                       buffer =>
            {
                var state = new BufferState(buffer.Bytes, 0, buffer.Length);

                // Try to write as much as possible without registering a callback.
                try
                {
                    state.Advance(socket.Send(state.Bytes, state.Offset, state.Length, socketFlags));
                    if (state.Length == 0)
                    {
                        return;
                    }
                }
                catch (Exception exception)
                {
                    if (!exception.IsWouldBlock())
                    {
                        throw;
                    }
                }

                var waitEvent = new AutoResetEvent(false);
                var waitHandles = new[] { token.WaitHandle, waitEvent };
                Exception error = null;

                selector.AddCallback(SelectMode.SelectWrite, socket,
                                     _ =>
                {
                    try
                    {
                        state.Advance(socket.Send(state.Bytes, state.Offset, state.Length, socketFlags));
                        if (state.Length == 0)
                        {
                            selector.RemoveCallback(SelectMode.SelectWrite, socket);
                            waitEvent.Set();
                        }
                    }
                    catch (Exception exception)
                    {
                        if (exception.IsWouldBlock())
                        {
                            return;
                        }

                        error = exception;
                        selector.RemoveCallback(SelectMode.SelectWrite, socket);
                        waitEvent.Set();
                    }
                });

                while (state.Length > 0)
                {
                    if (WaitHandle.WaitAny(waitHandles) == 0)
                    {
                        token.ThrowIfCancellationRequested();
                    }

                    if (error != null)
                    {
                        throw error;
                    }
                }
            }));
        }
Example #18
0
        private void assembleData(BufferState bufState)
        {
            //do

            if (!bufState.hasRemaing)
            {
                try
                {
                    //Console.WriteLine("开始接收数据,");
                    bufState.remaining = client.Receive(bufState.buf);
                    //Console.WriteLine("接收数据完成");
                    //Console.WriteLine("remaining: "+bufState.remaining);
                    bufState.hasRemaing = true;
                }
                catch
                {
                    disConnect();
                    updateInfo("接收数据异常,退出Socket连接", MyConfig.INT_UPDATEUI_TXBOX);
                    bufState.init();
                    return;
                }
            }
            if (bufState.hasHead)
            {
                //Console.WriteLine("remaining : " + bufState.remaining);
                while (bufState.remaining < MyConfig.INT_PACKAGE_HEAD_LEN)
                {
                    //复制下一个buf的头部;
                    MyUtil.copyArray(bufState.buf, bufState.bufPos, bufState.buf, 0, bufState.remaining);
                    //接收数据组合正常头部包;
                    Int32 size = client.Receive(bufState.buf, bufState.remaining, MyConfig.INT_SOCKET_BUFFER_SIZE - bufState.remaining, SocketFlags.None);
                    bufState.remaining = bufState.remaining + size;
                    bufState.bufPos    = 0;
                    bufState.tempPos   = 0;
                }
                byte headFlag = decode.getHeadFlag(bufState.buf, bufState.bufPos);
                byte dataType = decode.getDataType(bufState.buf, bufState.bufPos);
                byte reqType  = decode.getReqType(bufState.buf, bufState.bufPos);
                if (headFlag == MyConfig.PROTOCOL_HEAD_FLAG && reqType > 0 && reqType < 8)
                {
                    bufState.target = decode.getPackLen(bufState.buf, bufState.bufPos);
                    if (bufState.target < MyConfig.INT_PACKAGE_HEAD_LEN || bufState.target >= Int32.MaxValue)
                    {
                        Console.WriteLine("bufState.target err : " + bufState.target);
                        bufState.drop();
                    }
                    else
                    {
                        bufState.isRightPackage = true;
                        bufState.pending        = bufState.target;
                        bufState.temp           = new byte[bufState.target];
                    }
                }
                else
                {
                    Console.WriteLine("dataType err : " + dataType);
                    bufState.drop();
                }
            }

            if (bufState.pending == bufState.remaining && bufState.isRightPackage == true)
            {
                MyUtil.copyArray(bufState.buf, bufState.bufPos, bufState.temp, bufState.tempPos, bufState.remaining);
                byte   reqType = decode.getReqType(bufState.temp, 0);
                String token   = decode.getToken(bufState.temp);
                byte[] result  = decode.getData(bufState.temp);
                //Console.WriteLine("temp: " + bufState.temp.Length);
                coreProccessing(reqType, token, result);
                bufState.init();
            }

            if (bufState.pending < bufState.remaining && bufState.isRightPackage == true)
            {
                MyUtil.copyArray(bufState.buf, bufState.bufPos, bufState.temp, bufState.tempPos, bufState.pending);
                byte   reqType = decode.getReqType(bufState.temp, 0);
                String token   = decode.getToken(bufState.temp);
                byte[] result  = decode.getData(bufState.temp);
                //Console.WriteLine("temp:  " + bufState.temp.Length);
                coreProccessing(reqType, token, result);
                bufState.skip();
            }
            if (bufState.pending > bufState.remaining && bufState.isRightPackage == true)
            {
                MyUtil.copyArray(bufState.buf, bufState.bufPos, bufState.temp, bufState.tempPos, bufState.remaining);
                //数据没有接收完整,重新接收数据
                //Console.WriteLine("temp: " + bufState.temp.Length);
                bufState.connect();
            }
        }
Example #19
0
 public NetworkBuffer(BufferState State, int Size)
 {
     Reset(State, Size);
 }
 internal void RestoreState(BufferState state)
 {
     this.pos      = state.pos;
     this.bitBuf   = state.bitBuf;
     this.bitCount = state.bitCount;
 }
Example #21
0
 public BufferSlot()
 {
     GraphicBuffer = new AndroidStrongPointer <GraphicBuffer>();
     BufferState   = BufferState.Free;
 }
Example #22
0
 public BufferEntry(BufferState state)
 {
     State = state;
     Latch = new LatchEntry(this);
 }
Example #23
0
 /// <summary>Buffer the chunks data to a vbo so it can be rendered.</summary>
 /// <remarks>When benchmarking this method, it happens so fast quite often the stopwatch would report 0ms, so dont worry about it.</remarks>
 private void BufferData()
 {
     foreach (var chunkVbo in _chunkVbos.Where(chunkVbo => chunkVbo != null))
     {
         chunkVbo.BufferData();
     }
     _shortestFaceHeight = _shortestFaceHeightTemp;
     ChunkBufferState = BufferState.VboBuffered;
 }
Example #24
0
 public BufferEntry(BufferState state, PagePosition pos)
 {
     State    = state;
     Latch    = new LatchEntry(this, LockRecursionPolicy.SupportsRecursion);
     Position = pos;
 }
 public static BufferState Advance(this BufferState bufferState, int count)
 {
     bufferState.Offset += count;
     bufferState.Length -= count;
     return(bufferState);
 }
Example #26
0
 internal void RestoreState(BufferState state)
 {
     _pos      = state._pos;
     _bitBuf   = state._bitBuf;
     _bitCount = state._bitCount;
 }
Example #27
0
 internal void RestoreState(BufferState state)
 {
     BytesWritten = state.pos;
     bitBuf       = state.bitBuf;
     bitCount     = state.bitCount;
 }
 public void RestoreState(BufferState state)
 {
     this.BytesWritten = state.Pos;
     _bitBuffer = state.BitBuffer;
     _bitCount = state.BitCount;
 }
Example #29
0
 public void CloseSection()
 {
     if (_bufferState != BufferState.Writing)
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidStateException());
     _writer.Dispose();
     _writer = null;
     _bufferState = BufferState.Created;
     int size = (int)_stream.Length - _offset;
     _sections.Add(new Section(_offset, size, _quotas));
     _offset += size;
 }
Example #30
0
        public static IObserver <DisposableValue <ArraySegment <byte> > > ToFrameClientObserver(this Socket socket, SocketFlags socketFlags, Selector selector, CancellationToken token)
        {
            return(Observer.Create <DisposableValue <ArraySegment <byte> > >(disposableBuffer =>
            {
                var header = BitConverter.GetBytes(disposableBuffer.Value.Count);
                var headerState = new BufferState(header, 0, header.Length);
                var contentState = new BufferState(disposableBuffer.Value.Array, 0, disposableBuffer.Value.Count);

                try
                {
                    headerState.Advance(socket.Send(headerState.Bytes, headerState.Offset, headerState.Length, socketFlags));

                    if (headerState.Length == 0)
                    {
                        contentState.Advance(socket.Send(contentState.Bytes, contentState.Offset, contentState.Length, socketFlags));
                    }

                    if (contentState.Length == 0)
                    {
                        return;
                    }
                }
                catch (Exception exception)
                {
                    if (!exception.IsWouldBlock())
                    {
                        throw;
                    }
                }

                var waitEvent = new AutoResetEvent(false);
                var waitHandles = new[] { token.WaitHandle, waitEvent };
                Exception error = null;

                selector.AddCallback(SelectMode.SelectWrite, socket,
                                     _ =>
                {
                    try
                    {
                        if (headerState.Length > 0)
                        {
                            headerState.Advance(socket.Send(headerState.Bytes, headerState.Offset, headerState.Length, socketFlags));
                        }

                        if (headerState.Length == 0)
                        {
                            contentState.Advance(socket.Send(contentState.Bytes, contentState.Offset, contentState.Length, socketFlags));
                        }

                        if (contentState.Length == 0)
                        {
                            selector.RemoveCallback(SelectMode.SelectWrite, socket);
                            waitEvent.Set();
                        }
                    }
                    catch (Exception exception)
                    {
                        if (exception.IsWouldBlock())
                        {
                            return;
                        }

                        error = exception;
                        selector.RemoveCallback(SelectMode.SelectWrite, socket);
                        waitEvent.Set();
                    }
                });

                while (headerState.Length > 0 && contentState.Length > 0)
                {
                    if (WaitHandle.WaitAny(waitHandles) == 0)
                    {
                        token.ThrowIfCancellationRequested();
                    }

                    if (error != null)
                    {
                        throw error;
                    }
                }

                disposableBuffer.Dispose();
            }));
        }
Example #31
0
 // Constructs a new InfiniteBuffer.
 internal InfiniteBuffer()
 {
     buffer = new Queue <T>(100);
     state  = BufferState.Empty;
 }
        public static IObserver<DisposableByteBuffer> ToFrameClientObserver(this Socket socket, SocketFlags socketFlags, Selector selector, CancellationToken token)
        {
            return Observer.Create<DisposableByteBuffer>(disposableBuffer =>
            {
                var header = BitConverter.GetBytes(disposableBuffer.Length);
                var headerState = new BufferState(header, 0, header.Length);
                var contentState = new BufferState(disposableBuffer.Bytes, 0, disposableBuffer.Length);

                try
                {
                    headerState.Advance(socket.Send(headerState.Bytes, headerState.Offset, headerState.Length, socketFlags));

                    if (headerState.Length == 0)
                        contentState.Advance(socket.Send(contentState.Bytes, contentState.Offset, contentState.Length, socketFlags));

                    if (contentState.Length == 0)
                        return;
                }
                catch (Exception exception)
                {
                    if (!exception.IsWouldBlock())
                        throw;
                }

                var waitEvent = new AutoResetEvent(false);
                var waitHandles = new[] { token.WaitHandle, waitEvent };
                Exception error = null;

                selector.AddCallback(SelectMode.SelectWrite, socket,
                    _ =>
                    {
                        try
                        {
                            if (headerState.Length > 0)
                                headerState.Advance(socket.Send(headerState.Bytes, headerState.Offset, headerState.Length, socketFlags));

                            if (headerState.Length == 0)
                                contentState.Advance(socket.Send(contentState.Bytes, contentState.Offset, contentState.Length, socketFlags));

                            if (contentState.Length == 0)
                            {
                                selector.RemoveCallback(SelectMode.SelectWrite, socket);
                                waitEvent.Set();
                            }
                        }
                        catch (Exception exception)
                        {
                            if (exception.IsWouldBlock())
                                return;

                            error = exception;
                            selector.RemoveCallback(SelectMode.SelectWrite, socket);
                            waitEvent.Set();
                        }
                    });

                while (headerState.Length > 0 && contentState.Length > 0)
                {
                    if (WaitHandle.WaitAny(waitHandles) == 0)
                        token.ThrowIfCancellationRequested();

                    if (error != null)
                        throw error;
                }

                disposableBuffer.Dispose();
            });
        }
 public void RestoreState(BufferState state)
 {
     this.BytesWritten = state.Pos;
     _bitBuffer        = state.BitBuffer;
     _bitCount         = state.BitCount;
 }
Example #34
0
        private IEnumerable <IMappingTagSpan <T> > GetTagsForBuffer(NormalizedSnapshotSpanCollection snapshotSpans,
                                                                    BufferState taggersForBuffer, ITextSnapshot root, CancellationToken?cancel)
        {
            ITextSnapshot snapshot = snapshotSpans[0].Snapshot;

            for (int t = 0; t < taggersForBuffer.Taggers.Count; ++t)
            {
                ITagger <T> tagger = taggersForBuffer.Taggers[t];
                IEnumerator <ITagSpan <T> > tags = null;
                try
                {
                    IEnumerable <ITagSpan <T> > tagEnumerable;

                    if (cancel.HasValue)
                    {
                        cancel.Value.ThrowIfCancellationRequested();

                        var tagger2 = tagger as IAccurateTagger <T>;
                        if (tagger2 != null)
                        {
                            tagEnumerable = tagger2.GetAllTags(snapshotSpans, cancel.Value);
                        }
                        else
                        {
                            tagEnumerable = tagger.GetTags(snapshotSpans);
                        }
                    }
                    else
                    {
                        tagEnumerable = tagger.GetTags(snapshotSpans);
                    }

                    if (tagEnumerable != null)
                    {
                        tags = tagEnumerable.GetEnumerator();
                    }
                }
                catch (OperationCanceledException)
                {
                    // Rethrow cancellation exceptions since we expect our callers to deal with it.
                    throw;
                }
                catch (Exception e)
                {
                    this.TagAggregatorFactoryService.GuardedOperations.HandleException(tagger, e);
                }

                if (tags != null)
                {
                    try
                    {
                        while (true)
                        {
                            ITagSpan <T> tagSpan = null;
                            try
                            {
                                if (tags.MoveNext())
                                {
                                    tagSpan = tags.Current;
                                }
                            }
                            catch (Exception e)
                            {
                                this.TagAggregatorFactoryService.GuardedOperations.HandleException(tagger, e);
                            }

                            if (tagSpan == null)
                            {
                                break;
                            }

                            var snapshotSpan = tagSpan.Span;

                            if (snapshotSpans.IntersectsWith(snapshotSpan.TranslateTo(snapshot, SpanTrackingMode.EdgeExclusive)))
                            {
                                yield return(new MappingTagSpan <T>(
                                                 (root == null)
                                    ? this.BufferGraph.CreateMappingSpan(snapshotSpan, SpanTrackingMode.EdgeExclusive)
                                    : MappingSpanSnapshot.Create(root, snapshotSpan, SpanTrackingMode.EdgeExclusive, this.BufferGraph),
                                                 tagSpan.Tag));
                            }
                            else
                            {
#if DEBUG
                                Debug.WriteLine("tagger provided an extra (non-intersecting) tag at " + snapshotSpan + " when queried for tags over " + snapshotSpans);
#endif
                            }
                        }
                    }
                    finally
                    {
                        try
                        {
                            tags.Dispose();
                        }
                        catch (Exception e)
                        {
                            this.TagAggregatorFactoryService.GuardedOperations.HandleException(tagger, e);
                        }
                    }
                }
            }
        }
Example #35
0
        private void OnSocketReceived(SocketAsyncEventArgs e)
        {
            bool   flag   = false;
            bool   flag2  = true;
            Socket socket = e.AcceptSocket;

            if (e.LastOperation == SocketAsyncOperation.Receive)
            {
                socket = (e.UserToken as Socket);
            }
            C connection = base.GetConnection(socket);

            lock (this._lockServer)
            {
                if (e.SocketError != SocketError.Success || e.BytesTransferred == 0 || !socket.Connected)
                {
                    if (connection != null)
                    {
                        base.RemoveConnection(socket);
                    }
                    ServicesAPI.OnDisconnected(socket);
                    if (e.LastOperation == SocketAsyncOperation.Receive)
                    {
                        if (socket.Connected)
                        {
                            socket.Shutdown(SocketShutdown.Both);
                            socket.Disconnect(false);
                        }
                        socket.Close();
                        e.AcceptSocket = null;
                        e.UserToken    = null;
                        e.Completed   -= new EventHandler <SocketAsyncEventArgs>(this.IO_Completed);
                        this._receiveSocketArgs.Enqueue(e);
                    }
                    Common.WriteLine(this._threadName + ": connection down: " + this._connected, new string[0]);
                    return;
                }
                this._speedMeter.Received(e.BytesTransferred);
                if (connection != null)
                {
                    BufferState bufferState = new BufferState();
                    bufferState._ctx    = connection;
                    bufferState._buffer = e.Buffer;
                    if (bufferState._buffer != null)
                    {
                        Interlocked.Increment(ref this._totalRequests);
                        SessionAPI.Update(connection._uid);
                        int           num  = 0;
                        List <byte[]> list = connection.ReceivedBuffer(bufferState, e.BytesTransferred, ref num);
                        if (list != null)
                        {
                            flag2 = false;
                            foreach (byte[] current in list)
                            {
                                if (!socket.Connected)
                                {
                                    break;
                                }
                                this.StartSend(connection, current);
                            }
                        }
                    }
                }
            }
            if (!flag2)
            {
                if (e.LastOperation == SocketAsyncOperation.Receive)
                {
                    flag = true;
                    lock (this._lockServer)
                    {
                        if (socket.Connected)
                        {
                            flag = socket.ReceiveAsync(e);
                        }
                        else
                        {
                            ServicesAPI.OnDisconnected(socket);
                            if (connection != null)
                            {
                                base.RemoveConnection(socket);
                            }
                            e.AcceptSocket = null;
                            e.UserToken    = null;
                            e.Completed   -= new EventHandler <SocketAsyncEventArgs>(this.IO_Completed);
                            this._receiveSocketArgs.Enqueue(e);
                        }
                    }
                    if (!flag)
                    {
                        this.OnSocketReceived(e);
                    }
                }
                return;
            }
            if (connection != null)
            {
                base.RemoveConnection(socket);
            }
            ServicesAPI.OnDisconnected(socket);
            lock (this._lockServer)
            {
                if (socket.Connected)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Disconnect(false);
                }
                socket.Close();
            }
            if (e.LastOperation == SocketAsyncOperation.Receive)
            {
                e.AcceptSocket = null;
                e.UserToken    = null;
                e.Completed   -= new EventHandler <SocketAsyncEventArgs>(this.IO_Completed);
                this._receiveSocketArgs.Enqueue(e);
            }
            Common.WriteLine("Receive Processing Error", new string[0]);
        }
        public Token Dispense()
        {
            Debug.Assert(Ready());

            char ch = _buffer[_buffer.Count() - 1];
            _buffer.RemoveAt(_buffer.Count() - 1);

            string text = string.Concat(_buffer);
            TokenType type = GetTokenType(text);


            _state = BufferType(ch);
            _buffer.Clear();
            _buffer.Add(ch);

            _ready = false;

            return new Token(type, text);
        }
        public static IObservable<DisposableByteBuffer> ToFrameClientObservable(this Socket socket, SocketFlags socketFlags, BufferManager bufferManager, Selector selector)
        {
            return Observable.Create<DisposableByteBuffer>(observer =>
            {
                var headerState = new BufferState(new byte[sizeof(int)], 0, sizeof(int));
                var contentState = new BufferState(null, 0, -1);

                var selectMode = socketFlags.HasFlag(SocketFlags.OutOfBand) ? SelectMode.SelectError : SelectMode.SelectRead;

                selector.AddCallback(selectMode, socket, _ =>
                {
                    try
                    {
                        if (headerState.Length > 0)
                        {
                            headerState.Advance(socket.Receive(headerState.Bytes, headerState.Offset, headerState.Length, socketFlags));

                            if (headerState.Length == 0)
                            {
                                contentState.Length = BitConverter.ToInt32(headerState.Bytes, 0);
                                contentState.Offset = 0;
                                contentState.Bytes = bufferManager.TakeBuffer(contentState.Length);
                            }
                        }

                        if (contentState.Bytes != null)
                        {
                            contentState.Advance(socket.Receive(contentState.Bytes, contentState.Offset, contentState.Length, socketFlags));

                            if (contentState.Length == 0)
                            {
                                var managedBuffer = contentState.Bytes;
                                var length = contentState.Offset;
                                observer.OnNext(new DisposableByteBuffer(managedBuffer, length, Disposable.Create(() => bufferManager.ReturnBuffer(managedBuffer))));

                                contentState.Bytes = null;

                                headerState.Length = headerState.Offset;
                                headerState.Offset = 0;
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        if (!exception.IsWouldBlock())
                            observer.OnError(exception);
                    }
                });

                return Disposable.Create(() => selector.RemoveCallback(SelectMode.SelectRead, socket));
            });
        }
        public Token Flush()
        {
            string text = string.Concat(_buffer);
            _buffer.Clear();
            TokenType type = GetTokenType(text);

            _state = BufferState.EmptyState;

            _ready = false;
            return new Token(type, text);
        }
		public void RefreshBufferState()
		{
			BufferState nextBufferState = bufferState;
		
			if (sound != null && sound.CurrentSubSound != null)
			{
				if (sound.CurrentSubSound.BufferIsStarving)
				{
					nextBufferState = BufferState.Starving;
				}
				else
				{
					if (sound.CurrentSubSound.OpenState == OpenState.Loading)
						nextBufferState = BufferState.Loading;
					else if (sound.CurrentSubSound.OpenState == OpenState.Buffering)
					{
						if (sound.CurrentSubSound.PercentBuffered < 100)
							nextBufferState = BufferState.Buffering;
						else nextBufferState = BufferState.Full;
					}
					else nextBufferState = BufferState.None;
				}
			}
			else nextBufferState = BufferState.None;

			if (bufferState != nextBufferState)
			{
				bufferState = nextBufferState;
				if (BufferStateChanged != null)
					BufferStateChanged(this, new MediaStateChangedEventArgs(BufferState, NetworkState, PlaybackState, SeekState));
			}
		}
Example #40
0
 private void OnReceived(object sender, SocketAsyncEventArgs e)
 {
     lock (this.thisClientLock)
     {
         Socket socket = e.UserToken as Socket;
         try
         {
             if (e.SocketError != SocketError.Success || socket == null || e.BytesTransferred == 0)
             {
                 ClientAPI.OnClosed(this._context, -1);
                 if (e.LastOperation == SocketAsyncOperation.Receive)
                 {
                     if (socket != null)
                     {
                         Common.WriteLine(string.Concat(new object[]
                         {
                             "[#",
                             socket.Handle,
                             "]OnReceived Closed, bytes=",
                             e.BytesTransferred,
                             ", err=",
                             e.SocketError.ToString()
                         }), new string[0]);
                         this.AbortOnError(this._context);
                     }
                     e.UserToken  = null;
                     e.Completed -= new EventHandler <SocketAsyncEventArgs>(this.Socket_Completed);
                 }
                 this._tDelayConnectFrom.Start();
                 Interlocked.Exchange(ref this._nConnectState, -1L);
                 return;
             }
             this._speedMeter.Received(e.BytesTransferred);
             BufferState bufferState = new BufferState();
             bufferState._ctx    = this._context;
             bufferState._buffer = e.Buffer;
             if (bufferState._buffer != null)
             {
                 int           num  = 0;
                 List <byte[]> list = this._context.ReceivedBuffer(bufferState, e.BytesTransferred, ref num);
                 if (num > 0)
                 {
                     this._tLastReceivedPacket = (long)Environment.TickCount;
                 }
                 if (list != null)
                 {
                     foreach (byte[] current in list)
                     {
                         if (!socket.Connected)
                         {
                             break;
                         }
                         this.StartSend(this._context, current);
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             Common.WriteLine("OnReceived failed: {0}", new string[]
             {
                 ex.Message
             });
             this.AbortOnError(this._context);
         }
     }
     this.StartReceive(e);
 }