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

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

View File

@ -36,27 +36,27 @@ namespace DTLib
// вывод цветного текста
public static void Write(params string[] input)
{
if(input.Length==1)
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)
else if (input.Length % 2 == 0)
{
StringBuilder strB = new();
for(ushort i = 0; i<input.Length; i++)
for (ushort i = 0; i < input.Length; i++)
{
ConsoleColor c = ParseColor(input[i]);
if(Console.ForegroundColor!=c)
if (Console.ForegroundColor != c)
{
Console.Write(strB.ToString());
Console.ForegroundColor=c;
Console.ForegroundColor = c;
strB.Clear();
}
strB.Append(input[++i]);
}
if(strB.Length>0)
if (strB.Length > 0)
Console.Write(strB.ToString());
}
else
@ -67,8 +67,8 @@ namespace DTLib
public static string Read(string color)
{
ConsoleColor c = ParseColor(color);
if(Console.ForegroundColor!=c)
Console.ForegroundColor=c;
if (Console.ForegroundColor != c)
Console.ForegroundColor = c;
return Console.ReadLine();
}
}

View File

@ -16,32 +16,32 @@ namespace DTLib
public void CompressArray(T[] sourceArray)
{
var listMem = new List<T>();
var listDesc = new List<byte>();
List<T> listMem = new List<T>();
List<byte> 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++)
for (int i = 1; i < sourceArray.Length; i++)
{
if(prevElement.CompareTo(sourceArray[i])==0)
if (prevElement.CompareTo(sourceArray[i]) == 0)
repeats++;
else
{
listMem.Add(sourceArray[i]);
listDesc.Add(1);
if(repeats>1)
if (repeats > 1)
{
listDesc[listDesc.Count-2]=repeats;
repeats=1;
listDesc[listDesc.Count - 2] = repeats;
repeats = 1;
}
}
prevElement=sourceArray[i];
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++)
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");
}
@ -56,14 +56,11 @@ namespace DTLib
storageUsing.WaitOne();
T output = default;
int sum = 0;
for(int i = 0; i<Description.Length; i++)
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 output = sum == index ? Memory[i] : Memory[i - 1];
}
storageUsing.ReleaseMutex();
return output;

View File

@ -25,27 +25,18 @@ namespace DTLib.Dtsod
//public Dictionary<string, dynamic> Values { get; set; }
public DtsodV21(string text)
{
Text=text;
foreach(KeyValuePair<string, dynamic> pair in Parse(text))
Text = text;
foreach (KeyValuePair<string, dynamic> pair in Parse(text))
Add(pair.Key, pair.Value);
}
// выдаёт Exception
public new dynamic this[string key]
{
get
{
if(TryGetValue(key, out dynamic value))
return value;
else
throw new Exception($"Dtsod[{key}] key not found");
}
get => TryGetValue(key, out dynamic value) ? value : 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)) throw new Exception($"Dtsod[{key}] key not found");
}
}
@ -54,12 +45,12 @@ namespace DTLib.Dtsod
{
try
{
value=base[key];
value = base[key];
return true;
}
catch(KeyNotFoundException)
catch (KeyNotFoundException)
{
value=null;
value = null;
return false;
}
}
@ -67,10 +58,10 @@ namespace DTLib.Dtsod
{
try
{
base[key]=value;
base[key] = value;
return true;
}
catch(KeyNotFoundException)
catch (KeyNotFoundException)
{
return false;
}
@ -90,7 +81,7 @@ namespace DTLib.Dtsod
{
Dictionary<string, dynamic> parsed = new();
int i = 0;
for(; i<text.Length; i++)
for (; i < text.Length; i++)
ReadName();
DebugNoTime("g", $"Parse returns {parsed.Keys.Count} keys\n");
return parsed;
@ -109,9 +100,9 @@ namespace DTLib.Dtsod
StringBuilder defaultNameBuilder = new();
DebugNoTime("m", "ReadName\n");
for(; i<text.Length; i++)
for (; i < text.Length; i++)
{
switch(text[i])
switch (text[i])
{
case ' ':
case '\t':
@ -121,11 +112,11 @@ namespace DTLib.Dtsod
case ':':
i++;
string name = defaultNameBuilder.ToString();
value=ReadValue();
value = ReadValue();
DebugNoTime("c", $"parsed.Add({name}, {value} { value.GetType() })\n");
if(isListElem)
if (isListElem)
{
if(!parsed.ContainsKey(name))
if (!parsed.ContainsKey(name))
parsed.Add(name, new List<dynamic>());
parsed[name].Add(value);
}
@ -137,16 +128,16 @@ namespace DTLib.Dtsod
//ReadCommentLine();
break;
case '}':
throw new Exception("Parse.ReadName() error: unexpected '}' at "+i+" char");
throw new Exception("Parse.ReadName() error: unexpected '}' at " + i + " char");
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
case '$':
DebugNoTime("w", text[i].ToString());
if(defaultNameBuilder.ToString().Length!=0)
throw new Exception("Parse.ReadName() error: unexpected '$' at "+i+" char");
isListElem=true;
if (defaultNameBuilder.ToString().Length != 0)
throw new Exception("Parse.ReadName() error: unexpected '$' at " + i + " char");
isListElem = true;
break;
case ';':
throw new Exception("Parse.ReadName() error: unexpected ';' at "+i+" char");
throw new Exception("Parse.ReadName() error: unexpected ';' at " + i + " char");
default:
DebugNoTime("w", text[i].ToString());
defaultNameBuilder.Append(text[i]);
@ -165,14 +156,14 @@ namespace DTLib.Dtsod
i++;
StringBuilder valueBuilder = new();
valueBuilder.Append('"');
for(; text[i]!='"'||text[i-1]=='\\'; i++)
for (; text[i] != '"' || text[i - 1] == '\\'; i++)
{
DebugNoTime("gray", text[i].ToString());
valueBuilder.Append(text[i]);
}
valueBuilder.Append('"');
DebugNoTime("gray", text[i].ToString());
type=ValueType.String;
type = ValueType.String;
return valueBuilder.ToString();
}
@ -181,10 +172,10 @@ namespace DTLib.Dtsod
i++;
List<dynamic> output = new();
StringBuilder valueBuilder = new();
for(; text[i]!=']'; i++)
for (; text[i] != ']'; i++)
{
DebugNoTime("c", text[i].ToString());
switch(text[i])
switch (text[i])
{
case ' ':
case '\t':
@ -201,13 +192,13 @@ namespace DTLib.Dtsod
break;
}
}
if(valueBuilder.Length>0)
if (valueBuilder.Length > 0)
{
ParseValueToRightType(valueBuilder.ToString());
output.Add(value);
}
DebugNoTime("c", text[i].ToString());
type=ValueType.List;
type = ValueType.List;
return output;
}
@ -216,10 +207,10 @@ namespace DTLib.Dtsod
StringBuilder valueBuilder = new();
int balance = 1;
i++;
for(; balance!=0; i++)
for (; balance != 0; i++)
{
DebugNoTime("y", text[i].ToString());
switch(text[i])
switch (text[i])
{
case '"':
valueBuilder.Append(ReadString());
@ -227,7 +218,7 @@ namespace DTLib.Dtsod
case '}':
balance--;
DebugNoTime("b", $"\nbalance -- = {balance}\n");
if(balance!=0)
if (balance != 0)
valueBuilder.Append(text[i]);
break;
case '{':
@ -241,7 +232,7 @@ namespace DTLib.Dtsod
}
}
i--; // i++ в for выполняется даже когда balance == 0, то есть text[i] получается == ;, что ломает всё
type=ValueType.Complex;
type = ValueType.Complex;
return Parse(valueBuilder.ToString());
}
@ -249,54 +240,54 @@ namespace DTLib.Dtsod
{
DebugNoTime("b", $"\nParseValueToRightType({stringValue})\n");
switch(stringValue)
switch (stringValue)
{
// bool
case "true":
case "false":
value=stringValue.ToBool();
value = stringValue.ToBool();
break;
// null
case "null":
value=null;
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')
else if (stringValue.Length > 2 && stringValue[stringValue.Length - 2] == 'u')
{
switch(stringValue[stringValue.Length-1])
switch (stringValue[stringValue.Length - 1])
{
case 's':
value=stringValue.Remove(stringValue.Length-2).ToUShort();
value = stringValue.Remove(stringValue.Length - 2).ToUShort();
break;
case 'i':
value=stringValue.Remove(stringValue.Length-2).ToUInt();
value = stringValue.Remove(stringValue.Length - 2).ToUInt();
break;
case 'l':
value=stringValue.Remove(stringValue.Length-2).ToULong();
value = stringValue.Remove(stringValue.Length - 2).ToULong();
break;
default:
throw new Exception($"Dtsod.Parse.ReadValue() error: value= wrong type <u{stringValue[stringValue.Length-1]}>");
throw new Exception($"Dtsod.Parse.ReadValue() error: value= wrong type <u{stringValue[stringValue.Length - 1]}>");
};
}
// short; long; int
else
switch(stringValue[stringValue.Length-1])
switch (stringValue[stringValue.Length - 1])
{
case 's':
value=stringValue.Remove(stringValue.Length-1).ToShort();
value = stringValue.Remove(stringValue.Length - 1).ToShort();
break;
case 'l':
value=stringValue.Remove(stringValue.Length-1).ToLong();
value = stringValue.Remove(stringValue.Length - 1).ToLong();
break;
default:
value=stringValue.ToShort();
value = stringValue.ToShort();
break;
}
break;
@ -305,10 +296,10 @@ namespace DTLib.Dtsod
StringBuilder defaultValueBuilder = new();
DebugNoTime("m", "\nReadValue\n");
for(; i<text.Length; i++)
for (; i < text.Length; i++)
{
DebugNoTime("b", text[i].ToString());
switch(text[i])
switch (text[i])
{
case ' ':
case '\t':
@ -316,10 +307,10 @@ namespace DTLib.Dtsod
case '\n':
break;
case '"':
value=ReadString();
value = ReadString();
break;
case ';':
switch(type)
switch (type)
{
case ValueType.String:
ParseValueToRightType(value);
@ -330,10 +321,10 @@ namespace DTLib.Dtsod
};
return value;
case '[':
value=ReadList();
value = ReadList();
break;
case '{':
value=ReadComplex();
value = ReadComplex();
break;
// строка, начинающаяся с # будет считаться комментом
case '#':
@ -350,12 +341,12 @@ namespace DTLib.Dtsod
void Debug(params string[] msg)
{
if(debug)
if (debug)
Log(msg);
}
void DebugNoTime(params string[] msg)
{
if(debug)
if (debug)
LogNoTime(msg);
}
}

View File

@ -31,15 +31,15 @@ namespace DTLib.Dtsod
public bool IsList;
public ValueStruct(ValueTypes type, dynamic value, bool isList)
{
Value=value;
Type=type;
IsList=isList;
Value = value;
Type = type;
IsList = isList;
}
public ValueStruct(ValueTypes type, dynamic value)
{
Value=value;
Type=type;
IsList=false;
Value = value;
Type = type;
IsList = false;
}
}
@ -64,32 +64,23 @@ namespace DTLib.Dtsod
public DtsodV22(string text)
{
foreach(KeyValuePair<string, ValueStruct> pair in Parse(text))
foreach (KeyValuePair<string, ValueStruct> pair in Parse(text))
Add(pair.Key, pair.Value);
}
public DtsodV22(Dictionary<string, DtsodV22.ValueStruct> dict)
{
foreach(KeyValuePair<string, ValueStruct> pair in dict)
foreach (KeyValuePair<string, ValueStruct> pair in dict)
Add(pair.Key, pair.Value);
}
// выдаёт Exception
public new dynamic this[string key]
{
get
{
if(TryGetValue(key, out dynamic value))
return value;
else
throw new Exception($"Dtsod[{key}] key not found");
}
get => TryGetValue(key, out dynamic value) ? value : 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)) throw new Exception($"Dtsod[{key}] key not found");
}
}
@ -98,12 +89,12 @@ namespace DTLib.Dtsod
{
try
{
value=base[key].Value;
value = base[key].Value;
return true;
}
catch(KeyNotFoundException)
catch (KeyNotFoundException)
{
value=null;
value = null;
return false;
}
}
@ -111,25 +102,19 @@ namespace DTLib.Dtsod
{
try
{
bool isList;
if(value is IList)
isList=true;
else
isList=false;
base[key]=new(base[key].Type, value, isList);
bool isList = value is IList;
base[key] = new(base[key].Type, value, isList);
return true;
}
catch(KeyNotFoundException)
{
return false;
}
catch (KeyNotFoundException)
{ return false; }
}
DtsodV22 Parse(string text)
{
Dictionary<string, ValueStruct> parsed = new();
int i = 0;
for(; i<text.Length; i++)
for (; i < text.Length; i++)
ReadName();
DebugNoTime("g", $"Parse returns {parsed.Keys.Count} keys\n");
return new DtsodV22(parsed);
@ -148,9 +133,9 @@ namespace DTLib.Dtsod
StringBuilder defaultNameBuilder = new();
DebugNoTime("m", "ReadName\n");
for(; i<text.Length; i++)
for (; i < text.Length; i++)
{
switch(text[i])
switch (text[i])
{
case ' ':
case '\t':
@ -160,11 +145,11 @@ namespace DTLib.Dtsod
case ':':
i++;
string name = defaultNameBuilder.ToString();
value=ReadValue(out ValueTypes type, out bool isList);
value = ReadValue(out ValueTypes type, out bool isList);
DebugNoTime("c", $"parsed.Add({name},{type} {value} )\n");
if(isListElem)
if (isListElem)
{
if(!parsed.ContainsKey(name))
if (!parsed.ContainsKey(name))
parsed.Add(name, new(type, new List<dynamic>(), isList));
parsed[name].Value.Add(value);
}
@ -176,16 +161,16 @@ namespace DTLib.Dtsod
//ReadCommentLine();
break;
case '}':
throw new Exception("Parse.ReadName() error: unexpected '}' at "+i+" char");
throw new Exception("Parse.ReadName() error: unexpected '}' at " + i + " char");
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
case '$':
DebugNoTime("w", text[i].ToString());
if(defaultNameBuilder.ToString().Length!=0)
throw new Exception("Parse.ReadName() error: unexpected '$' at "+i+" char");
isListElem=true;
if (defaultNameBuilder.ToString().Length != 0)
throw new Exception("Parse.ReadName() error: unexpected '$' at " + i + " char");
isListElem = true;
break;
case ';':
throw new Exception("Parse.ReadName() error: unexpected ';' at "+i+" char");
throw new Exception("Parse.ReadName() error: unexpected ';' at " + i + " char");
default:
DebugNoTime("w", text[i].ToString());
defaultNameBuilder.Append(text[i]);
@ -197,7 +182,7 @@ namespace DTLib.Dtsod
dynamic ReadValue(out ValueTypes outType, out bool isList)
{
ValueTypes type = ValueTypes.Unknown;
isList=false;
isList = false;
dynamic value = null;
string ReadString()
@ -205,14 +190,14 @@ namespace DTLib.Dtsod
i++;
StringBuilder valueBuilder = new();
valueBuilder.Append('"');
for(; text[i]!='"'||text[i-1]=='\\'; i++)
for (; text[i] != '"' || text[i - 1] == '\\'; i++)
{
DebugNoTime("gray", text[i].ToString());
valueBuilder.Append(text[i]);
}
valueBuilder.Append('"');
DebugNoTime("gray", text[i].ToString());
type=ValueTypes.String;
type = ValueTypes.String;
return valueBuilder.ToString();
}
@ -221,10 +206,10 @@ namespace DTLib.Dtsod
i++;
List<dynamic> output = new();
StringBuilder valueBuilder = new();
for(; text[i]!=']'; i++)
for (; text[i] != ']'; i++)
{
DebugNoTime("c", text[i].ToString());
switch(text[i])
switch (text[i])
{
case ' ':
case '\t':
@ -241,13 +226,13 @@ namespace DTLib.Dtsod
break;
}
}
if(valueBuilder.Length>0)
if (valueBuilder.Length > 0)
{
ParseValueToRightType(valueBuilder.ToString());
output.Add(value);
}
DebugNoTime("c", text[i].ToString());
type=ValueTypes.List;
type = ValueTypes.List;
return output;
}
@ -256,10 +241,10 @@ namespace DTLib.Dtsod
StringBuilder valueBuilder = new();
int balance = 1;
i++;
for(; balance!=0; i++)
for (; balance != 0; i++)
{
DebugNoTime("y", text[i].ToString());
switch(text[i])
switch (text[i])
{
case '"':
valueBuilder.Append(ReadString());
@ -267,7 +252,7 @@ namespace DTLib.Dtsod
case '}':
balance--;
DebugNoTime("b", $"\nbalance -- = {balance}\n");
if(balance!=0)
if (balance != 0)
valueBuilder.Append(text[i]);
break;
case '{':
@ -281,55 +266,55 @@ namespace DTLib.Dtsod
}
}
i--; // i++ в for выполняется даже когда balance == 0, то есть text[i] получается == ;, что ломает всё
type=ValueTypes.Complex;
type = ValueTypes.Complex;
return Parse(valueBuilder.ToString());
}
void ParseValueToRightType(string stringValue)
{
DebugNoTime("b", $"\nParseValueToRightType({stringValue})\n");
switch(stringValue)
switch (stringValue)
{
// bool
case "true":
case "false":
type=ValueTypes.Bool;
value=stringValue.ToBool();
type = ValueTypes.Bool;
value = stringValue.ToBool();
break;
// null
case "null":
type=ValueTypes.Null;
value=null;
type = ValueTypes.Null;
value = null;
break;
default:
if(stringValue.Contains('"'))
if (stringValue.Contains('"'))
{
type=ValueTypes.String;
value=stringValue.Remove(stringValue.Length-1).Remove(0, 1);
type = ValueTypes.String;
value = stringValue.Remove(stringValue.Length - 1).Remove(0, 1);
}
// double
else if(stringValue.Contains('.'))
else if (stringValue.Contains('.'))
{
type=ValueTypes.Double;
value=stringValue.ToDouble();
type = ValueTypes.Double;
value = stringValue.ToDouble();
}
// ushort; ulong; uint
else if(stringValue.Length>2&&stringValue[stringValue.Length-2]=='u')
else if (stringValue.Length > 2 && stringValue[stringValue.Length - 2] == 'u')
{
switch(stringValue[stringValue.Length-1])
switch (stringValue[stringValue.Length - 1])
{
case 's':
type=ValueTypes.UShort;
value=stringValue.Remove(stringValue.Length-2).ToUShort();
type = ValueTypes.UShort;
value = stringValue.Remove(stringValue.Length - 2).ToUShort();
break;
case 'i':
type=ValueTypes.UInt;
value=stringValue.Remove(stringValue.Length-2).ToUInt();
type = ValueTypes.UInt;
value = stringValue.Remove(stringValue.Length - 2).ToUInt();
break;
case 'l':
type=ValueTypes.ULong;
value=stringValue.Remove(stringValue.Length-2).ToULong();
type = ValueTypes.ULong;
value = stringValue.Remove(stringValue.Length - 2).ToULong();
break;
default:
throw new Exception($"Dtsod.Parse.ReadValue() error: value <{stringValue}> has wrong type");
@ -337,19 +322,19 @@ namespace DTLib.Dtsod
}
// short; long; int
else
switch(stringValue[stringValue.Length-1])
switch (stringValue[stringValue.Length - 1])
{
case 's':
type=ValueTypes.Short;
value=stringValue.Remove(stringValue.Length-1).ToShort();
type = ValueTypes.Short;
value = stringValue.Remove(stringValue.Length - 1).ToShort();
break;
case 'l':
type=ValueTypes.Long;
value=stringValue.Remove(stringValue.Length-1).ToLong();
type = ValueTypes.Long;
value = stringValue.Remove(stringValue.Length - 1).ToLong();
break;
default:
type=ValueTypes.Int;
value=stringValue.ToShort();
type = ValueTypes.Int;
value = stringValue.ToShort();
break;
}
break;
@ -358,10 +343,10 @@ namespace DTLib.Dtsod
StringBuilder defaultValueBuilder = new();
DebugNoTime("m", "\nReadValue\n");
for(; i<text.Length; i++)
for (; i < text.Length; i++)
{
DebugNoTime("b", text[i].ToString());
switch(text[i])
switch (text[i])
{
case ' ':
case '\t':
@ -369,16 +354,16 @@ namespace DTLib.Dtsod
case '\n':
break;
case '"':
value=ReadString();
value = ReadString();
break;
case '[':
value=ReadList();
value = ReadList();
break;
case '{':
value=ReadComplex();
value = ReadComplex();
break;
case ';':
switch(type)
switch (type)
{
case ValueTypes.String:
ParseValueToRightType(value);
@ -387,10 +372,10 @@ namespace DTLib.Dtsod
ParseValueToRightType(defaultValueBuilder.ToString());
break;
case ValueTypes.List:
isList=true;
isList = true;
break;
};
outType=type;
outType = type;
return value;
// строка, начинающаяся с # будет считаться комментом
case '#':
@ -411,13 +396,13 @@ namespace DTLib.Dtsod
string Deconstruct(DtsodV22 dtsod)
{
StringBuilder outBuilder = new();
foreach(string key in dtsod.Keys)
foreach (string key in dtsod.Keys)
{
outBuilder.Append('\t', tabCount);
outBuilder.Append(key);
outBuilder.Append(": ");
dtsod.TryGetValue(key, out ValueStruct value);
switch(value.Type)
switch (value.Type)
{
case ValueTypes.List:
outBuilder.Append("\"list deconstruction is'nt implemented yet\"");
@ -480,13 +465,13 @@ namespace DTLib.Dtsod
void DebugNoTime(params string[] msg)
{
if(debug)
if (debug)
PublicLog.LogNoTime(msg);
}
public DtsodV22 Extend(DtsodV22 newPart)
{
foreach(KeyValuePair<string, ValueStruct> pair in newPart)
foreach (KeyValuePair<string, ValueStruct> pair in newPart)
Add(pair.Key, pair.Value);
return this;
}

View File

@ -1,14 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTLib.Dtsod
{
public class DtsodSerializableAttribute : Attribute
{
public DtsodVersion Version;
public DtsodSerializableAttribute(DtsodVersion ver) => Version=ver;
public DtsodSerializableAttribute(DtsodVersion ver) => Version = ver;
}
}

View File

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

View File

@ -10,10 +10,10 @@ namespace DTLib.Filesystem
// создает папку, если её не существует
public static void Create(string dir)
{
if(!Directory.Exists(dir))
if (!Directory.Exists(dir))
{
// проверяет существование папки, в которой нужно создать dir
if(dir.Contains("\\")&&!Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
if (dir.Contains("\\") && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
Create(dir.Remove(dir.LastIndexOf('\\')));
System.IO.Directory.CreateDirectory(dir);
}
@ -22,13 +22,13 @@ namespace DTLib.Filesystem
public static void Copy(string source_dir, string new_dir, bool owerwrite = false)
{
Create(new_dir);
var subdirs = new List<string>();
List<string> subdirs = new List<string>();
List<string> files = GetAllFiles(source_dir, ref subdirs);
for(int i = 0; i<subdirs.Count; i++)
for (int i = 0; i < subdirs.Count; i++)
{
Create(subdirs[i].Replace(source_dir, new_dir));
}
for(int i = 0; i<files.Count; i++)
for (int i = 0; i < files.Count; i++)
{
string f = files[i].Replace(source_dir, new_dir);
File.Copy(files[i], f, owerwrite);
@ -39,18 +39,18 @@ namespace DTLib.Filesystem
// копирует все файлы и папки и выдаёт список конфликтующих файлов
public static void Copy(string source_dir, string new_dir, out List<string> conflicts, bool owerwrite = false)
{
conflicts=new List<string>();
var subdirs = new List<string>();
conflicts = new List<string>();
List<string> subdirs = new List<string>();
List<string> files = GetAllFiles(source_dir, ref subdirs);
Create(new_dir);
for(int i = 0; i<subdirs.Count; i++)
for (int i = 0; i < subdirs.Count; i++)
{
Create(subdirs[i].Replace(source_dir, new_dir));
}
for(int i = 0; i<files.Count; i++)
for (int i = 0; i < files.Count; i++)
{
string newfile = files[i].Replace(source_dir, new_dir);
if(File.Exists(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,18 +60,18 @@ namespace DTLib.Filesystem
// удаляет папку со всеми подпапками и файлами
public static void Delete(string dir)
{
var subdirs = new List<string>();
List<string> subdirs = new List<string>();
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]);
for(int i = subdirs.Count-1; i>=0; i--)
for (int i = subdirs.Count - 1; i >= 0; i--)
{
PublicLog.Log($"deleting {subdirs[i]}\n");
if(Directory.Exists(subdirs[i]))
if (Directory.Exists(subdirs[i]))
System.IO.Directory.Delete(subdirs[i], true);
}
PublicLog.Log($"deleting {dir}\n");
if(Directory.Exists(dir))
if (Directory.Exists(dir))
System.IO.Directory.Delete(dir, true);
}
@ -82,15 +82,15 @@ namespace DTLib.Filesystem
// выдает список всех файлов
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);
for(int i = 0; i<cur_files.Length; i++)
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++)
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]));
@ -101,15 +101,15 @@ namespace DTLib.Filesystem
// выдает список всех файлов и подпапок в папке
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);
for(int i = 0; i<cur_files.Length; i++)
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++)
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" });
@ -122,13 +122,13 @@ namespace DTLib.Filesystem
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();
dirSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
new System.Security.Principal.SecurityIdentifier(
System.Security.Principal.WellKnownSidType.WorldSid, null),
System.Security.AccessControl.FileSystemRights.FullControl,
System.Security.AccessControl.InheritanceFlags.ObjectInherit|
System.Security.AccessControl.InheritanceFlags.ObjectInherit |
System.Security.AccessControl.InheritanceFlags.ContainerInherit,
System.Security.AccessControl.PropagationFlags.NoPropagateInherit,
System.Security.AccessControl.AccessControlType.Allow));

View File

@ -11,11 +11,11 @@ namespace DTLib.Filesystem
// если файл не существует, создаёт файл, создаёт папки из его пути
public static void Create(string file, bool delete_old = false)
{
if(delete_old&&File.Exists(file))
if (delete_old && File.Exists(file))
File.Delete(file);
if(!File.Exists(file))
if (!File.Exists(file))
{
if(file.Contains("\\"))
if (file.Contains("\\"))
Directory.Create(file.Remove(file.LastIndexOf('\\')));
using System.IO.FileStream stream = System.IO.File.Create(file);
stream.Close();
@ -24,7 +24,7 @@ namespace DTLib.Filesystem
public static void Copy(string srcPath, string newPath, bool replace = false)
{
if(!replace&&Exists(newPath))
if (!replace && Exists(newPath))
throw new Exception($"file <{newPath}> alredy exists");
Create(newPath);
WriteAllBytes(newPath, ReadAllBytes(srcPath));
@ -62,12 +62,8 @@ namespace DTLib.Filesystem
public static void AppendAllText(string file, string content) => AppendAllBytes(file, content.ToBytes());
public static System.IO.FileStream OpenRead(string file)
{
if(!Exists(file))
throw new Exception($"file not found: <{file}>");
return System.IO.File.OpenRead(file);
}
public static System.IO.FileStream OpenRead(string file) =>
Exists(file) ? System.IO.File.OpenRead(file) : throw new Exception($"file not found: <{file}>");
public static System.IO.FileStream OpenWrite(string file)
{
File.Create(file, true);

View File

@ -10,7 +10,7 @@ namespace DTLib.Filesystem
// записывает текст в файл и закрывает файл
public static void LogToFile(string logfile, string msg)
{
lock(new object())
lock (new object())
{
File.AppendAllText(logfile, msg);
}
@ -19,41 +19,41 @@ namespace DTLib.Filesystem
// чтение параметров из конфига
public static string ReadFromConfig(string configfile, string key)
{
lock(new object())
lock (new object())
{
key+=": ";
using var reader = new System.IO.StreamReader(configfile);
while(!reader.EndOfStream)
key += ": ";
using System.IO.StreamReader reader = new System.IO.StreamReader(configfile);
while (!reader.EndOfStream)
{
string st = reader.ReadLine();
if(st.StartsWith(key))
if (st.StartsWith(key))
{
string value = "";
for(int i = key.Length; i<st.Length; i++)
for (int i = key.Length; i < st.Length; i++)
{
if(st[i]=='#')
if (st[i] == '#')
return value;
if(st[i]=='%')
if (st[i] == '%')
{
bool stop = false;
string placeholder = "";
i++;
while(!stop)
while (!stop)
{
if(st[i]=='%')
if (st[i] == '%')
{
stop=true;
value+=ReadFromConfig(configfile, placeholder);
stop = true;
value += ReadFromConfig(configfile, placeholder);
}
else
{
placeholder+=st[i];
placeholder += st[i];
i++;
}
}
}
else
value+=st[i];
value += st[i];
}
reader.Close();
//if (value == "") throw new System.Exception($"ReadFromConfig({configfile}, {key}) error: key not found");

View File

@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
// включает init и record из c# 9.0
@ -22,9 +21,9 @@ namespace DTLib
// эти методы работают как надо, в отличии от стандартных, которые иногда дуркуют
public static bool StartsWith(this byte[] source, byte[] startsWith)
{
for(int i = 0; i<startsWith.Length; i++)
for (int i = 0; i < startsWith.Length; i++)
{
if(source[i]!=startsWith[i])
if (source[i] != startsWith[i])
return false;
}
return true;
@ -32,9 +31,9 @@ namespace DTLib
public static bool EndsWith(this byte[] source, byte[] endsWith)
{
for(int i = 0; i<endsWith.Length; i++)
for (int i = 0; i < endsWith.Length; i++)
{
if(source[source.Length-endsWith.Length+i]!=endsWith[i])
if (source[source.Length - endsWith.Length + i] != endsWith[i])
return false;
}
return true;
@ -47,7 +46,7 @@ namespace DTLib
// массив в лист
public static List<T> ToList<T>(this T[] input)
{
var list = new List<T>();
List<T> list = new List<T>();
list.AddRange(input);
return list;
}
@ -55,17 +54,17 @@ namespace DTLib
// удаление нескольких элементов массива
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);
return list.ToArray();
}
public static T[] RemoveRange<T>(this T[] input, int startIndex) => input.RemoveRange(startIndex, input.Length-startIndex);
public static T[] RemoveRange<T>(this T[] input, int startIndex) => input.RemoveRange(startIndex, input.Length - startIndex);
// метод как у листов
public static bool Contains<T>(this T[] array, T value)
{
for(int i = 0; i<array.Length; i++)
if(array[i].Equals(value))
for (int i = 0; i < array.Length; i++)
if (array[i].Equals(value))
return true;
return false;
}
@ -85,18 +84,18 @@ 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;
}
public static byte[] ToBytes(this int num)
{
List<byte> output = new();
while(num!=0)
while (num != 0)
{
output.Add(ToByte(num%256));
num=Truncate(num/256);
output.Add(ToByte(num % 256));
num = Truncate(num / 256);
}
output.Reverse();
return output.ToArray();
@ -110,8 +109,8 @@ namespace DTLib
// хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
public static string HashToString(this byte[] hash)
{
var builder = new StringBuilder();
for(int i = 0; i<hash.Length; i++)
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
builder.Append(hash[i].ToString("x2"));
}
@ -121,27 +120,27 @@ namespace DTLib
public static string MergeToString(params object[] parts)
{
StringBuilder builder = new();
for(int i = 0; i<parts.Length; i++)
for (int i = 0; i < parts.Length; i++)
builder.Append(parts[i].ToString());
return builder.ToString();
}
public static string MergeToString<T>(this IEnumerable<T> collection, string separator)
{
StringBuilder builder = new();
foreach(T elem in collection)
foreach (T elem in collection)
{
builder.Append(elem.ToString());
builder.Append(separator);
}
if(builder.Length==0)
if (builder.Length == 0)
return "";
builder.Remove(builder.Length-separator.Length, separator.Length);
builder.Remove(builder.Length - separator.Length, separator.Length);
return builder.ToString();
}
public static string MergeToString<T>(this IEnumerable<T> collection)
{
StringBuilder builder = new();
foreach(T elem in collection)
foreach (T elem in collection)
builder.Append(elem.ToString());
return builder.ToString();
}
@ -149,7 +148,7 @@ namespace DTLib
public static string Multiply(this string input, int howMany)
{
StringBuilder b = new();
for(int i = 0; i<howMany; i++)
for (int i = 0; i < howMany; i++)
b.Append(input);
return b.ToString();
}
@ -158,28 +157,28 @@ namespace DTLib
public static void ForEach<T>(this IEnumerable<T> en, Action<T> act)
{
foreach(T elem in en)
foreach (T elem in en)
act(elem);
}
// делает что надо в отличии от String.Split(), который не убирает char c из начала
public static List<string> SplitToList(this string s, char c)
{
var ar = s.ToCharArray();
char[] ar = s.ToCharArray();
StringBuilder b = new();
List<string> o = new();
if(ar[0]!=c)
if (ar[0] != c)
b.Append(ar[0]);
for(int i = 1; i<ar.Length; i++)
if(ar[i]==c)
for (int i = 1; i < ar.Length; i++)
if (ar[i] == c)
{
if(b.Length>0)
if (b.Length > 0)
o.Add(b.ToString());
b.Clear();
}
else
b.Append(ar[i]);
if(b.Length>0)
if (b.Length > 0)
o.Add(b.ToString());
return o;
}
@ -188,19 +187,14 @@ namespace DTLib
public static List<string> Split(this string s, int length)
{
List<string> parts = new();
int max = (s.Length/length).Truncate();
for(int i = 0; i<max; i++)
parts.Add(s.Substring(i*length, length));
if(max*length!=s.Length) parts.Add(s.Substring(max*length, s.Length-max*length));
int max = (s.Length / length).Truncate();
for (int i = 0; i < max; i++)
parts.Add(s.Substring(i * length, length));
if (max * length != s.Length) parts.Add(s.Substring(max * length, s.Length - max * length));
return parts;
}
public static T If<T>(this T input, bool condition, Func<T,T> if_true, Func<T,T> if_false)
{
if(condition)
return if_true(input);
else
return if_false(input);
}
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);
}
}

View File

@ -1,6 +1,6 @@
using DTLib.Filesystem;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Security.Cryptography;
using DTLib.Filesystem;
namespace DTLib
{
@ -20,7 +20,7 @@ namespace DTLib
// хеш из двух массивов
public byte[] Hash(byte[] input, byte[] salt)
{
var rez = new List<byte>();
List<byte> rez = new List<byte>();
rez.AddRange(input);
rez.AddRange(salt);
return sha256.ComputeHash(rez.ToArray());
@ -29,18 +29,18 @@ namespace DTLib
// хеш двух массивов зацикленный
public byte[] HashCycled(byte[] input, byte[] salt, ushort cycles)
{
for(uint i = 0; i<cycles; i++)
for (uint i = 0; i < cycles; i++)
{
input=Hash(input, salt);
input = Hash(input, salt);
}
return input;
}
// хеш зацикленный
public byte[] HashCycled(byte[] input, ushort cycles)
{
for(uint i = 0; i<cycles; i++)
for (uint i = 0; i < cycles; i++)
{
input=Hash(input);
input = Hash(input);
}
return input;
}

View File

@ -1,7 +1,7 @@
using DTLib.Dtsod;
using DTLib.Filesystem;
using System.Net.Sockets;
using System.Net.Sockets;
using System.Text;
using DTLib.Dtsod;
using DTLib.Filesystem;
using static DTLib.PublicLog;
namespace DTLib.Network
@ -13,7 +13,7 @@ namespace DTLib.Network
{
Socket MainSocket { get; init; }
public static bool debug = false;
public FSP(Socket _mainSocket) => MainSocket=_mainSocket;
public FSP(Socket _mainSocket) => MainSocket = _mainSocket;
public uint BytesDownloaded = 0;
public uint BytesUploaded = 0;
@ -54,7 +54,7 @@ namespace DTLib.Network
public byte[] DownloadFileToMemory()
{
using var fileStream = new System.IO.MemoryStream();
using System.IO.MemoryStream fileStream = new System.IO.MemoryStream();
Download_SharedCode(fileStream, false);
byte[] output = fileStream.GetBuffer();
fileStream.Close();
@ -66,71 +66,71 @@ namespace DTLib.Network
{
Mutex.Execute(() =>
{
BytesDownloaded=0;
Filesize=MainSocket.GetPackage().BytesToString().ToUInt();
BytesDownloaded = 0;
Filesize = MainSocket.GetPackage().BytesToString().ToUInt();
MainSocket.SendPackage("ready".ToBytes());
int packagesCount = 0;
byte[] buffer = new byte[5120];
int fullPackagesCount = FrameworkFix.Truncate(Filesize/buffer.Length);
int fullPackagesCount = FrameworkFix.Truncate(Filesize / buffer.Length);
// получение полных пакетов файла
for(byte n = 0; packagesCount<fullPackagesCount; packagesCount++)
for (byte n = 0; packagesCount < fullPackagesCount; packagesCount++)
{
buffer=MainSocket.GetPackage();
BytesDownloaded+=(uint)buffer.Length;
buffer = MainSocket.GetPackage();
BytesDownloaded += (uint)buffer.Length;
fileStream.Write(buffer, 0, buffer.Length);
if(requiresFlushing)
if (requiresFlushing)
{
if(n==100)
if (n == 100)
{
fileStream.Flush();
n=0;
n = 0;
}
else
n++;
}
}
// получение остатка
if((Filesize-fileStream.Position)>0)
if ((Filesize - fileStream.Position) > 0)
{
MainSocket.SendPackage("remain request".ToBytes());
buffer=MainSocket.GetPackage();
BytesDownloaded+=(uint)buffer.Length;
buffer = MainSocket.GetPackage();
BytesDownloaded += (uint)buffer.Length;
fileStream.Write(buffer, 0, buffer.Length);
}
});
if(requiresFlushing)
if (requiresFlushing)
fileStream.Flush();
}
// отдаёт файл с помощью FSP протокола
public void UploadFile(string filePath)
{
BytesUploaded=0;
BytesUploaded = 0;
Debug("b", $"uploading file {filePath}\n");
using System.IO.FileStream fileStream = File.OpenRead(filePath);
Filesize=File.GetSize(filePath).ToUInt();
Filesize = File.GetSize(filePath).ToUInt();
Mutex.Execute(() =>
{
MainSocket.SendPackage(Filesize.ToString().ToBytes());
MainSocket.GetAnswer("ready");
byte[] buffer = new byte[5120];
int packagesCount = 0;
int fullPackagesCount = FrameworkFix.Truncate(Filesize/buffer.Length);
int fullPackagesCount = FrameworkFix.Truncate(Filesize / buffer.Length);
// отправка полных пакетов файла
for(; packagesCount<fullPackagesCount; packagesCount++)
for (; packagesCount < fullPackagesCount; packagesCount++)
{
fileStream.Read(buffer, 0, buffer.Length);
MainSocket.SendPackage(buffer);
BytesUploaded+=(uint)buffer.Length;
BytesUploaded += (uint)buffer.Length;
}
// отправка остатка
if((Filesize-fileStream.Position)>0)
if ((Filesize - fileStream.Position) > 0)
{
MainSocket.GetAnswer("remain request");
buffer=new byte[(Filesize-fileStream.Position).ToInt()];
buffer = new byte[(Filesize - fileStream.Position).ToInt()];
fileStream.Read(buffer, 0, buffer.Length);
MainSocket.SendPackage(buffer);
BytesUploaded+=(uint)buffer.Length;
BytesUploaded += (uint)buffer.Length;
}
});
fileStream.Close();
@ -139,37 +139,37 @@ 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+="\\";
Debug("b", "downloading manifest <", "c", dirOnServer+"manifest.dtsod", "b", ">\n");
var manifest = new Dtsod.DtsodV22(DownloadFileToMemory(dirOnServer+"manifest.dtsod").BytesToString());
if (!dirOnClient.EndsWith("\\"))
dirOnClient += "\\";
if (!dirOnServer.EndsWith("\\"))
dirOnServer += "\\";
Debug("b", "downloading manifest <", "c", dirOnServer + "manifest.dtsod", "b", ">\n");
DtsodV22 manifest = new Dtsod.DtsodV22(DownloadFileToMemory(dirOnServer + "manifest.dtsod").BytesToString());
Debug("g", $"found {manifest.Values.Count} files in manifest\n");
var hasher = new Hasher();
foreach(string fileOnServer in manifest.Keys)
Hasher hasher = new Hasher();
foreach (string fileOnServer in manifest.Keys)
{
string fileOnClient = dirOnClient+fileOnServer;
string fileOnClient = dirOnClient + fileOnServer;
Debug("b", "file <", "c", fileOnClient, "b", ">... ");
if(!File.Exists(fileOnClient))
if (!File.Exists(fileOnClient))
{
DebugNoTime("y", "doesn't exist\n");
DownloadFile(dirOnServer+fileOnServer, fileOnClient);
DownloadFile(dirOnServer + fileOnServer, fileOnClient);
}
else if(overwrite&&hasher.HashFile(fileOnClient).HashToString()!=manifest[fileOnServer])
else if (overwrite && hasher.HashFile(fileOnClient).HashToString() != manifest[fileOnServer])
{
DebugNoTime("y", "outdated\n");
DownloadFile(dirOnServer+fileOnServer, fileOnClient);
DownloadFile(dirOnServer + fileOnServer, fileOnClient);
}
else
DebugNoTime("g", "without changes\n");
}
// удаление лишних файлов
if(delete_excess)
if (delete_excess)
{
foreach(string file in Directory.GetAllFiles(dirOnClient))
foreach (string file in Directory.GetAllFiles(dirOnClient))
{
if(!manifest.ContainsKey(file.Remove(0, dirOnClient.Length)))
if (!manifest.ContainsKey(file.Remove(0, dirOnClient.Length)))
{
Debug("y", $"deleting excess file: {file}\n");
File.Delete(file);
@ -180,34 +180,34 @@ 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");
foreach(string _file in Directory.GetAllFiles(dir))
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);
manifestBuilder.Append(file);
manifestBuilder.Append(": \"");
byte[] hash = hasher.HashFile(dir+file);
byte[] hash = hasher.HashFile(dir + file);
manifestBuilder.Append(hash.HashToString());
manifestBuilder.Append("\";\n");
}
Debug($"g", $" manifest of {dir} created\n");
File.WriteAllText(dir+"manifest.dtsod", manifestBuilder.ToString());
File.WriteAllText(dir + "manifest.dtsod", manifestBuilder.ToString());
}
static void Debug(params string[] msg)
{
if(debug)
if (debug)
Log(msg);
}
static void DebugNoTime(params string[] msg)
{
if(debug)
if (debug)
LogNoTime(msg);
}
}

View File

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

View File

@ -16,16 +16,16 @@ namespace DTLib.Network
int packageSize = 0;
byte[] data = new byte[2];
// цикл выполняется пока не пройдёт 2000 мс
for(ushort s = 0; s<400; s+=1)
for (ushort s = 0; s < 400; s += 1)
{
if(packageSize==0&&socket.Available>=2)
if (packageSize == 0 && socket.Available >= 2)
{
socket.Receive(data, data.Length, 0);
packageSize=data.ToInt();
packageSize = data.ToInt();
}
if(packageSize!=0&&socket.Available>=packageSize)
if (packageSize != 0 && socket.Available >= packageSize)
{
data=new byte[packageSize];
data = new byte[packageSize];
socket.Receive(data, data.Length, 0);
return data;
}
@ -38,13 +38,13 @@ namespace DTLib.Network
// отправляет пакет
public static void SendPackage(this Socket socket, byte[] data)
{
if(data.Length>65536)
if (data.Length > 65536)
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");
var list = new List<byte>();
List<byte> list = new List<byte>();
byte[] packageSize = data.Length.ToBytes();
if(packageSize.Length==1)
if (packageSize.Length == 1)
list.Add(0);
list.AddRange(packageSize);
list.AddRange(data);
@ -56,7 +56,7 @@ namespace DTLib.Network
public static void GetAnswer(this Socket socket, string answer)
{
string rec = socket.GetPackage().BytesToString();
if(rec!=answer)
if (rec != answer)
throw new Exception($"GetAnswer() error: invalid answer: <{rec}>");
}

View File

@ -13,13 +13,13 @@ namespace DTLib
{
try
{
exception=null;
exception = null;
Execute(action);
}
catch(Exception ex)
catch (Exception ex)
{
exception=ex;
if(!isReleased)
exception = ex;
if (!isReleased)
Mutex.ReleaseMutex();
}
}
@ -29,14 +29,14 @@ namespace DTLib
Mutex.WaitOne();
action();
Mutex.ReleaseMutex();
isReleased=true;
isReleased = true;
}
public T Execute<T>(Func<T> action)
{
Mutex.WaitOne();
T rezult = action();
Mutex.ReleaseMutex();
isReleased=true;
isReleased = true;
return rezult;
}
}

View File

@ -16,16 +16,16 @@ namespace DTLib
// таймер сразу запускается
public Timer(bool repeat, int delay, Action method)
{
Repeat=repeat;
TimerTask=new Task(() =>
Repeat = repeat;
TimerTask = new Task(() =>
{
do
{
if(кансель.Token.IsCancellationRequested)
if (кансель.Token.IsCancellationRequested)
return;
Task.Delay(delay).Wait();
method();
} while(Repeat);
} while (Repeat);
});
}
@ -35,7 +35,7 @@ namespace DTLib
// завершение потока
public void Stop()
{
Repeat=false;
Repeat = false;
кансель.Cancel();
}
}

115
XXHash.cs
View File

@ -28,33 +28,33 @@ namespace DTLib
static XXHash32()
{
if(BitConverter.IsLittleEndian)
if (BitConverter.IsLittleEndian)
{
FuncGetLittleEndianUInt32=new Func<byte[], int, uint>((x, i) =>
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
{
unsafe
{
fixed(byte* array = x)
fixed (byte* array = x)
{
return *(uint*)(array+i);
return *(uint*)(array + i);
}
}
});
FuncGetFinalHashUInt32=new Func<uint, uint>(i => (i&0x000000FFU)<<24|(i&0x0000FF00U)<<8|(i&0x00FF0000U)>>8|(i&0xFF000000U)>>24);
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) =>
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
{
unsafe
{
fixed(byte* array = x)
fixed (byte* array = x)
{
return (uint)(array[i++]|(array[i++]<<8)|(array[i++]<<16)|(array[i]<<24));
return (uint)(array[i++] | (array[i++] << 8) | (array[i++] << 16) | (array[i] << 24));
}
}
});
FuncGetFinalHashUInt32=new Func<uint, uint>(i => i);
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => i);
}
}
@ -71,7 +71,7 @@ namespace DTLib
// 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.");
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>
@ -80,11 +80,11 @@ namespace DTLib
get => _Seed32;
set
{
if(value!=_Seed32)
if (value != _Seed32)
{
if(State!=0)
if (State != 0)
throw new InvalidOperationException("Hash computation has not yet completed.");
_Seed32=value;
_Seed32 = value;
Initialize();
}
}
@ -93,10 +93,10 @@ namespace DTLib
// 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;
_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.
@ -105,30 +105,30 @@ 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;
int size = cbSize-ibStart;
_RemainingLength=size&15;
if(cbSize>=16)
if (State != 1)
State = 1;
int size = cbSize - ibStart;
_RemainingLength = size & 15;
if (cbSize >= 16)
{
int limit = size-_RemainingLength;
int 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);
_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)
_TotalLength += cbSize;
if (_RemainingLength != 0)
{
_CurrentArray=array;
_CurrentIndex=ibStart;
_CurrentArray = array;
_CurrentIndex = ibStart;
}
}
@ -136,46 +136,41 @@ namespace DTLib
// <returns>The computed hash code.</returns>
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)
: _Seed32 + PRIME32_5;
_Hash32 += (uint)_TotalLength;
while (_RemainingLength >= 4)
{
_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;
_Hash32 = RotateLeft32(_Hash32 + FuncGetLittleEndianUInt32(_CurrentArray, _CurrentIndex) * PRIME32_3, 17) * PRIME32_4;
_CurrentIndex += 4;
_RemainingLength -= 4;
}
unsafe
{
fixed(byte* arrayPtr = _CurrentArray)
fixed (byte* arrayPtr = _CurrentArray)
{
while(_RemainingLength-->=1)
while (_RemainingLength-- >= 1)
{
_Hash32=RotateLeft32(_Hash32+arrayPtr[_CurrentIndex++]*PRIME32_5, 11)*PRIME32_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;
_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 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 static uint RotateLeft32(uint value, int count) => (value << count) | (value >> (32 - count));
private void Initialize(uint seed)
{
HashSizeValue=32;
_Seed32=seed;
HashSizeValue = 32;
_Seed32 = seed;
Initialize();
}
}