Пример #1
0
Файл: LZW.cs Проект: ybug/CivOne
        public static byte[] Encode(byte[] input, bool clearEnd = false, bool flushDictionary = true, int maxBits = 11)
        {
            Dictionary <string, int> dictionary = EncodeDictionary(clearEnd);
            ByteList byteList = new ByteList();

            if (clearEnd)
            {
                byteList.Add(dictionary["CLR"], dictionary.Count);
            }

            byte[] entry = new byte[0];
            for (int i = 0; i < input.Length; i++)
            {
                byte[] newEntry = Append(entry, input[i]);
                if (dictionary.ContainsKey(string.Join(",", newEntry)))
                {
                    entry = newEntry;
                    continue;
                }
                byteList.Add(dictionary[string.Join(",", entry)], dictionary.Count);
                if (flushDictionary)
                {
                    if (CodeLength(dictionary.Count) <= maxBits)
                    {
                        dictionary.Add(string.Join(",", newEntry), dictionary.Count);
                    }
                    else
                    {
                        dictionary = EncodeDictionary(clearEnd);
                    }
                }
                else if (CodeLength(dictionary.Count + 1) <= maxBits)
                {
                    dictionary.Add(string.Join(",", newEntry), dictionary.Count);
                }

                entry = new byte[] { input[i] };
            }

            if (entry.Length > 0)
            {
                byteList.Add(dictionary[string.Join(",", entry)], dictionary.Count);
            }

            if (clearEnd)
            {
                byteList.Add(dictionary["END"], dictionary.Count);
            }
            byteList.Close();

            return(byteList.ToArray());
        }