Example #1
1
 protected int ReadByteAfterWhitespace(Stream s)
 {
     int buff = s.ReadByte();
     while (buff >= 0 && IsWhitespace(buff))
         buff = s.ReadByte();
     return buff;
 }
Example #2
0
 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 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);
        }
    /// <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;
    }
Example #5
0
 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;
 }
Example #6
0
 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();
 }
Example #7
0
		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);
				}
			}
		}
Example #8
0
 public MX(String  Name,
           Stream  Stream)
     : base(Name, TypeId, Stream)
 {
     this._Preference  = (Stream.ReadByte() << 8) | (Stream.ReadByte() & Byte.MaxValue);
     this._Exchange    = DNSTools.ExtractName(Stream);
 }
Example #9
0
        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);
        }
Example #10
0
 private static Stream MoveStream(Stream stream)
 {
     // HACK: we need this to get the DeflateStream to read properly
     stream.ReadByte();
     stream.ReadByte();
     return stream;
 }
		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();
		}
        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();
        }
        /// <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 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 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;
		}
Example #16
0
 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;
 }
Example #17
0
		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);
		}
Example #18
0
        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;
            }
        }
Example #19
0
        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();
        }
Example #20
0
        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,
                };
            }
        }
Example #21
0
        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;
            }
        }
Example #22
0
 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
 }
        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;
        }
Example #24
0
 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);
 }
Example #25
0
        // 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;
        }
Example #26
0
 private static bool IsPortable(Stream pdbStream)
 {
     return pdbStream.ReadByte() == 'B' &&
         pdbStream.ReadByte() == 'S' &&
         pdbStream.ReadByte() == 'J' &&
         pdbStream.ReadByte() == 'B';
 }
Example #27
0
 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;
             }
         }
     }
 }
Example #28
0
		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 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();
        }
Example #30
0
 /// <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);
 }