refactoring

This commit is contained in:
Timerix22 2021-10-26 19:05:31 +03:00
parent dcc1ad3e17
commit 5538178cab
18 changed files with 405 additions and 457 deletions

View File

@ -16,8 +16,8 @@ namespace DTLib
public void CompressArray(T[] sourceArray) public void CompressArray(T[] sourceArray)
{ {
var listMem = new List<T>(); List<T> listMem = new List<T>();
var listDesc = new List<byte>(); List<byte> listDesc = new List<byte>();
T prevElement = sourceArray[0]; T prevElement = sourceArray[0];
listMem.Add(sourceArray[0]); listMem.Add(sourceArray[0]);
listDesc.Add(1); listDesc.Add(1);
@ -60,10 +60,7 @@ namespace DTLib
{ {
if (sum < index) if (sum < index)
sum += Description[i]; sum += Description[i];
else if(sum==index) else output = sum == index ? Memory[i] : Memory[i - 1];
output=Memory[i];
else
output=Memory[i-1];
} }
storageUsing.ReleaseMutex(); storageUsing.ReleaseMutex();
return output; return output;

View File

@ -33,19 +33,10 @@ namespace DTLib.Dtsod
// выдаёт Exception // выдаёт Exception
public new dynamic this[string key] public new dynamic this[string key]
{ {
get get => TryGetValue(key, out dynamic value) ? value : throw new Exception($"Dtsod[{key}] key not found");
{
if(TryGetValue(key, out dynamic value))
return value;
else
throw new Exception($"Dtsod[{key}] key not found");
}
set set
{ {
if(TrySetValue(key, value)) if (!TrySetValue(key, value)) throw new Exception($"Dtsod[{key}] key not found");
return;
else
throw new Exception($"Dtsod[{key}] key not found");
} }
} }

View File

@ -77,19 +77,10 @@ namespace DTLib.Dtsod
// выдаёт Exception // выдаёт Exception
public new dynamic this[string key] public new dynamic this[string key]
{ {
get get => TryGetValue(key, out dynamic value) ? value : throw new Exception($"Dtsod[{key}] key not found");
{
if(TryGetValue(key, out dynamic value))
return value;
else
throw new Exception($"Dtsod[{key}] key not found");
}
set set
{ {
if(TrySetValue(key, value)) if (!TrySetValue(key, value)) throw new Exception($"Dtsod[{key}] key not found");
return;
else
throw new Exception($"Dtsod[{key}] key not found");
} }
} }
@ -111,18 +102,12 @@ namespace DTLib.Dtsod
{ {
try try
{ {
bool isList; bool isList = value is IList;
if(value is IList)
isList=true;
else
isList=false;
base[key] = new(base[key].Type, value, isList); base[key] = new(base[key].Type, value, isList);
return true; return true;
} }
catch (KeyNotFoundException) catch (KeyNotFoundException)
{ { return false; }
return false;
}
} }
DtsodV22 Parse(string text) DtsodV22 Parse(string text)

View File

@ -1,8 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTLib.Dtsod namespace DTLib.Dtsod
{ {

View File

@ -1,12 +1,6 @@
using System; namespace DTLib.Dtsod
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTLib.Dtsod
{ {
static public class DtsodV30 public static class DtsodV30
{ {
/* /*
public static DtsodV30 FromObject(object target) public static DtsodV30 FromObject(object target)

View File

@ -22,7 +22,7 @@ namespace DTLib.Filesystem
public static void Copy(string source_dir, string new_dir, bool owerwrite = false) public static void Copy(string source_dir, string new_dir, bool owerwrite = false)
{ {
Create(new_dir); Create(new_dir);
var subdirs = new List<string>(); List<string> subdirs = new List<string>();
List<string> files = GetAllFiles(source_dir, ref subdirs); List<string> files = GetAllFiles(source_dir, ref subdirs);
for (int i = 0; i < subdirs.Count; i++) for (int i = 0; i < subdirs.Count; i++)
{ {
@ -40,7 +40,7 @@ namespace DTLib.Filesystem
public static void Copy(string source_dir, string new_dir, out List<string> conflicts, bool owerwrite = false) public static void Copy(string source_dir, string new_dir, out List<string> conflicts, bool owerwrite = false)
{ {
conflicts = new List<string>(); conflicts = new List<string>();
var subdirs = new List<string>(); List<string> subdirs = new List<string>();
List<string> files = GetAllFiles(source_dir, ref subdirs); List<string> files = GetAllFiles(source_dir, ref subdirs);
Create(new_dir); Create(new_dir);
for (int i = 0; i < subdirs.Count; i++) for (int i = 0; i < subdirs.Count; i++)
@ -60,7 +60,7 @@ namespace DTLib.Filesystem
// удаляет папку со всеми подпапками и файлами // удаляет папку со всеми подпапками и файлами
public static void Delete(string dir) public static void Delete(string dir)
{ {
var subdirs = new List<string>(); List<string> subdirs = new List<string>();
List<string> files = GetAllFiles(dir, ref subdirs); List<string> files = GetAllFiles(dir, ref subdirs);
for (int i = 0; i < files.Count; i++) for (int i = 0; i < files.Count; i++)
File.Delete(files[i]); File.Delete(files[i]);
@ -82,7 +82,7 @@ namespace DTLib.Filesystem
// выдает список всех файлов // выдает список всех файлов
public static List<string> GetAllFiles(string dir) public static List<string> GetAllFiles(string dir)
{ {
var all_files = new List<string>(); List<string> all_files = new List<string>();
string[] cur_files = Directory.GetFiles(dir); string[] cur_files = Directory.GetFiles(dir);
for (int i = 0; i < cur_files.Length; i++) for (int i = 0; i < cur_files.Length; i++)
{ {
@ -101,7 +101,7 @@ namespace DTLib.Filesystem
// выдает список всех файлов и подпапок в папке // выдает список всех файлов и подпапок в папке
public static List<string> GetAllFiles(string dir, ref List<string> all_subdirs) public static List<string> GetAllFiles(string dir, ref List<string> all_subdirs)
{ {
var all_files = new List<string>(); List<string> all_files = new List<string>();
string[] cur_files = Directory.GetFiles(dir); string[] cur_files = Directory.GetFiles(dir);
for (int i = 0; i < cur_files.Length; i++) for (int i = 0; i < cur_files.Length; i++)
{ {
@ -122,7 +122,7 @@ namespace DTLib.Filesystem
public static void GrantAccess(string fullPath) public static void GrantAccess(string fullPath)
{ {
var dirInfo = new System.IO.DirectoryInfo(fullPath); System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(fullPath);
System.Security.AccessControl.DirectorySecurity dirSecurity = dirInfo.GetAccessControl(); System.Security.AccessControl.DirectorySecurity dirSecurity = dirInfo.GetAccessControl();
dirSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( dirSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
new System.Security.Principal.SecurityIdentifier( new System.Security.Principal.SecurityIdentifier(

View File

@ -62,12 +62,8 @@ namespace DTLib.Filesystem
public static void AppendAllText(string file, string content) => AppendAllBytes(file, content.ToBytes()); public static void AppendAllText(string file, string content) => AppendAllBytes(file, content.ToBytes());
public static System.IO.FileStream OpenRead(string file) public static System.IO.FileStream OpenRead(string file) =>
{ Exists(file) ? System.IO.File.OpenRead(file) : throw new Exception($"file not found: <{file}>");
if(!Exists(file))
throw new Exception($"file not found: <{file}>");
return System.IO.File.OpenRead(file);
}
public static System.IO.FileStream OpenWrite(string file) public static System.IO.FileStream OpenWrite(string file)
{ {
File.Create(file, true); File.Create(file, true);

View File

@ -22,7 +22,7 @@ namespace DTLib.Filesystem
lock (new object()) lock (new object())
{ {
key += ": "; key += ": ";
using var reader = new System.IO.StreamReader(configfile); using System.IO.StreamReader reader = new System.IO.StreamReader(configfile);
while (!reader.EndOfStream) while (!reader.EndOfStream)
{ {
string st = reader.ReadLine(); string st = reader.ReadLine();

View File

@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq;
using System.Text; using System.Text;
// включает init и record из c# 9.0 // включает init и record из c# 9.0
@ -47,7 +46,7 @@ namespace DTLib
// массив в лист // массив в лист
public static List<T> ToList<T>(this T[] input) public static List<T> ToList<T>(this T[] input)
{ {
var list = new List<T>(); List<T> list = new List<T>();
list.AddRange(input); list.AddRange(input);
return list; return list;
} }
@ -55,7 +54,7 @@ namespace DTLib
// удаление нескольких элементов массива // удаление нескольких элементов массива
public static T[] RemoveRange<T>(this T[] input, int startIndex, int count) public static T[] RemoveRange<T>(this T[] input, int startIndex, int count)
{ {
var list = input.ToList(); List<T> list = input.ToList();
list.RemoveRange(startIndex, count); list.RemoveRange(startIndex, count);
return list.ToArray(); return list.ToArray();
} }
@ -110,7 +109,7 @@ namespace DTLib
// хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним) // хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
public static string HashToString(this byte[] hash) public static string HashToString(this byte[] hash)
{ {
var builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (int i = 0; i < hash.Length; i++) for (int i = 0; i < hash.Length; i++)
{ {
builder.Append(hash[i].ToString("x2")); builder.Append(hash[i].ToString("x2"));
@ -165,7 +164,7 @@ namespace DTLib
// делает что надо в отличии от String.Split(), который не убирает char c из начала // делает что надо в отличии от String.Split(), который не убирает char c из начала
public static List<string> SplitToList(this string s, char c) public static List<string> SplitToList(this string s, char c)
{ {
var ar = s.ToCharArray(); char[] ar = s.ToCharArray();
StringBuilder b = new(); StringBuilder b = new();
List<string> o = new(); List<string> o = new();
if (ar[0] != c) if (ar[0] != c)
@ -195,12 +194,7 @@ namespace DTLib
return parts; return parts;
} }
public static T If<T>(this T input, bool condition, Func<T,T> if_true, Func<T,T> if_false) public static T If<T>(this T input, bool condition, Func<T, T> if_true, Func<T, T> if_false) =>
{ condition ? if_true(input) : if_false(input);
if(condition)
return if_true(input);
else
return if_false(input);
}
} }
} }

View File

@ -1,6 +1,6 @@
using DTLib.Filesystem; using System.Collections.Generic;
using System.Collections.Generic;
using System.Security.Cryptography; using System.Security.Cryptography;
using DTLib.Filesystem;
namespace DTLib namespace DTLib
{ {
@ -20,7 +20,7 @@ namespace DTLib
// хеш из двух массивов // хеш из двух массивов
public byte[] Hash(byte[] input, byte[] salt) public byte[] Hash(byte[] input, byte[] salt)
{ {
var rez = new List<byte>(); List<byte> rez = new List<byte>();
rez.AddRange(input); rez.AddRange(input);
rez.AddRange(salt); rez.AddRange(salt);
return sha256.ComputeHash(rez.ToArray()); return sha256.ComputeHash(rez.ToArray());

View File

@ -1,7 +1,7 @@
using DTLib.Dtsod; using System.Net.Sockets;
using DTLib.Filesystem;
using System.Net.Sockets;
using System.Text; using System.Text;
using DTLib.Dtsod;
using DTLib.Filesystem;
using static DTLib.PublicLog; using static DTLib.PublicLog;
namespace DTLib.Network namespace DTLib.Network
@ -54,7 +54,7 @@ namespace DTLib.Network
public byte[] DownloadFileToMemory() public byte[] DownloadFileToMemory()
{ {
using var fileStream = new System.IO.MemoryStream(); using System.IO.MemoryStream fileStream = new System.IO.MemoryStream();
Download_SharedCode(fileStream, false); Download_SharedCode(fileStream, false);
byte[] output = fileStream.GetBuffer(); byte[] output = fileStream.GetBuffer();
fileStream.Close(); fileStream.Close();
@ -144,9 +144,9 @@ namespace DTLib.Network
if (!dirOnServer.EndsWith("\\")) if (!dirOnServer.EndsWith("\\"))
dirOnServer += "\\"; dirOnServer += "\\";
Debug("b", "downloading manifest <", "c", dirOnServer + "manifest.dtsod", "b", ">\n"); Debug("b", "downloading manifest <", "c", dirOnServer + "manifest.dtsod", "b", ">\n");
var manifest = new Dtsod.DtsodV22(DownloadFileToMemory(dirOnServer+"manifest.dtsod").BytesToString()); DtsodV22 manifest = new Dtsod.DtsodV22(DownloadFileToMemory(dirOnServer + "manifest.dtsod").BytesToString());
Debug("g", $"found {manifest.Values.Count} files in manifest\n"); Debug("g", $"found {manifest.Values.Count} files in manifest\n");
var hasher = new Hasher(); Hasher hasher = new Hasher();
foreach (string fileOnServer in manifest.Keys) foreach (string fileOnServer in manifest.Keys)
{ {
string fileOnClient = dirOnClient + fileOnServer; string fileOnClient = dirOnClient + fileOnServer;

View File

@ -16,7 +16,7 @@ namespace DTLib.Network
// пингует айпи с помощью встроенной в винду проги, возвращает задержку // пингует айпи с помощью встроенной в винду проги, возвращает задержку
public static string PingIP(string address) public static string PingIP(string address)
{ {
var proc = new Process(); Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "/c @echo off & chcp 65001 >nul & ping -n 5 " + address; proc.StartInfo.Arguments = "/c @echo off & chcp 65001 >nul & ping -n 5 " + address;
proc.StartInfo.CreateNoWindow = true; proc.StartInfo.CreateNoWindow = true;

View File

@ -42,7 +42,7 @@ namespace DTLib.Network
throw new Exception($"SendPackage() error: package is too big ({data.Length} bytes)"); throw new Exception($"SendPackage() error: package is too big ({data.Length} bytes)");
if (data.Length == 0) if (data.Length == 0)
throw new Exception($"SendPackage() error: package has zero size"); throw new Exception($"SendPackage() error: package has zero size");
var list = new List<byte>(); List<byte> list = new List<byte>();
byte[] packageSize = data.Length.ToBytes(); byte[] packageSize = data.Length.ToBytes();
if (packageSize.Length == 1) if (packageSize.Length == 1)
list.Add(0); list.Add(0);

View File

@ -136,14 +136,9 @@ namespace DTLib
// <returns>The computed hash code.</returns> // <returns>The computed hash code.</returns>
protected override byte[] HashFinal() protected override byte[] HashFinal()
{ {
if(_TotalLength>=16) _Hash32 = _TotalLength >= 16
{ ? RotateLeft32(_ACC32_1, 1) + RotateLeft32(_ACC32_2, 7) + RotateLeft32(_ACC32_3, 12) + RotateLeft32(_ACC32_4, 18)
_Hash32=RotateLeft32(_ACC32_1, 1)+RotateLeft32(_ACC32_2, 7)+RotateLeft32(_ACC32_3, 12)+RotateLeft32(_ACC32_4, 18); : _Seed32 + PRIME32_5;
}
else
{
_Hash32=_Seed32+PRIME32_5;
}
_Hash32 += (uint)_TotalLength; _Hash32 += (uint)_TotalLength;
while (_RemainingLength >= 4) while (_RemainingLength >= 4)
{ {