Example #1
0
        public override void Compress(BinaryReader reader, BinaryWriter writer)
        {
            CodeTable tb = new CodeTable(_codeLength);

            tb.FillChars();
            char   firstChar   = (char)reader.ReadByte();
            string match       = firstChar.ToString();
            int    lastPercent = 0;

            while (reader.BaseStream.Position < reader.BaseStream.Length)
            {
                lastPercent = RaiseEvent(reader, lastPercent);
                char   nextChar  = (char)reader.ReadByte();
                string nextMatch = match + nextChar.ToString();
                if (tb.Contains(nextMatch))
                {
                    if (tb.HasSpace)
                    {
                        match = nextMatch;
                    }
                    else
                    {
                        WriteCode(writer, tb.GetCode(nextMatch));
                        if (reader.BaseStream.Position < reader.BaseStream.Length)
                        {
                            match = ((char)reader.ReadByte()).ToString();
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    WriteCode(writer, tb.GetCode(match));
                    if (tb.HasSpace)
                    {
                        tb.AddString(nextMatch);
                    }

                    match = nextChar.ToString();
                }

                Debug.Assert(writer.BaseStream.Position % 2 == 0);
            }

            WriteCode(writer, tb.GetCode(match));
            RaiseFinishEvent();
        }