Добавьте файлы проекта.
This commit is contained in:
57
.old 4/DTLib/Color.cs
Normal file
57
.old 4/DTLib/Color.cs
Normal file
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
public class Color
|
||||
{
|
||||
public class RGBA
|
||||
{
|
||||
public byte R;
|
||||
public byte G;
|
||||
public byte B;
|
||||
public byte A;
|
||||
|
||||
public RGBA() { }
|
||||
|
||||
public RGBA(byte R, byte G, byte B, byte A)
|
||||
{
|
||||
this.R = R;
|
||||
this.G = G;
|
||||
this.B = B;
|
||||
this.A = A;
|
||||
}
|
||||
|
||||
public RGBA(byte[] arrayRGBA)
|
||||
{
|
||||
if (arrayRGBA.Length != 4) throw new Exception("Color.RGBA(byte[] arrayRGBA) error: arrayRGBA.Length != 4\n");
|
||||
R = arrayRGBA[0];
|
||||
G = arrayRGBA[1];
|
||||
B = arrayRGBA[2];
|
||||
A = arrayRGBA[3];
|
||||
}
|
||||
}
|
||||
public class RGB
|
||||
{
|
||||
public byte R;
|
||||
public byte G;
|
||||
public byte B;
|
||||
|
||||
public RGB() { }
|
||||
|
||||
public RGB(byte R, byte G, byte B)
|
||||
{
|
||||
this.R = R;
|
||||
this.G = G;
|
||||
this.B = B;
|
||||
}
|
||||
|
||||
public RGB(byte[] arrayRGB)
|
||||
{
|
||||
if (arrayRGB.Length != 4) throw new Exception("Color.RGB(byte[] arrayRGB) error: arrayRGB.Length != 4\n");
|
||||
R = arrayRGB[0];
|
||||
G = arrayRGB[1];
|
||||
B = arrayRGB[2];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
83
.old 4/DTLib/ColoredConsole.cs
Normal file
83
.old 4/DTLib/ColoredConsole.cs
Normal file
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// вывод и ввод цветного текста в консоли
|
||||
// работает медленнее чем хотелось бы
|
||||
//
|
||||
public static class ColoredConsole
|
||||
{
|
||||
// парсит название цвета в ConsoleColor
|
||||
public static ConsoleColor ParseColor(string color)
|
||||
{
|
||||
switch (color)
|
||||
{
|
||||
//case "magneta":
|
||||
case "m":
|
||||
return ConsoleColor.Magenta;
|
||||
//case "green":
|
||||
case "g":
|
||||
return ConsoleColor.Green;
|
||||
//case "red":
|
||||
case "r":
|
||||
return ConsoleColor.Red;
|
||||
//case "yellow":
|
||||
case "y":
|
||||
return ConsoleColor.Yellow;
|
||||
//case "white":
|
||||
case "w":
|
||||
return ConsoleColor.White;
|
||||
//case "blue":
|
||||
case "b":
|
||||
return ConsoleColor.Blue;
|
||||
//case "cyan":
|
||||
case "c":
|
||||
return ConsoleColor.Cyan;
|
||||
//case "gray":
|
||||
case "gray":
|
||||
return ConsoleColor.Gray;
|
||||
//case "black":
|
||||
case "black":
|
||||
return ConsoleColor.Black;
|
||||
default:
|
||||
throw new Exception("incorrect color: " + color);
|
||||
}
|
||||
}
|
||||
|
||||
// вывод цветного текста
|
||||
public static void Write(params string[] input)
|
||||
{
|
||||
if (input.Length == 1)
|
||||
{
|
||||
if (Console.ForegroundColor != ConsoleColor.Green) Console.ForegroundColor = ConsoleColor.Gray;
|
||||
Console.Write(input[0]);
|
||||
}
|
||||
else if (input.Length % 2 == 0)
|
||||
{
|
||||
string str = "";
|
||||
for (ushort i = 0; i < input.Length; i++)
|
||||
{
|
||||
var c = ParseColor(input[i]);
|
||||
if (Console.ForegroundColor != c)
|
||||
{
|
||||
Console.Write(str);
|
||||
Console.ForegroundColor = c;
|
||||
str = "";
|
||||
}
|
||||
str += input[++i];
|
||||
}
|
||||
if (str != "") Console.Write(str);
|
||||
}
|
||||
else throw new Exception("error in Write(): every text string must have color string before");
|
||||
}
|
||||
|
||||
// ввод цветного текста
|
||||
public static string Read(string color)
|
||||
{
|
||||
var c = ParseColor(color);
|
||||
if (Console.ForegroundColor != c) Console.ForegroundColor = c;
|
||||
return Console.ReadLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
72
.old 4/DTLib/CompressedArray.cs
Normal file
72
.old 4/DTLib/CompressedArray.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
public class CompressedArray
|
||||
{
|
||||
public class Array1D<T> where T : IComparable<T>
|
||||
{
|
||||
byte[] Description;
|
||||
T[] Memory;
|
||||
|
||||
public Array1D() { }
|
||||
public Array1D(T[] sourceArray)
|
||||
{
|
||||
CompressArray(sourceArray);
|
||||
}
|
||||
|
||||
public void CompressArray(T[] sourceArray)
|
||||
{
|
||||
var listMem = new List<T>();
|
||||
var listDesc = new List<byte>();
|
||||
T prevElement = sourceArray[0];
|
||||
listMem.Add(sourceArray[0]);
|
||||
listDesc.Add(1);
|
||||
byte repeats = 1;
|
||||
for (int i = 1; i < sourceArray.Length; i++)
|
||||
{
|
||||
if (prevElement.CompareTo(sourceArray[i]) == 0) repeats++;
|
||||
else
|
||||
{
|
||||
listMem.Add(sourceArray[i]);
|
||||
listDesc.Add(1);
|
||||
if (repeats > 1)
|
||||
{
|
||||
listDesc[listDesc.Count - 2] = repeats;
|
||||
repeats = 1;
|
||||
}
|
||||
}
|
||||
prevElement = sourceArray[i];
|
||||
}
|
||||
Memory = listMem.ToArray();
|
||||
Description = listDesc.ToArray();
|
||||
ColoredConsole.Write("b", "listMem.Count: ", "c", listMem.Count.ToString(), "b", " listDesc.Count: ", "c", listDesc.Count + "\n");
|
||||
for (short i = 0; i < listDesc.Count; i++)
|
||||
{
|
||||
ColoredConsole.Write("y", $"{Description[i]}:{Memory[i]}\n");
|
||||
}
|
||||
}
|
||||
|
||||
// блокирует обращение к памяти из нескольких потоков
|
||||
Mutex storageUsing = new Mutex();
|
||||
|
||||
// возвращает элемент по индексу так, как если бы шло обращение к обычном массиву
|
||||
public T GetElement(int index)
|
||||
{
|
||||
storageUsing.WaitOne();
|
||||
T output = default;
|
||||
int sum = 0;
|
||||
for (int i = 0; i < Description.Length; i++)
|
||||
{
|
||||
if (sum < index) sum += Description[i];
|
||||
else if (sum == index) output = Memory[i];
|
||||
else output = Memory[i - 1];
|
||||
}
|
||||
storageUsing.ReleaseMutex();
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
52
.old 4/DTLib/DTLib.csproj
Normal file
52
.old 4/DTLib/DTLib.csproj
Normal file
@@ -0,0 +1,52 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>DTLib</RootNamespace>
|
||||
<AssemblyName>DTLib</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<Deterministic>true</Deterministic>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Build|AnyCPU' ">
|
||||
<DebugType>none</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Color.cs" />
|
||||
<Compile Include="CompressedArray.cs" />
|
||||
<Compile Include="FileWork.cs" />
|
||||
<Compile Include="ColoredConsole.cs" />
|
||||
<Compile Include="PublicLog.cs" />
|
||||
<Compile Include="NetWork.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Hasher.cs" />
|
||||
<Compile Include="SecureRandom.cs" />
|
||||
<Compile Include="SimpleConverter.cs" />
|
||||
<Compile Include="TImer.cs" />
|
||||
<Compile Include="XXHash.cs" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>
|
||||
</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
167
.old 4/DTLib/FileWork.cs
Normal file
167
.old 4/DTLib/FileWork.cs
Normal file
@@ -0,0 +1,167 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// методы для работы с файловой системой
|
||||
//
|
||||
public static class FileWork
|
||||
{
|
||||
// записывает текст в файл и закрывает файл
|
||||
public static void Log(string logfile, string msg)
|
||||
{
|
||||
lock (new object())
|
||||
{
|
||||
var st = File.Open(logfile, FileMode.Append);
|
||||
var writer = new StreamWriter(st, SimpleConverter.UTF8);
|
||||
writer.Write(msg);
|
||||
writer.Close();
|
||||
st.Close();
|
||||
}
|
||||
}
|
||||
|
||||
// создает папку если её не существует
|
||||
public static void DirCreate(string dir)
|
||||
{
|
||||
if (!Directory.Exists(dir))
|
||||
{
|
||||
// проверяет существование папки, в которой нужно создать dir
|
||||
if (dir.Contains("\\") && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
|
||||
DirCreate(dir.Remove(dir.LastIndexOf('\\')));
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
}
|
||||
|
||||
// чтение параметров из конфига
|
||||
public static string ReadFromConfig(string configfile, string key)
|
||||
{
|
||||
key += ": ";
|
||||
var reader = new StreamReader(configfile);
|
||||
while (!reader.EndOfStream)
|
||||
{
|
||||
string st = reader.ReadLine();
|
||||
if (st.StartsWith(key))
|
||||
{
|
||||
string value = "";
|
||||
for (int i = key.Length; i < st.Length; i++)
|
||||
{
|
||||
if (st[i] == '#') return value;
|
||||
if (st[i] == '%')
|
||||
{
|
||||
bool stop = false;
|
||||
string placeholder = "";
|
||||
i++;
|
||||
while (!stop)
|
||||
{
|
||||
if (st[i] == '%')
|
||||
{
|
||||
stop = true;
|
||||
value += ReadFromConfig(configfile, placeholder);
|
||||
}
|
||||
else
|
||||
{
|
||||
placeholder += st[i];
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
else value += st[i];
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
reader.Close();
|
||||
return null;
|
||||
}
|
||||
|
||||
// копирует все файли и папки
|
||||
public static void DirCopy(string source_dir, string new_dir, bool Override)
|
||||
{
|
||||
DirCreate(new_dir);
|
||||
List<string> subdirs = new List<string>();
|
||||
List<string> files = GetAllFiles(source_dir, ref subdirs);
|
||||
for (int i = 0; i < subdirs.Count; i++)
|
||||
{
|
||||
DirCreate(subdirs[i].Replace(source_dir, new_dir));
|
||||
}
|
||||
for (int i = 0; i < files.Count; i++)
|
||||
{
|
||||
string f = files[i].Replace(source_dir, new_dir);
|
||||
File.Copy(files[i], f, Override);
|
||||
//PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
|
||||
}
|
||||
}
|
||||
|
||||
// копирует все файли и папки и выдаёт список конфликтующих файлов
|
||||
public static void DirCopy(string source_dir, string new_dir, bool owerwrite, out List<string> conflicts)
|
||||
{
|
||||
conflicts = new List<string>();
|
||||
var subdirs = new List<string>();
|
||||
var files = GetAllFiles(source_dir, ref subdirs);
|
||||
DirCreate(new_dir);
|
||||
for (int i = 0; i < subdirs.Count; i++)
|
||||
{
|
||||
DirCreate(subdirs[i].Replace(source_dir, new_dir));
|
||||
}
|
||||
for (int i = 0; i < files.Count; i++)
|
||||
{
|
||||
string newfile = files[i].Replace(source_dir, new_dir);
|
||||
if (File.Exists(newfile)) conflicts.Add(newfile);
|
||||
File.Copy(files[i], newfile, owerwrite);
|
||||
//PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
|
||||
}
|
||||
}
|
||||
|
||||
// выдает список всех файлов
|
||||
public static List<string> GetAllFiles(string dir)
|
||||
{
|
||||
List<string> all_files = new List<string>();
|
||||
string[] cur_files = Directory.GetFiles(dir);
|
||||
for (int i = 0; i < cur_files.Length; i++)
|
||||
{
|
||||
all_files.Add(cur_files[i]);
|
||||
//PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
|
||||
}
|
||||
string[] cur_subdirs = Directory.GetDirectories(dir);
|
||||
for (int i = 0; i < cur_subdirs.Length; i++)
|
||||
{
|
||||
//PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
|
||||
all_files.AddRange(GetAllFiles(cur_subdirs[i]));
|
||||
}
|
||||
return all_files;
|
||||
}
|
||||
|
||||
// выдает список всех файлов и подпапок в папке
|
||||
public static List<string> GetAllFiles(string dir, ref List<string> all_subdirs)
|
||||
{
|
||||
List<string> all_files = new List<string>();
|
||||
string[] cur_files = Directory.GetFiles(dir);
|
||||
for (int i = 0; i < cur_files.Length; i++)
|
||||
{
|
||||
all_files.Add(cur_files[i]);
|
||||
//PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
|
||||
}
|
||||
string[] cur_subdirs = Directory.GetDirectories(dir);
|
||||
for (int i = 0; i < cur_subdirs.Length; i++)
|
||||
{
|
||||
all_subdirs.Add(cur_subdirs[i]);
|
||||
//PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
|
||||
all_files.AddRange(GetAllFiles(cur_subdirs[i], ref all_subdirs));
|
||||
}
|
||||
return all_files;
|
||||
}
|
||||
|
||||
// удаляет папку со всеми подпапками и файлами
|
||||
public static void DirDelete(string dir)
|
||||
{
|
||||
var subdirs = new List<string>();
|
||||
var files = GetAllFiles(dir, ref subdirs);
|
||||
for (int i = 0; i < files.Count; i++)
|
||||
File.Delete(files[i]);
|
||||
for (int i = subdirs.Count - 1; i >= 0; i--)
|
||||
Directory.Delete(subdirs[i]);
|
||||
Directory.Delete(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
59
.old 4/DTLib/Hasher.cs
Normal file
59
.old 4/DTLib/Hasher.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// хеширует массивы байтов алшоритмом SHA256 и файлы алгоримом XXHash32
|
||||
//
|
||||
public class Hasher
|
||||
{
|
||||
readonly HashAlgorithm sha256 = SHA256.Create();
|
||||
readonly HashAlgorithm xxh32 = XXHash32.Create();
|
||||
|
||||
public Hasher() { }
|
||||
|
||||
// хеш массива
|
||||
public byte[] Hash(byte[] input)
|
||||
=> sha256.ComputeHash(input);
|
||||
|
||||
// хеш из двух массивов
|
||||
public byte[] Hash(byte[] input, byte[] salt)
|
||||
{
|
||||
List<byte> rez = new List<byte>();
|
||||
rez.AddRange(input);
|
||||
rez.AddRange(salt);
|
||||
return sha256.ComputeHash(rez.ToArray());
|
||||
}
|
||||
|
||||
// хеш двух массивов зацикленный
|
||||
public byte[] HashCycled(byte[] input, byte[] salt, ushort cycles)
|
||||
{
|
||||
for (uint i = 0; i < cycles; i++)
|
||||
{
|
||||
input = Hash(input, salt);
|
||||
}
|
||||
return input;
|
||||
}
|
||||
// хеш зацикленный
|
||||
public byte[] HashCycled(byte[] input, ushort cycles)
|
||||
{
|
||||
for (uint i = 0; i < cycles; i++)
|
||||
{
|
||||
input = Hash(input);
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
// хеш файла
|
||||
public byte[] HashFile(string filename)
|
||||
{
|
||||
//var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
|
||||
var hash = xxh32.ComputeHash(File.OpenRead(filename));
|
||||
//var now = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
|
||||
//PublicLog.Log($"xxh32 hash: {hash.HashToString()} time: {now - then}\n");
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
}
|
||||
290
.old 4/DTLib/NetWork.cs
Normal file
290
.old 4/DTLib/NetWork.cs
Normal file
@@ -0,0 +1,290 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using static DTLib.PublicLog;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// весь униврсальный неткод тут
|
||||
// большинство методов предназначены для работы с TCP сокетами (Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
|
||||
//
|
||||
public static class NetWork
|
||||
{
|
||||
// получение информации (сокет должен быть в режиме Listen)
|
||||
public static byte[] GetData(this Socket socket)
|
||||
{
|
||||
List<byte> output = new List<byte>();
|
||||
byte[] data = new byte[256];
|
||||
do
|
||||
{
|
||||
int amount = socket.Receive(data, data.Length, 0);
|
||||
for (int i = 0; i < amount; i++)
|
||||
{
|
||||
output.Add(data[i]);
|
||||
}
|
||||
}
|
||||
while (socket.Available > 0);
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
// отправка запроса и получение ответа на него (сокет должен быть в режиме Listen)
|
||||
public static byte[] Request(this Socket socket, string request)
|
||||
{
|
||||
socket.Send(request.ToBytes());
|
||||
return GetData(socket);
|
||||
}
|
||||
public static byte[] Request(this Socket socket, byte[] request)
|
||||
{
|
||||
socket.Send(request);
|
||||
return GetData(socket);
|
||||
}
|
||||
|
||||
// скачивание файла с фтп сервера
|
||||
public static void FtpDownload(string address, string login, string password, string outfile)
|
||||
{
|
||||
try
|
||||
{
|
||||
// debug
|
||||
Log(new string[] { "y", "file on server: <", "c", address, "y", ">\nfile on client: <", "c", outfile, "y", ">\n" });
|
||||
// создание запроса
|
||||
// "ftp://m1net.keenetic.pro:20000/" + @infile
|
||||
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
|
||||
request.Credentials = new NetworkCredential(login, password);
|
||||
request.Method = WebRequestMethods.Ftp.DownloadFile;
|
||||
// получение ответа на запрос
|
||||
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
|
||||
Stream responseStream = response.GetResponseStream();
|
||||
FileStream fs = new FileStream(@Directory.GetCurrentDirectory() + '\\' + @outfile, FileMode.Create);
|
||||
byte[] buffer = new byte[64];
|
||||
int size = 0;
|
||||
|
||||
while ((size = responseStream.Read(buffer, 0, buffer.Length)) > 0)
|
||||
fs.Write(buffer, 0, size);
|
||||
fs.Close();
|
||||
response.Close();
|
||||
}
|
||||
catch (WebException e) { throw new Exception("ftp error:\n" + ((FtpWebResponse)e.Response).StatusDescription + '\n'); }
|
||||
}
|
||||
|
||||
// запрашивает список серверов с главного сервера
|
||||
public static ServerObject[] RequestServersList(Socket centralServer)
|
||||
{
|
||||
List<ServerObject> servers = new List<ServerObject>();
|
||||
string[] lines = Request(centralServer, "a356a4257dbf9d87c77cf87c3c694b30160b6ddfd3db82e7f62320207109e352").ToStr().Split('\n');
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
string[] properties = lines[i].Split(',');
|
||||
servers.Add(new ServerObject(properties[0], properties[1], properties[2]));
|
||||
}
|
||||
return servers.ToArray();
|
||||
}
|
||||
|
||||
// пингует айпи с помощью встроенной в винду проги, возвращает задержку
|
||||
public static string PingIP(string address)
|
||||
{
|
||||
Process proc = new Process();
|
||||
proc.StartInfo.FileName = "cmd.exe";
|
||||
proc.StartInfo.Arguments = "/c @echo off & chcp 65001 >nul & ping -n 5 " + address;
|
||||
proc.StartInfo.CreateNoWindow = true;
|
||||
proc.StartInfo.UseShellExecute = false;
|
||||
proc.StartInfo.RedirectStandardOutput = true;
|
||||
proc.Start();
|
||||
var outStream = proc.StandardOutput;
|
||||
var rezult = outStream.ReadToEnd();
|
||||
rezult = rezult.Remove(0, rezult.LastIndexOf('=') + 2);
|
||||
return rezult.Remove(rezult.Length - 4);
|
||||
}
|
||||
|
||||
// пингует сервер (сервер должен уметь принимать такой запрос от клиента), возвращает true если сервер правильно ответил
|
||||
public static bool Ping(this Socket socket)
|
||||
{
|
||||
if (Request(socket, "ab53bf045004875fb17086f7f992b0514fb96c038f336e0bfc21609b20303f07").ToStr() == "91b5c0383b75fb1708f00486f7f9b96c038ab3bfc21059b20176f603692b05e0") return true;
|
||||
else return false;
|
||||
}
|
||||
|
||||
// скачивает файл с помощью моего собственного протокола
|
||||
public static void FSP_Download(this Socket mainSocket, FSP_FileObject file)
|
||||
{
|
||||
Log(new string[] { "c", $"remote socket accepted download request: {file.ClientFilePath}\n" });
|
||||
mainSocket.Send("requesting file download".ToBytes());
|
||||
string answ = mainSocket.GetPackageClear(64, "<", ">").ToStr();
|
||||
if (answ != "download request accepted")
|
||||
throw new Exception($"FSP_Download() error: a download socket recieved an incorrect message: {answ}\n");
|
||||
|
||||
mainSocket.SendPackage(276, file.ServerFilePath.ToBytes(), "<filename>", "<filename>");
|
||||
file.Size = Convert.ToUInt32(mainSocket.GetPackageClear(64, "<filesize>", "<filesize>").ToStr());
|
||||
file.Hash = mainSocket.GetPackageClear(64, "<filehash>", "<filehash>");
|
||||
mainSocket.SendPackage(64, "ready".ToBytes(), "<", ">");
|
||||
file.Stream = File.Open(file.ClientFilePath, FileMode.Create, FileAccess.Write);
|
||||
int packagesCount = 0;
|
||||
byte[] buffer = new byte[5120];
|
||||
var hashstr = file.Hash.HashToString();
|
||||
int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length);
|
||||
// рассчёт скорости
|
||||
int seconds = 0;
|
||||
var speedCounter = new Timer(true, 1000, () =>
|
||||
{
|
||||
seconds++;
|
||||
Log("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
|
||||
});
|
||||
// получение файла
|
||||
for (; packagesCount < fullPackagesCount; packagesCount++)
|
||||
{
|
||||
string header = $"<{packagesCount}>";
|
||||
buffer = mainSocket.GetPackageRaw(buffer.Length + 2 + header.Length, header, "<>");
|
||||
file.Stream.Write(buffer, 0, buffer.Length);
|
||||
file.Stream.Flush();
|
||||
}
|
||||
Log(new string[] { "y", " full packages recieved\n" });
|
||||
speedCounter.Stop();
|
||||
// получение остатка
|
||||
mainSocket.SendPackage(64, "remain request".ToBytes(), "<", ">");
|
||||
buffer = mainSocket.GetPackageRaw(Convert.ToInt32(file.Size - fullPackagesCount * 5120) + 16, "<remain>", "<remain>");
|
||||
file.Stream.Write(buffer, 0, buffer.Length);
|
||||
file.Stream.Flush();
|
||||
file.Stream.Close();
|
||||
Log(new string[] { "g", $" file {file.ClientFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) downloaded.\n" });
|
||||
}
|
||||
|
||||
// отдаёт файл с помощью моего протокола
|
||||
public static void FSP_Upload(this Socket mainSocket)
|
||||
{
|
||||
mainSocket.SendPackage(64, "download request accepted".ToBytes(), "<", ">");
|
||||
var file = new FSP_FileObject
|
||||
{
|
||||
ServerFilePath = mainSocket.GetPackageClear(276, "<filename>", "<filename>").ToStr()
|
||||
};
|
||||
file.Size = new FileInfo(file.ServerFilePath).Length;
|
||||
file.Hash = new Hasher().HashFile(file.ServerFilePath);
|
||||
mainSocket.SendPackage(64, file.Size.ToString().ToBytes(), "<filesize>", "<filesize>");
|
||||
mainSocket.SendPackage(64, file.Hash, "<filehash>", "<filehash>");
|
||||
if (mainSocket.GetPackageClear(64, "<", ">").ToStr() != "ready")
|
||||
throw new Exception("user socket isn't ready");
|
||||
Log(new string[] { "c", $"local socket accepted file download request: {file.ServerFilePath}\n" });
|
||||
file.Stream = new FileStream(file.ServerFilePath, FileMode.Open, FileAccess.Read);
|
||||
byte[] buffer = new byte[5120];
|
||||
var hashstr = file.Hash.HashToString();
|
||||
int packagesCount = 0;
|
||||
int seconds = 0;
|
||||
// рассчёт скорости
|
||||
var speedCounter = new Timer(true, 1000, () =>
|
||||
{
|
||||
seconds++;
|
||||
Log("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
|
||||
});
|
||||
// отправка файла
|
||||
int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length);
|
||||
for (; packagesCount < fullPackagesCount; packagesCount++)
|
||||
{
|
||||
string header = $"<{packagesCount}>";
|
||||
file.Stream.Read(buffer, 0, buffer.Length);
|
||||
try { mainSocket.SendPackage(buffer.Length + 2 + header.Length, buffer, header, "<>"); }
|
||||
catch (Exception ex) { Log(new string[] { "r", "FSP_Upload() error: " + ex.Message + "\n" + ex.StackTrace + '\n' }); }
|
||||
}
|
||||
Log(new string[] { "y", " full packages send\n" });
|
||||
speedCounter.Stop();
|
||||
// досылка остатка
|
||||
var req = mainSocket.GetPackageClear(64, "<", ">");
|
||||
if (req.ToStr() != "remain request")
|
||||
throw new Exception("FSP_Upload() error: didn't get remain request");
|
||||
buffer = new byte[Convert.ToInt32(file.Size - file.Stream.Position)];
|
||||
file.Stream.Read(buffer, 0, buffer.Length);
|
||||
mainSocket.SendPackage(buffer.Length + 16, buffer, "<remain>", "<remain>");
|
||||
file.Stream.Close();
|
||||
Log(new string[] { "g", $" file {file.ServerFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) uploaded.\n" });
|
||||
}
|
||||
|
||||
// ждёт пакет заданного размера с заданным началом и концом
|
||||
// убирает пустые байты в конце пакета
|
||||
public static byte[] GetPackageClear(this Socket socket, int packageSize, string startsWith, string endsWith)
|
||||
{
|
||||
byte[] data = socket.GetPackageRaw(packageSize, startsWith, endsWith);
|
||||
bool clean = false;
|
||||
for (int i = 0; !clean; i++)
|
||||
{
|
||||
if (data[i] != 00)
|
||||
{
|
||||
if (i != 0) data = data.RemoveRange(0, i);
|
||||
clean = true;
|
||||
}
|
||||
else clean = i == data.Length - 1;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
//не убирает пустые байты в конце пакета
|
||||
public static byte[] GetPackageRaw(this Socket socket, int packageSize, string startsWith, string endsWith)
|
||||
{
|
||||
byte[] data = new byte[packageSize];
|
||||
//Log(new string[] { "y", $"GetPackage() packegesize=<","c",packageSize.ToString(),
|
||||
// "y", "> startsWith=<", "c", startsWith, "y", "> endsWith=<", "c", endsWith, "y", ">\n" });
|
||||
for (short s = 0; s < 2000; s += 10)
|
||||
{
|
||||
if (socket.Available >= packageSize)
|
||||
{
|
||||
socket.Receive(data, packageSize, 0);
|
||||
if (data.StartsWith(startsWith.ToBytes()) & data.EndsWith(endsWith.ToBytes()))
|
||||
{
|
||||
data = data.RemoveRange(0, startsWith.ToBytes().Length);
|
||||
data = data.RemoveRange(data.Length - endsWith.ToBytes().Length, endsWith.ToBytes().Length);
|
||||
return data;
|
||||
}
|
||||
else throw new Exception($"GetPackage() error: has got incorrect package\n");
|
||||
}
|
||||
else Thread.Sleep(10);
|
||||
}
|
||||
throw new Exception($"GetPackage() error: timeout\n");
|
||||
}
|
||||
|
||||
// отправляет пакет заданного размера, добавля в начало и конец заданные значения
|
||||
public static void SendPackage(this Socket socket, int length, byte[] data, string startsWith, string endsWith)
|
||||
{
|
||||
var list = new List<byte>();
|
||||
list.AddRange(startsWith.ToBytes());
|
||||
int i = startsWith.ToBytes().Length + endsWith.ToBytes().Length + data.Length;
|
||||
//Log(new string[] { "y", $"SendPackage() length=<","c",length.ToString(),"y", "> packegesize=<","c",i.ToString(),
|
||||
// "y", "> data.Length=<","c",data.Length.ToString(), "y", "> startsWith=<", "c", startsWith, "y", "> endsWith=<", "c", endsWith, "y", ">\n" });
|
||||
if (i > length) throw new Exception("SendPackage() error: int length is too small\n");
|
||||
|
||||
for (; i < length; i++) list.Add(0);
|
||||
list.AddRange(data);
|
||||
list.AddRange(endsWith.ToBytes());
|
||||
socket.Send(list.ToArray());
|
||||
}
|
||||
|
||||
|
||||
|
||||
// хранит свойства файла, передаваемого с помощью моего протокола
|
||||
public class FSP_FileObject
|
||||
{
|
||||
public string ServerFilePath;
|
||||
public string ClientFilePath;
|
||||
public long Size;
|
||||
public byte[] Hash;
|
||||
public Stream Stream;
|
||||
|
||||
public FSP_FileObject() { }
|
||||
}
|
||||
|
||||
// хранит свойства сервера, полученные с помощью RequestServersList()
|
||||
public class ServerObject
|
||||
{
|
||||
public string Address;
|
||||
public string Name;
|
||||
public string Speed;
|
||||
|
||||
public ServerObject(string address, string name, string speed)
|
||||
{
|
||||
Address = address;
|
||||
Name = name;
|
||||
Speed = speed;
|
||||
}
|
||||
|
||||
public ServerObject() { }
|
||||
}
|
||||
}
|
||||
}
|
||||
35
.old 4/DTLib/Properties/AssemblyInfo.cs
Normal file
35
.old 4/DTLib/Properties/AssemblyInfo.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// Общие сведения об этой сборке предоставляются следующим набором
|
||||
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
|
||||
// связанные со сборкой.
|
||||
[assembly: AssemblyTitle("DTLib")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("DTLib")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2021")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
|
||||
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
|
||||
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
|
||||
[assembly: Guid("ce793497-2d5c-42d8-b311-e9b32af9cdfb")]
|
||||
|
||||
// Сведения о версии сборки состоят из указанных ниже четырех значений:
|
||||
//
|
||||
// Основной номер версии
|
||||
// Дополнительный номер версии
|
||||
// Номер сборки
|
||||
// Редакция
|
||||
//
|
||||
// Можно задать все значения или принять номера сборки и редакции по умолчанию
|
||||
// используя "*", как показано ниже:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
16
.old 4/DTLib/PublicLog.cs
Normal file
16
.old 4/DTLib/PublicLog.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// вывод логов со всех классов в библиотеке
|
||||
//
|
||||
public static class PublicLog
|
||||
{
|
||||
public delegate void LogDelegate(string[] msg);
|
||||
// вот к этому объекту подключайте методы для вывода логов
|
||||
public static LogDelegate LogDel;
|
||||
|
||||
// этот метод вызывается в библиотеке
|
||||
public static void Log(params string[] msg)
|
||||
=> LogDel(msg);
|
||||
}
|
||||
}
|
||||
37
.old 4/DTLib/SecureRandom.cs
Normal file
37
.old 4/DTLib/SecureRandom.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// Вычисление псевдослучайного числа из множества параметров.
|
||||
// Работает медленнее чем класс System.Random, но выдаёт более случайные значения
|
||||
//
|
||||
public class SecureRandom
|
||||
{
|
||||
private RNGCryptoServiceProvider crypt = new RNGCryptoServiceProvider();
|
||||
|
||||
// получение массива случайных байтов
|
||||
public byte[] GenBytes(uint length)
|
||||
{
|
||||
byte[] output = new byte[length];
|
||||
crypt.GetNonZeroBytes(output);
|
||||
return output;
|
||||
}
|
||||
|
||||
// получение случайного числа от 0 до 2147483647
|
||||
/*public int NextInt(uint from, int to)
|
||||
{
|
||||
int output = 0;
|
||||
int rez = 0;
|
||||
while (true)
|
||||
{
|
||||
rez = output * 10 + NextBytes(1)[0];
|
||||
if (rez < to && rez > from)
|
||||
{
|
||||
output = rez;
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
88
.old 4/DTLib/SimpleConverter.cs
Normal file
88
.old 4/DTLib/SimpleConverter.cs
Normal file
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// содержит методы расширения для различных операций и преобразований
|
||||
//
|
||||
public static class SimpleConverter
|
||||
{
|
||||
public static Encoding UTF8 = new UTF8Encoding(false);
|
||||
// байты в кодировке UTF8 в строку
|
||||
public static string ToStr(this byte[] bytes)
|
||||
=> UTF8.GetString(bytes);
|
||||
public static string ToStr(this List<byte> bytes)
|
||||
=> UTF8.GetString(bytes.ToArray());
|
||||
|
||||
// хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
|
||||
public static string HashToString(this byte[] hash)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
for (int i = 0; i < hash.Length; i++)
|
||||
{
|
||||
builder.Append(hash[i].ToString("x2"));
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
// строку в байты
|
||||
public static byte[] ToBytes(this string str)
|
||||
=> UTF8.GetBytes(str);
|
||||
|
||||
// эти методы работают как надо, в отличии от стандартных, которые иногда дуркуют
|
||||
public static bool StartsWith(this byte[] source, byte[] startsWith)
|
||||
{
|
||||
for (int i = 0; i < startsWith.Length; i++)
|
||||
{
|
||||
if (source[i] != startsWith[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool EndsWith(this byte[] source, byte[] endsWith)
|
||||
{
|
||||
for (int i = 0; i < endsWith.Length; i++)
|
||||
{
|
||||
if (source[source.Length - endsWith.Length + i] != endsWith[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Math.Truncate принимает как decimal, так и doublе,
|
||||
// из-за чего вызов метода так: Math.Truncate(10/3) выдаст ошибку "неоднозначный вызов"
|
||||
public static int Truncate(decimal number)
|
||||
=> Convert.ToInt32(Math.Truncate(number));
|
||||
|
||||
// сортирует в порядке возрастания элементы если это возможно, используя стандартный метод list.Sort();
|
||||
public static T[] Sort<T>(this T[] array)
|
||||
{
|
||||
var list = array.ToList();
|
||||
list.Sort();
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
// массив в лист
|
||||
public static List<T> ToList<T>(this T[] input)
|
||||
{
|
||||
var list = new List<T>();
|
||||
list.AddRange(input);
|
||||
return list;
|
||||
}
|
||||
|
||||
// удаление нескольких элементов массива
|
||||
public static T[] RemoveRange<T>(this T[] input, int startIndex, int count)
|
||||
{
|
||||
List<T> list = input.ToList();
|
||||
list.RemoveRange(startIndex, count);
|
||||
return list.ToArray();
|
||||
}
|
||||
public static T[] RemoveRange<T>(this T[] input, int startIndex)
|
||||
=> input.RemoveRange(startIndex, input.Length - startIndex);
|
||||
|
||||
//
|
||||
public static int ToInt<T>(this T input)
|
||||
=> Convert.ToInt32(input);
|
||||
}
|
||||
}
|
||||
36
.old 4/DTLib/TImer.cs
Normal file
36
.old 4/DTLib/TImer.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// простой и понятный класс для выполнения каких-либо действий в отдельном потоке раз в некоторое время
|
||||
//
|
||||
public class Timer
|
||||
{
|
||||
Thread TimerThread;
|
||||
bool Repeat;
|
||||
|
||||
// таймер сразу запускается
|
||||
public Timer(bool repeat, int delay, Action method)
|
||||
{
|
||||
Repeat = repeat;
|
||||
TimerThread = new Thread(() =>
|
||||
{
|
||||
do
|
||||
{
|
||||
Thread.Sleep(delay);
|
||||
method();
|
||||
} while (Repeat);
|
||||
});
|
||||
TimerThread.Start();
|
||||
}
|
||||
|
||||
// завершение потока
|
||||
public void Stop()
|
||||
{
|
||||
Repeat = false;
|
||||
TimerThread.Abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
180
.old 4/DTLib/XXHash.cs
Normal file
180
.old 4/DTLib/XXHash.cs
Normal file
@@ -0,0 +1,180 @@
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// честно взятый с гитхаба алгоритм хеширования
|
||||
// выдаёт хеш в виде массива четырёх байтов
|
||||
//
|
||||
sealed class XXHash32 : HashAlgorithm
|
||||
{
|
||||
private const uint PRIME32_1 = 2654435761U;
|
||||
private const uint PRIME32_2 = 2246822519U;
|
||||
private const uint PRIME32_3 = 3266489917U;
|
||||
private const uint PRIME32_4 = 668265263U;
|
||||
private const uint PRIME32_5 = 374761393U;
|
||||
private static readonly Func<byte[], int, uint> FuncGetLittleEndianUInt32;
|
||||
private static readonly Func<uint, uint> FuncGetFinalHashUInt32;
|
||||
private uint _Seed32;
|
||||
private uint _ACC32_1;
|
||||
private uint _ACC32_2;
|
||||
private uint _ACC32_3;
|
||||
private uint _ACC32_4;
|
||||
private uint _Hash32;
|
||||
private int _RemainingLength;
|
||||
private long _TotalLength = 0;
|
||||
private int _CurrentIndex;
|
||||
private byte[] _CurrentArray;
|
||||
|
||||
static XXHash32()
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* array = x)
|
||||
{
|
||||
return *(uint*)(array + i);
|
||||
}
|
||||
}
|
||||
});
|
||||
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => (i & 0x000000FFU) << 24 | (i & 0x0000FF00U) << 8 | (i & 0x00FF0000U) >> 8 | (i & 0xFF000000U) >> 24);
|
||||
}
|
||||
else
|
||||
{
|
||||
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* array = x)
|
||||
{
|
||||
return (uint)(array[i++] | (array[i++] << 8) | (array[i++] << 16) | (array[i] << 24));
|
||||
}
|
||||
}
|
||||
});
|
||||
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => i);
|
||||
}
|
||||
}
|
||||
|
||||
// Creates an instance of <see cref="XXHash32"/> class by default seed(0).
|
||||
// <returns></returns>
|
||||
public static new XXHash32 Create() => new XXHash32();
|
||||
|
||||
// Initializes a new instance of the <see cref="XXHash32"/> class by default seed(0).
|
||||
public XXHash32() => Initialize(0);
|
||||
|
||||
// Initializes a new instance of the <see cref="XXHash32"/> class, and sets the <see cref="Seed"/> to the specified value.
|
||||
// <param name="seed">Represent the seed to be used for xxHash32 computing.</param>
|
||||
public XXHash32(uint seed) => Initialize(seed);
|
||||
|
||||
// Gets the <see cref="uint"/> value of the computed hash code.
|
||||
// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
||||
public uint HashUInt32 => State == 0 ? _Hash32 : throw new InvalidOperationException("Hash computation has not yet completed.");
|
||||
|
||||
// Gets or sets the value of seed used by xxHash32 algorithm.
|
||||
// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
||||
public uint Seed
|
||||
{
|
||||
get => _Seed32;
|
||||
set
|
||||
{
|
||||
if (value != _Seed32)
|
||||
{
|
||||
if (State != 0) throw new InvalidOperationException("Hash computation has not yet completed.");
|
||||
_Seed32 = value;
|
||||
Initialize();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Initializes this instance for new hash computing.
|
||||
public override void Initialize()
|
||||
{
|
||||
_ACC32_1 = _Seed32 + PRIME32_1 + PRIME32_2;
|
||||
_ACC32_2 = _Seed32 + PRIME32_2;
|
||||
_ACC32_3 = _Seed32 + 0;
|
||||
_ACC32_4 = _Seed32 - PRIME32_1;
|
||||
}
|
||||
|
||||
// Routes data written to the object into the hash algorithm for computing the hash.
|
||||
// <param name="array">The input to compute the hash code for.</param>
|
||||
// <param name="ibStart">The offset into the byte array from which to begin using data.</param>
|
||||
// <param name="cbSize">The number of bytes in the byte array to use as data.</param>
|
||||
protected override void HashCore(byte[] array, int ibStart, int cbSize)
|
||||
{
|
||||
if (State != 1) State = 1;
|
||||
var size = cbSize - ibStart;
|
||||
_RemainingLength = size & 15;
|
||||
if (cbSize >= 16)
|
||||
{
|
||||
var limit = size - _RemainingLength;
|
||||
do
|
||||
{
|
||||
_ACC32_1 = Round32(_ACC32_1, FuncGetLittleEndianUInt32(array, ibStart));
|
||||
ibStart += 4;
|
||||
_ACC32_2 = Round32(_ACC32_2, FuncGetLittleEndianUInt32(array, ibStart));
|
||||
ibStart += 4;
|
||||
_ACC32_3 = Round32(_ACC32_3, FuncGetLittleEndianUInt32(array, ibStart));
|
||||
ibStart += 4;
|
||||
_ACC32_4 = Round32(_ACC32_4, FuncGetLittleEndianUInt32(array, ibStart));
|
||||
ibStart += 4;
|
||||
} while (ibStart < limit);
|
||||
}
|
||||
_TotalLength += cbSize;
|
||||
if (_RemainingLength != 0)
|
||||
{
|
||||
_CurrentArray = array;
|
||||
_CurrentIndex = ibStart;
|
||||
}
|
||||
}
|
||||
|
||||
// Finalizes the hash computation after the last data is processed by the cryptographic stream object.
|
||||
// <returns>The computed hash code.</returns>
|
||||
protected override byte[] HashFinal()
|
||||
{
|
||||
if (_TotalLength >= 16)
|
||||
{
|
||||
_Hash32 = RotateLeft32(_ACC32_1, 1) + RotateLeft32(_ACC32_2, 7) + RotateLeft32(_ACC32_3, 12) + RotateLeft32(_ACC32_4, 18);
|
||||
}
|
||||
else
|
||||
{
|
||||
_Hash32 = _Seed32 + PRIME32_5;
|
||||
}
|
||||
_Hash32 += (uint)_TotalLength;
|
||||
while (_RemainingLength >= 4)
|
||||
{
|
||||
_Hash32 = RotateLeft32(_Hash32 + FuncGetLittleEndianUInt32(_CurrentArray, _CurrentIndex) * PRIME32_3, 17) * PRIME32_4;
|
||||
_CurrentIndex += 4;
|
||||
_RemainingLength -= 4;
|
||||
}
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* arrayPtr = _CurrentArray)
|
||||
{
|
||||
while (_RemainingLength-- >= 1)
|
||||
{
|
||||
_Hash32 = RotateLeft32(_Hash32 + arrayPtr[_CurrentIndex++] * PRIME32_5, 11) * PRIME32_1;
|
||||
}
|
||||
}
|
||||
}
|
||||
_Hash32 = (_Hash32 ^ (_Hash32 >> 15)) * PRIME32_2;
|
||||
_Hash32 = (_Hash32 ^ (_Hash32 >> 13)) * PRIME32_3;
|
||||
_Hash32 ^= _Hash32 >> 16;
|
||||
_TotalLength = State = 0;
|
||||
return BitConverter.GetBytes(FuncGetFinalHashUInt32(_Hash32));
|
||||
}
|
||||
|
||||
private static uint Round32(uint input, uint value) => RotateLeft32(input + (value * PRIME32_2), 13) * PRIME32_1;
|
||||
|
||||
private static uint RotateLeft32(uint value, int count) => (value << count) | (value >> (32 - count));
|
||||
|
||||
private void Initialize(uint seed)
|
||||
{
|
||||
HashSizeValue = 32;
|
||||
_Seed32 = seed;
|
||||
Initialize();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user