Пример #1
0
    private void LoadSpecies()
    {
        const int maxIndexNumber = 190;

        int numBaseStats = IsYellow ? 151 : 150;

        byte[]     pokedex = ROM.Subarray(SYM["PokedexOrder"], maxIndexNumber);
        ReadStream data    = ROM.From("BaseStats");

        for (int i = 0; i < numBaseStats; i++)
        {
            byte indexNumber = (byte)Array.IndexOf(pokedex, data.Peek());
            Species.Add(new RbySpecies(this, ++indexNumber, data));
        }

        if (this is RedBlue)
        {
            Species.Add(new RbySpecies(this, 21, ROM.From(SYM["MewBaseStats"])));
        }

        // Add MISSINGNO data
        for (int i = 1; i <= maxIndexNumber; i++)
        {
            if (pokedex[i - 1] == 0)
            {
                RbySpecies species = new RbySpecies(this, (byte)i);
                Species.Add(new RbySpecies(this, (byte)i));
            }
        }
    }
Пример #2
0
 public void ReadTestStruct(ReadStream stream, out TestStruct testStruct)
 {
     stream.Bool(out testStruct.bool_value);
     stream.Int(out testStruct.int_value, -100, 100);
     stream.Uint(out testStruct.uint_value, 100, 1000);
     stream.Bits(out testStruct.bits_value, 23);
 }
 public override IEnumerator DoAsync()
 {
     ReadStream = File.OpenRead(this.SourcePath + this.FilePath);
     ByteDatas  = new byte[ReadStream.Length];
     ReadStream.BeginRead(ByteDatas, 0, (int)ReadStream.Length, new AsyncCallback(OnReadStreamCallback), this);
     yield break;
 }
Пример #4
0
        public void Read(ReadStream stream, StreamContext context)
        {
            // Remove from in-flight
            if (context.deltaUpdatesOnly && context.reliableChannel)
            {
                _cache.RemoveUpdateFromInflight(context.updateID);
            }

            // Read properties
            uint propertyID;

            while (stream.ReadNextPropertyID(out propertyID))
            {
                switch (propertyID)
                {
                case (uint)Properties.ActiveState:
                    _activeState = stream.ReadVarint32();
                    FireActiveStateChanged();
                    break;

                case (uint)Properties.DeviceType:
                    _deviceType = stream.ReadVarint32();
                    break;

                default:
                    stream.SkipProperty();
                    break;
                }
            }
        }
Пример #5
0
        public FileReadValue(Path path)

        {
            super(path);

            _is = path.openRead();
        }
Пример #6
0
    public GscTileset(Gsc game, byte id, ReadStream data)
    {
        Game = game;
        Id   = id;
        GFX  = data.u8() << 16 | data.u16le();
        Meta = data.u8() << 16 | data.u16le();
        Coll = data.u8() << 16 | data.u16le();
        Anim = data.u16le();
        data.Seek(2);
        PalMap = data.u16le();

        LandPermissions  = new PermissionSet();
        WaterPermissions = new PermissionSet();
        ReadStream collisionData = game.ROM.From("TileCollisionTable");

        for (int i = 0; i < 256; i++)
        {
            CollisionPermissions perms = (CollisionPermissions)(collisionData.u8() & 0xf);  // Ignore the upper nybble as it only indicates whether the tile can be interacted with.
            if (perms == CollisionPermissions.Land)
            {
                LandPermissions.Add((byte)i);
            }
            else if (perms == CollisionPermissions.Water)
            {
                WaterPermissions.Add((byte)i);
            }
        }
    }
Пример #7
0
    public RbyTrainerClass(Rby game, byte id, int length, ReadStream data, ReadStream name)
    {
        Id    = id;
        Name  = game.Charmap.Decode(name.Until(Charmap.Terminator));
        Teams = new List <List <RbyPokemon> >();

        long initial = data.Position;

        while (data.Position - initial < length)
        {
            List <RbyPokemon> team = new List <RbyPokemon>();
            byte format            = data.u8();
            byte level             = format;
            byte speciesIndex;

            while ((speciesIndex = data.u8()) != 0x00)
            {
                if (format == 0xff)
                {
                    level        = speciesIndex;
                    speciesIndex = data.u8();
                }
                team.Add(new RbyPokemon(game.Species[speciesIndex], level));
            }
            Teams.Add(team);
        }
    }
Пример #8
0
    public RbyTrainer(RbySprite baseSprite, ReadStream data) : base(baseSprite, data)
    {
        TrainerClass = Map.Game.TrainerClasses[data.u8()];
        TeamIndex    = (byte)(data.u8() - 1);

        int textPointer   = Map.Bank << 16 | Map.TextPointer + (TextId - 1) * 2;
        int scriptPointer = Map.Bank << 16 | Map.Game.ROM.u16le(textPointer);
        int headerPointer = Map.Bank << 16 | Map.Game.ROM.u16le(scriptPointer + 2);

        if (baseSprite.Map.Id == 166 || TrainerClass == null || TrainerClass.Name.Contains("RIVAL"))
        {
            return;
        }

        ReadStream header = Map.Game.ROM.From(headerPointer);

        EventFlagBit     = header.u8();
        SightRange       = (byte)(header.u8() >> 4);
        EventFlagAddress = header.u16le();

        if (EventFlagBit >= 8)
        {
            EventFlagBit -= 8;
            EventFlagAddress++;
        }
    }
        private void DeserializeCachedChildViewsModelIfNeeded()
        {
            if (_cachedChildViewsModel == null)
            {
                return;
            }

            if (_childViewsModel == null)
            {
                Debug.LogError("RealtimeViewModel asked to read cached child views model, but doesn't have a child views model to read into. This is a bug!");
                return;
            }

            // Deserialize child views model
            ReadStream cachedChildViewsModelStream = new ReadStream(_cachedChildViewsModel);

            cachedChildViewsModelStream.DeserializeRootModel(_childViewsModel);
            _cachedChildViewsModel = null;

            // Deserialize child views model delta updates
            foreach (CachedDeltaUpdate cachedChildViewsModelDeltaUpdate in _cachedChildViewsModelDeltaUpdates)
            {
                cachedChildViewsModelStream = new ReadStream(cachedChildViewsModelDeltaUpdate.buffer);
                cachedChildViewsModelStream.DeserializeRootModelDeltaUpdates(_childViewsModel, true, cachedChildViewsModelDeltaUpdate.updateID);
            }
            _cachedChildViewsModelDeltaUpdates = null;
        }
Пример #10
0
    private void LoadItems()
    {
        ReadStream nameStream = ROM.From("ItemNames");

        for (int i = 0; i < 256; i++)
        {
            string name;
            if (i > 0x0 && i <= 0x61)
            {
                name = Charmap.Decode(nameStream.Until(Charmap.Terminator));
            }
            else if (i >= 0xc4 && i <= 0xc8)
            {
                name = String.Format("HM{0}", (i + 1 - 0xc4).ToString("D2"));
            }
            else if (i >= 0xc9 && i <= 0xff)
            {
                name = String.Format("TM{0}", (i + 1 - 0xc9).ToString("D2"));
            }
            else
            {
                name = String.Format("hex{0:X2}", i);
            }

            Items.Add(new RbyItem(this, (byte)i, name));
        }
    }
        protected override void Read(ReadStream stream, StreamContext context)
        {
            while (stream.ReadNextPropertyID(out uint propertyID))
            {
                switch (propertyID)
                {
                case (uint)PropertyID.ClientID: {
                    int previousValue = _clientID;
                    _clientID = (int)stream.ReadVarint32();
                    bool clientIDExistsInChangeCache = _cache.ValueExistsInCache(entry => entry.clientIDSet);
                    if (!clientIDExistsInChangeCache && _clientID != previousValue)
                    {
                        FireClientIDDidChange(_clientID);
                    }
                    break;
                }

                case (uint)PropertyID.StreamID: {
                    int previousValue = _streamID;
                    _streamID = (int)stream.ReadVarint32();
                    bool streamIDExistsInChangeCache = _cache.ValueExistsInCache(entry => entry.streamIDSet);
                    if (!streamIDExistsInChangeCache && _streamID != previousValue)
                    {
                        FireStreamIDDidChange(_streamID);
                    }
                    break;
                }

                default: {
                    stream.SkipProperty();
                    break;
                }
                }
            }
        }
Пример #12
0
        public void init(ReadStream @is, WriteStream os)
        {
            super.init(@is, os);

            _is = is;
            _os = os;
        }
Пример #13
0
    public void PlayGambatteMovie(string filename)
    {
        byte[]     file  = File.ReadAllBytes(filename);
        ReadStream movie = new ReadStream(file);

        Debug.Assert(movie.u8() == 0xfe, "The specified file was not a gambatte movie.");
        Debug.Assert(movie.u8() == 0x01, "The specified gambatte movie was of an incorrect version.");

        int stateSize = movie.u24be();

        byte[] state = movie.Read(stateSize);

        LoadState(state);

        while (movie.Position < file.Length)
        {
            long samples = movie.u32be();
            byte input   = movie.u8();

            if (input == 0xff)
            {
                HardReset();
            }
            else
            {
                CurrentJoypad = (Joypad)input;
                while (samples > 0)
                {
                    samples -= RunFor((int)Math.Min(samples, SamplesPerFrame));
                }
            }
        }
    }
Пример #14
0
    private static void Add_Item(ReadStream rs)
    {
        int
            id =

            rs.ReadInt();



        string
            name =

            rs.ReadString();



        string
            Text =

            rs.ReadString();


        RepConfig new_obj_RepConfig = new RepConfig(id, name, Text);

        if (dic.ContainsKey(id))
        {
            LogWarning("duplicate key: " + id);
            return;
        }

        dic.Add(id, new_obj_RepConfig);
        array.Add(new_obj_RepConfig);
    }
Пример #15
0
    public static void Repeat(ReadStream compressed, List <byte> decompressed, int length, int direction, bool flipped)
    {
        // Repeater commands repeat any data already present in the decompressed stream.
        // They take an additional singed operand to mark the relative starting point.
        int offset = 0;

        if (compressed.Peek() >= 0x80)
        {
            // If the operand is negative, it wraps around from the current position.
            offset = compressed.u8() & 0x7f;
            offset = decompressed.Count - offset - 1;
        }
        else
        {
            // For positive operands, a 16-bit offset is used.
            offset = compressed.u16be();
        }

        for (int i = 0; i < length; i++)
        {
            byte b = decompressed[offset + i * direction];
            // Reverse the bits if the command desires it.
            if (flipped)
            {
                b = (byte)(((b * 0x0802LU & 0x22110LU) | (b * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16);
            }
            decompressed.Add(b);
        }
    }
Пример #16
0
    private static void OnLoadFile(byte[] data)
    {
        ReadStream rs = new ReadStream(data);

        /*int file_len = */ rs.ReadInt();
        string flag = rs.ReadString();

        if (flag != "RepConfig")
        {
            LogWarning("invalid file flag" + flag);
            return;
        }

        int col_cnt = rs.ReadShort();

        if (col_cnt != 3)
        {
            LogWarning("col cnt invalid" + col_cnt + " : " + 3);
            return;
        }

        int row_cnt = rs.ReadInt();

        for (int i = 0; i < row_cnt; i++)
        {
            Add_Item(rs);
        }

        resLoaded = true;
    }
Пример #17
0
        private bool parseImageJpeg(ReadStream is)

        {
            int ch = @is.read();

            if (ch != 0xff)
            {
                return(false);
            }

            if (@is.read() != 0xd8)
            {
                return(false);
            }

            TempStream ts = new TempStream();

            WriteStream ws = new WriteStream(ts);

            ws.write(0xff);
            ws.write(0xd8);
            @is.writeToStream(ws);
            ws.close();

            // XXX: issues with _jpegHead vs ts.openReadAndSaveBuffer()
            _jpegHead = ts.getHead();
            @is.close();

            _is = new ReadStream();
            ts.openRead(_is);

            parseJPEG();

            return(true);
        }
Пример #18
0
    // Returns a stream of the ROM data seeked to the specified offset.
    public ReadStream From(int offset)
    {
        ReadStream stream = new ReadStream(Data);

        stream.Seek(offset, SeekOrigin.Begin);
        return(stream);
    }
        protected virtual int WriteOutputStream(IntPtr buffer, int requestedBytes)
        {
            if (_deviceState == DeviceState.Stopped || _outputStreamEnded)
            {
                return((int)BASSStreamProc.BASS_STREAMPROC_END);
            }

            int read = ReadStream.Read(buffer, requestedBytes);

            if (read != -1)
            {
                return(read);
            }

            // We're done!
            // Play silence until playback has stopped to avoid any buffer underruns.
            read = _silence.Write(buffer, requestedBytes);

            // Set a flag so we call HandleOutputStreamEnded() only once.
            _outputStreamEnded = true;

            // Our input stream is finished, wait for device to end playback
            HandleOutputStreamAboutToEnd();
            return(read);
        }
        private void init(Path path)

        {
            _in = path.openRead();

            _isLittleEndian = true;
            int magic = readInt();

            if (magic == 0xde120495)
            {
                _isLittleEndian = false;
            }
            else if (magic != 0x950412de)
            {
                return;
            }

            // Ignore file format revision
            readInt();

            _numberOfStrings   = readInt();
            _offsetOriginal    = readInt();
            _offsetTranslation = readInt();

            if (_numberOfStrings < 0 || _offsetOriginal < 0 || _offsetTranslation < 0)
            {
                return;
            }

            StringValue metadata = getMetadata();

            _pluralExpr = PluralExpr.getPluralExpr(metadata);
            _charset    = getCharset(metadata);
        }
Пример #21
0
        public void MemoryStream_1024_BufferSize_512()
        {
            const int streamLength = 1024;
            const int bufferSize   = 512;

            TestProbe    owner      = CreateTestProbe(name: "owner");
            MemoryStream stream     = CreateMemoryStream(streamLength);
            IActorRef    readStream = ActorOf(
                ReadStream.Create("memory-stream-1024-buffer-size-512", owner, stream, bufferSize)
                );

            Within(TimeSpan.FromSeconds(1), () =>
            {
                // Exactly 2 packets
                for (int iteration = 0; iteration < streamLength / bufferSize; iteration++)
                {
                    owner.ExpectMsg <ReadStream.StreamData>(streamData =>
                    {
                        Assert.Equal(bufferSize, streamData.Data.Count);
                    });
                }
                owner.ExpectMsg <ReadStream.StreamData>(streamData =>
                {
                    Assert.Equal(0, streamData.Data.Count);
                    Assert.True(streamData.IsEndOfStream);
                });
            });
        }
Пример #22
0
    private static void Add_Item(ReadStream rs)
    {
        int
            id =

            rs.ReadInt();



        string
            str =

            rs.ReadString();


        StrConfig new_obj_StrConfig = new StrConfig(id, str);

        if (dic.ContainsKey(id))
        {
            LogWarning("duplicate key: " + id);
            return;
        }

        dic.Add(id, new_obj_StrConfig);
        array.Add(new_obj_StrConfig);
    }
Пример #23
0
    private void LoadMaps()
    {
        const int numMapGroups = 26;

        byte bank = (byte)(SYM["MapGroupPointers"] >> 16);

        int[]      mapGroupOffsets = new int[numMapGroups];
        ReadStream mapGroupsStream = ROM.From("MapGroupPointers");

        for (int i = 0; i < numMapGroups; i++)
        {
            mapGroupOffsets[i] = bank << 16 | mapGroupsStream.u16le();
        }

        for (int mapGroup = 0; mapGroup < numMapGroups; mapGroup++)
        {
            int        currentOffset   = mapGroupOffsets[mapGroup];
            int        nextGroupOffset = mapGroup == numMapGroups - 1 ? SYM["NewBarkTown_MapAttributes"] : mapGroupOffsets[mapGroup + 1];
            int        numMaps         = (nextGroupOffset - currentOffset) / 9;
            ReadStream dataStream      = ROM.From(mapGroupOffsets[mapGroup]);
            for (int map = 0; map < numMaps; map++)
            {
                Maps.Add(new GscMap(this, mapGroup + 1, map + 1, dataStream));
            }
        }
    }
Пример #24
0
    static void test_serialization()
    {
        Log("test_serialization");
        const int MaxPacketSize = 1024;
        var       serializer    = new TestSerializer();
        var       buffer        = new uint[MaxPacketSize / 4];
        var       writeStream   = new WriteStream();

        writeStream.Start(buffer);
        TestStruct input;

        input.bool_value = true;
        input.int_value  = -5;
        input.uint_value = 215;
        input.bits_value = 12345;
        serializer.WriteTestStruct(writeStream, ref input);
        writeStream.Finish();

        var packet     = writeStream.GetData();
        var readStream = new ReadStream();

        readStream.Start(packet);
        TestStruct output;

        serializer.ReadTestStruct(readStream, out output);
        readStream.Finish();

        AreEqual(input.bool_value, output.bool_value);
        AreEqual(input.int_value, output.int_value);
        AreEqual(input.uint_value, output.uint_value);
        AreEqual(input.bits_value, output.bits_value);
    }
Пример #25
0
        public void execute(ReadStream stream)

        {
            QuercusPage page = parse(stream);

            WriteStream os = new WriteStream(StdoutStream.create());

            os.setNewlineString("\n");
            os.setEncoding("iso-8859-1");

            Env env = createEnv(page, os, null, null);

            env.start();

            try {
                env.execute();
            } catch (QuercusDieException e) {
                log.log(Level.FINER, e.ToString(), e);
            } catch (QuercusExitException e) {
                log.log(Level.FINER, e.ToString(), e);
            } catch (QuercusErrorException e) {
                log.log(Level.FINER, e.ToString(), e);
            } finally {
                env.close();

                os.flush();
            }
        }
Пример #26
0
    private void LoadTrainerClasses()
    {
        const int numTrainerClasses = 47;

        ReadStream nameStream         = ROM.From("TrainerNames");
        ReadStream trainerClassStream = ROM.From("TrainerDataPointers");

        int[] trainerDataOffsets = new int[numTrainerClasses];

        for (int i = 0; i < numTrainerClasses; i++)
        {
            trainerDataOffsets[i] = 0x0e << 16 | trainerClassStream.u16le();
        }

        for (int trainerClass = 0; trainerClass < numTrainerClasses; trainerClass++)
        {
            int currentOffset     = trainerDataOffsets[trainerClass];
            int nextTrainerOffset = trainerClass == numTrainerClasses - 1 ? SYM["TrainerAI"] : trainerDataOffsets[trainerClass + 1];
            int length            = nextTrainerOffset - currentOffset;

            if (length == 0)
            {
                nameStream.Until(Charmap.Terminator);
                continue;
            }

            ReadStream dataStream = ROM.From(trainerDataOffsets[trainerClass]);
            TrainerClasses.Add(new RbyTrainerClass(this, (byte)(trainerClass + 201), length, dataStream, nameStream));
        }
    }
Пример #27
0
 public Task <byte[]> ReadAsync(int length, CancellationToken cancel_token)
 {
     if (closedCancelSource.IsCancellationRequested)
     {
         throw new ObjectDisposedException(GetType().Name);
     }
     return(WaitOrCancelTask(async(ct) => {
         var buf = new byte[length];
         var offset = 0;
         while (offset < length)
         {
             ct.ThrowIfCancellationRequested();
             var len = await ReadStream.ReadAsync(buf, offset, length - offset, ct).ConfigureAwait(false);
             if (len == 0)
             {
                 throw new EndOfStreamException();
             }
             else
             {
                 offset += len;
                 readBytesCounter.Add(len);
             }
         }
         return buf;
     }, ReadTimeout, cancel_token));
 }
Пример #28
0
    private void LoadMissableSprites()
    {
        ReadStream data = ROM.From("MissableObjects");

        for (int id = 0; ; id++)
        {
            byte mapId    = data.u8();
            byte spriteId = data.u8();
            byte state    = data.u8();

            if (mapId == 0xff)
            {
                break;
            }

            RbyMap map = Maps[mapId];
            if (map == null)
            {
                continue;
            }

            RbySprite sprite = map.Sprites[spriteId - 1];
            if (sprite == null)
            {
                continue;
            }

            sprite.CanBeMissable   = true;
            sprite.MissableAddress = SYM["wMissableObjectFlags"] + id / 8;
            sprite.MissableBit     = id % 8;
        }
    }
Пример #29
0
        protected virtual int ReadBytes(byte[] buffer, int numberOfBytes)
        {
            var readBytes = ReadStream.Read(buffer, 0, numberOfBytes);

            Position += readBytes;
            return(readBytes);
        }
Пример #30
0
 public GscSpecies(Gsc game, ReadStream data, ReadStream name)   // Names are padded to 10 length using terminator characters.
 {
     Game               = game;
     Name               = game.Charmap.Decode(name.Read(10));
     Id                 = data.u8();
     BaseHP             = data.u8();
     BaseAttack         = data.u8();
     BaseDefense        = data.u8();
     BaseSpeed          = data.u8();
     BaseSpecialAttack  = data.u8();
     BaseSpecialDefense = data.u8();
     Type1              = (GscType)data.u8();
     Type2              = (GscType)data.u8();
     CatchRate          = data.u8();
     BaseExp            = data.u8();
     Item1              = data.u8();
     Item2              = data.u8();
     GenderRatio        = data.u8();
     Unknown1           = data.u8();
     HatchCycles        = data.u8();
     Unknown2           = data.u8();
     FrontSpriteWidth   = data.Nybble();
     FrontSpriteHeight  = data.Nybble();
     data.Seek(4); // 4 unused bytes
     GrowthRate = (GrowthRate)data.u8();
     EggGroup1  = (GscEggGroup)data.Nybble();
     EggGroup2  = (GscEggGroup)data.Nybble();
     data.Seek(8); // TODO: HMs/TMs
 }
Пример #31
0
        internal static PooledStream CreateReadableStream(Stream stream, long length, CancellationToken cancellationToken)
        {
            if (length == -1)
            {
                length = stream.Length;
            }

            long chunkCount = (length + ChunkSize - 1) / ChunkSize;
            byte[][] chunks = new byte[chunkCount][];

            try
            {
                for (long i = 0, c = 0; i < length; i += ChunkSize, c++)
                {
                    int count = (int)Math.Min(ChunkSize, length - i);
                    var chunk = SharedPools.ByteArray.Allocate();

                    int chunkOffset = 0;
                    while (count > 0)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        int bytesRead = stream.Read(chunk, chunkOffset, count);
                        if (bytesRead > 0)
                        {
                            count = count - bytesRead;
                            chunkOffset += bytesRead;
                        }
                        else
                        {
                            break;
                        }
                    }

                    chunks[c] = chunk;
                }

                var result = new ReadStream(length, chunks);
                chunks = null;
                return result;
            }
            finally
            {
                BlowChunks(chunks);
            }
        }
Пример #32
0
 public static void CreatePipe(out Stream write, out Stream read)
 {
     var buffer = new PipeStream();
     write = new WriteStream(buffer);
     read = new ReadStream(buffer);
 }
Пример #33
0
 public ProxyStream(WriteStream writer, ReadStream reader)
 {
     m_writer = writer ?? base.Write;
       m_reader = reader ?? base.Read;
 }
Пример #34
0
        //
        //
        //
        private Stream Lookup(string key, out RequestCacheEntry cacheEntry, bool isThrow)
        {
            if(Logging.On) Logging.Enter(Logging.RequestCache, "WinInetCache.Retrieve", "key = " + key);

            if (key == null) {
                throw new ArgumentNullException("key");
            }

            Stream result = Stream.Null;
            SafeUnlockUrlCacheEntryFile handle = null;
            _WinInetCache.Entry entry = new _WinInetCache.Entry(key, _MaximumResponseHeadersLength);
            try {
                handle = _WinInetCache.LookupFile(entry);

                if (entry.Error == _WinInetCache.Status.Success) {
                    if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_filename, "WinInetCache.Retrieve()", entry.Filename, entry.Error));

                    cacheEntry = new RequestCacheEntry(entry, IsPrivateCache);

                    if (entry.MetaInfo != null && entry.MetaInfo.Length != 0)
                    {
                        // convert metadata to upto two string collections
                        unsafe
                        {
                            int start = 0;
                            int length = entry.MetaInfo.Length;
                            StringCollection sc = new StringCollection();
                            fixed (char * ch = entry.MetaInfo)
                            {
                                int i;
                                for (i = 0; i < length; ++i)
                                {
                                    // WinInet specific block!!
                                    // The point here is that wininet scans for ~U: throughly with no regard to \r\n so we mimic the same behavior
                                    if (i == start && i+2 < length)
                                    {
                                        if (ch[i] == '~' && (ch[i+1] == 'U' || ch[i+1] == 'u') && ch[i+2] == ':')
                                        {
                                            //Security: don't report what the username is
                                            while(i < length && ch[++i] != '\n') {;}
                                            start = i+1;
                                            continue;
                                        }

                                    }

                                    // note a metadata entry must terminate with \r\n

                                    if ((i+1 == length) || (ch[i] == '\n'))
                                    {
                                        string value = entry.MetaInfo.Substring(start, (ch[i-1] == '\r'? (i-1):(i+1)) - start);

                                        if (value.Length == 0 && cacheEntry.EntryMetadata == null)
                                        {
                                            // done with headers, prepare for system metadata
                                            cacheEntry.EntryMetadata = sc;
                                            sc = new StringCollection();
                                        }
                                        else
                                        {
                                            //WinInet specific block!!
                                            // HACK: if we are parsing system metadata and have found our hack,
                                            // then convert it to a sparse entry type (entry.Info.EntryType & _WinInetCache.EntryType.Sparse)
                                            if (cacheEntry.EntryMetadata != null && value.StartsWith(c_SPARSE_ENTRY_HACK, StringComparison.Ordinal))
                                                cacheEntry.IsPartialEntry = true;
                                            else
                                                sc.Add(value);
                                        }
                                        start = i+1;
                                    }
                                }
                            }
                            if (cacheEntry.EntryMetadata == null )
                                {cacheEntry.EntryMetadata = sc;}
                            else
                                {cacheEntry.SystemMetadata = sc;}
                        }
                    }

                    result = new ReadStream(entry, handle, async);

                }
                else {
                    if (handle != null) {
                        handle.Close();
                    }

                    cacheEntry = new RequestCacheEntry();
                    cacheEntry.IsPrivateEntry = IsPrivateCache;

                    if (entry.Error != _WinInetCache.Status.FileNotFound)
                    {
                        if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_lookup_failed, "WinInetCache.Retrieve()", new Win32Exception((int)entry.Error).Message));
                        if(Logging.On)Logging.Exit(Logging.RequestCache, "WinInetCache.Retrieve()");
                        if(isThrow)
                        {
                            Win32Exception win32Exception = new Win32Exception((int)entry.Error);
                            throw new IOException(SR.GetString(SR.net_cache_retrieve_failure, win32Exception.Message), win32Exception);
                        }
                        return null;
                    }
                }
            }
            catch (Exception exception) {
                if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) {
                    throw;
                }

                if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_exception, "WinInetCache.Retrieve()", exception.ToString()));
                if(Logging.On)Logging.Exit(Logging.RequestCache, "WinInetCache.Retrieve()");

                if (handle != null) {
                    handle.Close();
                }
                result.Close();
                result = Stream.Null;
                cacheEntry = new RequestCacheEntry();
                cacheEntry.IsPrivateEntry = IsPrivateCache;
                if (isThrow)
                {
                    throw;
                }
                return null;
            }
            if(Logging.On)Logging.Exit(Logging.RequestCache, "WinInetCache.Retrieve()", "Status = " + entry.Error.ToString());
            return result;
        }
 private unsafe Stream Lookup(string key, out RequestCacheEntry cacheEntry, bool isThrow)
 {
     if (Logging.On)
     {
         Logging.Enter(Logging.RequestCache, "WinInetCache.Retrieve", "key = " + key);
     }
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     Stream @null = Stream.Null;
     SafeUnlockUrlCacheEntryFile handle = null;
     _WinInetCache.Entry entry = new _WinInetCache.Entry(key, _MaximumResponseHeadersLength);
     try
     {
         handle = _WinInetCache.LookupFile(entry);
         if (entry.Error == _WinInetCache.Status.Success)
         {
             if (Logging.On)
             {
                 Logging.PrintInfo(Logging.RequestCache, SR.GetString("net_log_cache_filename", new object[] { "WinInetCache.Retrieve()", entry.Filename, entry.Error }));
             }
             cacheEntry = new RequestCacheEntry(entry, base.IsPrivateCache);
             if ((entry.MetaInfo != null) && (entry.MetaInfo.Length != 0))
             {
                 int startIndex = 0;
                 int length = entry.MetaInfo.Length;
                 StringCollection strings = new StringCollection();
                 fixed (char* str2 = ((char*) entry.MetaInfo))
                 {
                     char* chPtr = str2;
                     for (int i = 0; i < length; i++)
                     {
                         if ((((i == startIndex) && ((i + 2) < length)) && (chPtr[i] == '~')) && (((chPtr[i + 1] == 'U') || (chPtr[i + 1] == 'u')) && (chPtr[i + 2] == ':')))
                         {
                             while ((i < length) && (chPtr[++i] != '\n'))
                             {
                             }
                             startIndex = i + 1;
                         }
                         else if (((i + 1) == length) || (chPtr[i] == '\n'))
                         {
                             string str = entry.MetaInfo.Substring(startIndex, ((chPtr[i - 1] == '\r') ? (i - 1) : (i + 1)) - startIndex);
                             if ((str.Length == 0) && (cacheEntry.EntryMetadata == null))
                             {
                                 cacheEntry.EntryMetadata = strings;
                                 strings = new StringCollection();
                             }
                             else if ((cacheEntry.EntryMetadata != null) && str.StartsWith("~SPARSE_ENTRY:", StringComparison.Ordinal))
                             {
                                 cacheEntry.IsPartialEntry = true;
                             }
                             else
                             {
                                 strings.Add(str);
                             }
                             startIndex = i + 1;
                         }
                     }
                 }
                 if (cacheEntry.EntryMetadata == null)
                 {
                     cacheEntry.EntryMetadata = strings;
                 }
                 else
                 {
                     cacheEntry.SystemMetadata = strings;
                 }
             }
             @null = new ReadStream(entry, handle, this.async);
         }
         else
         {
             if (handle != null)
             {
                 handle.Close();
             }
             cacheEntry = new RequestCacheEntry();
             cacheEntry.IsPrivateEntry = base.IsPrivateCache;
             if (entry.Error != _WinInetCache.Status.FileNotFound)
             {
                 if (Logging.On)
                 {
                     Logging.PrintError(Logging.RequestCache, SR.GetString("net_log_cache_lookup_failed", new object[] { "WinInetCache.Retrieve()", new Win32Exception((int) entry.Error).Message }));
                 }
                 if (Logging.On)
                 {
                     Logging.Exit(Logging.RequestCache, "WinInetCache.Retrieve()");
                 }
                 if (isThrow)
                 {
                     Win32Exception innerException = new Win32Exception((int) entry.Error);
                     throw new IOException(SR.GetString("net_cache_retrieve_failure", new object[] { innerException.Message }), innerException);
                 }
                 return null;
             }
         }
     }
     catch (Exception exception2)
     {
         if (((exception2 is ThreadAbortException) || (exception2 is StackOverflowException)) || (exception2 is OutOfMemoryException))
         {
             throw;
         }
         if (Logging.On)
         {
             Logging.PrintError(Logging.RequestCache, SR.GetString("net_log_cache_exception", new object[] { "WinInetCache.Retrieve()", exception2.ToString() }));
         }
         if (Logging.On)
         {
             Logging.Exit(Logging.RequestCache, "WinInetCache.Retrieve()");
         }
         if (handle != null)
         {
             handle.Close();
         }
         @null.Close();
         @null = Stream.Null;
         cacheEntry = new RequestCacheEntry();
         cacheEntry.IsPrivateEntry = base.IsPrivateCache;
         if (isThrow)
         {
             throw;
         }
         return null;
     }
     if (Logging.On)
     {
         Logging.Exit(Logging.RequestCache, "WinInetCache.Retrieve()", "Status = " + entry.Error.ToString());
     }
     return @null;
 }