REFACTORING

This commit is contained in:
Timerix 2021-10-04 23:25:42 +03:00
parent c71d2b8356
commit 2defc3ae5e
25 changed files with 583 additions and 539 deletions

View File

@ -8,7 +8,8 @@ namespace DTLib
{
public RGBA(byte[] arrayRGBA) : this(arrayRGBA[0], arrayRGBA[1], arrayRGBA[2], arrayRGBA[3])
{
if (arrayRGBA.Length != 4) throw new Exception("Color.RGBA(byte[] arrayRGBA) error: arrayRGBA.Length != 4\n");
if(arrayRGBA.Length!=4)
throw new Exception("Color.RGBA(byte[] arrayRGBA) error: arrayRGBA.Length != 4\n");
}
}
@ -16,7 +17,8 @@ namespace DTLib
{
public RGB(byte[] arrayRGB) : this(arrayRGB[0], arrayRGB[1], arrayRGB[2])
{
if (arrayRGB.Length != 3) throw new Exception("Color.RGB(byte[] arrayRGB) error: arrayRGB.Length != 3\n");
if(arrayRGB.Length!=3)
throw new Exception("Color.RGB(byte[] arrayRGB) error: arrayRGB.Length != 3\n");
}
}
}

View File

@ -10,9 +10,7 @@ namespace DTLib
public static class ColoredConsole
{
// парсит название цвета в ConsoleColor
public static ConsoleColor ParseColor(string color)
{
return color switch
public static ConsoleColor ParseColor(string color) => color switch
{
//case "magneta":
"m" => ConsoleColor.Magenta,
@ -34,14 +32,14 @@ namespace DTLib
"black" => ConsoleColor.Black,
_ => throw new Exception($"ColoredConsole.ParseColor({color}) error: incorrect color"),
};
}
// вывод цветного текста
public static void Write(params string[] input)
{
if(input.Length==1)
{
if (Console.ForegroundColor != ConsoleColor.Gray) Console.ForegroundColor = ConsoleColor.Gray;
if(Console.ForegroundColor!=ConsoleColor.Gray)
Console.ForegroundColor=ConsoleColor.Gray;
Console.Write(input[0]);
}
else if(input.Length%2==0)
@ -49,7 +47,7 @@ namespace DTLib
StringBuilder strB = new();
for(ushort i = 0; i<input.Length; i++)
{
var c = ParseColor(input[i]);
ConsoleColor c = ParseColor(input[i]);
if(Console.ForegroundColor!=c)
{
Console.Write(strB.ToString());
@ -58,16 +56,19 @@ namespace DTLib
}
strB.Append(input[++i]);
}
if (strB.Length > 0) Console.Write(strB.ToString());
if(strB.Length>0)
Console.Write(strB.ToString());
}
else throw new Exception("ColoredConsole.Write() error: every text string must have color string before");
else
throw new Exception("ColoredConsole.Write() error: 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;
ConsoleColor c = ParseColor(color);
if(Console.ForegroundColor!=c)
Console.ForegroundColor=c;
return Console.ReadLine();
}
}

View File

@ -12,10 +12,7 @@ namespace DTLib
T[] Memory;
public Array1D() { }
public Array1D(T[] sourceArray)
{
CompressArray(sourceArray);
}
public Array1D(T[] sourceArray) => CompressArray(sourceArray);
public void CompressArray(T[] sourceArray)
{
@ -27,7 +24,8 @@ namespace DTLib
byte repeats = 1;
for(int i = 1; i<sourceArray.Length; i++)
{
if (prevElement.CompareTo(sourceArray[i]) == 0) repeats++;
if(prevElement.CompareTo(sourceArray[i])==0)
repeats++;
else
{
listMem.Add(sourceArray[i]);
@ -60,9 +58,12 @@ namespace DTLib
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];
if(sum<index)
sum+=Description[i];
else if(sum==index)
output=Memory[i];
else
output=Memory[i-1];
}
storageUsing.ReleaseMutex();
return output;

View File

@ -31,7 +31,7 @@ namespace DTLib.ConsoleGUI
switch(layout[Name]["children"][element_name]["type"])
{
case "label":
this.Add(new Label(element_name,
Add(new Label(element_name,
layout[Name]["children"][element_name]["resdir"]+$"\\{element_name}.textmap",
layout[Name]["children"][element_name]["resdir"]+$"\\{element_name}.colormap")
{
@ -48,7 +48,7 @@ namespace DTLib.ConsoleGUI
Textmap=new char[Width*Height];
for(int i = 0; i<Textmap.Length; i++)
Textmap[i]=' ';
foreach (var element in this)
foreach(IDrawable element in this)
{
element.GenTextmap();
Log("m", $"Length: {element.Textmap.Length} calculated: {element.Width*element.Height}\n");

View File

@ -23,10 +23,7 @@ namespace DTLib.ConsoleGUI
Name=name;
}
public void GenColormap()
{
Colormap = File.ReadAllText(ColormapFile).ToCharArray();
}
public void GenColormap() => Colormap=File.ReadAllText(ColormapFile).ToCharArray();
public void GenTextmap()
{

View File

@ -97,10 +97,7 @@ namespace DTLib.ConsoleGUI
r.Close();
}*/
public void ResetCursor()
{
Console.SetCursorPosition(0, WindowHeight);
}
public void ResetCursor() => Console.SetCursorPosition(0, WindowHeight);
// заменяет символ выведенный, использовать после ShowAll()
public void ChangeChar(sbyte x, sbyte y, char ch)

View File

@ -34,13 +34,17 @@ namespace DTLib.Dtsod
{
get
{
if (TryGetValue(key, out dynamic value)) return value;
else 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
{
if (TrySetValue(key, value)) return;
else throw new Exception($"Dtsod[{key}] key not found");
if(TrySetValue(key, value))
return;
else
throw new Exception($"Dtsod[{key}] key not found");
}
}
@ -94,7 +98,8 @@ namespace DTLib.Dtsod
{
Dictionary<string, dynamic> parsed = new();
int i = 0;
for (; i < text.Length; i++) ReadName();
for(; i<text.Length; i++)
ReadName();
DebugNoTime("g", $"Parse returns {parsed.Keys.Count} keys\n");
return parsed;
@ -128,10 +133,12 @@ namespace DTLib.Dtsod
DebugNoTime("c", $"parsed.Add({name}, {value} { value.GetType() })\n");
if(isListElem)
{
if (!parsed.ContainsKey(name)) parsed.Add(name, new List<dynamic>());
if(!parsed.ContainsKey(name))
parsed.Add(name, new List<dynamic>());
parsed[name].Add(value);
}
else parsed.Add(name, value);
else
parsed.Add(name, value);
return;
// строка, начинающаяся с # будет считаться комментом
case '#':
@ -142,7 +149,8 @@ namespace DTLib.Dtsod
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
case '$':
DebugNoTime("w", text[i].ToString());
if (defaultNameBuilder.ToString().Length != 0) throw new Exception("Parse.ReadName() error: unexpected '$' at " + i + " char");
if(defaultNameBuilder.ToString().Length!=0)
throw new Exception("Parse.ReadName() error: unexpected '$' at "+i+" char");
isListElem=true;
break;
case ';':
@ -227,7 +235,8 @@ namespace DTLib.Dtsod
case '}':
balance--;
DebugNoTime("b", $"\nbalance -- = {balance}\n");
if (balance != 0) valueBuilder.Append(text[i]);
if(balance!=0)
valueBuilder.Append(text[i]);
break;
case '{':
balance++;
@ -261,9 +270,11 @@ namespace DTLib.Dtsod
value=null;
break;
default:
if (stringValue.Contains('"')) value = stringValue.Remove(stringValue.Length - 1).Remove(0, 1);
if(stringValue.Contains('"'))
value=stringValue.Remove(stringValue.Length-1).Remove(0, 1);
// double
else if (stringValue.Contains('.')) value = stringValue.ToDouble();
else if(stringValue.Contains('.'))
value=stringValue.ToDouble();
// ushort; ulong; uint
else if(stringValue.Length>2&&stringValue[stringValue.Length-2]=='u')
{
@ -283,7 +294,8 @@ namespace DTLib.Dtsod
};
}
// short; long; int
else switch (stringValue[stringValue.Length - 1])
else
switch(stringValue[stringValue.Length-1])
{
case 's':
value=stringValue.Remove(stringValue.Length-1).ToShort();
@ -347,11 +359,13 @@ namespace DTLib.Dtsod
void Debug(params string[] msg)
{
if (debug) Log(msg);
if(debug)
Log(msg);
}
void DebugNoTime(params string[] msg)
{
if (debug) LogNoTime(msg);
if(debug)
LogNoTime(msg);
}
}
}

View File

@ -66,13 +66,17 @@ namespace DTLib.Dtsod
{
get
{
if (TryGetValue(key, out dynamic value)) return value;
else 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
{
if (TrySetValue(key, value)) return;
else throw new Exception($"Dtsod[{key}] key not found");
if(TrySetValue(key, value))
return;
else
throw new Exception($"Dtsod[{key}] key not found");
}
}
@ -95,8 +99,10 @@ namespace DTLib.Dtsod
try
{
bool isList;
if (value is IList) isList = true;
else isList = false;
if(value is IList)
isList=true;
else
isList=false;
base[key]=new(base[key].Type, value, isList);
return true;
}
@ -110,7 +116,8 @@ namespace DTLib.Dtsod
{
Dictionary<string, ValueStruct> parsed = new();
int i = 0;
for (; i < text.Length; i++) ReadName();
for(; i<text.Length; i++)
ReadName();
DebugNoTime("g", $"Parse returns {parsed.Keys.Count} keys\n");
return new DtsodV23(parsed);
@ -140,14 +147,16 @@ namespace DTLib.Dtsod
case ':':
i++;
string name = defaultNameBuilder.ToString();
value = ReadValue(out var type, out var isList);
value=ReadValue(out ValueTypes type, out bool isList);
DebugNoTime("c", $"parsed.Add({name},{type} {value} )\n");
if(isListElem)
{
if (!parsed.ContainsKey(name)) parsed.Add(name, new(type, new List<dynamic>(), isList));
if(!parsed.ContainsKey(name))
parsed.Add(name, new(type, new List<dynamic>(), isList));
parsed[name].Value.Add(value);
}
else parsed.Add(name, new(type, value, isList));
else
parsed.Add(name, new(type, value, isList));
return;
// строка, начинающаяся с # будет считаться комментом
case '#':
@ -158,7 +167,8 @@ namespace DTLib.Dtsod
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
case '$':
DebugNoTime("w", text[i].ToString());
if (defaultNameBuilder.ToString().Length != 0) throw new Exception("Parse.ReadName() error: unexpected '$' at " + i + " char");
if(defaultNameBuilder.ToString().Length!=0)
throw new Exception("Parse.ReadName() error: unexpected '$' at "+i+" char");
isListElem=true;
break;
case ';':
@ -244,7 +254,8 @@ namespace DTLib.Dtsod
case '}':
balance--;
DebugNoTime("b", $"\nbalance -- = {balance}\n");
if (balance != 0) valueBuilder.Append(text[i]);
if(balance!=0)
valueBuilder.Append(text[i]);
break;
case '{':
balance++;
@ -312,7 +323,8 @@ namespace DTLib.Dtsod
};
}
// short; long; int
else switch (stringValue[stringValue.Length - 1])
else
switch(stringValue[stringValue.Length-1])
{
case 's':
type=ValueTypes.Short;
@ -386,7 +398,7 @@ namespace DTLib.Dtsod
string Deconstruct(DtsodV23 dtsod)
{
StringBuilder outBuilder = new();
foreach (var key in dtsod.Keys)
foreach(string key in dtsod.Keys)
{
outBuilder.Append('\t', tabCount);
outBuilder.Append(key);
@ -455,7 +467,8 @@ namespace DTLib.Dtsod
void DebugNoTime(params string[] msg)
{
if (debug) PublicLog.LogNoTime(msg);
if(debug)
PublicLog.LogNoTime(msg);
}
public void Expand(DtsodV23 newPart)

View File

@ -2,5 +2,7 @@
namespace DTLib
{
#pragma warning disable IDE1006 // Стили именования
public delegate Task EventHandlerAsync<TEventArgs>(object sender, TEventArgs e);
#pragma warning restore IDE1006 // Стили именования
}

View File

@ -22,7 +22,7 @@ namespace DTLib.Filesystem
public static void Copy(string source_dir, string new_dir, bool owerwrite = false)
{
Create(new_dir);
List<string> subdirs = new List<string>();
var subdirs = new List<string>();
List<string> files = GetAllFiles(source_dir, ref subdirs);
for(int i = 0; i<subdirs.Count; i++)
{
@ -41,7 +41,7 @@ namespace DTLib.Filesystem
{
conflicts=new List<string>();
var subdirs = new List<string>();
var files = GetAllFiles(source_dir, ref subdirs);
List<string> files = GetAllFiles(source_dir, ref subdirs);
Create(new_dir);
for(int i = 0; i<subdirs.Count; i++)
{
@ -50,7 +50,8 @@ namespace DTLib.Filesystem
for(int i = 0; i<files.Count; i++)
{
string newfile = files[i].Replace(source_dir, new_dir);
if (File.Exists(newfile)) conflicts.Add(newfile);
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'" });
}
@ -60,16 +61,18 @@ namespace DTLib.Filesystem
public static void Delete(string dir)
{
var subdirs = new List<string>();
var files = GetAllFiles(dir, ref subdirs);
List<string> 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--)
{
PublicLog.Log($"deleting {subdirs[i]}\n");
if (Directory.Exists(subdirs[i])) System.IO.Directory.Delete(subdirs[i], true);
if(Directory.Exists(subdirs[i]))
System.IO.Directory.Delete(subdirs[i], true);
}
PublicLog.Log($"deleting {dir}\n");
if (Directory.Exists(dir)) System.IO.Directory.Delete(dir, true);
if(Directory.Exists(dir))
System.IO.Directory.Delete(dir, true);
}
public static string[] GetFiles(string dir) => System.IO.Directory.GetFiles(dir);
@ -79,7 +82,7 @@ namespace DTLib.Filesystem
// выдает список всех файлов
public static List<string> GetAllFiles(string dir)
{
List<string> all_files = new List<string>();
var all_files = new List<string>();
string[] cur_files = Directory.GetFiles(dir);
for(int i = 0; i<cur_files.Length; i++)
{
@ -98,7 +101,7 @@ namespace DTLib.Filesystem
// выдает список всех файлов и подпапок в папке
public static List<string> GetAllFiles(string dir, ref List<string> all_subdirs)
{
List<string> all_files = new List<string>();
var all_files = new List<string>();
string[] cur_files = Directory.GetFiles(dir);
for(int i = 0; i<cur_files.Length; i++)
{
@ -119,7 +122,7 @@ namespace DTLib.Filesystem
public static void GrantAccess(string fullPath)
{
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(fullPath);
var dirInfo = new System.IO.DirectoryInfo(fullPath);
System.Security.AccessControl.DirectorySecurity dirSecurity = dirInfo.GetAccessControl();
dirSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
new System.Security.Principal.SecurityIdentifier(

View File

@ -11,18 +11,21 @@ namespace DTLib.Filesystem
// если файл не существует, создаёт файл, создаёт папки из его пути
public static void Create(string file, bool delete_old = false)
{
if (delete_old && File.Exists(file)) File.Delete(file);
if(delete_old&&File.Exists(file))
File.Delete(file);
if(!File.Exists(file))
{
if (file.Contains("\\")) Directory.Create(file.Remove(file.LastIndexOf('\\')));
using var stream = System.IO.File.Create(file);
if(file.Contains("\\"))
Directory.Create(file.Remove(file.LastIndexOf('\\')));
using System.IO.FileStream stream = System.IO.File.Create(file);
stream.Close();
}
}
public static void Copy(string srcPath, string newPath, bool replace = false)
{
if (!replace && Exists(newPath)) throw new Exception($"file <{newPath}> alredy exists");
if(!replace&&Exists(newPath))
throw new Exception($"file <{newPath}> alredy exists");
Create(newPath);
WriteAllBytes(newPath, ReadAllBytes(srcPath));
}
@ -31,7 +34,7 @@ namespace DTLib.Filesystem
public static byte[] ReadAllBytes(string file)
{
using var stream = File.OpenRead(file);
using System.IO.FileStream stream = File.OpenRead(file);
int size = GetSize(file);
byte[] output = new byte[size];
stream.Read(output, 0, size);
@ -43,7 +46,7 @@ namespace DTLib.Filesystem
public static void WriteAllBytes(string file, byte[] content)
{
using var stream = File.OpenWrite(file);
using System.IO.FileStream stream = File.OpenWrite(file);
stream.Write(content, 0, content.Length);
stream.Close();
}
@ -52,7 +55,7 @@ namespace DTLib.Filesystem
public static void AppendAllBytes(string file, byte[] content)
{
using var stream = File.OpenAppend(file);
using System.IO.FileStream stream = File.OpenAppend(file);
stream.Write(content, 0, content.Length);
stream.Close();
}
@ -61,7 +64,8 @@ namespace DTLib.Filesystem
public static System.IO.FileStream OpenRead(string file)
{
if (!Exists(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)

View File

@ -31,7 +31,8 @@ namespace DTLib.Filesystem
string value = "";
for(int i = key.Length; i<st.Length; i++)
{
if (st[i] == '#') return value;
if(st[i]=='#')
return value;
if(st[i]=='%')
{
bool stop = false;
@ -51,7 +52,8 @@ namespace DTLib.Filesystem
}
}
}
else value += st[i];
else
value+=st[i];
}
reader.Close();
//if (value == "") throw new System.Exception($"ReadFromConfig({configfile}, {key}) error: key not found");

View File

@ -20,7 +20,7 @@ namespace DTLib
// хеш из двух массивов
public byte[] Hash(byte[] input, byte[] salt)
{
List<byte> rez = new List<byte>();
var rez = new List<byte>();
rez.AddRange(input);
rez.AddRange(salt);
return sha256.ComputeHash(rez.ToArray());
@ -48,9 +48,9 @@ namespace DTLib
// хеш файла
public byte[] HashFile(string filename)
{
using var fileStream = File.OpenRead(filename);
using System.IO.FileStream fileStream = File.OpenRead(filename);
//var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
var hash = xxh32.ComputeHash(fileStream);
byte[] hash = xxh32.ComputeHash(fileStream);
//var now = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
//PublicLog.Log($"xxh32 hash: {hash.HashToString()} time: {now - then}\n");
fileStream.Close();

View File

@ -1,5 +1,6 @@
using DTLib.Dtsod;
using DTLib.Filesystem;
using System;
using System.Net.Sockets;
using System.Text;
using static DTLib.PublicLog;
@ -11,9 +12,9 @@ namespace DTLib.Network
//
public class FSP
{
Socket mainSocket { get; init; }
static public bool debug = false;
public FSP(Socket _mainSocket) => mainSocket = _mainSocket;
Socket MainSocket { get; init; }
public static bool debug = false;
public FSP(Socket _mainSocket) => MainSocket=_mainSocket;
public uint BytesDownloaded = 0;
public uint BytesUploaded = 0;
@ -27,9 +28,9 @@ namespace DTLib.Network
Mutex.Execute(() =>
{
Debug("b", $"requesting file download: {filePath_server}\n");
mainSocket.SendPackage("requesting file download".ToBytes());
mainSocket.SendPackage(filePath_server.ToBytes());
}, out var exception);
MainSocket.SendPackage("requesting file download".ToBytes());
MainSocket.SendPackage(filePath_server.ToBytes());
}, out Exception exception);
exception?.Throw();
DownloadFile(filePath_client);
}
@ -47,9 +48,9 @@ namespace DTLib.Network
Mutex.Execute(() =>
{
Debug("b", $"requesting file download: {filePath_server}\n");
mainSocket.SendPackage("requesting file download".ToBytes());
mainSocket.SendPackage(filePath_server.ToBytes());
}, out var exception);
MainSocket.SendPackage("requesting file download".ToBytes());
MainSocket.SendPackage(filePath_server.ToBytes());
}, out System.Exception exception);
exception?.Throw();
return DownloadFileToMemory();
}
@ -69,15 +70,15 @@ namespace DTLib.Network
Mutex.Execute(() =>
{
BytesDownloaded=0;
Filesize = SimpleConverter.ToString(mainSocket.GetPackage()).ToUInt();
mainSocket.SendPackage("ready".ToBytes());
Filesize=SimpleConverter.ToString(MainSocket.GetPackage()).ToUInt();
MainSocket.SendPackage("ready".ToBytes());
int packagesCount = 0;
byte[] buffer = new byte[5120];
int fullPackagesCount = SimpleConverter.Truncate(Filesize/buffer.Length);
// получение полных пакетов файла
for(byte n = 0; packagesCount<fullPackagesCount; packagesCount++)
{
buffer = mainSocket.GetPackage();
buffer=MainSocket.GetPackage();
BytesDownloaded+=(uint)buffer.Length;
fileStream.Write(buffer, 0, buffer.Length);
if(requiresFlushing)
@ -87,20 +88,22 @@ namespace DTLib.Network
fileStream.Flush();
n=0;
}
else n++;
else
n++;
}
}
// получение остатка
if((Filesize-fileStream.Position)>0)
{
mainSocket.SendPackage("remain request".ToBytes());
buffer = mainSocket.GetPackage();
MainSocket.SendPackage("remain request".ToBytes());
buffer=MainSocket.GetPackage();
BytesDownloaded+=(uint)buffer.Length;
fileStream.Write(buffer, 0, buffer.Length);
}
}, out var exception);
}, out System.Exception exception);
exception?.Throw();
if (requiresFlushing) fileStream.Flush();
if(requiresFlushing)
fileStream.Flush();
}
// отдаёт файл с помощью FSP протокола
@ -108,12 +111,12 @@ namespace DTLib.Network
{
BytesUploaded=0;
Debug("b", $"uploading file {filePath}\n");
using var fileStream = File.OpenRead(filePath);
using System.IO.FileStream fileStream = File.OpenRead(filePath);
Filesize=File.GetSize(filePath).ToUInt();
Mutex.Execute(() =>
{
mainSocket.SendPackage(Filesize.ToString().ToBytes());
mainSocket.GetAnswer("ready");
MainSocket.SendPackage(Filesize.ToString().ToBytes());
MainSocket.GetAnswer("ready");
byte[] buffer = new byte[5120];
int packagesCount = 0;
int fullPackagesCount = SimpleConverter.Truncate(Filesize/buffer.Length);
@ -121,19 +124,19 @@ namespace DTLib.Network
for(; packagesCount<fullPackagesCount; packagesCount++)
{
fileStream.Read(buffer, 0, buffer.Length);
mainSocket.SendPackage(buffer);
MainSocket.SendPackage(buffer);
BytesUploaded+=(uint)buffer.Length;
}
// отправка остатка
if((Filesize-fileStream.Position)>0)
{
mainSocket.GetAnswer("remain request");
MainSocket.GetAnswer("remain request");
buffer=new byte[(Filesize-fileStream.Position).ToInt()];
fileStream.Read(buffer, 0, buffer.Length);
mainSocket.SendPackage(buffer);
MainSocket.SendPackage(buffer);
BytesUploaded+=(uint)buffer.Length;
}
}, out var exception);
}, out System.Exception exception);
exception?.Throw();
fileStream.Close();
Debug(new string[] { "g", $" uploaded {BytesUploaded} of {Filesize} bytes\n" });
@ -141,8 +144,10 @@ namespace DTLib.Network
public void DownloadByManifest(string dirOnServer, string dirOnClient, bool overwrite = false, bool delete_excess = false)
{
if (!dirOnClient.EndsWith("\\")) dirOnClient += "\\";
if (!dirOnServer.EndsWith("\\")) dirOnServer += "\\";
if(!dirOnClient.EndsWith("\\"))
dirOnClient+="\\";
if(!dirOnServer.EndsWith("\\"))
dirOnServer+="\\";
Debug("b", "downloading manifest <", "c", dirOnServer+"manifest.dtsod", "b", ">\n");
var manifest = new DtsodV23(SimpleConverter.ToString(DownloadFileToMemory(dirOnServer+"manifest.dtsod")));
Debug("g", $"found {manifest.Values.Count} files in manifest\n");
@ -161,7 +166,8 @@ namespace DTLib.Network
DebugNoTime("y", "outdated\n");
DownloadFile(dirOnServer+fileOnServer, fileOnClient);
}
else DebugNoTime("g", "without changes\n");
else
DebugNoTime("g", "without changes\n");
}
// удаление лишних файлов
if(delete_excess)
@ -179,11 +185,13 @@ namespace DTLib.Network
public static void CreateManifest(string dir)
{
if (!dir.EndsWith("\\")) dir += "\\";
if(!dir.EndsWith("\\"))
dir+="\\";
Log($"b", $"creating manifest of {dir}\n");
StringBuilder manifestBuilder = new();
Hasher hasher = new();
if (Directory.GetFiles(dir).Contains(dir + "manifest.dtsod")) File.Delete(dir + "manifest.dtsod");
if(Directory.GetFiles(dir).Contains(dir+"manifest.dtsod"))
File.Delete(dir+"manifest.dtsod");
foreach(string _file in Directory.GetAllFiles(dir))
{
string file = _file.Remove(0, dir.Length);
@ -199,11 +207,13 @@ namespace DTLib.Network
static void Debug(params string[] msg)
{
if (debug) Log(msg);
if(debug)
Log(msg);
}
static void DebugNoTime(params string[] msg)
{
if (debug) LogNoTime(msg);
if(debug)
LogNoTime(msg);
}
}
}

View File

@ -16,15 +16,15 @@ namespace DTLib.Network
// пингует айпи с помощью встроенной в винду проги, возвращает задержку
public static string PingIP(string address)
{
Process proc = new Process();
var 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();
System.IO.StreamReader outStream = proc.StandardOutput;
string rezult = outStream.ReadToEnd();
rezult=rezult.Remove(0, rezult.LastIndexOf('=')+2);
return rezult.Remove(rezult.Length-4);
}

View File

@ -29,7 +29,8 @@ namespace DTLib.Network
socket.Receive(data, data.Length, 0);
return data;
}
else Thread.Sleep(5);
else
Thread.Sleep(5);
}
throw new Exception($"GetPackage() error: timeout. socket.Available={socket.Available}\n");
}
@ -37,11 +38,14 @@ namespace DTLib.Network
// отправляет пакет
public static void SendPackage(this Socket socket, byte[] data)
{
if (data.Length > 65536) throw new Exception($"SendPackage() error: package is too big ({data.Length} bytes)");
if (data.Length == 0) throw new Exception($"SendPackage() error: package has zero size");
if(data.Length>65536)
throw new Exception($"SendPackage() error: package is too big ({data.Length} bytes)");
if(data.Length==0)
throw new Exception($"SendPackage() error: package has zero size");
var list = new List<byte>();
byte[] packageSize = data.Length.ToBytes();
if (packageSize.Length == 1) list.Add(0);
if(packageSize.Length==1)
list.Add(0);
list.AddRange(packageSize);
list.AddRange(data);
socket.Send(list.ToArray());
@ -51,8 +55,9 @@ namespace DTLib.Network
// получает пакет и выбрасывает исключение, если пакет не соответствует образцу
public static void GetAnswer(this Socket socket, string answer)
{
var rec = SimpleConverter.ToString(socket.GetPackage());
if (rec != answer) throw new Exception($"GetAnswer() error: invalid answer: <{rec}>");
string rec = SimpleConverter.ToString(socket.GetPackage());
if(rec!=answer)
throw new Exception($"GetAnswer() error: invalid answer: <{rec}>");
}
public static byte[] RequestPackage(this Socket socket, byte[] request)

View File

@ -11,20 +11,17 @@ namespace DTLib.Reactive
public ReactiveListener(IEnumerable<ReactiveStream<T>> streams) : base(streams) { }
public Action<object, T> ElementAddedHandler;
public void SetHandler(Action<object, T> handler) => ReactiveWorkerMutex.Execute(() => { ElementAddedHandler = handler; });
public void SetHandler(Action<object, T> handler) => ReactiveWorkerMutex.Execute(() => ElementAddedHandler=handler);
public async Task ElementAdded(object s, T e) => await Task.Run(() => ElementAddedHandler?.Invoke(s, e));
public override void Join(ReactiveStream<T> stream)
{
public override void Join(ReactiveStream<T> stream) =>
ReactiveWorkerMutex.Execute(() =>
{
Streams.Add(stream);
stream.ElementAdded+=ElementAdded;
});
}
public override void Leave(ReactiveStream<T> stream)
{
public override void Leave(ReactiveStream<T> stream) =>
ReactiveWorkerMutex.Execute(() =>
{
Streams.Remove(stream);
@ -32,4 +29,3 @@ namespace DTLib.Reactive
});
}
}
}

View File

@ -11,27 +11,18 @@ namespace DTLib.Reactive
public ReactiveProvider(IEnumerable<ReactiveStream<T>> streams) : base(streams) { }
event Action<T> AnnounceEvent;
public void Announce(T e)
{
ReactiveWorkerMutex.Execute(() => AnnounceEvent.Invoke(e));
}
public void Announce(T e) => ReactiveWorkerMutex.Execute(() => AnnounceEvent.Invoke(e));
public override void Join(ReactiveStream<T> stream)
{
ReactiveWorkerMutex.Execute(() =>
public override void Join(ReactiveStream<T> stream) => ReactiveWorkerMutex.Execute(() =>
{
Streams.Add(stream);
AnnounceEvent+=stream.Add;
});
}
public override void Leave(ReactiveStream<T> stream)
{
ReactiveWorkerMutex.Execute(() =>
public override void Leave(ReactiveStream<T> stream) => ReactiveWorkerMutex.Execute(() =>
{
Streams.Remove(stream);
AnnounceEvent-=stream.Add;
});
}
}
}

View File

@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
namespace DTLib.Reactive
{
@ -8,7 +7,7 @@ namespace DTLib.Reactive
List<T> Storage = new();
public event EventHandlerAsync<T> ElementAdded;
SafeMutex StorageMutex = new();
public int Length { get { return StorageMutex.Execute(() => Storage.Count); } }
public int Length => StorageMutex.Execute(() => Storage.Count);
public ReactiveStream() { }

View File

@ -12,7 +12,7 @@ namespace DTLib.Reactive
public ReactiveWorker(ReactiveStream<T> stream) => Join(stream);
public ReactiveWorker(IEnumerable<ReactiveStream<T>> streams) =>
ReactiveWorkerMutex.Execute(() => { foreach (var stream in streams) Join(stream); });
ReactiveWorkerMutex.Execute(() => { foreach(ReactiveStream<T> stream in streams) Join(stream); });
public abstract void Join(ReactiveStream<T> stream);
public abstract void Leave(ReactiveStream<T> stream);

View File

@ -19,7 +19,8 @@ namespace DTLib
catch(Exception ex)
{
exception=ex;
if (!isReleased) Mutex.ReleaseMutex();
if(!isReleased)
Mutex.ReleaseMutex();
}
}
@ -33,7 +34,7 @@ namespace DTLib
public T Execute<T>(Func<T> action)
{
Mutex.WaitOne();
var rezult = action();
T rezult = action();
Mutex.ReleaseMutex();
isReleased=true;
return rezult;

View File

@ -15,7 +15,8 @@ namespace DTLib
{
for(int i = 0; i<startsWith.Length; i++)
{
if (source[i] != startsWith[i]) return false;
if(source[i]!=startsWith[i])
return false;
}
return true;
}
@ -24,7 +25,8 @@ namespace DTLib
{
for(int i = 0; i<endsWith.Length; i++)
{
if (source[source.Length - endsWith.Length + i] != endsWith[i]) return false;
if(source[source.Length-endsWith.Length+i]!=endsWith[i])
return false;
}
return true;
}
@ -44,7 +46,7 @@ namespace DTLib
// удаление нескольких элементов массива
public static T[] RemoveRange<T>(this T[] input, int startIndex, int count)
{
List<T> list = input.ToList();
var list = input.ToList();
list.RemoveRange(startIndex, count);
return list.ToArray();
}
@ -54,7 +56,8 @@ namespace DTLib
public static bool Contains<T>(this T[] array, T value)
{
for(int i = 0; i<array.Length; i++)
if (array[i].Equals(value)) return true;
if(array[i].Equals(value))
return true;
return false;
}
@ -73,7 +76,8 @@ namespace DTLib
public static int ToInt(this byte[] bytes)
{
int output = 0;
for (ushort i = 0; i < bytes.Length; i++) output = output * 256 + bytes[i];
for(ushort i = 0; i<bytes.Length; i++)
output=output*256+bytes[i];
return output;
}

View File

@ -60,7 +60,7 @@ namespace DTLib
// Creates an instance of <see cref="XXHash32"/> class by default seed(0).
// <returns></returns>
public static new XXHash32 Create() => new XXHash32();
public static new XXHash32 Create() => new();
// Initializes a new instance of the <see cref="XXHash32"/> class by default seed(0).
public XXHash32() => Initialize(0);
@ -82,7 +82,8 @@ namespace DTLib
{
if(value!=_Seed32)
{
if (State != 0) throw new InvalidOperationException("Hash computation has not yet completed.");
if(State!=0)
throw new InvalidOperationException("Hash computation has not yet completed.");
_Seed32=value;
Initialize();
}
@ -104,12 +105,13 @@ namespace DTLib
// <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;
if(State!=1)
State=1;
int size = cbSize-ibStart;
_RemainingLength=size&15;
if(cbSize>=16)
{
var limit = size - _RemainingLength;
int limit = size-_RemainingLength;
do
{
_ACC32_1=Round32(_ACC32_1, FuncGetLittleEndianUInt32(array, ibStart));