/// <summary> /// Ctr. /// </summary> /// <param name="connection">Parent connection</param> /// <param name="inputStream">Incoming data stream from server</param> /// <param name="holders">Array of holder objects that must be disposed when reader is closed</param> public PqlDataReader(PqlDataConnection connection, BufferedReaderStream inputStream, params IDisposable[] holders) { m_protocolUtility = new PqlProtocolUtility(connection, inputStream, holders); try { m_reader = inputStream.MyReader; m_scheme = m_protocolUtility.ReadResponseHeaders(inputStream); if (m_scheme.Fields != null && m_scheme.Fields.Length > 0) { m_currentRow = new RowData(m_scheme.Fields.Select(x => x.DataType).ToArray()); m_state = ReaderState.New; } else { m_state = ReaderState.Closed; } connection.SwitchToFetchingState(); } catch { m_protocolUtility.Dispose(); throw; } }
public static void DiscardValue(ReaderState reader, SerializedType?knownType = null) { var valueType = knownType ?? (SerializedType)reader.Read <byte>(); switch (valueType) { case SerializedType.CustomObject: DiscardValue(reader); // custom object ID while ((EnumerableType)reader.Read <byte>() == EnumerableType.HasItem) { reader.ReadString(); // key DiscardValue(reader); // value } break; case SerializedType.Object: while ((EnumerableType)reader.Read <byte>() == EnumerableType.HasItem) { reader.ReadString(); // key DiscardValue(reader); // value } break; case SerializedType.Dictionary: var kvpCount = reader.Read <int>(); for (var i = 0; i < kvpCount; i++) { DiscardValue(reader); // key DiscardValue(reader); // value } break; case SerializedType.List: var count = reader.Read <int>(); for (var i = 0; i < count; i++) { DiscardValue(reader); } break; case SerializedType.Enumerable: while ((EnumerableType)reader.Read <byte>() == EnumerableType.HasItem) { DiscardValue(reader); } break; case SerializedType.String: Reader.ReadString(reader); break; case SerializedType.Byte: Reader.ReadByte(reader); break; case SerializedType.SByte: Reader.ReadSByte(reader); break; case SerializedType.UShort: Reader.ReadUShort(reader); break; case SerializedType.Short: Reader.ReadShort(reader); break; case SerializedType.UInt: Reader.ReadUInt(reader); break; case SerializedType.Int: Reader.ReadInt(reader); break; case SerializedType.ULong: Reader.ReadULong(reader); break; case SerializedType.Long: Reader.ReadLong(reader); break; case SerializedType.Float: Reader.ReadFloat(reader); break; case SerializedType.Double: Reader.ReadDouble(reader); break; case SerializedType.Bool: Reader.ReadBool(reader); break; case SerializedType.Decimal: Reader.ReadDecimal(reader); break; case SerializedType.DateTime: Reader.ReadDateTime(reader); break; case SerializedType.Char: Reader.ReadChar(reader); break; case SerializedType.Null: break; default: throw new NotSupportedException($"SerializedType '{valueType}' is not supported"); } }
private static extern int SCardGetStatusChange(IntPtr context, uint timeout, ref ReaderState readerState, uint count);
/*^ #pragma warning disable 2674, 2666 ^*/ internal PEFileReader( PeReader moduleReadWriteFactory, IBinaryDocumentMemoryBlock binaryDocumentMemoryBlock ) { this.ErrorContainer = new MetadataErrorContainer(moduleReadWriteFactory, binaryDocumentMemoryBlock.BinaryDocument); this.ReaderState = ReaderState.Initialized; this.BinaryDocumentMemoryBlock = binaryDocumentMemoryBlock; if (!this.ReadPEFileLevelData()) return; if (!this.ReadCORModuleLevelData()) return; if (!this.ReadMetadataLevelData()) return; // TODO: Add phase for Metadata validation of offsets type row ids etc... }
bool ReadMetadataRoot() { var metadataRoot = new MemoryBlock(this.BinaryDocumentMemoryBlock.Pointer, (int)this.BinaryDocumentMemoryBlock.Length); MemoryReader memReader = new MemoryReader(metadataRoot); if ( !this.ReadMetadataHeader(ref memReader) || !this.ReadStorageHeader(ref memReader) || !this.ReadStreamHeaders(ref memReader) || !this.ProcessAndCacheStreams(ref metadataRoot) ) { return false; } this.ReaderState = ReaderState.CORModule; return true; }
/// <summary> /// Advances the <see cref="T:System.Data.IDataReader"/> to the next record. /// </summary> /// <returns> /// true if there are more rows; otherwise, false. /// </returns> /// <filterpriority>2</filterpriority> public override bool Read() { if (m_state != ReaderState.Closed) { try { m_state = m_currentRow.Read(m_reader) ? m_state = ReaderState.Fetching : ReaderState.Closed; } catch { // mark connection as bad, because RowData.Read only throws in case of network error or data corruption var conn = m_protocolUtility.Connection; if (conn != null) { conn.ConfirmExecutionCompletion(false); m_protocolUtility.Connection = null; } Close(); throw; } } return m_state == ReaderState.Fetching; }
void IMessageReader.Stop() { StopReading(); _state = ReaderState.Idle; }
public ParsedContent Read(Stream stream) { var res = new ParsedContent(); var bodies = new List<Element>(); var info = new AtomCollection(Channel.ChannelInfo.Extra); var processed = false; var eos = false; while (!eos) { var start_pos = stream.Position; try { var elt = Element.ReadHeader(stream); if (ebml.MaxIDLength <elt.ID.Length || ebml.MaxSizeLength<elt.Size.Length) { throw new BadDataException(); } switch (state) { case ReaderState.EBML: if (elt.ID.BinaryEquals(Elements.EBML)) { elt.ReadBody(stream); ebml = new EBML(elt); state = ReaderState.Segment; } else { throw new BadDataException(); } break; case ReaderState.Segment: if (elt.ID.BinaryEquals(Elements.Segment)) { segment = new Segment(elt); state = ReaderState.EndOfHeader; } else if (elt.ID.BinaryEquals(Elements.EBML)) { stream.Position = elt.Position; state = ReaderState.EBML; continue; } else if (elt.ID.BinaryEquals(Elements.Void) || elt.ID.BinaryEquals(Elements.CRC32)) { elt.ReadBody(stream); } else { throw new BadDataException(); } break; case ReaderState.EndOfHeader: if (elt.ID.BinaryEquals(Elements.Segment)) { stream.Position = elt.Position; state = ReaderState.Segment; continue; } else if (elt.ID.BinaryEquals(Elements.EBML)) { stream.Position = elt.Position; state = ReaderState.EBML; continue; } else if (elt.ID.BinaryEquals(Elements.Cluster)) { stream.Position = elt.Position; state = ReaderState.Cluster; clusters.Clear(); MemoryStream header; using (header=new MemoryStream()) { ebml.Element.Write(header); segment.Element.Write(header); foreach (var c in segment.HeaderElements) { c.Write(header); } } streamIndex = Channel.GenerateStreamID(); streamOrigin = DateTime.Now; res.ContentHeader = new Content(streamIndex, TimeSpan.Zero, 0, header.ToArray()); if (ebml.DocType=="webm") { info.SetChanInfoType("WEBM"); info.SetChanInfoStreamType("video/webm"); info.SetChanInfoStreamExt(".webm"); } else { info.SetChanInfoType("MKV"); info.SetChanInfoStreamType("video/x-matroska"); info.SetChanInfoStreamExt(".mkv"); } res.ChannelInfo = new ChannelInfo(info); } else { elt.ReadBody(stream); segment.AddHeader(elt); } break; case ReaderState.Cluster: if (elt.ID.BinaryEquals(Elements.Segment)) { stream.Position = elt.Position; state = ReaderState.Segment; continue; } else if (elt.ID.BinaryEquals(Elements.EBML)) { stream.Position = elt.Position; state = ReaderState.EBML; continue; } else if (elt.ID.BinaryEquals(Elements.Cluster)) { if (clusters.Count>0) { var timespan = clusters.Sum(c => c.Timespan); if (timespan>=30.0) { var sz = clusters.Sum(c => c.Timespan>0 ? c.BlockSize : 0); var kbps = (int)((sz*8/timespan+900) / 1000.0); info.SetChanInfoBitrate(kbps); res.ChannelInfo = new ChannelInfo(info); while (clusters.Count>1) clusters.RemoveFirst(); } } var cluster = new Cluster(elt); clusters.AddLast(cluster); bodies.Add(elt); state = ReaderState.Timecode; } else if (elt.ID.BinaryEquals(Elements.Void) || elt.ID.BinaryEquals(Elements.CRC32)) { elt.ReadBody(stream); bodies.Add(elt); } else { throw new BadDataException(); } break; case ReaderState.Timecode: if (elt.ID.BinaryEquals(Elements.Segment)) { stream.Position = elt.Position; state = ReaderState.Segment; continue; } else if (elt.ID.BinaryEquals(Elements.EBML)) { stream.Position = elt.Position; state = ReaderState.EBML; continue; } else if (elt.ID.BinaryEquals(Elements.Cluster)) { stream.Position = elt.Position; state = ReaderState.Cluster; continue; } else if (elt.ID.BinaryEquals(Elements.Timecode)) { elt.ReadBody(stream); if (clusters.Last!=null) { clusters.Last.Value.Timecode = Element.ReadUInt(new MemoryStream(elt.Data), elt.Data.Length)*(segment.TimecodeScale/1000000000.0); if (clusters.Count>1) { clusters.Last.Previous.Value.Timespan = clusters.Last.Value.Timecode - clusters.Last.Previous.Value.Timecode; } } bodies.Add(elt); state = ReaderState.Block; } else if (elt.ID.BinaryEquals(Elements.SimpleBlock) || elt.ID.BinaryEquals(Elements.BlockGroup)) { stream.Position = elt.Position; state = ReaderState.Block; continue; } else { elt.ReadBody(stream); bodies.Add(elt); } break; case ReaderState.Block: if (elt.ID.BinaryEquals(Elements.Segment)) { stream.Position = elt.Position; state = ReaderState.Segment; continue; } else if (elt.ID.BinaryEquals(Elements.EBML)) { stream.Position = elt.Position; state = ReaderState.EBML; continue; } else if (elt.ID.BinaryEquals(Elements.Cluster)) { stream.Position = elt.Position; state = ReaderState.Cluster; continue; } else if ((elt.ID.BinaryEquals(Elements.SimpleBlock) || elt.ID.BinaryEquals(Elements.BlockGroup)) && (clusters.Last.Value.BlockID==null || elt.ID.BinaryEquals(clusters.Last.Value.BlockID))) { elt.ReadBody(stream); clusters.Last.Value.BlockSize += elt.Size.Value; clusters.Last.Value.BlockID = elt.ID.Binary; bodies.Add(elt); } else if (clusters.Last.Value.BlockID==null) { elt.ReadBody(stream); bodies.Add(elt); } else { stream.Position = elt.Position; state = ReaderState.Cluster; continue; } break; } processed = true; } catch (EndOfStreamException) { if (!processed) throw; stream.Position = start_pos; eos = true; } catch (BadDataException) { stream.Position = start_pos+1; } } if (res.ContentHeader!=null) { position = res.ContentHeader.Position + res.ContentHeader.Data.Length; } if (bodies.Count>0) { res.Contents = new List<Content>(); foreach (var body in bodies) { MemoryStream s; using (s=new MemoryStream()) { body.Write(s); } var data = s.ToArray(); res.Contents.Add(new Content(streamIndex, DateTime.Now-streamOrigin, position, data)); position += data.Length; } } return res; }
public JsonReader(string json) { _json = json.ToCharArray(); _position = 0; _state = ReaderState.Begin; }
private void Validate() { var hasOpenBrace = false; foreach (var token in _json) { if (char.IsWhiteSpace(token)) continue; if (token == JsonChar.OpenBracket) { _state = ReaderState.Value; return; } if (hasOpenBrace) return; if (token == JsonChar.OpenBrace) { hasOpenBrace = true; _state = ReaderState.Property; } } throw new JsonBadFormat("Json contains invalid format."); }
private void ReadValue() { var start = ReadTo(JsonChar.Empty, char.IsWhiteSpace); var end = ReadTo(JsonChar.Empty, t => !IsCloser(t), true); var partialArray = _json.SubArray(start, end); Text = new string(partialArray); switch (Type) { case JsonType.Object: Value = JsonParser.ReadAsObject(partialArray); break; case JsonType.Array: Value = JsonParser.ReadAsArray(partialArray); break; case JsonType.String: Value = JsonParser.ReadAsString(partialArray); break; case JsonType.Number: Value = JsonParser.ReadAsNumber(partialArray); break; case JsonType.Boolean: Value = JsonParser.ReadAsBoolean(partialArray); break; default: Value = null; break; } _state = ReaderState.Begin; _position++; }
private int ReadTo(char value, Func<char, bool> next = null, bool trackEncapsulation = false) { var cap = new Stack<char>(); var complementryValue = GetComplement(value); var start = _position; for (; _position < _json.Length; _position++) { var token = _json[_position]; var previous = _position > 0 ? _json[_position - 1] : JsonChar.Empty; if (trackEncapsulation && complementryValue == JsonChar.Empty && IsOpener(token)) { value = token; complementryValue = GetComplement(value); if (value == complementryValue) continue; } if (trackEncapsulation && token == value && previous != JsonChar.Escape) cap.Push(token); if (next == null && token != value) continue; if (next != null && next(token)) continue; if (trackEncapsulation) { if ((complementryValue != JsonChar.Empty && token != complementryValue) || previous == JsonChar.Escape) continue; if (cap.Count > 0) cap.Pop(); if (cap.Count == 0) return _position; } else { return _position; } } if (_state == ReaderState.Property && value == JsonChar.DoubleQuote) { _state = ReaderState.End; } else { throw new JsonParseError(string.Format("ReadTo could not find value ({0}) started at ({1}).", value, start)); } return -1; }
private void ReadProperty() { var start = ReadTo(JsonChar.DoubleQuote); if (start == -1) return; var end = ReadTo(JsonChar.PropertySeparator); Property = JsonParser.ReadAsString(_json.SubArray(start, end)); _state = ReaderState.Value; _position++; }
public ParsedContent Read(Stream stream) { var res = new ParsedContent(); var info = new AtomCollection(Channel.ChannelInfo.Extra); var processed = false; var eos = false; while (!eos) { var start_pos = stream.Position; try { switch (state) { case ReaderState.Header: { var bin = ReadBytes(stream, 13); var header = new FileHeader(bin); if (header.IsValid) { Logger.Info("FLV Header found"); fileHeader = header; bin = header.Binary; res.ContentHeader = new Content(position, bin); res.Contents = null; info.SetChanInfoType("FLV"); info.SetChanInfoStreamType("video/x-flv"); info.SetChanInfoStreamExt(".flv"); res.ChannelInfo = new ChannelInfo(info); position = bin.Length; tags.Clear(); state = ReaderState.Body; } else { throw new BadDataException(); } } break; case ReaderState.Body: { var bin = ReadBytes(stream, 11); var read_valid = false; var body = new FLVTag(bin); if (body.IsValidHeader) { body.ReadBody(stream); body.ReadFooter(stream); if (body.IsValidFooter) { read_valid = true; bin = body.Binary; if (res.Contents==null) res.Contents = new List<Content>(); res.Contents.Add(new Content(position, bin)); tags.AddLast(new TagDesc { Timestamp=body.Timestamp/1000.0, DataSize=body.DataSize }); var timespan = tags.Last.Value.Timestamp-tags.First.Value.Timestamp; if (timespan>=30.0) { var sz = tags.Take(tags.Count-1).Sum(t => t.DataSize); info.SetChanInfoBitrate((int)(sz*8/timespan+900)/1000); res.ChannelInfo = new ChannelInfo(info); while (tags.Count>1) tags.RemoveFirst(); } position += bin.Length; } } if (!read_valid) { stream.Position = start_pos; var header = new FileHeader(ReadBytes(stream, 13)); if (header.IsValid) { Logger.Info("New FLV Header found"); read_valid = true; fileHeader = header; bin = header.Binary; res.ContentHeader = new Content(0, bin); res.Contents = null; info.SetChanInfoType("FLV"); info.SetChanInfoStreamType("video/x-flv"); info.SetChanInfoStreamExt(".flv"); res.ChannelInfo = new ChannelInfo(info); tags.Clear(); position = bin.Length; } } if (!read_valid) throw new BadDataException(); } break; } processed = true; } catch (EndOfStreamException) { if (!processed) throw; stream.Position = start_pos; eos = true; } catch (BadDataException) { stream.Position = start_pos+1; } } return res; }
public int ReadClearText(Span <byte> buffer) { if (State != ReaderState.ClearText) { throw new InvalidOperationException(); } // We usually try to output one character for one input character // but new line and dash sequences can produce up to 4 characters // at once, so size the buffer to accommodate that. We can also // overshoot the buffer with pending whitespace. var outputBuffer = new ArrayBufferWriter <byte>(buffer.Length + 3); if (pendingData != null) { outputBuffer.Write(pendingData); } while (!endOfClearText && outputBuffer.WrittenCount < buffer.Length) { var b = innerStream.ReadByte(); // End of stream if (b == -1) { break; } switch (b) { case ' ': case '\t': // Collect pending whitespace because it could be trailing whitespace // at end of line pendingWhitespace.GetSpan(1)[0] = (byte)b; pendingWhitespace.Advance(1); break; case '\r': case '\n': // Ignore \n that was still part of header if (ignoreNL && b == '\n') { ignoreNL = false; break; } // Discard any pending whitespace pendingWhitespace.Clear(); // Read next character after the new line var nextB = innerStream.ReadByte(); if (b == '\r' && nextB == '\n') { nextB = innerStream.ReadByte(); } if (nextB == '-') { // New line followed byt dash. Now we are looking either at the end of // clear text or a dash escape nextB = innerStream.ReadByte(); if (nextB == ' ') { // Dash escape, remove it and flush the new line outputBuffer.Write(new[] { (byte)'\r', (byte)'\n' }); } else if (nextB == '-') { // Possible end of clear text endOfClearText = true; break; } else { // Invalid clear text, flush the new lind and output it var clearText = outputBuffer.GetSpan(4); clearText[0] = (byte)'\r'; clearText[1] = (byte)'\n'; clearText[2] = (byte)'-'; clearText[3] = (byte)nextB; outputBuffer.Advance(4); } } else { // Flush the new line outputBuffer.Write(new[] { (byte)'\r', (byte)'\n' }); if (nextB == '\r' || nextB == '\n') { b = nextB; goto case '\r'; } else if (nextB == ' ' || nextB == '\t') { pendingWhitespace.GetSpan(1)[0] = (byte)nextB; pendingWhitespace.Advance(1); } else { outputBuffer.GetSpan(1)[0] = (byte)nextB; outputBuffer.Advance(1); } } break; default: // Flush any pending whitespace if (pendingWhitespace.WrittenCount > 0) { outputBuffer.Write(pendingWhitespace.WrittenSpan); pendingWhitespace.Clear(); } outputBuffer.GetSpan(1)[0] = (byte)b; outputBuffer.Advance(1); break; } } if (outputBuffer.WrittenCount > buffer.Length) { pendingData = outputBuffer.WrittenSpan.Slice(buffer.Length).ToArray(); outputBuffer.WrittenSpan.Slice(0, buffer.Length).CopyTo(buffer); return(buffer.Length); } else { if (endOfClearText) { State = ReaderState.Headers; } pendingData = null; outputBuffer.WrittenSpan.CopyTo(buffer); return(outputBuffer.WrittenCount); } }
internal ReaderStateChanged(IReader reader, ReaderState readerState) { Reader = reader; ReaderState = readerState; }
private DeviceState ReaderStatusToCardStatus(ReaderState state) { if ((state & ReaderState.SCARD_STATE_EMPTY) == ReaderState.SCARD_STATE_EMPTY) return DeviceState.Missing; if ((state & (ReaderState.SCARD_STATE_PRESENT | ReaderState.SCARD_STATE_INUSE | ReaderState.SCARD_STATE_MUTE)) == ReaderState.SCARD_STATE_PRESENT) return DeviceState.Present; if ((state & ReaderState.SCARD_STATE_INUSE) == ReaderState.SCARD_STATE_INUSE) return DeviceState.InUse; if ((state & ReaderState.SCARD_STATE_MUTE) == ReaderState.SCARD_STATE_MUTE) return DeviceState.Mute; return DeviceState.Unknown; }
/// <summary> /// Reads the <see cref="T:PListNet.PNode"/> at the specified idx. /// </summary> /// <param name="readerState">Reader state.</param> /// <param name="elemIdx">The elem idx.</param> /// <returns>The <see cref="T:PListNet.PNode"/> at the specified idx.</returns> private PNode ReadInternal(ReaderState readerState, int elemIdx) { readerState.Stream.Seek(readerState.NodeOffsets[elemIdx], SeekOrigin.Begin); return(ReadInternal(readerState)); }
private void ReadInDictionary(IDictionary <string, PNode> node, int nodeLength, ReaderState readerState) { var bufKeys = new byte[nodeLength * readerState.ObjectRefSize]; var bufVals = new byte[nodeLength * readerState.ObjectRefSize]; if (readerState.Stream.Read(bufKeys, 0, bufKeys.Length) != bufKeys.Length) { throw new PListFormatException(); } if (readerState.Stream.Read(bufVals, 0, bufVals.Length) != bufVals.Length) { throw new PListFormatException(); } for (var i = 0; i < nodeLength; i++) { var topNode = GetNodeOffset(readerState, bufKeys, i); var plKey = ReadInternal(readerState, topNode); var stringKey = plKey as StringNode; if (stringKey == null) { throw new PListFormatException("Key is not a string"); } topNode = GetNodeOffset(readerState, bufVals, i); var plVal = ReadInternal(readerState, topNode); node.Add(stringKey.Value, plVal); } }
void IMessageReader.Resume() { ResumeReading(); _state = ReaderState.Reading; }
public ParsedContent Read(Stream stream) { var processed = false; var eos = false; while (!eos) { var start_pos = stream.Position; try { switch (state) { case ReaderState.Header: { var bin = ReadBytes(stream, 13); var header = new FileHeader(bin); if (header.IsValid) { Logger.Info("FLV Header found"); contentBuffer.OnStart(); state = ReaderState.Body; } else { throw new BadDataException(); } } break; case ReaderState.Body: { var bin = ReadBytes(stream, 11); var read_valid = false; var body = new FLVTag(bin); if (body.IsValidHeader) { body.ReadBody(stream); body.ReadFooter(stream); if (body.IsValidFooter) { read_valid = true; switch (body.Type) { case FLVTag.TagType.Audio: contentBuffer.OnAudio(body.ToRTMPMessage()); break; case FLVTag.TagType.Video: contentBuffer.OnVideo(body.ToRTMPMessage()); break; case FLVTag.TagType.Script: contentBuffer.OnData(new RTMP.DataAMF0Message(body.ToRTMPMessage())); break; } } } if (!read_valid) { stream.Position = start_pos; var header = new FileHeader(ReadBytes(stream, 13)); if (header.IsValid) { Logger.Info("New FLV Header found"); read_valid = true; contentBuffer.OnStart(); } } if (!read_valid) { throw new BadDataException(); } } break; } processed = true; } catch (EndOfStreamException) { if (!processed) { throw; } stream.Position = start_pos; eos = true; } catch (BadDataException) { stream.Position = start_pos + 1; } } return(contentBuffer.GetContents()); }
public void MultipleWriterTest() { const int WRITERS = 5; const int READERS = 5; const int writes = 10000; ArrayList written_list = new ArrayList(); ArrayList read_list = new ArrayList(); ArrayList write_threads = new ArrayList(); ArrayList read_threads = new ArrayList(); BlockingQueue q = new BlockingQueue(); /* Start the writers */ for( int i = 0; i < WRITERS; i++ ) { WriterState ws = new WriterState(q, written_list, writes); Thread t = new Thread( ws.Start ); write_threads.Add( t ); t.Start(); } /* Start the readers */ for( int i = 0; i < READERS; i++) { ReaderState rs = new ReaderState(q, read_list); Thread t = new Thread( rs.Start ); read_threads.Add( t ); t.Start(); } foreach(Thread t in write_threads) { t.Join(); } //Writing is done, close the queue, and join the readers: q.Close(); foreach(Thread t in read_threads) { t.Join(); } //Check that the reader list is the same as the written list: ArrayList read_copy = new ArrayList(read_list); ArrayList write_copy = new ArrayList(written_list); //Remove all the reads from the written copy: foreach(object o in read_list) { int i = write_copy.IndexOf(o); Assert.IsTrue( i >= 0, "read something not in written"); write_copy.RemoveAt(i); } Assert.IsTrue( write_copy.Count == 0, "More written than read"); //Remove all the writes from the read copy: foreach(object o in written_list) { int i = read_copy.IndexOf(o); Assert.IsTrue( i >= 0, "wrote something not in read"); read_copy.RemoveAt(i); } Assert.IsTrue( read_copy.Count == 0, "More written than read"); }
public static void Populate <T>(T obj, ReaderState reader) => ObjectReaders.Populate <T>(reader, obj);
public override bool Read() { if(null == Results || (_readerState & (ReaderState.HasRows | ReaderState.Eof)) != ReaderState.HasRows) return false; bool firstRead = false; try { if ((_readerState & ReaderState.FirstRed) != 0) { firstRead = true; _readerState &= ~ReaderState.FirstRed; return true; } else { bool next = Results.next(); if (!next) _readerState |= ReaderState.Eof; return next; } } catch (SQLException exp) { // suppress exception as .Net does return false; } finally { // in case of first read we could sampled the first value // to see whether there is a resultset, so _currentCacheFilledPosition // might be already inited if (!firstRead) _currentCacheFilledPosition = -1; } }
public static object ReadValue <T>(ReaderState reader) { var valueType = Reader.ReadSerializedType(reader); return(ReadValue <T>(reader, valueType)); }
bool ReadCORModuleLevelData() //^ requires this.ReaderState >= ReaderState.PEFile; { if (!this.ReadCOR20Header()) { return false; } MemoryBlock metadataRoot = this.DirectoryToMemoryBlock(this.COR20Header.MetaDataDirectory); if (metadataRoot.Length < this.COR20Header.MetaDataDirectory.Size) { this.ErrorContainer.AddDirectoryError(Directories.Cor20HeaderMetaData, 0, MetadataReaderErrorKind.NotEnoughSpaceForMetadataDirectory); return false; } MemoryReader memReader = new MemoryReader(metadataRoot); if ( !this.ReadMetadataHeader(ref memReader) || !this.ReadStorageHeader(ref memReader) || !this.ReadStreamHeaders(ref memReader) || !this.ProcessAndCacheStreams(ref metadataRoot) ) { return false; } this.ReaderState = ReaderState.CORModule; this.ResourceMemoryReader = new MemoryReader(this.DirectoryToMemoryBlock(this.COR20Header.ResourcesDirectory)); this.StrongNameSignature = this.DirectoryToMemoryBlock(this.COR20Header.StrongNameSignatureDirectory); return true; }
public bool Read(Stream stream, IRTMPContentSink sink) { var processed = false; var eos = false; while (!eos) { retry: var start_pos = stream.Position; try { switch (state) { case ReaderState.Header: { var bin = ReadBytes(stream, 13, out eos); if (eos) goto error; var header = new FileHeader(bin); if (header.IsValid) { sink.OnFLVHeader(); state = ReaderState.Body; } else { throw new BadDataException(); } } break; case ReaderState.Body: { var bin = ReadBytes(stream, 11, out eos); if (eos) goto error; var read_valid = false; var body = new FLVTag(this, bin); if (body.IsValidHeader) { if (!body.ReadBody(stream)) { eos = true; goto error; } if (!body.ReadFooter(stream)) { eos = true; goto error; } if (body.IsValidFooter) { read_valid = true; switch (body.Type) { case FLVTag.TagType.Audio: sink.OnAudio(body.ToRTMPMessage()); break; case FLVTag.TagType.Video: sink.OnVideo(body.ToRTMPMessage()); break; case FLVTag.TagType.Script: sink.OnData(new DataAMF0Message(body.ToRTMPMessage())); break; } } } else { stream.Position = start_pos; var headerbin = ReadBytes(stream, 13, out eos); if (eos) goto error; var header = new FileHeader(headerbin); if (header.IsValid) { read_valid = true; sink.OnFLVHeader(); } } if (!read_valid) { stream.Position = start_pos+1; var b = stream.ReadByte(); while (true) { if (b<0) { eos = true; goto error; } if ((b & 0xC0)==0 && ((b & 0x1F)==8 || (b & 0x1F)==9 || (b & 0x1F)==18)) { break; } b = stream.ReadByte(); } stream.Position = stream.Position-1; goto retry; } } break; } processed = true; } catch (EndOfStreamException) { stream.Position = start_pos; eos = true; } catch (BadDataException) { stream.Position = start_pos+1; } error: if (eos) { stream.Position = start_pos; eos = true; } } return processed; }
public static object ReadValue <T>(ReaderState reader, SerializedType valueType) => GetValueReader <T> .Reader.Read(reader, valueType);
private bool ParseUriOrCommentMarker() { ShiftBuffer(); InitializeToken(); while (true) { switch (_buffer[_cursor]) { case '\0' when IsEndOfBufferedData(): if (IsEndOfFile()) { return ParseEndOfFile(); } else continue; case '\r' when IsCrLf(): case '\n': return ParseEndOfLine(); case '#': return parseCommentMarker(); default: return parseUri(); } } bool parseUri() { while (true) { switch (_buffer[_cursor]) { case '\0' when IsEndOfBufferedData(): if (IsEndOfFile()) { SetToken(PlaylistTokenType.Uri); _state = ReaderState.EndOfFile; return true; } else continue; case '\r' when IsCrLf(): case '\n': SetToken(PlaylistTokenType.Uri); _state = ReaderState.EndOfLine; return true; default: _cursor++; continue; } } } bool parseCommentMarker() { Debug.Assert(_buffer[_cursor] == '#'); _cursor++; SetToken(PlaylistTokenType.CommentMarker); _state = ReaderState.CommentOrTagName; return _verbose; } }
public string[] ReadHeaderLines() { if (State != ReaderState.Headers) { throw new InvalidOperationException(); } List <string> lines = new List <string>(); var outputBuffer = new ArrayBufferWriter <byte>(); if (endOfClearText) { // If we were reading clear text before then we consumed // the first two dashes of the separator. outputBuffer.Write(new[] { (byte)'-', (byte)'-' }); } for (; ;) { var b = innerStream.ReadByte(); switch (b) { case -1: return(Array.Empty <string>()); case '\n': if (!ignoreNL) { goto case '\r'; } ignoreNL = false; break; case '\r': ignoreNL = b == '\r'; // Non-empty line string?line = null; if (outputBuffer.WrittenCount > 0) { line = Encoding.ASCII.GetString(outputBuffer.WrittenSpan); outputBuffer.Clear(); } if (!string.IsNullOrWhiteSpace(line)) { lines.Add(line); } else if (lines.Count > 0) { // TODO: Verify the headers headerEndLineLength = lines.First().Length - 2; // -2 for BEGIN -> END State = !endOfClearText && Equals(lines.FirstOrDefault(), "-----BEGIN PGP SIGNED MESSAGE-----") ? ReaderState.ClearText : ReaderState.Base64; return(lines.ToArray()); } break; default: outputBuffer.GetSpan(1)[0] = (byte)b; outputBuffer.Advance(1); break; } } }
private bool ParseCommentOrTagName() { ShiftBuffer(); InitializeToken(); if (HasLookahead(2) && _buffer[_cursor] == 'E' && _buffer[_cursor + 1] == 'X' && _buffer[_cursor + 2] == 'T') // parse tag name { _cursor += 3; while (true) { switch (_buffer[_cursor]) { case '\0' when IsEndOfBufferedData(): if (IsEndOfFile()) { SetToken(PlaylistTokenType.TagName); _state = ReaderState.EndOfFile; return true; } else continue; case '\r' when IsCrLf(): case '\n': SetToken(PlaylistTokenType.TagName); _state = ReaderState.EndOfLine; return true; case ':': SetToken(PlaylistTokenType.TagName); _state = ReaderState.TagNameValueSeparator; return true; default: _cursor++; continue; } } } else // parse comment { while (true) { switch (_buffer[_cursor]) { case '\0' when IsEndOfBufferedData(): if (IsEndOfFile()) { SetToken(PlaylistTokenType.Comment); _state = ReaderState.EndOfFile; return true; } else continue; case '\r' when IsCrLf(): case '\n': SetToken(PlaylistTokenType.Comment); _state = ReaderState.EndOfLine; return true; default: _cursor++; continue; } } } }
public int ReadArmoredData(Span <byte> buffer) { int totalWritten = 0; if (State != ReaderState.Base64) { throw new InvalidOperationException(); } if (pendingData != null) { totalWritten = Math.Min(buffer.Length, pendingData.Length); pendingData.AsSpan(0, totalWritten).CopyTo(buffer); pendingData = totalWritten == pendingData.Length ? null : pendingData.AsSpan(totalWritten).ToArray(); buffer = buffer.Slice(totalWritten); } if (buffer.Length > 0) { Span <byte> base64Data = new byte[((buffer.Length + 2) / 3) * 4]; int base64Pos = 0; while (base64Pos < base64Data.Length) { var b = innerStream.ReadByte(); if (b == -1) { State = ReaderState.EndOfArmor; // Invalid break; } if (b == '\r' || b == '\n') { var nextB = innerStream.ReadByte(); while (nextB == '\n' || nextB == '\r') { nextB = innerStream.ReadByte(); } // We reached the CRC if (nextB == '=') { State = ReaderState.CRC; break; } b = nextB; } if ((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '+' || b == '/' || b == '=') { base64Data[base64Pos++] = (byte)b; } } // TODO: Should we pad the data if the padding is missing? var status = Base64.DecodeFromUtf8InPlace(base64Data.Slice(0, base64Pos), out var bytesWritten); Debug.Assert(status == OperationStatus.Done); Debug.Assert(((bytesWritten + 2) / 3) * 4 == base64Pos); if (bytesWritten > buffer.Length) { pendingData = base64Data.Slice(buffer.Length, bytesWritten - buffer.Length).ToArray(); base64Data.Slice(0, buffer.Length).CopyTo(buffer); totalWritten += buffer.Length; } else { pendingData = null; base64Data.Slice(0, bytesWritten).CopyTo(buffer); totalWritten += bytesWritten; } } return(totalWritten); }
/// <summary> /// Wait for the state to change from a specific state. /// </summary> /// <returns> /// The current state. /// </returns> /// <remarks> /// If the state change to a final state, then all awaiting tasks will complete. /// </remarks> public static async ValueTask <ReaderStateChanged> StateChangedFrom(this IReader reader, ReaderState state, CancellationToken cancellationToken = default) { var newState = await reader.OnStateChangeFrom(state, cancellationToken).ConfigureAwait(false); return(new ReaderStateChanged(reader, newState)); }
protected override void Setup() { base.Setup(); this.state = ReaderState.DescriptionView; }
private void ReadInDictionary(IDictionary <string, PNode> node, int nodeLength, ReaderState readerState) { var bufKeys = new byte[nodeLength * readerState.IndexSize]; var bufVals = new byte[nodeLength * readerState.IndexSize]; if (readerState.Stream.Read(bufKeys, 0, bufKeys.Length) != bufKeys.Length) { throw new PListFormatException(); } if (readerState.Stream.Read(bufVals, 0, bufVals.Length) != bufVals.Length) { throw new PListFormatException(); } for (int i = 0; i < nodeLength; i++) { var topNode = readerState.IndexSize == 1 ? bufKeys[i] : EndianConverter.NetworkToHostOrder(BitConverter.ToInt16(bufKeys, 2 * i)); var plKey = ReadInternal(readerState, topNode); var stringKey = plKey as StringNode; if (stringKey == null) { throw new PListFormatException("Key is not a string"); } topNode = readerState.IndexSize == 1 ? bufVals[i] : EndianConverter.NetworkToHostOrder(BitConverter.ToInt16(bufVals, 2 * i)); var plVal = ReadInternal(readerState, topNode); node.Add(stringKey.Value, plVal); } }
public ParsedContent Read(Stream stream) { var processed = false; var eos = false; while (!eos) { var start_pos = stream.Position; try { switch (state) { case ReaderState.Header: { var bin = ReadBytes(stream, 13); var header = new FileHeader(bin); if (header.IsValid) { Logger.Info("FLV Header found"); contentBuffer.OnStart(); state = ReaderState.Body; } else { throw new BadDataException(); } } break; case ReaderState.Body: { var bin = ReadBytes(stream, 11); var read_valid = false; var body = new FLVTag(bin); if (body.IsValidHeader) { body.ReadBody(stream); body.ReadFooter(stream); if (body.IsValidFooter) { read_valid = true; switch (body.Type) { case FLVTag.TagType.Audio: contentBuffer.OnAudio(body.ToRTMPMessage()); break; case FLVTag.TagType.Video: contentBuffer.OnVideo(body.ToRTMPMessage()); break; case FLVTag.TagType.Script: contentBuffer.OnData(new RTMP.DataAMF0Message(body.ToRTMPMessage())); break; } } } if (!read_valid) { stream.Position = start_pos; var header = new FileHeader(ReadBytes(stream, 13)); if (header.IsValid) { Logger.Info("New FLV Header found"); read_valid = true; contentBuffer.OnStart(); } } if (!read_valid) throw new BadDataException(); } break; } processed = true; } catch (EndOfStreamException) { if (!processed) throw; stream.Position = start_pos; eos = true; } catch (BadDataException) { stream.Position = start_pos+1; } } return contentBuffer.GetContents(); }
void IMessageReader.Start(Filters filters) { Reset(); StartReading(filters); _state = ReaderState.Reading; }
private bool TransitionTo(ReaderState targetState) { return(TransitionTo(targetState, true)); }
void IMessageReader.Pause() { PauseReading(); _state = ReaderState.Paused; }
private bool TransitionTo(ReaderState targetState, bool result) { state = targetState; return(result); }
public static object ReadDictionary <T>(ReaderState reader) => GetDictionaryReader <T> .Reader.Read(reader);
public static object ReadEnumerable <T>(ReaderState reader) => GetEnumerableReader <T> .Reader.Read(reader);
/// <summary> /// Releases the managed resources used by the <see cref="T:System.Data.Common.DbDataReader"/> and optionally releases the unmanaged resources. /// </summary> /// <param name="disposing">true to release managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { m_state = ReaderState.Closed; if (m_protocolUtility != null) { var conn = m_protocolUtility.Connection; try { m_protocolUtility.Dispose(); } finally { if (conn != null && CloseConnection) { conn.Close(); } } } }
public static object ReadList <T>(ReaderState reader) => GetListReader <T> .Reader.Read(reader);
internal PEFileReader(PeReader moduleReadWriteFactory, IBinaryDocumentMemoryBlock binaryDocumentMemoryBlock, bool snapshot = false) { this.ErrorContainer = new MetadataErrorContainer(moduleReadWriteFactory, binaryDocumentMemoryBlock.BinaryDocument); this.ReaderState = ReaderState.Initialized; this.BinaryDocumentMemoryBlock = binaryDocumentMemoryBlock; if (!snapshot) { if (!this.ReadPEFileLevelData()) return; if (!this.ReadCORModuleLevelData()) return; } else { this.SectionHeaders = new SectionHeader[0]; if (!this.ReadMetadataRoot()) return; } if (!this.ReadMetadataLevelData()) return; // TODO: Add phase for Metadata validation of offsets type row ids etc... }
public object Read(ReaderState reader) => GenericReader.ReadObjectAsDictionary(reader, type, elementType);
private bool CloseCurrentResultSet() { if (_resultSetStack.Count > 0) { try{ _resultsMetaData = null; _readerCache = null; _readerState = ReaderState.Uninitialized; ResultSet rs = (ResultSet)_resultSetStack.Pop(); rs.close(); return true; } catch (SQLException exp) { throw CreateException(exp); } } return false; }
public object Read(ReaderState reader) => Deserializer.ReadObject(reader);
public bool Read(char symbol) { var currentState = _readerState; switch (_readerState) { #region starting case ReaderState.EntryStart: if (symbol == '{') _readerState = ReaderState.KeyStart; break; case ReaderState.KeyStart: if (symbol == '"') _readerState = ReaderState.KeyRead; break; case ReaderState.ValueStart: if (symbol == '"') _readerState = ReaderState.ValueRead; break; #endregion #region reading case ReaderState.KeyRead: switch(symbol) { case '"': _readerState = ReaderState.KeyEnd; break; case '\\': _readerState = ReaderState.KeySpecialChar; _buffer.Append(symbol); break; default: _buffer.Append(symbol); break; } break; case ReaderState.ValueRead: switch (symbol) { case '"': _readerState = ReaderState.ValueEnd; break; case '\\': _readerState = ReaderState.ValueSpecialChar; _buffer.Append(symbol); break; default: _buffer.Append(symbol); break; } break; case ReaderState.KeySpecialChar: _readerState = ReaderState.KeyRead; _buffer.Append(symbol); break; case ReaderState.ValueSpecialChar: _readerState = ReaderState.ValueRead; _buffer.Append(symbol); break; #endregion #region ending case ReaderState.EntryEnd: if (symbol == ',') _readerState = ReaderState.EntryStart; break; case ReaderState.KeyEnd: if (symbol == ':') _readerState = ReaderState.ValueStart; break; case ReaderState.ValueEnd: if (symbol == ',') _readerState = ReaderState.KeyStart; if (symbol == '}') _readerState = ReaderState.EntryEnd; break; #endregion } if (_readerState == ReaderState.KeyEnd) { _currentKey.Append(_buffer.ToString()); _buffer.Length = 0; } if (_readerState == ReaderState.ValueEnd) { _currentValue.Append(_buffer.ToString()); _buffer.Length = 0; _currentEntry.Add(_currentKey.ToString(), _currentValue.ToString()); _currentKey.Length = 0; _currentValue.Length = 0; } if (_readerState == ReaderState.EntryEnd && currentState != _readerState) // only if changed { _entries.Push(_currentEntry); _currentEntry = new NameValueCollection(); return true; } return false; }
public static object ReadObject <T>(ReaderState reader) => GetObjectReaderGeneric <T> .Reader.Read(reader);
bool ReadPEFileLevelData() //^ requires this.ReaderState >= ReaderState.Initialized; { MemoryReader memReader = new MemoryReader(this.BinaryDocumentMemoryBlock.Pointer, this.BinaryDocumentMemoryBlock.Length); if (memReader.RemainingBytes < PEFileConstants.BasicPEHeaderSize) { this.ErrorContainer.AddBinaryError(0, MetadataReaderErrorKind.FileSizeTooSmall); return false; } // Look for DOS Signature "MZ" ushort dosSig = memReader.PeekUInt16(0); if (dosSig != PEFileConstants.DosSignature) { this.ErrorContainer.AddBinaryError(0, MetadataReaderErrorKind.DosHeader); return false; } // Skip the DOS Header int ntHeaderOffset = memReader.PeekInt32(PEFileConstants.PESignatureOffsetLocation); if (!memReader.SeekOffset(ntHeaderOffset)) { this.ErrorContainer.AddBinaryError(memReader.Offset, MetadataReaderErrorKind.FileSizeTooSmall); return false; } // Look for PESignature "PE\0\0" uint NTSignature = memReader.ReadUInt32(); if (NTSignature != PEFileConstants.PESignature) { this.ErrorContainer.AddBinaryError(memReader.Offset - sizeof(uint), MetadataReaderErrorKind.PESignature); return false; } // Read the COFF Header if (!this.ReadCOFFFileHeader(ref memReader)) { return false; } // Read the magic to determine if its PE or PE+ PEMagic magic = (PEMagic)memReader.PeekUInt16(0); switch (magic) { case PEMagic.PEMagic32: if ( !this.ReadOptionalHeaderStandardFields32(ref memReader) || !this.ReadOptionalHeaderNTAdditionalFields32(ref memReader) ) { return false; } break; case PEMagic.PEMagic64: if ( !this.ReadOptionalHeaderStandardFields64(ref memReader) || !this.ReadOptionalHeaderNTAdditionalFields64(ref memReader) ) { return false; } break; default: this.ErrorContainer.AddBinaryError(memReader.Offset, MetadataReaderErrorKind.UnknownPEMagic); return false; } if (!this.ReadOptionalHeaderDirectoryEntries(ref memReader)) { return false; } if (!this.ReadSectionHeaders(ref memReader)) { return false; } this.ReaderState = ReaderState.PEFile; this.Win32ResourceMemoryReader = new MemoryReader(this.DirectoryToMemoryBlock(this.OptionalHeaderDirectoryEntries.ResourceTableDirectory)); return true; }
public static object ReadValue <T>(ReaderState reader) { var valueType = (SerializedType)reader.Read <byte>(); return(ReadValue <T>(reader, valueType)); }
bool ReadMetadataLevelData() //^ requires this.ReaderState >= ReaderState.CORModule; { MemoryReader memReader = new MemoryReader(this.MetadataTableStream); if ( !this.ReadMetadataTableInformation(ref memReader) || !this.ProcessAndCacheMetadataTableBlocks(memReader.RemainingMemoryBlock) ) { return false; } if (this.ModuleTable.NumberOfRows != 1) return false; this.ReaderState = ReaderState.Metadata; return true; }
public void WaitForStatusChange(string reader, SmartCardState currentState, SmartCardState newState, long timeout) { if ((timeout < 0) || (timeout > uint.MaxValue)) throw new ArgumentOutOfRangeException("timeout must be a 32-bit unsigned integer value"); ReaderState readerState = new ReaderState(); readerState.Reader = reader; readerState.UserData = IntPtr.Zero; readerState.CurrentState = currentState; readerState.EventState = newState; readerState.AtrLength = 0; int ret = SCardGetStatusChange(context, (uint)timeout, ref readerState, 1); if (ret != 0) throw ToException(ret); }