Esempio n. 1
0
        public string Decompress(byte[] input)
        {
            var data = new CompressedData();

            data.Load(input);

            _huffmanTree.Build(data.Frequencies);

            var output = new StringBuilder();

            var bits = new BitReader(data.Data);

            var node = _huffmanTree.Root;

            var originalLength = data.OriginalLength;

            while (output.Length < originalLength)
            {
                if (node.Character != '\0')
                {
                    output.Append(node.Character);

                    node = _huffmanTree.Root;
                }

                node = bits.Read() ? node.Right : node.Left;
            }

            return(output.ToString());
        }
Esempio n. 2
0
        public unsafe byte[] Compress(string input)
        {
            var frequencies = _frequencyCalculator.GetFrequencies(input).ToList();

            _huffmanTree.Build(frequencies);

            var blob = new Blob();

            BuildPathCache(frequencies);

            var length = input.Length;

            fixed(char *inputPointer = input)
            {
                for (var i = 0; i < length; i++)
                {
                    blob.Append(_pathCache[inputPointer[i]]);
                }
            }

            var data = new CompressedData
            {
                Data           = blob.ToByteArray(),
                Frequencies    = frequencies,
                OriginalLength = input.Length
            };

            return(data.Save());
        }
Esempio n. 3
0
        public byte[] Compress(string input)
        {
            var frequencies = _frequencyCalculator.GetFrequencies(input).ToList();

            _huffmanTree.Build(frequencies);

            var blob = new Blob();

            _pathCache = new Dictionary <char, string>();

            foreach (var character in input)
            {
                _pathCache.TryGetValue(character, out var path);

                if (path == null)
                {
                    path = _huffmanTree.GetPath(character);

                    _pathCache.Add(character, path);

                    blob.Append(path);
                }
                else
                {
                    blob.Append(path);
                }
            }

            var data = new CompressedData
            {
                Data           = blob.ToByteArray(),
                Frequencies    = frequencies,
                OriginalLength = input.Length
            };

            return(data.Save());
        }