Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LZW #5

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -385,10 +385,10 @@ FodyWeavers.xsd

# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
#!.vscode/settings.json
#!.vscode/tasks.json
#!.vscode/launch.json
#!.vscode/extensions.json
*.code-workspace

# Local History for Visual Studio Code
Expand Down
24 changes: 24 additions & 0 deletions LZW/LZW.Src/Compressor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using LZW.Dependencies;

namespace Compressor;

internal static class Compressor
{
public static byte[] Compress(byte[] bytes, int BWTPosition = -1)
{
var trie = new Trie();
var buffer = new ByteBuffer();
buffer.SetBWTPosition(BWTPosition);
for (int i = 0; i < bytes.Length; ++i)
{
if (trie.Size == buffer.MaxSize)
{
buffer.MaxSize *= 2;
++buffer.currentBitCount;
}
int number = trie.Add(ref i, bytes);
buffer.AddNumber(number);
}
return buffer.ToByteArray();
}
}
89 changes: 89 additions & 0 deletions LZW/LZW.Src/Decompressor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using System.ComponentModel;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization.Formatters;
using LZW.Dependencies;

namespace Compressor;

internal class Decompressor
{
public static byte[] Decompress(byte[] bytes)
{
if (bytes.Length == 0)
{
throw new InvalidDataException("empty byte sequence");
}

Dictionary<int, List<byte>> dictionary = new();

for (int i = 0; i < 256; ++i)
{
dictionary[i] = new List<byte> { (byte)(i) };
}

int bwtPosition = BitConverter.ToInt32(new byte[] { bytes[0], bytes[1], bytes[2], bytes[3] });
var list = new List<byte>(bytes);
list.RemoveRange(0, 4);
bytes = list.ToArray();

if (bwtPosition != -1)
{
bytes = BWT.Revert(bytes, bwtPosition);
}

int counter = 256;
NumberBuffer numberBuffer = new();

for (int i = 0; i < bytes.Length; ++i)
{
if (counter == numberBuffer.MaxNumber)
{
numberBuffer.MaxNumber *= 2;
++numberBuffer.currentBitCount;
}

if (numberBuffer.AddByte(bytes[i]))
{
++counter;
}
}

int[] intArray = numberBuffer.ToIntArray();
counter = 256;

List<byte> decodedBytes = new();
for (int i = 0; i < intArray.Length - 1; ++i)
{
decodedBytes.AddRange(dictionary[intArray[i]]);

List<byte> newCodeSequence = new();
newCodeSequence.AddRange(dictionary[intArray[i]]);

if (!dictionary.ContainsKey(intArray[i + 1]))
{
newCodeSequence.Add(newCodeSequence[0]);
dictionary[counter] = newCodeSequence;
}
else
{
newCodeSequence.Add(dictionary[intArray[i + 1]][0]);
dictionary[counter] = newCodeSequence;
}

++counter;
}
return decodedBytes.ToArray();
}

// private static (int[], int) getNumbersAndBwtPosition(byte[] bytes)
// {
// int bwtPosition = BitConverter.ToInt32(new byte[] { bytes[0], bytes[1], bytes[2], bytes[3] });
// var buffer = new NumberBuffer();
// for (int i = 5; i < bytes.Length; ++i)
// {
// var oneByte = bytes[i];
// buffer.AddByte(oneByte, true);
// }
// return (buffer.Numbers.ToArray(), bwtPosition);
// }
}
Comment on lines +78 to +89
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete commented code

121 changes: 121 additions & 0 deletions LZW/LZW.Src/Dependencies/BWT.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
using System.Collections;
using System.Runtime.CompilerServices;
using System.Threading.Tasks.Dataflow;

namespace LZW.Dependencies;

/// <summary>
/// Класс, содержащий в себе методы для преобразования и обратного
/// преобразования Барроуза-Уилера для байтовых массивов
/// </summary>
public class BWT
{
/// <summary>
/// Строит преобразование Барроуза-Уилера
/// </summary>
/// <param name="bytes">Байтовый массив, для которого нужно построить
/// преобразование</param>
/// <returns>Байтовый массив - исходный массив после преобразования\n
/// и число - позиция исходной строке в таблице циклических сдвигов</returns>
public static (byte[], int) Transform(byte[] bytes)
{
var indexArray = new int[bytes.Length];
int BWTPosition = 0;

for (int i = 0; i < bytes.Length; ++i)
{
indexArray[i] = i;
}

Array.Sort(indexArray, (a, b) => Compare(a, b, bytes));

var transformedBytes = new byte[bytes.Length];
for (int i = 0; i < bytes.Length; ++i)
{
if (indexArray[i] == 0)
{
BWTPosition = i;
transformedBytes[i] = bytes[bytes.Length - 1];
continue;
}
transformedBytes[i] = bytes[indexArray[i] - 1];
}

return (transformedBytes, BWTPosition);
}


/// <summary>
/// Обратное преобразование
/// </summary>
/// <param name="bytes">Байтовая последовательность, по
/// которой нужно восстановить исходную</param>
/// <param name="BWTPosition">Позициая исходной строки в
/// таблице циклических сдвигов</param>
/// <returns>Исзходная байтовая последовательность</returns>
public static byte[] Revert(byte[] bytes, int BWTPosition)
{
var sortedBytes = new byte[bytes.Length];
Array.Copy(bytes, sortedBytes, bytes.Length);
Array.Sort(sortedBytes);

var result = new byte[bytes.Length];

for (int i = 0; i < bytes.Length; ++i)
{
byte currentByte = sortedBytes[BWTPosition];
result[i] = currentByte;

int countF = 0;
for (int k = 0; k < BWTPosition + 1; ++k)
{
if (sortedBytes[k] == currentByte)
{
++countF;
}
}

int countL = 0;
int j = 0;
for (; countL != countF; ++j)
{
if (bytes[j] == currentByte)
{
++countL;
}
}
BWTPosition = j - 1;
}

return result;
}

private static int Compare(int a, int b, byte[] bytes)
{
int min = bytes.Length - (a > b ? a : b);
for (int i = 0; i < min; ++i)
{
if (bytes[a + i] < bytes[b + i])
{
return -1;
}
else if (bytes[a + i] > bytes[b + i])
{
return 1;
}
}
if (a > b)
{
return -1;
}
else if (a < b)
{
return 1;
}
else
{
return 0;
}
}

}
69 changes: 69 additions & 0 deletions LZW/LZW.Src/Dependencies/ByteBuffer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
namespace LZW.Dependencies;

/// <summary>
/// Структура данных, представляющая собой последовательность чисел в двоичной форме, из которой можно получить байтовый массив
/// </summary>
class ByteBuffer
{
public int MaxSize = 256;
public int currentBitCount = 8;
private const int BITS_IN_BYTE = 8;
int currentByteSize = 0;
byte currentByte = 0;
List<byte> buffer = new();

/// <summary>
/// Добавляет 4 байта в начале - позиция исходной строки в таблице циклических сдвигов преобразования Барроуза-Уилера
/// </summary>
/// <param name="position">Позиция исходной строки в таблице</param>
public void SetBWTPosition(int position)
{
var positionBytes = BitConverter.GetBytes(position);
buffer.AddRange(positionBytes);
}

/// <summary>
/// Метод, добавляющий число в буффер
/// </summary>
/// <param name="number">Число, которое нужно добавить</param>
public void AddNumber(int number)
{
var bits = IntToByte(number);
foreach (var bit in bits)
{
currentByte = (byte)((currentByte << 1) + bit);
++currentByteSize;
if (currentByteSize == BITS_IN_BYTE)
{
currentByteSize = 0;
buffer.Add(currentByte);
currentByte = 0;
}
}
}

/// <summary>
/// Метод, позволяющий получить байтовый массив из текущего буффера
/// </summary>
/// <returns>байтовый массив</returns>
public byte[] ToByteArray()
{
currentByte <<= BITS_IN_BYTE - currentByteSize;
currentByteSize = 0;
currentByte = 0;
buffer.Add(currentByte);
return buffer.ToArray();
}

private byte[] IntToByte(int number)
{
var bits = new byte[currentBitCount];
for (int i = currentBitCount - 1; i >= 0; --i)
{
bits[i] = (byte)(number % 2);
number /= 2;
}

return bits;
}
}
72 changes: 72 additions & 0 deletions LZW/LZW.Src/Dependencies/NumberBuffer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using System.Transactions;

namespace LZW.Dependencies;

/// <summary>
/// Структура данных, хранящая последовательность чисел, из которой можно получить массив
/// </summary>
class NumberBuffer
{
public int currentBitCount = 8;
private int currentNumber = 0;
public int currentNumberLength = 0;
private const int BITS_IN_BYTE = 8;
public int MaxNumber = 256;
public List<int> Numbers;

public NumberBuffer()
{
Numbers = new List<int>();
}

/// <summary>
/// Метод, позволяющий добавить число, зашифрованное байтом (число добавляется, когда наберется нужно число байт для шифрования числа)
/// </summary>
/// <param name="oneByte">Байт, который нужно добавить</param>
/// <returns>True, если текущий байт был последним байтом числа и оно добавилось</returns>
public bool AddByte(byte oneByte)
{
bool newNumber = false;
var bits = ByteToByteArray(oneByte);
foreach (var bit in bits)
{
currentNumber = (currentNumber * 2) + bit;
if (++currentNumberLength == currentBitCount)
{
AddNumberToBuffer();
newNumber = true;
}
}

return newNumber;
}

/// <summary>
/// Позволяет получить массив уже добавленных чисел
/// </summary>
/// <returns>Массив чисел</returns>
public int[] ToIntArray()
{
AddNumberToBuffer();
return Numbers.ToArray();
}

private void AddNumberToBuffer()
{
Numbers.Add(currentNumber);
currentNumber = 0;
currentNumberLength = 0;
}

private byte[] ByteToByteArray(byte oneByte)
{
var bits = new byte[BITS_IN_BYTE];
for (int i = BITS_IN_BYTE - 1; i >=0; --i)
{
bits[i] = (byte)(oneByte % 2);
oneByte >>= 1;
}

return bits;
}
}
Loading