예제 #1
0
파일: LZ77.cs 프로젝트: okkt/jn18
 public void Compress(string path)
 {
     writer     = new CompressedFileWriter(path + ".lz");
     bitBuffer  = new List <bool>();
     dictionary = new StringBuilder();
     phrase     = string.Empty;
     using (var streamReader = new StreamReader(path))
     {
         var chars = new char[CHAR_BLOCK_LENGTH];
         while (!streamReader.EndOfStream)
         {
             var readChars       = streamReader.ReadBlock(chars, 0, CHAR_BLOCK_LENGTH);
             var dataToBeEncoded = new StringBuilder(new string(chars.Take(readChars).ToArray()));
             compressBlock(dataToBeEncoded);
         }
         writer.WriteBlock(bitBuffer);
     }
     writer.Close();
 }
예제 #2
0
파일: LZ77.cs 프로젝트: okkt/jn18
        private void compressBlock(StringBuilder dataToBeEncoded)
        {
            while (dataToBeEncoded.Length > 0)
            {
                var indexInData      = 0;
                var offset           = 2047; // nastaveny offset na 2047, polovica CHAR_BLOCK_LENGTH
                var actualDictionary = dictionary.ToString();
                phrase += dataToBeEncoded[indexInData];
                var indexOfPhrase = actualDictionary.IndexOf(phrase, 0);
                while (indexOfPhrase > -1 && indexInData + 1 < dataToBeEncoded.Length)
                {
                    offset        = indexOfPhrase;
                    phrase       += dataToBeEncoded[++indexInData];
                    indexOfPhrase = actualDictionary.IndexOf(phrase, indexOfPhrase);
                }

                var compressedPhrase = compressPhrase((ushort)offset, (ushort)(phrase.Length - 1), phrase.Last());
                if (bitBuffer.Count + compressedPhrase.Count < BIT_BLOCK_LENGTH)
                {
                    bitBuffer.AddRange(compressedPhrase);
                }
                else
                {
                    var missingBitsCount = BIT_BLOCK_LENGTH - bitBuffer.Count;
                    bitBuffer.AddRange(compressedPhrase.GetRange(0, missingBitsCount));
                    writer.WriteBlock(bitBuffer);
                    bitBuffer = compressedPhrase.GetRange(missingBitsCount, compressedPhrase.Count - missingBitsCount);
                }



                dictionary.Append(dataToBeEncoded.ToString(0, phrase.Length));
                if (dictionary.Length > DICTIONARY_SIZE)
                {
                    dictionary.Remove(DICTIONARY_SIZE, dictionary.Length - DICTIONARY_SIZE);
                }
                dataToBeEncoded.Remove(0, phrase.Length);
                phrase = string.Empty;
            }
        }