Skip to content
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
37 changes: 37 additions & 0 deletions LZW/LZW.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33403.182
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LZW", "LZW\LZW.csproj", "{B99BFF18-B071-406A-989E-994845F53D3B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestsBor", "TestsBor\TestsBor.csproj", "{019B956A-4284-4708-9B93-8D6FC218A62E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestLZW", "TestLZW\TestLZW.csproj", "{C3A8A289-5E8E-4D79-8263-3E4726F4A4CD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B99BFF18-B071-406A-989E-994845F53D3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B99BFF18-B071-406A-989E-994845F53D3B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B99BFF18-B071-406A-989E-994845F53D3B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B99BFF18-B071-406A-989E-994845F53D3B}.Release|Any CPU.Build.0 = Release|Any CPU
{019B956A-4284-4708-9B93-8D6FC218A62E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{019B956A-4284-4708-9B93-8D6FC218A62E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{019B956A-4284-4708-9B93-8D6FC218A62E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{019B956A-4284-4708-9B93-8D6FC218A62E}.Release|Any CPU.Build.0 = Release|Any CPU
{C3A8A289-5E8E-4D79-8263-3E4726F4A4CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C3A8A289-5E8E-4D79-8263-3E4726F4A4CD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C3A8A289-5E8E-4D79-8263-3E4726F4A4CD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C3A8A289-5E8E-4D79-8263-3E4726F4A4CD}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {40032E74-4213-49E7-9C40-632CA5D1FA92}
EndGlobalSection
EndGlobal
143 changes: 143 additions & 0 deletions LZW/LZW/Bor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
namespace Bor;

/// <summary>
/// String Parsing Tree
/// </summary>
public class Bor
{
private BorElement root = new();

/// <summary>
/// Adding an element to a Trie
/// </summary>
public (bool, int) Add(char[] buffer, int from = 0, int to = 0)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}

if (root == null)
{
throw new InvalidOperationException();

Choose a reason for hiding this comment

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

Если buffer null, надо кидать ArgumentNullException(nameof(buffer))

}
var walker = root;
int i = 0;
int pointer = from;
int toSymbolCode = -1;
bool isStringInBor = Contains(buffer, from, to);
while (i < to - from + 1)
{
int number = (int)buffer[pointer];
if (!walker.Next.ContainsKey(number))
{
walker.Next.Add(number, new BorElement());
++walker.SizeDictionary;
}
if (!isStringInBor)
{
++walker.Next[number].HowManyStringInDictionary;
}
toSymbolCode = walker.SymbolCode;
walker = walker.Next[number];
pointer++;
i++;
}
if (!walker.IsTerminal)
{
walker.SymbolCode = root.HowManyStringInDictionary;
root.HowManyStringInDictionary++;
}

if (!walker.IsTerminal)
{
walker.IsTerminal = true;
return (true, toSymbolCode);
}
else
{
return (true, toSymbolCode);
}

}

/// <summary>
/// Returns a stream by letter
/// </summary>
public int ReturnSymbolCodeByCharArray(char[] buffer, int to = 0, int from = 0)
{
if (buffer.Length == 0)
{
return -1;
}
var walker = root;
int i = 0;
int pointer = from;
while(i < to - from + 1)
{
int number = (int)buffer[pointer];
if (!walker.Next.ContainsKey(number))
{
return -1;
}
walker = walker.Next[number];
++i;
}
return walker.SymbolCode;
}

/// <summary>
/// Returns how many strings in a Trie
/// </summary>
public int HowManyStringsInBor()
{
if (root == null)
{
return -1;
}
return root.HowManyStringInDictionary;
}

/// <summary>
/// Checks whether the string in the Trie contains
/// </summary>
public bool Contains(char[] buffer, int from = 0 , int to = 0)
{
if (root == null)
{
return false;
}
var walker = root;
int i = 0;
int pointer = from;
while (i < to - from + 1)
{
if (!walker.Next.ContainsKey(buffer[pointer]))
{
return false;
}
walker = walker.Next[buffer[pointer]];
pointer++;
++i;
}
return true;
}

private class BorElement
{
public Dictionary<int, BorElement> Next { get; set; }
public bool IsTerminal { get; set; }

public int SizeDictionary { get; set; }

public int HowManyStringInDictionary { get; set; }

public int SymbolCode { get; set; }

public BorElement()
{
Next = new Dictionary<int, BorElement>();
SymbolCode = -1;
}
}
}
189 changes: 189 additions & 0 deletions LZW/LZW/LZW.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
namespace LZW;

using Bor;

/// <summary>
/// A class for compressing and decompressing data using the LZW algorithm
/// </summary>
public static class LZWAlgorithm
{
private static void AddAlphabetToBor(Bor bor)
{
var letter = new char[1];
for (int i = 0; i < 256; ++i)
{
letter[0] = (char)i;
bor.Add(letter, 0, 0);
}
}

private static bool CodeFile(string fileName, ref double compressionRatio)
{
double sizeForCompressionRatio = 0;
try
{
FileInfo fileFromMain = new(fileName);
sizeForCompressionRatio = fileFromMain.Length;
}
catch (FileNotFoundException)
{
return false;
}
string newFile = fileName + ".zipped";

File.WriteAllText(newFile, string.Empty);

var bor = new Bor();
AddAlphabetToBor(bor);

byte[] bufferIn = File.ReadAllBytes(fileName);
if (bufferIn.Length == 0)
{
compressionRatio = 1;
return true;
}
int j = 0;
var textFromFile = new char[bufferIn.Length];
for (int i = 0; i < bufferIn.Length; ++i)
{
textFromFile[j] = Convert.ToChar(bufferIn[i]);

Choose a reason for hiding this comment

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

Идеологически правильно было бы не конвертить в char-ы (которые в C# вообще двухбайтовые), а бор на байты переписать (от чего ему стало бы только лучше, 256 сыновей у вершины, а не 65536).

++j;
}

// Добавление потоков в файл
int walker = 0;
using var archivedFile = new FileStream(newFile, FileMode.Append);
for (int i = 0; i < textFromFile.Length; i++)
{
if (!bor.Contains(textFromFile, walker, i))
{
var (_, flow) = bor.Add(textFromFile, walker, i);
walker = i;
byte[] bytes = BitConverter.GetBytes(flow);
archivedFile.WriteAsync(bytes, 0, bytes.Length);
}
}

// Добавление последнего потока в файл
var flowLast = bor.ReturnSymbolCodeByCharArray(textFromFile, bufferIn.Length - 1, bufferIn.Length - 1);
byte[] bytesLast = BitConverter.GetBytes(flowLast);
archivedFile.WriteAsync(bytesLast, 0, bytesLast.Length);
archivedFile.Close();
var file = new FileInfo(newFile.ToString());
double newSizeForCompressionRatio = file.Length;
compressionRatio = newSizeForCompressionRatio / sizeForCompressionRatio;
return true;
}

private static bool DecodeFile(string fileName)
{
byte[]? bufferIn = null;
try
{
bufferIn = File.ReadAllBytes(fileName);
}
catch (FileNotFoundException)
{
return false;
}
int i = 0;
string newFile = fileName.Remove(fileName.Length - 7);

File.WriteAllText(newFile, string.Empty);

if (fileName.Length == 0)
{
return true;
}

var dictionaryForDecode = new Dictionary<int, char[]>();

for (int j = 0; j < 256; ++j)
{
var stringLetter = new char[1];
stringLetter[0] = (char)j;
dictionaryForDecode.Add(j, stringLetter);
}

int index = 256;
int input = 0;
char[]? previousString = null;
bool isFirst = true;
while (i < bufferIn.Length)
{
var symbolFromArray = new byte[4];
int pointerForSymbolsFromOneArray = 0;
int size = i + 4;
for (; i < size; ++i)
{
symbolFromArray[pointerForSymbolsFromOneArray] = bufferIn[i];
++pointerForSymbolsFromOneArray;
}

input = BitConverter.ToInt32(symbolFromArray, 0);

if (!isFirst)
{
if (!dictionaryForDecode.ContainsKey(input))
{
ArgumentNullException.ThrowIfNull(previousString);
Array.Resize(ref previousString, previousString.Length + 1);
previousString[previousString.Length - 1] = previousString[0];
dictionaryForDecode.Add(index, previousString);
}
var stringByIndex = dictionaryForDecode[input];
if (index != input)
{
ArgumentNullException.ThrowIfNull(previousString);
Array.Resize(ref previousString, previousString.Length + 1);
previousString[previousString.Length - 1] = stringByIndex[0];
dictionaryForDecode.Add(index, previousString);
}
FileStream file = File.Open(newFile, FileMode.Append);
foreach (var symbol in stringByIndex)
{
file.WriteByte((byte)symbol);
}
file.Close();
previousString = stringByIndex;
++index;
}
else
{
var stringByIndex = dictionaryForDecode[input];
previousString = stringByIndex;
isFirst = false;
using FileStream file = File.Open(newFile, FileMode.Append);
foreach (var symbol in stringByIndex)
{
file.WriteByte((byte)symbol);
}
file.Close();
}
}
return true;
}

/// <summary>
/// Function for accepting data
/// </summary>
/// <param name="parameter">Shows decompression or compression</param>
/// <returns>Returns whether it was executed correctly and what is the compression percentage</returns>
public static (bool, double) LzwAlgorithm(string fileName, string parameter)
{
if (parameter.Length == 2 && parameter[0] == '-' && parameter[1] == 'c')
{
double compressionRatio = 0;
var isCorrect = CodeFile(fileName, ref compressionRatio);
return (isCorrect, compressionRatio);
}
else if (parameter.Length == 2 && parameter[0] == '-' && parameter[1] == 'u')
{
return (DecodeFile(fileName), 0);
}
else
{
return (false, 0);
}
}
}
10 changes: 10 additions & 0 deletions LZW/LZW/LZW.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
10 changes: 10 additions & 0 deletions LZW/LZW/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using LZW;


var (isCorrect, compressionRatio) = LZWAlgorithm.LzwAlgorithm(args[0], args[1]);
if (!isCorrect)
{
Console.WriteLine("Problems...");
return;
}
Console.WriteLine(compressionRatio);
Loading