protected int ReadByteAfterWhitespace(Stream s) { int buff = s.ReadByte(); while (buff >= 0 && IsWhitespace(buff)) buff = s.ReadByte(); return buff; }
public static bool ReadBoolean(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } int b = stream.ReadByte(); if (b == 0xf4) { return false; } if (b == 0xf5) { return true; } while ((b >> 5) == 6) { // Skip tags until a tag character is no longer read if (b == 0xd8) { stream.ReadByte(); } else if (b == 0xd9) { stream.Position += 2; } else if (b == 0xda) { stream.Position += 4; } else if (b == 0xdb) { stream.Position += 8; } else if (b > 0xdb) { throw new IOException("Not a boolean"); } b = stream.ReadByte(); } if (b == 0xf4) { return false; } if (b == 0xf5) { return true; } throw new IOException("Not a boolean"); }
public void load(Stream stream) { int data = stream.ReadByte(); if (data <= 0) { _blocks = null; return; } int offsetX = _x * 16; int offsetY = _y * 16; int offsetZ = _z * 16; for (int z = 0; z < 16; ++z) { for (int y = 0; y < 16; ++y) { for (int x = 0; x < 16; ++x) { data = stream.ReadByte(); if (data < 0) { return; } Block block = new Block(x + offsetX, y + offsetY, offsetZ + z, 0); _blocks[x, y, z] = block; } } } }
public static long Find(string token, Stream fileStream) { while (fileStream.Length != fileStream.Position) { if (Compare(token[0], fileStream.ReadByte())) { var location = fileStream.Position - 1; bool fail = false; for (var index = 1; index <= token.Length - 1; index++) { if (!Compare(token[index], fileStream.ReadByte())) { fail = true; break; } } if (!fail) { return location; } } } return -1L; }
public override ScalarValue Decode(Stream inStream) { long value = 0; uint byt; try { byt = (uint) inStream.ReadByte(); if ((byt & 0x40) > 0) { value = - 1; } value = (value << 7) | (byt & 0x7f); while ((byt & StopBit) == 0) { byt = (uint) inStream.ReadByte(); value = (value << 7) | (byt & 0x7f); } } catch (IOException e) { throw new RuntimeException(e); } return CreateValue(value); }
// Copy from DataHelper class in I2P public static long ReadLong(Stream rawStream, int numBytes) { if (numBytes > 8) throw new ArgumentOutOfRangeException( "readLong doesn't currently support reading numbers > 8 bytes [as thats bigger than java's long]"); long rv = 0; for (int i = 0; i < numBytes; i++) { int cur = rawStream.ReadByte(); // was DataFormatException if (cur == -1) throw new EndOfStreamException("EOF reading " + numBytes + " byte value"); // we loop until we find a nonzero byte (or we reach the end) if (cur != 0) { // ok, data found, now iterate through it to fill the rv rv = cur & 0xff; for (int j = i + 1; j < numBytes; j++) { rv <<= 8; cur = rawStream.ReadByte(); // was DataFormatException if (cur == -1) throw new EndOfStreamException("EOF reading " + numBytes + " byte value"); rv |= cur & 0xff; } break; } } if (rv < 0) throw new InvalidOperationException("wtf, fromLong got a negative? " + rv + " numBytes=" + numBytes); return rv; }
/// <summary> /// Determines whether this instance can read palette from data the specified stream. /// </summary> /// <param name="stream">The stream.</param> /// <returns><c>true</c> if this instance can read palette data from the specified stream; otherwise, <c>false</c>.</returns> public override bool CanReadFrom(Stream stream) { bool result; if (stream == null) { throw new ArgumentNullException(nameof(stream)); } try { int version; // read the version, which occupies two bytes // first byte is 0, the second 1 so I assume this is added to make 1 //version = this.ReadShort(stream); version = stream.ReadByte() + stream.ReadByte(); result = (version == 1 || version == 2); } catch { result = false; } return result; }
public static byte[] ExtendFind(Stream stream, Func<byte, bool> check) { int currentByte; long leftPos = stream.Position; // left while ((currentByte = stream.ReadByte ()) >= 0 && check ((byte)currentByte)) { leftPos = stream.Position - 1; stream.Position = leftPos - 1; } // right while ((currentByte = stream.ReadByte ()) >= 0 && check ((byte)currentByte)) { } int count = (int)(stream.Position - leftPos) - 1; if (count < 1) return null; byte[] bytes = new byte[count]; stream.Position = leftPos; if (stream.Read (bytes, 0, count) != count) throw new IOException ("byte count mismatch"); return bytes; }
public static unsafe long DerLengthDecode(Stream bt) { long length = 0; byte b; b = (byte) bt.ReadByte(); if ((b & 0x80)==0) { length = b; } else { long lengthBytes = b & 0x7f; if (lengthBytes == 0) { throw new Exception("Indefinite length."); } length = 0; while (lengthBytes-- > 0) { if ((length >> (8*(sizeof(long)-1))) > 0) throw new Exception("Length overflow."); b = (byte) bt.ReadByte(); length = (length << 8) | b; } } return length; }
public CompletedResponse(Stream stream, ByteBuffer buffer) { int bRead; buffer.Reset(); for (bRead = stream.ReadByte(); bRead > 0 && bRead != ' '; bRead = stream.ReadByte()) buffer.Add((byte)bRead); if (bRead == ' ' && buffer.GetPosition() == INSERT.Length && buffer.AreSame(INSERT)) { long lioid = 0; for (bRead = stream.ReadByte(); bRead > 0 && bRead != ' '; bRead = stream.ReadByte()) lioid = (lioid << 3) + (lioid << 1) + bRead - 48; if (bRead == ' ') LastInsertedOID = lioid; } while (bRead > 0) { buffer.Reset(); for (bRead = stream.ReadByte(); bRead > 0 && bRead != ' '; bRead = stream.ReadByte()) buffer.Add((byte)bRead); } if (bRead == -1) { throw new IOException(); } RowsAffected = buffer.TryGetInt(); }
public static byte[] nextToken(Stream input, byte[] delimiter) { int nextByte; //If the stream has already ended, return null if ((nextByte = input.ReadByte()) == -1) return null; MemoryStream tokenBuffer = new MemoryStream(); do { tokenBuffer.WriteByte((byte)nextByte); byte[] currentToken = tokenBuffer.ToArray(); if (endsWith(currentToken, delimiter)) { int tokenLength = currentToken.Length - delimiter.Length; byte[] token = new byte[tokenLength]; Array.Copy(currentToken, 0, token, 0, tokenLength); return token; } } while ((nextByte = input.ReadByte()) != -1); return tokenBuffer.ToArray(); }
public override DecodedObject<object> decodeTag(Stream stream) { int result = 0; int bt = stream.ReadByte(); if (bt == -1) return null; result = bt; int len = 1; int tagValue = bt & 31; //bool isPrimitive = (bt & 0x20) == 0; if (tagValue == UniversalTags.LastUniversal) { bt = 0x80; while ((bt & 0x80) != 0 && len < 4) { result <<= 8; bt = stream.ReadByte(); if (bt >= 0) { result |= bt; len++; } else { result >>= 8; break; } } } return new DecodedObject<object>(result, len); }
private static Stream MoveStream(Stream stream) { // HACK: we need this to get the DeflateStream to read properly stream.ReadByte(); stream.ReadByte(); return stream; }
public override ImageMetaData ReadMetaData(Stream stream) { stream.Position = 4; int id = stream.ReadByte(); if (0x38 != id) return null; id = stream.ReadByte(); if (0x5f != id) return null; int version = stream.ReadByte(); if (0x30 != version) return null; version = stream.ReadByte() - 0x30; if (version != 0) return null; using (var reader = new BinaryReader (stream, Encoding.ASCII, true)) { uint width = reader.ReadUInt32(); uint height = reader.ReadUInt32(); if (width > 0x8000 || height > 0x8000) return null; return new ImageMetaData { Width = width, Height = height, OffsetX = 0, OffsetY = 0, BPP = 8, }; } }
public override async Task FromStreamAsync(Stream stream, uint tagLength, TagVersion version) { long streamStart = stream.Position; int encoding = stream.ReadByte(); switch (version) { case TagVersion.V24: case TagVersion.V23: if (encoding == 0x00) { MimeType = await stream.ReadAnsiString(streamStart + tagLength).ConfigureAwait(false); PictureType = (AttachedPictureType)stream.ReadByte(); Description = await stream.ReadAnsiString(streamStart + tagLength).ConfigureAwait(false); Data = new byte[tagLength - (stream.Position - streamStart)]; await stream.ReadAsync(Data, 0, Data.Length).ConfigureAwait(false); } else if (encoding == 0x01) { MimeType = await stream.ReadAnsiString(streamStart + tagLength).ConfigureAwait(false); PictureType = (AttachedPictureType)stream.ReadByte(); Description = await stream.ReadUnicodeStringAsync(streamStart + tagLength).ConfigureAwait(false); Data = new byte[tagLength - (stream.Position - streamStart)]; await stream.ReadAsync(Data, 0, Data.Length).ConfigureAwait(false); } break; default: Debug.WriteLine("APIC: Version not implemented - " + version.ToString()); break; } }
public static RequestLine Parse(Stream stream) { int b = stream.ReadByte(); while (b == CR || b == LF) { b = stream.ReadByte(); } var bytes = new LinkedList<byte>(); bytes.AddLast((byte) b); while (true) { b = stream.ReadByte(); if (b == CR || b < 0) { stream.ReadByte(); break; } bytes.AddLast((byte) b); } var text = Encoding.Default.GetString(bytes.ToArray()); var parts = text.Split(' '); if (parts.Length == 3) { return new RequestLine(parts[0], parts[1], parts[2]); } throw new InvalidRequestException("Invalid Request Line."); }
public static void DecodeLength(Stream strm, out uint length, out bool indefiniteForm) { indefiniteForm = false; int rdVal = 0; rdVal = strm.ReadByte(); if (rdVal == -1) throw new UnexpectedEndOfStreamException(); byte b = (byte)rdVal; if ( (b & 0x80) == 0) { length = (uint)0x7F & b; return; } byte lenlen = (byte)(b &0x7F); indefiniteForm = (lenlen == 0); length = 0; for (int i = 0; i < lenlen; i++) { rdVal = strm.ReadByte(); if (rdVal == -1) throw new UnexpectedEndOfStreamException(); b = (byte)rdVal; length <<= 8; length |= b; } }
public static TextBuffer NewTextBuff(Stream strm) { int num = strm.ReadByte(); int num1 = strm.ReadByte(); if (num != 254 || num1 != 0xff) { if (num != 0xff || num1 != 254) { int num2 = strm.ReadByte(); if (num != 239 || num1 != 187 || num2 != 191) { strm.Seek((long)0, SeekOrigin.Begin); return new TextBuffer(strm); } else { return new TextBuffer(strm); } } else { return new LittleEndTextBuffer(strm); } } else { return new BigEndTextBuffer(strm); } }
private static bool IsPortable(Stream pdbStream) { return pdbStream.ReadByte() == 'B' && pdbStream.ReadByte() == 'S' && pdbStream.ReadByte() == 'J' && pdbStream.ReadByte() == 'B'; }
public override ImageMetaData ReadMetaData(Stream stream) { if ('A' != stream.ReadByte() || 'M' != stream.ReadByte()) return null; var header = new byte[0x30]; if (0x2e != stream.Read (header, 2, 0x2e)) return null; uint size = LittleEndian.ToUInt32 (header, 2); if (size != stream.Length) return null; int am_type = header[0x16]; if (am_type != 2 && am_type != 1 || header[0x18] != 1) return null; var info = new AmMetaData(); info.Width = LittleEndian.ToUInt16 (header, 6); info.Height = LittleEndian.ToUInt16 (header, 8); info.MaskWidth = LittleEndian.ToUInt16 (header, 0x0a); info.MaskHeight = LittleEndian.ToUInt16 (header, 0x0c); info.Colors = LittleEndian.ToUInt16 (header, 0x12); info.BPP = header[0x14]; info.IsCompressed = 0 != header[0x15]; info.DataOffset = LittleEndian.ToUInt32 (header, 0x1a); info.DataLength = LittleEndian.ToUInt32 (header, 0x1e); info.MaskOffset = LittleEndian.ToUInt32 (header, 0x22); info.MaskLength = LittleEndian.ToUInt32 (header, 0x26); info.IsMaskCompressed = 0 != header[0x2a]; if (checked(info.DataLength + info.MaskLength) > size) return null; return info; }
private static byte[] ReadHeaderBytes(Stream stream) { var bytes = new LinkedList<byte>(); bool mightBeEnd = false; while (true) { int b = stream.ReadByte(); if (b == CR) { b = stream.ReadByte(); if (b != LF) { bytes.AddLast(CR); bytes.AddLast((byte) b); continue; } if (mightBeEnd) { break; } mightBeEnd = true; bytes.AddLast(CR); bytes.AddLast(LF); continue; } mightBeEnd = false; bytes.AddLast((byte) b); } return bytes.ToArray(); }
private static uint Read24(Stream patch) { int Upper = patch.ReadByte(); int Middle = patch.ReadByte(); int Lower = patch.ReadByte(); return (uint)(Upper * 0x10000 + Middle * 0x100 + Lower); }
public MX(String Name, Stream Stream) : base(Name, TypeId, Stream) { this._Preference = (Stream.ReadByte() << 8) | (Stream.ReadByte() & Byte.MaxValue); this._Exchange = DNSTools.ExtractName(Stream); }
public CLCreatePC(Stream stream) { // read size this.BodySize = ReadUInt32(stream); // read timestamp this.TimeStamp = ReadUInt32(stream); // read Name this.Name = ReadString(stream); // read Slot this.Slot = (Slot)stream.ReadByte(); // read BitSet this.BitSet = (byte)stream.ReadByte(); // read Colors this.ColorHair = ReadUInt16(stream); this.ColorSkin = ReadUInt16(stream); this.ColorShirt = ReadUInt16(stream); this.ColorShirt2 = ReadUInt16(stream); this.ColorJeans = ReadUInt16(stream); this.ColorJeans2 = ReadUInt16(stream); // read STR DEX & INT this.STR = ReadUInt16(stream); this.DEX = ReadUInt16(stream); this.INT = ReadUInt16(stream); // read PCType this.PCType = (PCType)stream.ReadByte(); }
private string ReadStringFromPositionAndReset( Stream s, uint stringPosition ) { long pos = s.Position; s.Position = stringPosition; StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[2]; int b = s.ReadByte(); while ( b != 0 && b != -1 ) { if ( b == 0x01 ) { sb.Append( '\n' ); } else if ( b == 0x02 ) { if ( s.ReadByte() != 0x00 ) { throw new Exception( "control code 0x02 not followed by a null byte!" ); } sb.AppendFormat( "<Voice: {0:x4}>", s.ReadUInt16() ); } else if ( b == 0x03 ) { throw new Exception( "unknown control code 0x03" ); } else if ( b == 0x04 ) { throw new Exception( "unknown control code 0x04" ); } else if ( ( b > 0x04 && b <= 0x80 ) || ( b >= 0xA0 && b <= 0xDF ) ) { // is a single byte buffer[0] = (byte)b; sb.Append( Util.ShiftJISEncoding.GetString( buffer, 0, 1 ) ); } else { // is two bytes buffer[0] = (byte)b; buffer[1] = (byte)s.ReadByte(); sb.Append( Util.ShiftJISEncoding.GetString( buffer ) ); } b = s.ReadByte(); } s.Position = pos; return sb.ToString(); }
public SSHFP(Stream Stream) : base(Stream, TypeId) { this._Algorithm = (SSHFP_Algorithm) (Stream.ReadByte() & Byte.MaxValue); this._Typ = (SSHFP_FingerprintType) (Stream.ReadByte() & Byte.MaxValue); this._Fingerprint = DNSTools.ExtractName(Stream); }
/// <summary> /// Reads Secure Packet data from a Stream /// </summary> /// <param name="stream">Stream</param> /// <returns>An IEnumerable of byte[] corresponding packet data</returns> public static IEnumerable Read(Stream stream) { while (stream.CanRead) { // Reading start sequence ReadStartSequence(stream); // Reading header // - ID byte id = (byte)stream.ReadByte(); if (id == currentId) // We skip the packet if it has already been read continue; currentId = id; // - Checksum & size byte checksum = (byte)stream.ReadByte(); byte size = (byte)stream.ReadByte(); // Reading data byte[] data = new byte[size]; for (int i = 0; i < size; i++) data[i] = (byte)stream.ReadByte(); // Integrity check byte dataChecksum = CheckSum(data); if (dataChecksum == checksum) // Checksum OK yield return data; } }
public int FindBytePattern(Stream stream, byte[] pattern) { //a simple pattern matcher stream.Seek(0, SeekOrigin.Begin); for (int i = 0; i < stream.Length; i++) { var b = stream.ReadByte(); if (b == pattern[0]) { bool match = true; for (int j = 1; j < pattern.Length; j++) { var b2 = stream.ReadByte(); if (b2 != pattern[j]) { match = false; break; } } if (match) return (int)stream.Position; else stream.Seek(i+1, SeekOrigin.Begin); } } return -1; //no match }
/// <summary> /// Read signed integer from the packet /// </summary> internal static int ReadInt(Stream source) { return (int)(source.ReadByte()) + (int)(source.ReadByte() << 8) + (int)(source.ReadByte() << 16) + (int)(source.ReadByte() << 24); }
public static StreamReader OpenStream(Stream fs, Encoding defaultEncoding) { if (fs == null) throw new ArgumentNullException("fs"); if (fs.Length >= 2) { // the autodetection of StreamReader is not capable of detecting the difference // between ISO-8859-1 and UTF-8 without BOM. int firstByte = fs.ReadByte(); int secondByte = fs.ReadByte(); switch ((firstByte << 8) | secondByte) { case 0x0000: // either UTF-32 Big Endian or a binary file; use StreamReader case 0xfffe: // Unicode BOM (UTF-16 LE or UTF-32 LE) case 0xfeff: // UTF-16 BE BOM case 0xefbb: // start of UTF-8 BOM // StreamReader autodetection works fs.Position = 0; return new StreamReader(fs); default: return AutoDetect(fs, (byte)firstByte, (byte)secondByte, defaultEncoding); } } else { if (defaultEncoding != null) { return new StreamReader(fs, defaultEncoding); } else { return new StreamReader(fs); } } }
/// <summary> /// Decompresses the input stream. /// </summary> /// <param name="data">Stream containing compressed data.</param> /// <returns>Byte array containing the decompressed data.</returns> public static byte[] Decompress(Stream data) { var comptype = data?.ReadByte() ?? throw new ArgumentNullException(nameof(data)); if (comptype == 0) { throw new NotImplementedException($"Compression type {comptype} is not currently supported"); } var tail = BuildList(_sPrime[comptype]); var head = BuildTree(tail); using var outputstream = new MemoryStream(); using var bitstream = new BitStream(data); while (true) { var node = Decode(bitstream, head); var decoded = node.DecompressedValue; switch (decoded) { case 256: outputstream.Seek(0, SeekOrigin.Begin); return(outputstream.ToArray()); case 257: var newvalue = bitstream.ReadBits(8); outputstream.WriteByte((byte)newvalue); tail = InsertNode(tail, newvalue); break; default: outputstream.WriteByte((byte)decoded); break; } } }
/// <summary>Read in an MThd chunk from the stream.</summary> /// <param name="inputStream">The stream from which to read the MThd chunk.</param> /// <returns>The MThd chunk read.</returns> public static MThdChunkHeader Read(Stream inputStream) { // Validate input if (inputStream == null) { throw new ArgumentNullException("inputStream"); } if (!inputStream.CanRead) { throw new ArgumentException("Stream must be readable.", "inputStream"); } // Read in a header from the stream and validate it ChunkHeader header = ChunkHeader.Read(inputStream); ValidateHeader(header); // Read in the format int format = 0; for (int i = 0; i < 2; i++) { int val = inputStream.ReadByte(); if (val < 0) { throw new InvalidOperationException("The stream is invalid."); } format <<= 8; format |= val; } // Read in the number of tracks int numTracks = 0; for (int i = 0; i < 2; i++) { int val = inputStream.ReadByte(); if (val < 0) { throw new InvalidOperationException("The stream is invalid."); } numTracks <<= 8; numTracks |= val; } // Read in the division int division = 0; for (int i = 0; i < 2; i++) { int val = inputStream.ReadByte(); if (val < 0) { throw new InvalidOperationException("The stream is invalid."); } division <<= 8; division |= val; } // Create a new MThd header and return it return(new MThdChunkHeader(format, numTracks, division)); }
public void Encode(Stream input, Stream output) { var originalOutputPosition = output.Position; output.Position += 0x10; var block = new Block(); var matches = _matchParser.ParseMatches(input); foreach (var match in matches) { // Write any data before the match, to the buffer while (input.Position < match.Position) { if (block.codeBlockPosition == 0) { WriteAndResetBuffer(output, block); } block.codeBlock |= (byte)(1 << --block.codeBlockPosition); block.buffer[block.bufferLength++] = (byte)input.ReadByte(); } // Write match data to the buffer var firstByte = (byte)((match.Displacement - 1) >> 8); var secondByte = (byte)(match.Displacement - 1); if (match.Length < 0x12) { // Since minimum _length should be 3 for Yay0, we get a minimum matchLength of 1 in this case firstByte |= (byte)((match.Length - 2) << 4); } if (block.codeBlockPosition == 0) { WriteAndResetBuffer(output, block); } block.codeBlockPosition--; // Since a match is flagged with a 0 bit, we don't need a bit shift and just decrease the position block.buffer[block.bufferLength++] = firstByte; block.buffer[block.bufferLength++] = secondByte; if (match.Length >= 0x12) { block.buffer[block.bufferLength++] = (byte)(match.Length - 0x12); } input.Position += match.Length; } // Write any data after last match, to the buffer while (input.Position < input.Length) { if (block.codeBlockPosition == 0) { WriteAndResetBuffer(output, block); } block.codeBlock |= (byte)(1 << --block.codeBlockPosition); block.buffer[block.bufferLength++] = (byte)input.ReadByte(); } // Flush remaining buffer to stream WriteAndResetBuffer(output, block); // Write header information WriteHeaderData(input, output, originalOutputPosition); }
public static void SeekTest(Stream stream, Boolean fSuppres) { long lngPos; byte btValue; stream.Position = 0; Assert.True(0 == stream.Position); int length = 1 << 10; //fancy way of writing 2 to the pow 10 byte[] btArr = new byte[length]; for (int i = 0; i < btArr.Length; i++) { btArr[i] = unchecked ((byte)i); } if (stream.CanWrite) { stream.Write(btArr, 0, btArr.Length); } else { stream.Position = btArr.Length; } Assert.True(btArr.Length == stream.Position); lngPos = stream.Seek(0, SeekOrigin.Begin); Assert.True(0 == lngPos); Assert.True(0 == stream.Position); for (int i = 0; i < btArr.Length; i++) { if (stream.CanWrite) { btValue = (byte)stream.ReadByte(); Assert.AreEqual(btArr[i], btValue); } else { stream.Seek(1, SeekOrigin.Current); } Assert.True((i + 1) == stream.Position); } Assert.Throws <IOException>(() => stream.Seek(-5, SeekOrigin.Begin)); lngPos = stream.Seek(5, SeekOrigin.Begin); Assert.True(5 == lngPos); Assert.True(5 == stream.Position); lngPos = stream.Seek(5, SeekOrigin.End); Assert.True((length + 5) == lngPos); Assert.Throws <IOException>(() => stream.Seek(-(btArr.Length + 1), SeekOrigin.End)); lngPos = stream.Seek(-5, SeekOrigin.End); Assert.True(btArr.Length - 5 == lngPos); Assert.True((btArr.Length - 5) == stream.Position); lngPos = stream.Seek(0, SeekOrigin.End); Assert.True(btArr.Length == stream.Position); for (int i = btArr.Length; i > 0; i--) { stream.Seek(-1, SeekOrigin.Current); Assert.True(i - 1 == stream.Position); } Assert.Throws <IOException>(() => stream.Seek(-1, SeekOrigin.Current)); }
public static void StreamTest(Stream stream, Boolean fSuppress) { string strValue; int iValue; //[] We will first use the stream's 2 writing methods int iLength = 1 << 10; stream.Seek(0, SeekOrigin.Begin); for (int i = 0; i < iLength; i++) { stream.WriteByte(unchecked ((byte)i)); } byte[] btArr = new byte[iLength]; for (int i = 0; i < iLength; i++) { btArr[i] = unchecked ((byte)i); } stream.Write(btArr, 0, iLength); //we will write many things here using a binary writer BinaryWriter bw1 = new BinaryWriter(stream); bw1.Write(false); bw1.Write(true); for (int i = 0; i < 10; i++) { bw1.Write((byte)i); bw1.Write((sbyte)i); bw1.Write((short)i); bw1.Write((char)i); bw1.Write((UInt16)i); bw1.Write(i); bw1.Write((uint)i); bw1.Write((Int64)i); bw1.Write((ulong)i); bw1.Write((float)i); bw1.Write((double)i); } //Some strings, chars and Bytes char[] chArr = new char[iLength]; for (int i = 0; i < iLength; i++) { chArr[i] = (char)i; } bw1.Write(chArr); bw1.Write(chArr, 512, 512); bw1.Write(new string(chArr)); bw1.Write(new string(chArr)); //[] we will now read stream.Seek(0, SeekOrigin.Begin); for (int i = 0; i < iLength; i++) { Assert.AreEqual(i % 256, stream.ReadByte()); } btArr = new byte[iLength]; stream.Read(btArr, 0, iLength); for (int i = 0; i < iLength; i++) { Assert.AreEqual(unchecked ((byte)i), btArr[i]); } //Now, for the binary reader BinaryReader br1 = new BinaryReader(stream); Assert.False(br1.ReadBoolean()); Assert.True(br1.ReadBoolean()); for (int i = 0; i < 10; i++) { Assert.AreEqual((byte)i, br1.ReadByte()); Assert.AreEqual((sbyte)i, br1.ReadSByte()); Assert.AreEqual((short)i, br1.ReadInt16()); Assert.AreEqual((char)i, br1.ReadChar()); Assert.AreEqual((UInt16)i, br1.ReadUInt16()); Assert.AreEqual(i, br1.ReadInt32()); Assert.AreEqual((uint)i, br1.ReadUInt32()); Assert.True((Int64)i == br1.ReadInt64()); Assert.True((ulong)i == br1.ReadUInt64()); Assert.AreEqual((float)i, br1.ReadSingle()); Assert.AreEqual((double)i, br1.ReadDouble()); } chArr = br1.ReadChars(iLength); for (int i = 0; i < iLength; i++) { Assert.AreEqual((char)i, chArr[i]); } chArr = new char[512]; chArr = br1.ReadChars(iLength / 2); for (int i = 0; i < iLength / 2; i++) { Assert.AreEqual((char)(iLength / 2 + i), chArr[i]); } chArr = new char[iLength]; for (int i = 0; i < iLength; i++) { chArr[i] = (char)i; } strValue = br1.ReadString(); Assert.AreEqual(new string(chArr), strValue); strValue = br1.ReadString(); Assert.AreEqual(new string(chArr), strValue); stream.Seek(1, SeekOrigin.Current); // In the original test, success here would end the test //[] we will do some async tests here now stream.Position = 0; btArr = new byte[iLength]; for (int i = 0; i < iLength; i++) { btArr[i] = unchecked ((byte)(i + 5)); } stream.Write(btArr, 0, btArr.Length); stream.Position = 0; for (int i = 0; i < iLength; i++) { Assert.AreEqual(unchecked ((byte)(i + 5)), stream.ReadByte()); } //we will read asynchronously stream.Position = 0; byte[] compArr = new byte[iLength]; iValue = stream.Read(compArr, 0, compArr.Length); Assert.AreEqual(btArr.Length, iValue); for (int i = 0; i < iLength; i++) { Assert.AreEqual(compArr[i], btArr[i]); } }
/// <summary> /// Custom LZSS decompression with frame pre-initialization and reveresed control bits meaning. /// </summary> static void LzssUnpack(Stream input, byte[] output) { int frame_pos = 0xfee; byte[] frame = new byte[0x1000]; for (int i = 0; i < frame_pos; ++i) { frame[i] = 0x20; } int dst = 0; int ctl = 0; while (dst < output.Length) { ctl >>= 1; if (0 == (ctl & 0x100)) { ctl = input.ReadByte(); if (-1 == ctl) { break; } ctl |= 0xff00; } if (0 == (ctl & 1)) { int v = input.ReadByte(); if (-1 == v) { break; } output[dst++] = (byte)v; frame[frame_pos++] = (byte)v; frame_pos &= 0xfff; } else { int offset = input.ReadByte(); if (-1 == offset) { break; } int count = input.ReadByte(); if (-1 == count) { break; } offset |= (count & 0xf0) << 4; count = (count & 0x0f) + 3; for (int i = 0; i < count; i++) { if (dst >= output.Length) { break; } byte v = frame[offset++]; offset &= 0xfff; frame[frame_pos++] = v; frame_pos &= 0xfff; output[dst++] = v; } } } }
public override int ReadByte() { return(inStream.ReadByte()); }
private FileInfo ReadFile() { FileInfo file = new FileInfo(); //int size = ReadSize(f); //long next = f.Position + size; // each file record contains the following attributes // 1 = file name // 2 = compressed size // 3 = uncompressed size // 4 = crc32 // 6 = delete file? 060101 // 8 = timestamp in unix time // 18 = hash of some sort (forms the URL) while (true) { int type = data.ReadByte(); if (type == 1) { file.Name = ReadString(); } else if (type == 2) { file.CompressedSize = ReadInt(); } else if (type == 3) { file.UncompressedSize = ReadInt(); } else if (type == 4) { file.CRC32 = ReadInt(); } else if (type == 8) { file.LastModified = ReadDateTime(); } else if (type == 10) { // no idea what type 10 is int len = ReadSize(); data.Position += len; } else if (type == 18) { int len = data.ReadByte(); byte[] hash = new byte[len]; data.Read(hash, 0, len); file.Url = EncodeAsBase16String(hash).Insert(5, "/").Insert(2, "/"); } else { break; } } //f.Position = next; //byte[] buf = new byte[next - f.Position]; //f.Read(buf, 0, buf.Length); //Console.Error.WriteLine(file); return(file); }
private static int ReadInt(Stream stream) { return((stream.ReadByte() << 8) + stream.ReadByte()); }
/// <summary> /// Initiates or continues establishing of the Security Session. /// </summary> /// <param name="input">A null reference or an incoming stream.</param> /// <param name="connectionLevel">Indicates whether the Security Session operates on connection level.</param> /// <returns>A stream containing data for sending to the remote host or a null reference if Security Session is established.</returns> public override GenuineChunkedStream EstablishSession(Stream input, bool connectionLevel) { // a dance is over if (this.IsEstablished) { return(null); } GenuineChunkedStream outputStream = null; BinaryFormatter binaryFormatter = new BinaryFormatter(); // skip the status flag if (connectionLevel) { if (input != null) { input.ReadByte(); } outputStream = new GenuineChunkedStream(false); } else { outputStream = this.CreateOutputStream(); } lock (this) { // write session is being established flag BinaryWriter binaryWriter = new BinaryWriter(outputStream); binaryWriter.Write((bool)false); // remote host sent nothing, send a RSA public key if (input == null || input == Stream.Null) { // serialize RSA public key RSAParameters rsaParameters = this._rsaCryptoServiceProviderDecryptor.ExportParameters(false); binaryFormatter.Serialize(outputStream, rsaParameters); binaryFormatter.Serialize(outputStream, this._localInstanceGuid); return(outputStream); } // deserialize incoming data Rijndael rijndael = null; object receivedObject = binaryFormatter.Deserialize(input); // RSA public key has been received if (receivedObject is RSAParameters) { this._remoteInstanceGuid = (string)binaryFormatter.Deserialize(input); if (string.Compare(this._remoteInstanceGuid, this._localInstanceGuid, false) > 0) { return(this.EstablishSession(Stream.Null, connectionLevel)); } if (this.RijndaelKey == null) { // create Rijndael key rijndael = Rijndael.Create(); this.RijndaelKey = rijndael.Key; } // encrypt it with public rsa key RSAParameters rsaParameters = (RSAParameters)receivedObject; RSACryptoServiceProvider rsaCryptoServiceProvider; try { // try the usual way, and if fails, use the patch in the catch block rsaCryptoServiceProvider = new RSACryptoServiceProvider(); } catch { CspParameters CSPParam = new CspParameters(); CSPParam.Flags = CspProviderFlags.UseMachineKeyStore; rsaCryptoServiceProvider = new RSACryptoServiceProvider(CSPParam); } rsaCryptoServiceProvider.ImportParameters(rsaParameters); // serialize byte[] encryptedContent = RSAUtility.Encrypt(rsaCryptoServiceProvider, this.RijndaelKey); binaryFormatter.Serialize(outputStream, encryptedContent); return(outputStream); } // Rijndael key has been received if (receivedObject is byte[]) { // first of all, retrieve it byte[] receivedRijndaelKey = RSAUtility.Decrypt(this._rsaCryptoServiceProviderDecryptor, (byte[])receivedObject); // accept received key this.RijndaelKey = receivedRijndaelKey; // confirm that the session has been established binaryFormatter.Serialize(outputStream, "OK"); this.SessionEstablished(); return(outputStream); } // a confirmation received that the session is established if (receivedObject is string) { this.SessionEstablished(); return(null); } } throw GenuineExceptions.Get_Receive_IncorrectData(); }
static int ByteOf(Stream stream, uint position) { stream.Position = position; return(stream.ReadByte()); }
public uint EncodeLZSS() { byte[] comp_buffer = new byte[LZSS.N * 2]; int i; for (i = LZSS.N - LZSS.F; i < LZSS.N * 2; i++) { int c = m_input.ReadByte(); if (-1 == c) { break; } comp_buffer[i] = (byte)c; } int bufferend = i; int r = LZSS.N - LZSS.F; int s = 0; while (r < bufferend) { int f1 = (LZSS.F <= bufferend - r) ? LZSS.F : bufferend - r; int x = 0; int y = 1; int c = comp_buffer[r]; for (i = r - 1; i >= s; i--) { if (comp_buffer[i] == c) { int j; for (j = 1; j < f1; j++) { if (comp_buffer[i + j] != comp_buffer[r + j]) { break; } } if (j > y) { x = i; y = j; } } } if (y <= LZSS.P) { Output1(c); } else { Output2(x & (LZSS.N - 1), y - 2); } r += y; s += y; if (r >= LZSS.N * 2 - LZSS.F) { for (i = 0; i < LZSS.N; i++) { comp_buffer[i] = comp_buffer[i + LZSS.N]; } bufferend -= LZSS.N; r -= LZSS.N; s -= LZSS.N; while (bufferend < LZSS.N * 2) { c = m_input.ReadByte(); if (-1 == c) { break; } comp_buffer[bufferend++] = (byte)c; } } } FlushBitBuffer(); return(m_code_count); }
/// <summary> /// Reads an integer encoded as little endian from buffer at the specified index /// </summary> public static ulong ReadLEUInt64(this Stream s) { var b1 = s.ReadByte(); if (b1 < 0) { throw new IO.NFXIOException(StringConsts.STREAM_READ_EOF_ERROR + "ReadLEUInt64()"); } var b2 = s.ReadByte(); if (b2 < 0) { throw new IO.NFXIOException(StringConsts.STREAM_READ_EOF_ERROR + "ReadLEUInt64()"); } var b3 = s.ReadByte(); if (b3 < 0) { throw new IO.NFXIOException(StringConsts.STREAM_READ_EOF_ERROR + "ReadLEUInt64()"); } var b4 = s.ReadByte(); if (b4 < 0) { throw new IO.NFXIOException(StringConsts.STREAM_READ_EOF_ERROR + "ReadLEUInt64()"); } var b5 = s.ReadByte(); if (b5 < 0) { throw new IO.NFXIOException(StringConsts.STREAM_READ_EOF_ERROR + "ReadLEUInt64()"); } var b6 = s.ReadByte(); if (b6 < 0) { throw new IO.NFXIOException(StringConsts.STREAM_READ_EOF_ERROR + "ReadLEUInt64()"); } var b7 = s.ReadByte(); if (b7 < 0) { throw new IO.NFXIOException(StringConsts.STREAM_READ_EOF_ERROR + "ReadLEUInt64()"); } var b8 = s.ReadByte(); if (b8 < 0) { throw new IO.NFXIOException(StringConsts.STREAM_READ_EOF_ERROR + "ReadLEUInt64()"); } return(((ulong)b8 << 56) + ((ulong)b7 << 48) + ((ulong)b6 << 40) + ((ulong)b5 << 32) + ((ulong)b4 << 24) + ((ulong)b3 << 16) + ((ulong)b2 << 8) + ((ulong)b1)); }
/// <summary> /// 发送POST数据 /// </summary> /// <param name="message">消息</param> /// <returns>返回消息</returns> public int SendRequest(CMessage message) { Binary bw = new Binary(); byte[] body = message.m_body; int bodyLength = message.m_bodyLength; int uncBodyLength = bodyLength; if (message.m_compressType == COMPRESSTYPE_GZIP) { using (MemoryStream cms = new MemoryStream()) { using (GZipStream gzip = new GZipStream(cms, CompressionMode.Compress)) { gzip.Write(body, 0, body.Length); } body = cms.ToArray(); bodyLength = body.Length; } } int len = sizeof(int) * 4 + bodyLength + sizeof(short) * 3 + sizeof(byte) * 2; bw.WriteInt(len); bw.WriteShort((short)message.m_groupID); bw.WriteShort((short)message.m_serviceID); bw.WriteShort((short)message.m_functionID); bw.WriteInt(message.m_sessionID); bw.WriteInt(message.m_requestID); bw.WriteByte((byte)message.m_state); bw.WriteByte((byte)message.m_compressType); bw.WriteInt(uncBodyLength); bw.WriteBytes(body); byte[] bytes = bw.GetBytes(); int length = bytes.Length; HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(m_url); webReq.Method = "POST"; webReq.ContentType = "application/x-www-form-urlencoded"; webReq.ContentLength = bytes.Length; if (bytes != null) { Stream writer = webReq.GetRequestStream(); writer.Write(bytes, 0, bytes.Length); writer.Close(); } HttpWebResponse response = (HttpWebResponse)webReq.GetResponse(); Stream reader = response.GetResponseStream(); long contentLength = response.ContentLength; byte[] dataArray = new byte[contentLength]; for (int i = 0; i < contentLength; i++) { dataArray[i] = (byte)reader.ReadByte(); } response.Close(); reader.Dispose(); bw.Close(); int ret = dataArray.Length; UpFlow += ret; IntPtr ptr = Marshal.AllocHGlobal(sizeof(byte) * ret); for (int i = 0; i < ret; i++) { IntPtr iptr = (IntPtr)((int)ptr + i); Marshal.WriteByte(iptr, dataArray[i]); } BaseService.CallBack(message.m_socketID, 0, ptr, ret); Marshal.FreeHGlobal(ptr); return(ret); }
private int readByte() { return(_innerStream.ReadByte()); }
/// <summary> /// Reads a byte from the stream and advances the position within the /// stream by one byte, or returns -1 if at the end of the stream. /// </summary> /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns> public override int ReadByte() { CheckClosed(); return(stream.ReadByte()); }
public int Read() { return((int)_is.ReadByte()); }
public static void FormatBuffer(TextWriter output, Stream input, int length) { output.WriteLine(" 0 1 2 3 4 5 6 7 8 9 A B C D E F"); output.WriteLine(" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --"); int byteIndex = 0; int whole = length >> 4; int rem = length & 0xF; for (int i = 0; i < whole; ++i, byteIndex += 16) { StringBuilder bytes = new StringBuilder(49); StringBuilder chars = new StringBuilder(16); for (int j = 0; j < 16; ++j) { int c = input.ReadByte(); bytes.Append(c.ToString("X2")); if (j != 7) { bytes.Append(' '); } else { bytes.Append(" "); } if (c >= 0x20 && c < 0x7F) { chars.Append((char)c); } else { chars.Append('.'); } } output.Write(byteIndex.ToString("X4")); output.Write(" "); output.Write(bytes.ToString()); output.Write(" "); output.WriteLine(chars.ToString()); } if (rem != 0) { StringBuilder bytes = new StringBuilder(49); StringBuilder chars = new StringBuilder(rem); for (int j = 0; j < 16; ++j) { if (j < rem) { int c = input.ReadByte(); bytes.Append(c.ToString("X2")); if (j != 7) { bytes.Append(' '); } else { bytes.Append(" "); } if (c >= 0x20 && c < 0x7F) { chars.Append((char)c); } else { chars.Append('.'); } } else { bytes.Append(" "); } } output.Write(byteIndex.ToString("X4")); output.Write(" "); output.Write(bytes.ToString()); output.Write(" "); output.WriteLine(chars.ToString()); } }
public object Unpack(Stream s) { int num = s.ReadByte(); if (num < 0) { throw new FormatException(); } if (num <= 127) { return((long)num); } if (num <= 143) { return(this.UnpackMap(s, (long)(num & 15))); } if (num <= 159) { return(this.UnpackArray(s, (long)(num & 15))); } if (num <= 191) { return(this.UnpackString(s, (long)(num & 31))); } if (num >= 224) { return((long)((sbyte)num)); } switch (num) { case 192: return(null); case 194: return(false); case 195: return(true); case 196: return(this.UnpackBinary(s, (long)s.ReadByte())); case 197: return(this.UnpackBinary(s, this.UnpackUint16(s))); case 198: return(this.UnpackBinary(s, this.UnpackUint32(s))); case 202: s.Read(this.tmp0, 0, 4); if (BitConverter.IsLittleEndian) { this.tmp1[0] = this.tmp0[3]; this.tmp1[1] = this.tmp0[2]; this.tmp1[2] = this.tmp0[1]; this.tmp1[3] = this.tmp0[0]; return((double)BitConverter.ToSingle(this.tmp1, 0)); } return((double)BitConverter.ToSingle(this.tmp0, 0)); case 203: s.Read(this.tmp0, 0, 8); if (BitConverter.IsLittleEndian) { this.tmp1[0] = this.tmp0[7]; this.tmp1[1] = this.tmp0[6]; this.tmp1[2] = this.tmp0[5]; this.tmp1[3] = this.tmp0[4]; this.tmp1[4] = this.tmp0[3]; this.tmp1[5] = this.tmp0[2]; this.tmp1[6] = this.tmp0[1]; this.tmp1[7] = this.tmp0[0]; return(BitConverter.ToDouble(this.tmp1, 0)); } return(BitConverter.ToDouble(this.tmp0, 0)); case 204: return((long)s.ReadByte()); case 205: return(this.UnpackUint16(s)); case 206: return(this.UnpackUint32(s)); case 207: if (s.Read(this.tmp0, 0, 8) != 8) { throw new FormatException(); } return((long)this.tmp0[0] << 56 | (long)this.tmp0[1] << 48 | (long)this.tmp0[2] << 40 | ((long)this.tmp0[3] << 32) + ((long)this.tmp0[4] << 24) | (long)this.tmp0[5] << 16 | (long)this.tmp0[6] << 8 | (long)this.tmp0[7]); case 208: return((long)((sbyte)s.ReadByte())); case 209: if (s.Read(this.tmp0, 0, 2) != 2) { throw new FormatException(); } return((long)((sbyte)this.tmp0[0]) << 8 | (long)this.tmp0[1]); case 210: if (s.Read(this.tmp0, 0, 4) != 4) { throw new FormatException(); } return((long)((sbyte)this.tmp0[0]) << 24 | (long)this.tmp0[1] << 16 | (long)this.tmp0[2] << 8 | (long)this.tmp0[3]); case 211: if (s.Read(this.tmp0, 0, 8) != 8) { throw new FormatException(); } return((long)((sbyte)this.tmp0[0]) << 56 | (long)this.tmp0[1] << 48 | (long)this.tmp0[2] << 40 | ((long)this.tmp0[3] << 32) + ((long)this.tmp0[4] << 24) | (long)this.tmp0[5] << 16 | (long)this.tmp0[6] << 8 | (long)this.tmp0[7]); case 217: return(this.UnpackString(s, (long)s.ReadByte())); case 218: return(this.UnpackString(s, this.UnpackUint16(s))); case 219: return(this.UnpackString(s, this.UnpackUint32(s))); case 220: return(this.UnpackArray(s, this.UnpackUint16(s))); case 221: return(this.UnpackArray(s, this.UnpackUint32(s))); case 222: return(this.UnpackMap(s, this.UnpackUint16(s))); case 223: return(this.UnpackMap(s, this.UnpackUint32(s))); } return(null); }
public static int wfd_append(Stream OutputStream, Stream InputStream, double offset, double length, double ovr, List <KeyValuePair <double, double> > KV) { List <double> p = new List <double>(); List <double> v = new List <double>(); foreach (KeyValuePair <double, double> kv in KV) { p.Add(kv.Key); v.Add(kv.Value); } for (int i = KV.Count; i < 5; i++) { p.Add(0); v.Add(0); } OutputStream.Seek(0, SeekOrigin.End);//SeekToEnd int outputFrames = wfd_ms2samples(length); int currentFrame = 0; Int16 sum; int c1, c2; WaveFileReader wfr = new WaveFileReader(InputStream); /* handle offset */ if (wfd_ms2samples(offset) > 0) { Emu_Sf_Seek(wfr, wfd_ms2samples(offset), SeekOrigin.Begin); } int[] p_f = { 0, 0, 0, 0, 0, 0, 0 }; double[] v_f = { 0, 0, 0, 0, 0, 0, 0 }; /* pre-calculate volume */ p_f[0] = 0; for (int i = 0; i < 2; i++) { p_f[i + 1] = wfd_ms2samples(p[i]) + p_f[i]; } p_f[3] = wfd_ms2samples(p[4]) + p_f[2]; p_f[6] = outputFrames; p_f[5] = p_f[6] - wfd_ms2samples(p[3]); p_f[4] = p_f[5] - wfd_ms2samples(p[2]); v_f[0] = 0.0; for (int i = 0; i < 2; i++) { v_f[i + 1] = v[i]; } v_f[3] = v[4]; v_f[4] = v[2]; v_f[5] = v[3]; v_f[6] = 0.0; if (p_f[1] == p_f[2]) { v_f[1] = v_f[2]; } if (p_f[0] == p_f[1]) { v_f[0] = v_f[1]; } if (p_f[5] == p_f[4]) { v_f[5] = v_f[4]; } if (p_f[6] == p_f[5]) { v_f[6] = v_f[5]; } int ovrFrames = wfd_ms2samples(ovr); if (ovrFrames > 0) { int seekMap = wfh_channels * (wfh_bits / 8) * ovrFrames; if (OutputStream.Length > seekMap) { OutputStream.Seek((-1) * seekMap, SeekOrigin.End); } } else if (ovr < 0.0) { /* output blank samples */ int ovrSamples = 0; int i, j, k; ovrSamples = wfd_ms2samples(-ovr); for (i = 0; i < ovrSamples; i++) { for (j = 0; j < wfh_channels; j++) { for (k = 0; k < (wfh_bits / 8); k++) { OutputStream.WriteByte((byte)'\0'); } } } OutputStream.Flush(); OutputStream.Seek(0, SeekOrigin.Current); ovr = 0.0; ovrFrames = 0; } /* output */ Int16[] Buf = new Int16[1] { 0 }; currentFrame = 0; for (; outputFrames > 0; outputFrames--) { if (wfr.CanRead) { Buf = Emu_Sf_Readf_Short(wfr, 1); if (Buf.Length < 1) { Buf = new Int16[(int)(wfr.WaveFormat.BlockAlign / 2)]; for (int j = 0; j < (int)(wfr.WaveFormat.BlockAlign / 2); j++) { Buf[j] = 0; } wfr.Close(); } } /* simple mix if there are multi-channels */ sum = Buf[0]; /* modify the volume */ if (wfr.WaveFormat.Channels > 0) { for (int i = 0; i < wfr.WaveFormat.Channels; i++) { sum += Buf[i]; } double vf; sum = (Int16)(sum / wfr.WaveFormat.Channels); vf = wfd_append_linear_volume(currentFrame, p_f, v_f); sum = (Int16)(((double)sum) * (vf / 100.0)); } else { sum = 0; } if (ovrFrames > 0) { Int16 d, r; c1 = OutputStream.ReadByte(); if (c1 == -1) { ovrFrames = 0; goto wfd_append_normal; } c2 = OutputStream.ReadByte(); if (c2 == -1) { ovrFrames = 0; goto wfd_append_normal; } OutputStream.Seek(-2, SeekOrigin.Current); d = (Int16)((c1 & (0x00ff)) | (((c2 & 0x00ff) << 8) & 0xff00)); r = wfd_mix(sum, d); OutputStream.WriteByte((byte)((r) & (0x00ff))); OutputStream.WriteByte((byte)((r >> 8) & 0x00ff)); OutputStream.Flush(); OutputStream.Seek(0, SeekOrigin.Current); ovrFrames--; wfd_append_normal: OutputStream.WriteByte((byte)((sum) & (0x00ff))); OutputStream.WriteByte((byte)((sum >> 8) & 0x00ff)); OutputStream.Flush(); OutputStream.Seek(0, SeekOrigin.Current); } else { OutputStream.WriteByte((byte)((sum) & (0x00ff))); OutputStream.WriteByte((byte)((sum >> 8) & 0x00ff)); OutputStream.Flush(); OutputStream.Seek(0, SeekOrigin.Current); } currentFrame++; } if (!wfr.CanRead) { wfr.Close(); } long ret = OutputStream.Length; OutputStream.Close(); return((int)ret); }
public void UnpackBinary(int b, Stream s, Stream ws) { if (b <= 191) { int num = b & 31; if (num != 0) { byte[] array = new byte[num]; s.Read(array, 0, num); ws.Write(array, 0, num); } } else { switch (b) { case 196: break; case 197: goto IL_9D; case 198: goto IL_EE; default: switch (b) { case 217: break; case 218: goto IL_9D; case 219: goto IL_EE; default: return; } break; } int num2 = s.ReadByte(); byte[] array2 = new byte[num2]; s.Read(array2, 0, num2); ws.WriteByte((byte)num2); ws.Write(array2, 0, num2); return; IL_9D: byte[] array3 = new byte[2]; s.Read(array3, 0, 2); byte[] array4 = new byte[(long)((int)array3[0] << 8 | (int)array3[1])]; s.Read(array4, 0, array4.Length); ws.Write(array3, 0, 2); ws.Write(array4, 0, array4.Length); return; IL_EE: byte[] array5 = new byte[4]; s.Read(array5, 0, 4); byte[] array6 = new byte[(long)array5[0] << 24 | (long)array5[1] << 16 | (long)array5[2] << 8 | (long)array5[3]]; s.Read(array6, 0, array6.Length); ws.Write(array5, 0, 4); ws.Write(array6, 0, array6.Length); } }
private string UnpackString(Stream s, long len) { if (MasterDataUnpacker.sb == null) { MasterDataUnpacker.sb = new StringBuilder((int)len); } else { MasterDataUnpacker.sb.Length = 0; MasterDataUnpacker.sb.EnsureCapacity((int)len); } uint num = 0u; uint num2 = 0u; uint num3 = 0u; int num4 = 0; while ((long)num4 < len) { uint num5 = (uint)s.ReadByte(); if (num2 == 0u) { if (num5 < 128u) { MasterDataUnpacker.sb.Append((char)num5); } else if ((num5 & 224u) == 192u) { num = (num5 & 31u); num3 = 1u; num2 = 2u; } else if ((num5 & 240u) == 224u) { num = (num5 & 15u); num3 = 1u; num2 = 3u; } else if ((num5 & 248u) == 240u) { num = (num5 & 7u); num3 = 1u; num2 = 4u; } else if ((num5 & 252u) == 248u) { num = (num5 & 3u); num3 = 1u; num2 = 5u; } else if ((num5 & 254u) == 252u) { num = (num5 & 3u); num3 = 1u; num2 = 6u; } } else if ((num5 & 192u) == 128u) { num = (num << 6 | (num5 & 63u)); if ((num3 += 1u) >= num2) { if (num < 65536u) { MasterDataUnpacker.sb.Append((char)num); } else if (num < 1114112u) { num -= 65536u; MasterDataUnpacker.sb.Append((char)((num >> 10) + 55296u)); MasterDataUnpacker.sb.Append((char)((num & 1023u) + 56320u)); } num2 = 0u; } } num4++; } return(MasterDataUnpacker.sb.ToString()); }
public void Sync() { WebResponse res = null; try { FileWebRequest req = (FileWebRequest)WebRequest.Create(_tempFileUri); req.ContentLength = 1; req.ContentType = "image/png"; try { Stream stream = req.GetRequestStream(); Assert.Fail("should throw exception"); } catch (ProtocolViolationException) { } req.Method = "PUT"; Stream wstream = req.GetRequestStream(); Assert.IsFalse(wstream.CanRead, "#1r"); Assert.IsTrue(wstream.CanWrite, "#1w"); Assert.IsTrue(wstream.CanSeek, "#1s"); wstream.WriteByte(72); wstream.WriteByte(101); wstream.WriteByte(108); wstream.WriteByte(108); wstream.WriteByte(111); wstream.Close(); Assert.AreEqual(1, req.ContentLength, "#1cl"); Assert.AreEqual("image/png", req.ContentType, "#1ct"); // stream written req = (FileWebRequest)WebRequest.Create(_tempFileUri); res = req.GetResponse(); Assert.AreEqual((long)5, res.ContentLength, "#2 len"); Assert.AreEqual("application/octet-stream", res.ContentType, "#2 type"); Assert.AreEqual("file", res.ResponseUri.Scheme, "#2 scheme"); Stream rstream = res.GetResponseStream(); Assert.IsTrue(rstream.CanRead, "#3r"); Assert.IsFalse(rstream.CanWrite, "#3w"); Assert.IsTrue(rstream.CanSeek, "#3s"); Assert.AreEqual(72, rstream.ReadByte(), "#4a"); Assert.AreEqual(101, rstream.ReadByte(), "#4b"); Assert.AreEqual(108, rstream.ReadByte(), "#4c"); Assert.AreEqual(108, rstream.ReadByte(), "#4d"); Assert.AreEqual(111, rstream.ReadByte(), "#4e"); rstream.Close(); try { long len = res.ContentLength; Assert.AreEqual((long)5, len, "#5"); } catch (ObjectDisposedException) { Assert.Fail("#disposed contentlength"); } try { WebHeaderCollection w = res.Headers; } catch (ObjectDisposedException) { Assert.Fail("#disposed headers"); } try { res.Close(); } catch (ObjectDisposedException) { Assert.Fail("#disposed close"); } } finally { if (res != null) { res.Close(); } } }
public void UnpackByte(Stream s, Stream ws) { int num = s.ReadByte(); ws.WriteByte((byte)num); if (num < 0) { throw new FormatException(); } if (num > 127) { if (num <= 143) { this.UnpackMapByte(num, s, ws); } else if (num <= 159) { this.UnpackArrayByte(num, s, ws); } else if (num <= 191) { this.UnpackBinary(num, s, ws); } else if (num >= 224) { } } switch (num) { case 196: case 197: case 198: case 217: case 218: case 219: this.UnpackBinary(num, s, ws); break; case 202: s.Read(this.tmp0, 0, 4); ws.Write(this.tmp0, 0, 4); break; case 203: s.Read(this.tmp0, 0, 8); ws.Write(this.tmp0, 0, 8); break; case 204: ws.WriteByte((byte)s.ReadByte()); break; case 205: s.Read(this.tmp0, 0, 2); ws.Write(this.tmp0, 0, 2); break; case 206: s.Read(this.tmp0, 0, 4); ws.Write(this.tmp0, 0, 4); break; case 207: if (s.Read(this.tmp0, 0, 8) != 8) { throw new FormatException(); } ws.Write(this.tmp0, 0, 8); break; case 208: ws.WriteByte((byte)s.ReadByte()); break; case 209: if (s.Read(this.tmp0, 0, 2) != 2) { throw new FormatException(); } ws.Write(this.tmp0, 0, 2); break; case 210: if (s.Read(this.tmp0, 0, 4) != 4) { throw new FormatException(); } ws.Write(this.tmp0, 0, 4); break; case 211: if (s.Read(this.tmp0, 0, 8) != 8) { throw new FormatException(); } ws.Write(this.tmp0, 0, 8); break; case 220: case 221: this.UnpackArrayByte(num, s, ws); break; case 222: case 223: this.UnpackMapByte(num, s, ws); break; } }
static void LogMouseEvent(Object obj, MouseEventArgs e) { Console.WriteLine("LogMouse"); ThreadStart ts = new ThreadStart(MyMethod); ThreadStart ts2 = MyMethod; Thread t = new Thread(ts2); t.Start(); StreamFactory factory = GenerateSampleData; using (Stream stream = factory()) { int data; while ((data = stream.ReadByte()) != -1) { Console.WriteLine(data); } } //======================= EventHandler handler = new EventHandler(LogPlainEvent); KeyPressEventHandler keyHandler = new KeyPressEventHandler(handler); //============== Dervied x = new Dervied(); SampleDelegate fac = new SampleDelegate(x.CandidateAction); fac("TEST!!"); ActionMethod(); //=============================== List <int> intList = new List <int>(); intList.Add(5); intList.Add(10); intList.Add(15); intList.Add(25); intList.ForEach(delegate(int n) { Console.WriteLine(Math.Sqrt(n)); }); //================ Predicate <int> isEven = delegate(int xx) { return(xx % 2 == 0); }; Console.WriteLine(isEven(10)); //SortAndShowFiles("Sort by name:",delegate(FileInfo f1,FileInfo f2) { return f1.Name.CompareTo(f2.Name); }); EnclosingMethod(); CaptureVariable(); Console.WriteLine("//======================="); MethodInvoker xxx = CreateDelegateInstace(); xxx(); xxx(); InitCapturedVariable(); }
public void Async() { WebResponse res = null; try { FileWebRequest req = (FileWebRequest)WebRequest.Create(_tempFileUri); req.Method = "PUT"; req.ContentLength = 1; req.ContentType = "image/png"; req.Timeout = 2 * 1000; IAsyncResult async = req.BeginGetRequestStream(null, null); try { req.BeginGetRequestStream(null, null); Assert.Fail("#1 should've failed"); } catch (InvalidOperationException) { // Cannot re-call BeginGetRequestStream/BeginGetResponse while // a previous call is still in progress } try { req.GetRequestStream(); Assert.Fail("#3 should've failed"); } catch (InvalidOperationException) { // Cannot re-call BeginGetRequestStream/BeginGetResponse while // a previous call is still in progress } using (Stream wstream = req.EndGetRequestStream(async)) { Assert.IsFalse(wstream.CanRead, "#1r"); Assert.IsTrue(wstream.CanWrite, "#1w"); Assert.IsTrue(wstream.CanSeek, "#1s"); wstream.WriteByte(72); wstream.WriteByte(101); wstream.WriteByte(108); wstream.WriteByte(108); wstream.WriteByte(111); wstream.Close(); } Assert.AreEqual(1, req.ContentLength, "#1cl"); Assert.AreEqual("image/png", req.ContentType, "#1ct"); // stream written req = (FileWebRequest)WebRequest.Create(_tempFileUri); res = req.GetResponse(); try { req.BeginGetRequestStream(null, null); Assert.Fail("#20: should've failed"); } catch (InvalidOperationException) { // Cannot send a content-body with this verb-type } try { req.Method = "PUT"; req.BeginGetRequestStream(null, null); Assert.Fail("#21: should've failed"); } catch (InvalidOperationException) { // This operation cannot be perfomed after the request has been submitted. } req.GetResponse(); IAsyncResult async2 = req.BeginGetResponse(null, null); // this succeeds !! WebResponse res2 = req.EndGetResponse(async2); Assert.AreSame(res, res2, "#23"); Assert.AreEqual(5, res.ContentLength, "#2 len"); Assert.AreEqual("application/octet-stream", res.ContentType, "#2 type"); Assert.AreEqual("file", res.ResponseUri.Scheme, "#2 scheme"); Stream rstream = res.GetResponseStream(); Assert.IsTrue(rstream.CanRead, "#3r"); Assert.IsFalse(rstream.CanWrite, "#3w"); Assert.IsTrue(rstream.CanSeek, "#3s"); Assert.AreEqual(72, rstream.ReadByte(), "#4a"); Assert.AreEqual(101, rstream.ReadByte(), "#4b"); Assert.AreEqual(108, rstream.ReadByte(), "#4c"); Assert.AreEqual(108, rstream.ReadByte(), "#4d"); Assert.AreEqual(111, rstream.ReadByte(), "#4e"); rstream.Close(); try { long len = res.ContentLength; Assert.AreEqual((long)5, len, "#5"); } catch (ObjectDisposedException) { Assert.Fail("#disposed contentlength"); } try { WebHeaderCollection w = res.Headers; } catch (ObjectDisposedException) { Assert.Fail("#disposed headers"); } try { res.Close(); } catch (ObjectDisposedException) { Assert.Fail("#disposed close"); } } finally { if (res != null) { res.Close(); } } }
public static int Read(this Stream stream) { return(stream.ReadByte()); }
public void Transfer(ref ResultDTO.MessageType val) { val = (ResultDTO.MessageType)_stream.ReadByte(); }
public override int ReadByte() => _stream.ReadByte();
/// <summary> /// <see cref="IRtspConnection.ReadByte"/> /// </summary> /// <returns></returns> public int ReadByte() { CheckAndAttemptReconnect(); return(_stream.ReadByte()); }