first commit from linux
This commit is contained in:
@@ -1,70 +1,70 @@
|
||||
namespace DTLib;
|
||||
|
||||
//
|
||||
// вывод и ввод цветного текста в консоли
|
||||
// работает медленнее чем хотелось бы
|
||||
//
|
||||
public static class ColoredConsole
|
||||
{
|
||||
// парсит название цвета в ConsoleColor
|
||||
public static ConsoleColor ParseColor(string color) => color switch
|
||||
{
|
||||
//case "magneta":
|
||||
"m" => ConsoleColor.Magenta,
|
||||
//case "green":
|
||||
"g" => ConsoleColor.Green,
|
||||
//case "red":
|
||||
"r" => ConsoleColor.Red,
|
||||
//case "yellow":
|
||||
"y" => ConsoleColor.Yellow,
|
||||
//case "white":
|
||||
"w" => ConsoleColor.White,
|
||||
//case "blue":
|
||||
"b" => ConsoleColor.Blue,
|
||||
//case "cyan":
|
||||
"c" => ConsoleColor.Cyan,
|
||||
//case "h":
|
||||
"h" or "gray" => ConsoleColor.Gray,
|
||||
//case "black":
|
||||
"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;
|
||||
Console.Write(input[0]);
|
||||
}
|
||||
else if (input.Length % 2 == 0)
|
||||
{
|
||||
StringBuilder strB = new();
|
||||
for (ushort i = 0; i < input.Length; i++)
|
||||
{
|
||||
ConsoleColor c = ParseColor(input[i]);
|
||||
if (Console.ForegroundColor != c)
|
||||
{
|
||||
Console.Write(strB.ToString());
|
||||
Console.ForegroundColor = c;
|
||||
strB.Clear();
|
||||
}
|
||||
strB.Append(input[++i]);
|
||||
}
|
||||
if (strB.Length > 0)
|
||||
Console.Write(strB.ToString());
|
||||
}
|
||||
else throw new Exception("ColoredConsole.Write() error: every text string must have color string before");
|
||||
}
|
||||
|
||||
// ввод цветного текста
|
||||
public static string Read(string color)
|
||||
{
|
||||
ConsoleColor c = ParseColor(color);
|
||||
if (Console.ForegroundColor != c)
|
||||
Console.ForegroundColor = c;
|
||||
return Console.ReadLine();
|
||||
}
|
||||
}
|
||||
namespace DTLib;
|
||||
|
||||
//
|
||||
// вывод и ввод цветного текста в консоли
|
||||
// работает медленнее чем хотелось бы
|
||||
//
|
||||
public static class ColoredConsole
|
||||
{
|
||||
// парсит название цвета в ConsoleColor
|
||||
public static ConsoleColor ParseColor(string color) => color switch
|
||||
{
|
||||
//case "magneta":
|
||||
"m" => ConsoleColor.Magenta,
|
||||
//case "green":
|
||||
"g" => ConsoleColor.Green,
|
||||
//case "red":
|
||||
"r" => ConsoleColor.Red,
|
||||
//case "yellow":
|
||||
"y" => ConsoleColor.Yellow,
|
||||
//case "white":
|
||||
"w" => ConsoleColor.White,
|
||||
//case "blue":
|
||||
"b" => ConsoleColor.Blue,
|
||||
//case "cyan":
|
||||
"c" => ConsoleColor.Cyan,
|
||||
//case "h":
|
||||
"h" or "gray" => ConsoleColor.Gray,
|
||||
//case "black":
|
||||
"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;
|
||||
Console.Write(input[0]);
|
||||
}
|
||||
else if (input.Length % 2 == 0)
|
||||
{
|
||||
StringBuilder strB = new();
|
||||
for (ushort i = 0; i < input.Length; i++)
|
||||
{
|
||||
ConsoleColor c = ParseColor(input[i]);
|
||||
if (Console.ForegroundColor != c)
|
||||
{
|
||||
Console.Write(strB.ToString());
|
||||
Console.ForegroundColor = c;
|
||||
strB.Clear();
|
||||
}
|
||||
strB.Append(input[++i]);
|
||||
}
|
||||
if (strB.Length > 0)
|
||||
Console.Write(strB.ToString());
|
||||
}
|
||||
else throw new Exception("ColoredConsole.Write() error: every text string must have color string before");
|
||||
}
|
||||
|
||||
// ввод цветного текста
|
||||
public static string Read(string color)
|
||||
{
|
||||
ConsoleColor c = ParseColor(color);
|
||||
if (Console.ForegroundColor != c)
|
||||
Console.ForegroundColor = c;
|
||||
return Console.ReadLine();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>false</ImplicitUsings>
|
||||
<Nullable>disable</Nullable>
|
||||
<DebugType>portable</DebugType>
|
||||
<AssemblyName>DTLib</AssemblyName>
|
||||
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<ProduceReferenceAssembly>False</ProduceReferenceAssembly>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Remove="Experimental\**" />
|
||||
<EmbeddedResource Remove="Experimental\**" />
|
||||
<None Remove="Experimental\**" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Experimental\Tester.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>false</ImplicitUsings>
|
||||
<Nullable>disable</Nullable>
|
||||
<DebugType>portable</DebugType>
|
||||
<AssemblyName>DTLib</AssemblyName>
|
||||
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<ProduceReferenceAssembly>False</ProduceReferenceAssembly>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Remove="Experimental\**" />
|
||||
<EmbeddedResource Remove="Experimental\**" />
|
||||
<None Remove="Experimental\**" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Experimental\Tester.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -1,327 +1,327 @@
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
// v21
|
||||
// парсер теперь не может игнорировать комменты, потом починю
|
||||
// теперь числовые значения конвертируются в правильный тип, а не в int64/uint64 (новый вариант switch из c#9.0 делал какую-то дичь)
|
||||
// исправлены некоторые другие баги
|
||||
|
||||
public class DtsodV21 : Dictionary<string, dynamic>, IDtsod
|
||||
{
|
||||
public DtsodVersion Version { get; } = DtsodVersion.V21;
|
||||
|
||||
public IDictionary<string, dynamic> ToDictionary() => this;
|
||||
|
||||
readonly string Text;
|
||||
|
||||
//public Dictionary<string, dynamic> Values { get; set; }
|
||||
public DtsodV21(string text)
|
||||
{
|
||||
Text = text;
|
||||
foreach (KeyValuePair<string, dynamic> pair in Parse(text))
|
||||
Add(pair.Key, pair.Value);
|
||||
}
|
||||
public DtsodV21(IDictionary<string, dynamic> rawDict)
|
||||
{
|
||||
Text = "";
|
||||
foreach (KeyValuePair<string, dynamic> pair in rawDict)
|
||||
Add(pair.Key, pair.Value);
|
||||
}
|
||||
|
||||
|
||||
// выдаёт Exception
|
||||
public new dynamic this[string key]
|
||||
{
|
||||
get => TryGetValue(key, out dynamic value) ? value : throw new Exception($"Dtsod[{key}] key not found");
|
||||
set
|
||||
{
|
||||
if (!TrySetValue(key, value)) throw new Exception($"Dtsod[{key}] key not found");
|
||||
}
|
||||
}
|
||||
|
||||
// не выдаёт KeyNotFoundException
|
||||
public new bool TryGetValue(string key, out dynamic value)
|
||||
{
|
||||
try
|
||||
{
|
||||
value = base[key];
|
||||
return true;
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{
|
||||
value = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public bool TrySetValue(string key, dynamic value)
|
||||
{
|
||||
try
|
||||
{
|
||||
base[key] = value;
|
||||
return true;
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString() => Text;
|
||||
|
||||
enum ValueType
|
||||
{
|
||||
List,
|
||||
Complex,
|
||||
String,
|
||||
Default
|
||||
}
|
||||
|
||||
Dictionary<string, dynamic> Parse(string text)
|
||||
{
|
||||
Dictionary<string, dynamic> parsed = new();
|
||||
int i = 0;
|
||||
for (; i < text.Length; i++)
|
||||
ReadName();
|
||||
return parsed;
|
||||
|
||||
// СЛОМАНО
|
||||
/*void ReadCommentLine()
|
||||
{
|
||||
for (; i < text.Length && text[i] != '\n'; i++) DebugNoTime("h", text[i].ToString());
|
||||
}*/
|
||||
|
||||
void ReadName()
|
||||
{
|
||||
|
||||
bool isListElem = false;
|
||||
dynamic value;
|
||||
StringBuilder defaultNameBuilder = new();
|
||||
|
||||
for (; i < text.Length; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case ':':
|
||||
i++;
|
||||
string name = defaultNameBuilder.ToString();
|
||||
value = ReadValue();
|
||||
// если value это null, эта строка выдавала ошибку
|
||||
//DebugNoTime("c", $"parsed.Add({name}, {value} { value.GetType() })");
|
||||
if (isListElem)
|
||||
{
|
||||
if (!parsed.ContainsKey(name))
|
||||
parsed.Add(name, new List<dynamic>());
|
||||
parsed[name].Add(value);
|
||||
}
|
||||
else
|
||||
parsed.Add(name, value);
|
||||
return;
|
||||
// строка, начинающаяся с # будет считаться комментом
|
||||
case '#':
|
||||
//ReadCommentLine();
|
||||
break;
|
||||
case '}':
|
||||
throw new Exception("Parse.ReadName() error: unexpected '}' at " + i + " char");
|
||||
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
|
||||
case '$':
|
||||
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");
|
||||
default:
|
||||
defaultNameBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dynamic ReadValue()
|
||||
{
|
||||
ValueType type = ValueType.Default;
|
||||
dynamic value = null;
|
||||
|
||||
string ReadString()
|
||||
{
|
||||
i++;
|
||||
StringBuilder valueBuilder = new();
|
||||
valueBuilder.Append('"');
|
||||
for (; text[i] != '"' || text[i - 1] == '\\'; i++)
|
||||
{
|
||||
valueBuilder.Append(text[i]);
|
||||
}
|
||||
valueBuilder.Append('"');
|
||||
type = ValueType.String;
|
||||
return valueBuilder.ToString();
|
||||
}
|
||||
|
||||
List<dynamic> ReadList()
|
||||
{
|
||||
i++;
|
||||
List<dynamic> output = new();
|
||||
StringBuilder valueBuilder = new();
|
||||
for (; text[i] != ']'; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case ',':
|
||||
ParseValueToRightType(valueBuilder.ToString());
|
||||
output.Add(value);
|
||||
valueBuilder.Clear();
|
||||
break;
|
||||
default:
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (valueBuilder.Length > 0)
|
||||
{
|
||||
ParseValueToRightType(valueBuilder.ToString());
|
||||
output.Add(value);
|
||||
}
|
||||
type = ValueType.List;
|
||||
return output;
|
||||
}
|
||||
|
||||
Dictionary<string, dynamic> ReadComplex()
|
||||
{
|
||||
StringBuilder valueBuilder = new();
|
||||
int balance = 1;
|
||||
i++;
|
||||
for (; balance != 0; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case '"':
|
||||
valueBuilder.Append(ReadString());
|
||||
break;
|
||||
case '}':
|
||||
balance--;
|
||||
if (balance != 0)
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
case '{':
|
||||
balance++;
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
default:
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
i--; // i++ в for выполняется даже когда balance == 0, то есть text[i] получается == ;, что ломает всё
|
||||
type = ValueType.Complex;
|
||||
return Parse(valueBuilder.ToString());
|
||||
}
|
||||
|
||||
void ParseValueToRightType(string stringValue)
|
||||
{
|
||||
|
||||
switch (stringValue)
|
||||
{
|
||||
|
||||
// bool
|
||||
case "true":
|
||||
case "false":
|
||||
value = stringValue.ToBool();
|
||||
break;
|
||||
// null
|
||||
case "null":
|
||||
value = null;
|
||||
break;
|
||||
default:
|
||||
if (stringValue.Contains('"'))
|
||||
value = stringValue.Remove(stringValue.Length - 1).Remove(0, 1);
|
||||
// double
|
||||
else if (stringValue.Contains('.'))
|
||||
value = stringValue.ToDouble();
|
||||
// ushort; ulong; uint
|
||||
else if (stringValue.Length > 2 && stringValue[stringValue.Length - 2] == 'u')
|
||||
{
|
||||
switch (stringValue[stringValue.Length - 1])
|
||||
{
|
||||
case 's':
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToUShort();
|
||||
break;
|
||||
case 'i':
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToUInt();
|
||||
break;
|
||||
case 'l':
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToULong();
|
||||
break;
|
||||
default:
|
||||
throw new Exception($"Dtsod.Parse.ReadValue() error: value= wrong type <u{stringValue[stringValue.Length - 1]}>");
|
||||
};
|
||||
}
|
||||
// short; long; int
|
||||
else
|
||||
switch (stringValue[stringValue.Length - 1])
|
||||
{
|
||||
case 's':
|
||||
value = stringValue.Remove(stringValue.Length - 1).ToShort();
|
||||
break;
|
||||
case 'l':
|
||||
value = stringValue.Remove(stringValue.Length - 1).ToLong();
|
||||
break;
|
||||
default:
|
||||
value = stringValue.ToInt();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
};
|
||||
}
|
||||
|
||||
StringBuilder defaultValueBuilder = new();
|
||||
for (; i < text.Length; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '"':
|
||||
value = ReadString();
|
||||
break;
|
||||
case ';':
|
||||
switch (type)
|
||||
{
|
||||
case ValueType.String:
|
||||
ParseValueToRightType(value);
|
||||
break;
|
||||
case ValueType.Default:
|
||||
ParseValueToRightType(defaultValueBuilder.ToString());
|
||||
break;
|
||||
};
|
||||
return value;
|
||||
case '[':
|
||||
value = ReadList();
|
||||
break;
|
||||
case '{':
|
||||
value = ReadComplex();
|
||||
break;
|
||||
// строка, начинающаяся с # будет считаться комментом
|
||||
case '#':
|
||||
//ReadCommentLine();
|
||||
break;
|
||||
default:
|
||||
defaultValueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw new Exception("Dtsod.Parse.ReadValue error: wtf it's the end of function");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
// v21
|
||||
// парсер теперь не может игнорировать комменты, потом починю
|
||||
// теперь числовые значения конвертируются в правильный тип, а не в int64/uint64 (новый вариант switch из c#9.0 делал какую-то дичь)
|
||||
// исправлены некоторые другие баги
|
||||
|
||||
public class DtsodV21 : Dictionary<string, dynamic>, IDtsod
|
||||
{
|
||||
public DtsodVersion Version { get; } = DtsodVersion.V21;
|
||||
|
||||
public IDictionary<string, dynamic> ToDictionary() => this;
|
||||
|
||||
readonly string Text;
|
||||
|
||||
//public Dictionary<string, dynamic> Values { get; set; }
|
||||
public DtsodV21(string text)
|
||||
{
|
||||
Text = text;
|
||||
foreach (KeyValuePair<string, dynamic> pair in Parse(text))
|
||||
Add(pair.Key, pair.Value);
|
||||
}
|
||||
public DtsodV21(IDictionary<string, dynamic> rawDict)
|
||||
{
|
||||
Text = "";
|
||||
foreach (KeyValuePair<string, dynamic> pair in rawDict)
|
||||
Add(pair.Key, pair.Value);
|
||||
}
|
||||
|
||||
|
||||
// выдаёт Exception
|
||||
public new dynamic this[string key]
|
||||
{
|
||||
get => TryGetValue(key, out dynamic value) ? value : throw new Exception($"Dtsod[{key}] key not found");
|
||||
set
|
||||
{
|
||||
if (!TrySetValue(key, value)) throw new Exception($"Dtsod[{key}] key not found");
|
||||
}
|
||||
}
|
||||
|
||||
// не выдаёт KeyNotFoundException
|
||||
public new bool TryGetValue(string key, out dynamic value)
|
||||
{
|
||||
try
|
||||
{
|
||||
value = base[key];
|
||||
return true;
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{
|
||||
value = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public bool TrySetValue(string key, dynamic value)
|
||||
{
|
||||
try
|
||||
{
|
||||
base[key] = value;
|
||||
return true;
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString() => Text;
|
||||
|
||||
enum ValueType
|
||||
{
|
||||
List,
|
||||
Complex,
|
||||
String,
|
||||
Default
|
||||
}
|
||||
|
||||
Dictionary<string, dynamic> Parse(string text)
|
||||
{
|
||||
Dictionary<string, dynamic> parsed = new();
|
||||
int i = 0;
|
||||
for (; i < text.Length; i++)
|
||||
ReadName();
|
||||
return parsed;
|
||||
|
||||
// СЛОМАНО
|
||||
/*void ReadCommentLine()
|
||||
{
|
||||
for (; i < text.Length && text[i] != '\n'; i++) DebugNoTime("h", text[i].ToString());
|
||||
}*/
|
||||
|
||||
void ReadName()
|
||||
{
|
||||
|
||||
bool isListElem = false;
|
||||
dynamic value;
|
||||
StringBuilder defaultNameBuilder = new();
|
||||
|
||||
for (; i < text.Length; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case ':':
|
||||
i++;
|
||||
string name = defaultNameBuilder.ToString();
|
||||
value = ReadValue();
|
||||
// если value это null, эта строка выдавала ошибку
|
||||
//DebugNoTime("c", $"parsed.Add({name}, {value} { value.GetType() })");
|
||||
if (isListElem)
|
||||
{
|
||||
if (!parsed.ContainsKey(name))
|
||||
parsed.Add(name, new List<dynamic>());
|
||||
parsed[name].Add(value);
|
||||
}
|
||||
else
|
||||
parsed.Add(name, value);
|
||||
return;
|
||||
// строка, начинающаяся с # будет считаться комментом
|
||||
case '#':
|
||||
//ReadCommentLine();
|
||||
break;
|
||||
case '}':
|
||||
throw new Exception("Parse.ReadName() error: unexpected '}' at " + i + " char");
|
||||
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
|
||||
case '$':
|
||||
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");
|
||||
default:
|
||||
defaultNameBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dynamic ReadValue()
|
||||
{
|
||||
ValueType type = ValueType.Default;
|
||||
dynamic value = null;
|
||||
|
||||
string ReadString()
|
||||
{
|
||||
i++;
|
||||
StringBuilder valueBuilder = new();
|
||||
valueBuilder.Append('"');
|
||||
for (; text[i] != '"' || text[i - 1] == '\\'; i++)
|
||||
{
|
||||
valueBuilder.Append(text[i]);
|
||||
}
|
||||
valueBuilder.Append('"');
|
||||
type = ValueType.String;
|
||||
return valueBuilder.ToString();
|
||||
}
|
||||
|
||||
List<dynamic> ReadList()
|
||||
{
|
||||
i++;
|
||||
List<dynamic> output = new();
|
||||
StringBuilder valueBuilder = new();
|
||||
for (; text[i] != ']'; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case ',':
|
||||
ParseValueToRightType(valueBuilder.ToString());
|
||||
output.Add(value);
|
||||
valueBuilder.Clear();
|
||||
break;
|
||||
default:
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (valueBuilder.Length > 0)
|
||||
{
|
||||
ParseValueToRightType(valueBuilder.ToString());
|
||||
output.Add(value);
|
||||
}
|
||||
type = ValueType.List;
|
||||
return output;
|
||||
}
|
||||
|
||||
Dictionary<string, dynamic> ReadComplex()
|
||||
{
|
||||
StringBuilder valueBuilder = new();
|
||||
int balance = 1;
|
||||
i++;
|
||||
for (; balance != 0; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case '"':
|
||||
valueBuilder.Append(ReadString());
|
||||
break;
|
||||
case '}':
|
||||
balance--;
|
||||
if (balance != 0)
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
case '{':
|
||||
balance++;
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
default:
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
i--; // i++ в for выполняется даже когда balance == 0, то есть text[i] получается == ;, что ломает всё
|
||||
type = ValueType.Complex;
|
||||
return Parse(valueBuilder.ToString());
|
||||
}
|
||||
|
||||
void ParseValueToRightType(string stringValue)
|
||||
{
|
||||
|
||||
switch (stringValue)
|
||||
{
|
||||
|
||||
// bool
|
||||
case "true":
|
||||
case "false":
|
||||
value = stringValue.ToBool();
|
||||
break;
|
||||
// null
|
||||
case "null":
|
||||
value = null;
|
||||
break;
|
||||
default:
|
||||
if (stringValue.Contains('"'))
|
||||
value = stringValue.Remove(stringValue.Length - 1).Remove(0, 1);
|
||||
// double
|
||||
else if (stringValue.Contains('.'))
|
||||
value = stringValue.ToDouble();
|
||||
// ushort; ulong; uint
|
||||
else if (stringValue.Length > 2 && stringValue[stringValue.Length - 2] == 'u')
|
||||
{
|
||||
switch (stringValue[stringValue.Length - 1])
|
||||
{
|
||||
case 's':
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToUShort();
|
||||
break;
|
||||
case 'i':
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToUInt();
|
||||
break;
|
||||
case 'l':
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToULong();
|
||||
break;
|
||||
default:
|
||||
throw new Exception($"Dtsod.Parse.ReadValue() error: value= wrong type <u{stringValue[stringValue.Length - 1]}>");
|
||||
};
|
||||
}
|
||||
// short; long; int
|
||||
else
|
||||
switch (stringValue[stringValue.Length - 1])
|
||||
{
|
||||
case 's':
|
||||
value = stringValue.Remove(stringValue.Length - 1).ToShort();
|
||||
break;
|
||||
case 'l':
|
||||
value = stringValue.Remove(stringValue.Length - 1).ToLong();
|
||||
break;
|
||||
default:
|
||||
value = stringValue.ToInt();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
};
|
||||
}
|
||||
|
||||
StringBuilder defaultValueBuilder = new();
|
||||
for (; i < text.Length; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '"':
|
||||
value = ReadString();
|
||||
break;
|
||||
case ';':
|
||||
switch (type)
|
||||
{
|
||||
case ValueType.String:
|
||||
ParseValueToRightType(value);
|
||||
break;
|
||||
case ValueType.Default:
|
||||
ParseValueToRightType(defaultValueBuilder.ToString());
|
||||
break;
|
||||
};
|
||||
return value;
|
||||
case '[':
|
||||
value = ReadList();
|
||||
break;
|
||||
case '{':
|
||||
value = ReadComplex();
|
||||
break;
|
||||
// строка, начинающаяся с # будет считаться комментом
|
||||
case '#':
|
||||
//ReadCommentLine();
|
||||
break;
|
||||
default:
|
||||
defaultValueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw new Exception("Dtsod.Parse.ReadValue error: wtf it's the end of function");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,445 +1,445 @@
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
// v22
|
||||
// метод ToString() теперь деконструирует объект в текст, а не возвращает параметр text из конструктора
|
||||
// деконструкция листов не работает из-за костыльного определения типов данных
|
||||
|
||||
public class DtsodV22 : Dictionary<string, DtsodV22.ValueStruct>, IDtsod
|
||||
{
|
||||
public DtsodVersion Version { get; } = DtsodVersion.V22;
|
||||
|
||||
public IDictionary<string, dynamic> ToDictionary()
|
||||
{
|
||||
Dictionary<string, dynamic> newdict = new();
|
||||
foreach (KeyValuePair<string, ValueStruct> pair in this)
|
||||
newdict.Add(pair.Key, pair.Value.Value);
|
||||
return newdict;
|
||||
}
|
||||
|
||||
public struct ValueStruct
|
||||
{
|
||||
public dynamic Value;
|
||||
public ValueTypes Type;
|
||||
public bool IsList;
|
||||
public ValueStruct(ValueTypes type, dynamic value, bool isList)
|
||||
{
|
||||
Value = value;
|
||||
Type = type;
|
||||
IsList = isList;
|
||||
}
|
||||
}
|
||||
|
||||
public enum ValueTypes
|
||||
{
|
||||
List,
|
||||
Complex,
|
||||
String,
|
||||
Short,
|
||||
Int,
|
||||
Long,
|
||||
UShort,
|
||||
UInt,
|
||||
ULong,
|
||||
Double,
|
||||
Null,
|
||||
Bool,
|
||||
Unknown
|
||||
}
|
||||
|
||||
public DtsodV22() { }
|
||||
|
||||
public DtsodV22(string text)
|
||||
{
|
||||
foreach (KeyValuePair<string, ValueStruct> pair in Parse(text))
|
||||
Add(pair.Key, pair.Value);
|
||||
}
|
||||
|
||||
public DtsodV22(Dictionary<string, ValueStruct> dict)
|
||||
{
|
||||
foreach (KeyValuePair<string, ValueStruct> pair in dict)
|
||||
Add(pair.Key, pair.Value);
|
||||
}
|
||||
|
||||
// выдаёт Exception
|
||||
public new dynamic this[string key]
|
||||
{
|
||||
get => TryGetValue(key, out dynamic value) ? value : throw new Exception($"Dtsod[{key}] key not found");
|
||||
set
|
||||
{
|
||||
if (!TrySetValue(key, value)) throw new Exception($"Dtsod[{key}] key not found");
|
||||
}
|
||||
}
|
||||
|
||||
// не выдаёт KeyNotFoundException
|
||||
public bool TryGetValue(string key, out dynamic value)
|
||||
{
|
||||
try
|
||||
{
|
||||
value = base[key].Value;
|
||||
return true;
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{
|
||||
value = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public bool TrySetValue(string key, dynamic value)
|
||||
{
|
||||
try
|
||||
{
|
||||
bool isList = value is IList;
|
||||
base[key] = new(base[key].Type, value, isList);
|
||||
return true;
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{ return false; }
|
||||
}
|
||||
|
||||
DtsodV22 Parse(string text)
|
||||
{
|
||||
Dictionary<string, ValueStruct> parsed = new();
|
||||
int i = 0;
|
||||
for (; i < text.Length; i++)
|
||||
ReadName();
|
||||
return new DtsodV22(parsed);
|
||||
|
||||
// СЛОМАНО
|
||||
/*void ReadCommentLine()
|
||||
{
|
||||
for (; i < text.Length && text[i] != '\n'; i++) Debug("h", text[i].ToString());
|
||||
}*/
|
||||
|
||||
void ReadName()
|
||||
{
|
||||
|
||||
bool isListElem = false;
|
||||
dynamic value;
|
||||
StringBuilder defaultNameBuilder = new();
|
||||
|
||||
for (; i < text.Length; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case ':':
|
||||
i++;
|
||||
string name = defaultNameBuilder.ToString();
|
||||
value = ReadValue(out ValueTypes type, out bool isList);
|
||||
if (isListElem)
|
||||
{
|
||||
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));
|
||||
return;
|
||||
// строка, начинающаяся с # будет считаться комментом
|
||||
case '#':
|
||||
//ReadCommentLine();
|
||||
break;
|
||||
case '}':
|
||||
throw new Exception("Parse.ReadName() error: unexpected '}' at " + i + " char");
|
||||
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
|
||||
case '$':
|
||||
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");
|
||||
default:
|
||||
defaultNameBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dynamic ReadValue(out ValueTypes outType, out bool isList)
|
||||
{
|
||||
ValueTypes type = ValueTypes.Unknown;
|
||||
isList = false;
|
||||
dynamic value = null;
|
||||
|
||||
string ReadString()
|
||||
{
|
||||
i++;
|
||||
StringBuilder valueBuilder = new();
|
||||
valueBuilder.Append('"');
|
||||
for (; text[i] != '"' || text[i - 1] == '\\'; i++)
|
||||
{
|
||||
valueBuilder.Append(text[i]);
|
||||
}
|
||||
valueBuilder.Append('"');
|
||||
type = ValueTypes.String;
|
||||
return valueBuilder.ToString();
|
||||
}
|
||||
|
||||
List<dynamic> ReadList()
|
||||
{
|
||||
i++;
|
||||
List<dynamic> output = new();
|
||||
StringBuilder valueBuilder = new();
|
||||
for (; text[i] != ']'; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case ',':
|
||||
ParseValueToRightType(valueBuilder.ToString());
|
||||
output.Add(value);
|
||||
valueBuilder.Clear();
|
||||
break;
|
||||
default:
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (valueBuilder.Length > 0)
|
||||
{
|
||||
ParseValueToRightType(valueBuilder.ToString());
|
||||
output.Add(value);
|
||||
}
|
||||
type = ValueTypes.List;
|
||||
return output;
|
||||
}
|
||||
|
||||
Dictionary<string, ValueStruct> ReadComplex()
|
||||
{
|
||||
StringBuilder valueBuilder = new();
|
||||
int balance = 1;
|
||||
i++;
|
||||
for (; balance != 0; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case '"':
|
||||
valueBuilder.Append(ReadString());
|
||||
break;
|
||||
case '}':
|
||||
balance--;
|
||||
if (balance != 0)
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
case '{':
|
||||
balance++;
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
default:
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
i--; // i++ в for выполняется даже когда balance == 0, то есть text[i] получается == ;, что ломает всё
|
||||
type = ValueTypes.Complex;
|
||||
return Parse(valueBuilder.ToString());
|
||||
}
|
||||
|
||||
void ParseValueToRightType(string stringValue)
|
||||
{
|
||||
switch (stringValue)
|
||||
{
|
||||
|
||||
// bool
|
||||
case "true":
|
||||
case "false":
|
||||
type = ValueTypes.Bool;
|
||||
value = stringValue.ToBool();
|
||||
break;
|
||||
// null
|
||||
case "null":
|
||||
type = ValueTypes.Null;
|
||||
value = null;
|
||||
break;
|
||||
default:
|
||||
if (stringValue.Contains('"'))
|
||||
{
|
||||
type = ValueTypes.String;
|
||||
value = stringValue.Remove(stringValue.Length - 1).Remove(0, 1);
|
||||
}
|
||||
// double
|
||||
else if (stringValue.Contains('.'))
|
||||
{
|
||||
type = ValueTypes.Double;
|
||||
value = stringValue.ToDouble();
|
||||
}
|
||||
// ushort; ulong; uint
|
||||
else if (stringValue.Length > 2 && stringValue[stringValue.Length - 2] == 'u')
|
||||
{
|
||||
switch (stringValue[stringValue.Length - 1])
|
||||
{
|
||||
case 's':
|
||||
type = ValueTypes.UShort;
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToUShort();
|
||||
break;
|
||||
case 'i':
|
||||
type = ValueTypes.UInt;
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToUInt();
|
||||
break;
|
||||
case 'l':
|
||||
type = ValueTypes.ULong;
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToULong();
|
||||
break;
|
||||
default:
|
||||
throw new Exception($"Dtsod.Parse.ReadValue() error: value <{stringValue}> has wrong type");
|
||||
};
|
||||
}
|
||||
// short; long; int
|
||||
else
|
||||
switch (stringValue[stringValue.Length - 1])
|
||||
{
|
||||
case 's':
|
||||
type = ValueTypes.Short;
|
||||
value = stringValue.Remove(stringValue.Length - 1).ToShort();
|
||||
break;
|
||||
case 'l':
|
||||
type = ValueTypes.Long;
|
||||
value = stringValue.Remove(stringValue.Length - 1).ToLong();
|
||||
break;
|
||||
default:
|
||||
type = ValueTypes.Int;
|
||||
value = stringValue.ToInt();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
};
|
||||
}
|
||||
|
||||
StringBuilder defaultValueBuilder = new();
|
||||
for (; i < text.Length; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '"':
|
||||
value = ReadString();
|
||||
break;
|
||||
case '[':
|
||||
value = ReadList();
|
||||
break;
|
||||
case '{':
|
||||
value = ReadComplex();
|
||||
break;
|
||||
case ';':
|
||||
switch (type)
|
||||
{
|
||||
case ValueTypes.String:
|
||||
ParseValueToRightType(value);
|
||||
break;
|
||||
case ValueTypes.Unknown:
|
||||
ParseValueToRightType(defaultValueBuilder.ToString());
|
||||
break;
|
||||
case ValueTypes.List:
|
||||
isList = true;
|
||||
break;
|
||||
};
|
||||
outType = type;
|
||||
return value;
|
||||
// строка, начинающаяся с # будет считаться комментом
|
||||
case '#':
|
||||
//ReadCommentLine();
|
||||
break;
|
||||
default:
|
||||
defaultValueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw new Exception("Dtsod.Parse.ReadValue error: wtf it's the end of function");
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString() => Deconstruct(this);
|
||||
|
||||
ushort tabCount = 0;
|
||||
string Deconstruct(DtsodV22 dtsod)
|
||||
{
|
||||
StringBuilder outBuilder = new();
|
||||
foreach (string key in dtsod.Keys)
|
||||
{
|
||||
outBuilder.Append('\t', tabCount);
|
||||
outBuilder.Append(key);
|
||||
outBuilder.Append(": ");
|
||||
dtsod.TryGetValue(key, out ValueStruct value);
|
||||
switch (value.Type)
|
||||
{
|
||||
case ValueTypes.List:
|
||||
outBuilder.Append('[').Append(StringConverter.MergeToString((IEnumerable<object>)value.Value, ",")).Append(']');
|
||||
//outBuilder.Append("\"list deconstruction is'nt implemented yet\"");
|
||||
break;
|
||||
case ValueTypes.Complex:
|
||||
outBuilder.Append('\n');
|
||||
outBuilder.Append('\t', tabCount);
|
||||
outBuilder.Append("{\n");
|
||||
tabCount++;
|
||||
outBuilder.Append(Deconstruct(value.Value));
|
||||
tabCount--;
|
||||
outBuilder.Append('\t', tabCount);
|
||||
outBuilder.Append('}');
|
||||
break;
|
||||
case ValueTypes.String:
|
||||
outBuilder.Append('\"');
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append('\"');
|
||||
break;
|
||||
case ValueTypes.Short:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append('s');
|
||||
break;
|
||||
case ValueTypes.Int:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
break;
|
||||
case ValueTypes.Long:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append('l');
|
||||
break;
|
||||
case ValueTypes.UShort:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append("us");
|
||||
break;
|
||||
case ValueTypes.UInt:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append("ui");
|
||||
break;
|
||||
case ValueTypes.ULong:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append("ul");
|
||||
break;
|
||||
case ValueTypes.Double:
|
||||
outBuilder.Append(value.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
break;
|
||||
case ValueTypes.Null:
|
||||
outBuilder.Append("null");
|
||||
break;
|
||||
case ValueTypes.Bool:
|
||||
outBuilder.Append(value.Value.ToString().ToLower());
|
||||
break;
|
||||
default:
|
||||
throw new Exception($"Dtsod.Deconstruct() error: unknown type: {value.Type}");
|
||||
}
|
||||
|
||||
outBuilder.Append(";\n");
|
||||
}
|
||||
return outBuilder.ToString();
|
||||
}
|
||||
|
||||
public void Add(KeyValuePair<string, ValueStruct> a) => Add(a.Key, a.Value);
|
||||
|
||||
public DtsodV22 Extend(DtsodV22 newPart)
|
||||
{
|
||||
foreach (KeyValuePair<string, ValueStruct> pair in newPart)
|
||||
Add(pair.Key, pair.Value);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
// v22
|
||||
// метод ToString() теперь деконструирует объект в текст, а не возвращает параметр text из конструктора
|
||||
// деконструкция листов не работает из-за костыльного определения типов данных
|
||||
|
||||
public class DtsodV22 : Dictionary<string, DtsodV22.ValueStruct>, IDtsod
|
||||
{
|
||||
public DtsodVersion Version { get; } = DtsodVersion.V22;
|
||||
|
||||
public IDictionary<string, dynamic> ToDictionary()
|
||||
{
|
||||
Dictionary<string, dynamic> newdict = new();
|
||||
foreach (KeyValuePair<string, ValueStruct> pair in this)
|
||||
newdict.Add(pair.Key, pair.Value.Value);
|
||||
return newdict;
|
||||
}
|
||||
|
||||
public struct ValueStruct
|
||||
{
|
||||
public dynamic Value;
|
||||
public ValueTypes Type;
|
||||
public bool IsList;
|
||||
public ValueStruct(ValueTypes type, dynamic value, bool isList)
|
||||
{
|
||||
Value = value;
|
||||
Type = type;
|
||||
IsList = isList;
|
||||
}
|
||||
}
|
||||
|
||||
public enum ValueTypes
|
||||
{
|
||||
List,
|
||||
Complex,
|
||||
String,
|
||||
Short,
|
||||
Int,
|
||||
Long,
|
||||
UShort,
|
||||
UInt,
|
||||
ULong,
|
||||
Double,
|
||||
Null,
|
||||
Bool,
|
||||
Unknown
|
||||
}
|
||||
|
||||
public DtsodV22() { }
|
||||
|
||||
public DtsodV22(string text)
|
||||
{
|
||||
foreach (KeyValuePair<string, ValueStruct> pair in Parse(text))
|
||||
Add(pair.Key, pair.Value);
|
||||
}
|
||||
|
||||
public DtsodV22(Dictionary<string, ValueStruct> dict)
|
||||
{
|
||||
foreach (KeyValuePair<string, ValueStruct> pair in dict)
|
||||
Add(pair.Key, pair.Value);
|
||||
}
|
||||
|
||||
// выдаёт Exception
|
||||
public new dynamic this[string key]
|
||||
{
|
||||
get => TryGetValue(key, out dynamic value) ? value : throw new Exception($"Dtsod[{key}] key not found");
|
||||
set
|
||||
{
|
||||
if (!TrySetValue(key, value)) throw new Exception($"Dtsod[{key}] key not found");
|
||||
}
|
||||
}
|
||||
|
||||
// не выдаёт KeyNotFoundException
|
||||
public bool TryGetValue(string key, out dynamic value)
|
||||
{
|
||||
try
|
||||
{
|
||||
value = base[key].Value;
|
||||
return true;
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{
|
||||
value = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public bool TrySetValue(string key, dynamic value)
|
||||
{
|
||||
try
|
||||
{
|
||||
bool isList = value is IList;
|
||||
base[key] = new(base[key].Type, value, isList);
|
||||
return true;
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{ return false; }
|
||||
}
|
||||
|
||||
DtsodV22 Parse(string text)
|
||||
{
|
||||
Dictionary<string, ValueStruct> parsed = new();
|
||||
int i = 0;
|
||||
for (; i < text.Length; i++)
|
||||
ReadName();
|
||||
return new DtsodV22(parsed);
|
||||
|
||||
// СЛОМАНО
|
||||
/*void ReadCommentLine()
|
||||
{
|
||||
for (; i < text.Length && text[i] != '\n'; i++) Debug("h", text[i].ToString());
|
||||
}*/
|
||||
|
||||
void ReadName()
|
||||
{
|
||||
|
||||
bool isListElem = false;
|
||||
dynamic value;
|
||||
StringBuilder defaultNameBuilder = new();
|
||||
|
||||
for (; i < text.Length; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case ':':
|
||||
i++;
|
||||
string name = defaultNameBuilder.ToString();
|
||||
value = ReadValue(out ValueTypes type, out bool isList);
|
||||
if (isListElem)
|
||||
{
|
||||
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));
|
||||
return;
|
||||
// строка, начинающаяся с # будет считаться комментом
|
||||
case '#':
|
||||
//ReadCommentLine();
|
||||
break;
|
||||
case '}':
|
||||
throw new Exception("Parse.ReadName() error: unexpected '}' at " + i + " char");
|
||||
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
|
||||
case '$':
|
||||
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");
|
||||
default:
|
||||
defaultNameBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dynamic ReadValue(out ValueTypes outType, out bool isList)
|
||||
{
|
||||
ValueTypes type = ValueTypes.Unknown;
|
||||
isList = false;
|
||||
dynamic value = null;
|
||||
|
||||
string ReadString()
|
||||
{
|
||||
i++;
|
||||
StringBuilder valueBuilder = new();
|
||||
valueBuilder.Append('"');
|
||||
for (; text[i] != '"' || text[i - 1] == '\\'; i++)
|
||||
{
|
||||
valueBuilder.Append(text[i]);
|
||||
}
|
||||
valueBuilder.Append('"');
|
||||
type = ValueTypes.String;
|
||||
return valueBuilder.ToString();
|
||||
}
|
||||
|
||||
List<dynamic> ReadList()
|
||||
{
|
||||
i++;
|
||||
List<dynamic> output = new();
|
||||
StringBuilder valueBuilder = new();
|
||||
for (; text[i] != ']'; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case ',':
|
||||
ParseValueToRightType(valueBuilder.ToString());
|
||||
output.Add(value);
|
||||
valueBuilder.Clear();
|
||||
break;
|
||||
default:
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (valueBuilder.Length > 0)
|
||||
{
|
||||
ParseValueToRightType(valueBuilder.ToString());
|
||||
output.Add(value);
|
||||
}
|
||||
type = ValueTypes.List;
|
||||
return output;
|
||||
}
|
||||
|
||||
Dictionary<string, ValueStruct> ReadComplex()
|
||||
{
|
||||
StringBuilder valueBuilder = new();
|
||||
int balance = 1;
|
||||
i++;
|
||||
for (; balance != 0; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case '"':
|
||||
valueBuilder.Append(ReadString());
|
||||
break;
|
||||
case '}':
|
||||
balance--;
|
||||
if (balance != 0)
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
case '{':
|
||||
balance++;
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
default:
|
||||
valueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
i--; // i++ в for выполняется даже когда balance == 0, то есть text[i] получается == ;, что ломает всё
|
||||
type = ValueTypes.Complex;
|
||||
return Parse(valueBuilder.ToString());
|
||||
}
|
||||
|
||||
void ParseValueToRightType(string stringValue)
|
||||
{
|
||||
switch (stringValue)
|
||||
{
|
||||
|
||||
// bool
|
||||
case "true":
|
||||
case "false":
|
||||
type = ValueTypes.Bool;
|
||||
value = stringValue.ToBool();
|
||||
break;
|
||||
// null
|
||||
case "null":
|
||||
type = ValueTypes.Null;
|
||||
value = null;
|
||||
break;
|
||||
default:
|
||||
if (stringValue.Contains('"'))
|
||||
{
|
||||
type = ValueTypes.String;
|
||||
value = stringValue.Remove(stringValue.Length - 1).Remove(0, 1);
|
||||
}
|
||||
// double
|
||||
else if (stringValue.Contains('.'))
|
||||
{
|
||||
type = ValueTypes.Double;
|
||||
value = stringValue.ToDouble();
|
||||
}
|
||||
// ushort; ulong; uint
|
||||
else if (stringValue.Length > 2 && stringValue[stringValue.Length - 2] == 'u')
|
||||
{
|
||||
switch (stringValue[stringValue.Length - 1])
|
||||
{
|
||||
case 's':
|
||||
type = ValueTypes.UShort;
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToUShort();
|
||||
break;
|
||||
case 'i':
|
||||
type = ValueTypes.UInt;
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToUInt();
|
||||
break;
|
||||
case 'l':
|
||||
type = ValueTypes.ULong;
|
||||
value = stringValue.Remove(stringValue.Length - 2).ToULong();
|
||||
break;
|
||||
default:
|
||||
throw new Exception($"Dtsod.Parse.ReadValue() error: value <{stringValue}> has wrong type");
|
||||
};
|
||||
}
|
||||
// short; long; int
|
||||
else
|
||||
switch (stringValue[stringValue.Length - 1])
|
||||
{
|
||||
case 's':
|
||||
type = ValueTypes.Short;
|
||||
value = stringValue.Remove(stringValue.Length - 1).ToShort();
|
||||
break;
|
||||
case 'l':
|
||||
type = ValueTypes.Long;
|
||||
value = stringValue.Remove(stringValue.Length - 1).ToLong();
|
||||
break;
|
||||
default:
|
||||
type = ValueTypes.Int;
|
||||
value = stringValue.ToInt();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
};
|
||||
}
|
||||
|
||||
StringBuilder defaultValueBuilder = new();
|
||||
for (; i < text.Length; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '"':
|
||||
value = ReadString();
|
||||
break;
|
||||
case '[':
|
||||
value = ReadList();
|
||||
break;
|
||||
case '{':
|
||||
value = ReadComplex();
|
||||
break;
|
||||
case ';':
|
||||
switch (type)
|
||||
{
|
||||
case ValueTypes.String:
|
||||
ParseValueToRightType(value);
|
||||
break;
|
||||
case ValueTypes.Unknown:
|
||||
ParseValueToRightType(defaultValueBuilder.ToString());
|
||||
break;
|
||||
case ValueTypes.List:
|
||||
isList = true;
|
||||
break;
|
||||
};
|
||||
outType = type;
|
||||
return value;
|
||||
// строка, начинающаяся с # будет считаться комментом
|
||||
case '#':
|
||||
//ReadCommentLine();
|
||||
break;
|
||||
default:
|
||||
defaultValueBuilder.Append(text[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw new Exception("Dtsod.Parse.ReadValue error: wtf it's the end of function");
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString() => Deconstruct(this);
|
||||
|
||||
ushort tabCount = 0;
|
||||
string Deconstruct(DtsodV22 dtsod)
|
||||
{
|
||||
StringBuilder outBuilder = new();
|
||||
foreach (string key in dtsod.Keys)
|
||||
{
|
||||
outBuilder.Append('\t', tabCount);
|
||||
outBuilder.Append(key);
|
||||
outBuilder.Append(": ");
|
||||
dtsod.TryGetValue(key, out ValueStruct value);
|
||||
switch (value.Type)
|
||||
{
|
||||
case ValueTypes.List:
|
||||
outBuilder.Append('[').Append(StringConverter.MergeToString((IEnumerable<object>)value.Value, ",")).Append(']');
|
||||
//outBuilder.Append("\"list deconstruction is'nt implemented yet\"");
|
||||
break;
|
||||
case ValueTypes.Complex:
|
||||
outBuilder.Append('\n');
|
||||
outBuilder.Append('\t', tabCount);
|
||||
outBuilder.Append("{\n");
|
||||
tabCount++;
|
||||
outBuilder.Append(Deconstruct(value.Value));
|
||||
tabCount--;
|
||||
outBuilder.Append('\t', tabCount);
|
||||
outBuilder.Append('}');
|
||||
break;
|
||||
case ValueTypes.String:
|
||||
outBuilder.Append('\"');
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append('\"');
|
||||
break;
|
||||
case ValueTypes.Short:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append('s');
|
||||
break;
|
||||
case ValueTypes.Int:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
break;
|
||||
case ValueTypes.Long:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append('l');
|
||||
break;
|
||||
case ValueTypes.UShort:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append("us");
|
||||
break;
|
||||
case ValueTypes.UInt:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append("ui");
|
||||
break;
|
||||
case ValueTypes.ULong:
|
||||
outBuilder.Append(value.Value.ToString());
|
||||
outBuilder.Append("ul");
|
||||
break;
|
||||
case ValueTypes.Double:
|
||||
outBuilder.Append(value.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
break;
|
||||
case ValueTypes.Null:
|
||||
outBuilder.Append("null");
|
||||
break;
|
||||
case ValueTypes.Bool:
|
||||
outBuilder.Append(value.Value.ToString().ToLower());
|
||||
break;
|
||||
default:
|
||||
throw new Exception($"Dtsod.Deconstruct() error: unknown type: {value.Type}");
|
||||
}
|
||||
|
||||
outBuilder.Append(";\n");
|
||||
}
|
||||
return outBuilder.ToString();
|
||||
}
|
||||
|
||||
public void Add(KeyValuePair<string, ValueStruct> a) => Add(a.Key, a.Value);
|
||||
|
||||
public DtsodV22 Extend(DtsodV22 newPart)
|
||||
{
|
||||
foreach (KeyValuePair<string, ValueStruct> pair in newPart)
|
||||
Add(pair.Key, pair.Value);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,330 +1,330 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
// v23
|
||||
// в процессе создания v30 появились идеи по улучшению 20-ой серии
|
||||
// новый парсер (опять)
|
||||
// улучшена сериализация и десериализация листов
|
||||
|
||||
public class DtsodV23 : DtsodDict<string, dynamic>, IDtsod
|
||||
{
|
||||
|
||||
public DtsodVersion Version { get; } = DtsodVersion.V30;
|
||||
public IDictionary<string, dynamic> ToDictionary() => this;
|
||||
|
||||
public DtsodV23() : base() {}
|
||||
public DtsodV23(IDictionary<string, dynamic> dict) : base(dict) {}
|
||||
public DtsodV23(string serialized) => Append(Deserialize(serialized));
|
||||
|
||||
static DtsodV23 Deserialize(string _text)
|
||||
{
|
||||
char[] text = _text.ToArray();
|
||||
char c;
|
||||
int i = -1; // ++i в ReadName
|
||||
StringBuilder b = new();
|
||||
Dictionary<string, dynamic> output = new();
|
||||
bool partOfDollarList = false;
|
||||
while (i < text.Length)
|
||||
{
|
||||
string name = ReadName();
|
||||
if (name == "") goto end;
|
||||
dynamic value = ReadValue(out bool _);
|
||||
if (partOfDollarList)
|
||||
{
|
||||
if (!output.TryGetValue(name, out var dollarList))
|
||||
{
|
||||
dollarList = new List<dynamic>();
|
||||
output.Add(name, dollarList);
|
||||
}
|
||||
dollarList.Add(value);
|
||||
}
|
||||
else output.Add(name, value);
|
||||
}
|
||||
end:return new DtsodV23(output);
|
||||
|
||||
string ReadName()
|
||||
{
|
||||
while (i < text.Length - 1)
|
||||
{
|
||||
c = text[++i];
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case ':':
|
||||
string _name = b.ToString();
|
||||
b.Clear();
|
||||
return _name;
|
||||
case '$':
|
||||
partOfDollarList = true;
|
||||
break;
|
||||
case '=':
|
||||
case '"':
|
||||
case '\'':
|
||||
case ';':
|
||||
case '[':
|
||||
case ']':
|
||||
case '{':
|
||||
case '}':
|
||||
throw new Exception($"DtsodV23.Deserialize() error: unexpected {c}");
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return b.Length == 0
|
||||
? ""
|
||||
: throw new Exception("DtsodV23.Deserialize.ReadName() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
dynamic ReadValue(out bool endOfList)
|
||||
{
|
||||
endOfList = false;
|
||||
|
||||
void ReadString()
|
||||
{
|
||||
bool prevIsBackslash = false;
|
||||
b.Append('"');
|
||||
c = text[++i];
|
||||
while (c != '"' || prevIsBackslash)
|
||||
{
|
||||
prevIsBackslash = c == '\\' && !prevIsBackslash;
|
||||
b.Append(c);
|
||||
if (++i >= text.Length) throw new Exception("DtsodV23.Deserialize() error: end of text\ntext:\n" + text);
|
||||
c = text[i];
|
||||
}
|
||||
b.Append('"');
|
||||
}
|
||||
|
||||
DtsodV23 ReadDtsod()
|
||||
{
|
||||
short bracketBalance = 1;
|
||||
c = text[++i]; //пропускает начальный символ '{'
|
||||
while (bracketBalance != 0)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case '{':
|
||||
bracketBalance++;
|
||||
b.Append(c);
|
||||
break;
|
||||
case '}':
|
||||
bracketBalance--;
|
||||
if (bracketBalance != 0)
|
||||
b.Append(c);
|
||||
break;
|
||||
case '"':
|
||||
ReadString();
|
||||
break;
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
|
||||
if (++i >= text.Length) throw new Exception("DtsodV23.Deserialize() error: end of text\ntext:\n" + text);
|
||||
c = text[i];
|
||||
}
|
||||
|
||||
var __text = b.ToString();
|
||||
b.Clear();
|
||||
return Deserialize(__text);
|
||||
}
|
||||
|
||||
List<dynamic> ReadList()
|
||||
{
|
||||
List<dynamic> list = new();
|
||||
while (true)
|
||||
{
|
||||
list.Add(ReadValue(out bool _eol));
|
||||
if (_eol) break;
|
||||
}
|
||||
|
||||
b.Clear();
|
||||
return list;
|
||||
}
|
||||
|
||||
dynamic ParseValue(string value_str)
|
||||
{
|
||||
switch (value_str)
|
||||
{
|
||||
case "true":
|
||||
case "false":
|
||||
return value_str.ToBool();
|
||||
case "null":
|
||||
return null;
|
||||
default:
|
||||
if (value_str.Contains('"'))
|
||||
return value_str.Substring(1, value_str.Length - 2).Replace("\\\\","\\").Replace("\\\"","\"");
|
||||
else if (value_str.Contains('\''))
|
||||
return value_str[1];
|
||||
else switch (value_str[value_str.Length - 1])
|
||||
{
|
||||
case 's':
|
||||
return value_str[value_str.Length - 2] == 'u'
|
||||
? value_str.Remove(value_str.Length - 2).ToUShort()
|
||||
: value_str.Remove(value_str.Length - 1).ToShort();
|
||||
case 'u':
|
||||
return value_str.Remove(value_str.Length - 1).ToUInt();
|
||||
case 'i':
|
||||
return value_str[value_str.Length - 2] == 'u'
|
||||
? value_str.Remove(value_str.Length - 2).ToUInt()
|
||||
: value_str.Remove(value_str.Length - 1).ToInt();
|
||||
case 'l':
|
||||
return value_str[value_str.Length - 2] == 'u'
|
||||
? value_str.Remove(value_str.Length - 2).ToULong()
|
||||
: value_str.Remove(value_str.Length - 1).ToLong();
|
||||
case 'b':
|
||||
return value_str[value_str.Length - 2] == 's'
|
||||
? value_str.Remove(value_str.Length - 2).ToSByte()
|
||||
: value_str.Remove(value_str.Length - 1).ToByte();
|
||||
case 'f':
|
||||
return value_str.Remove(value_str.Length - 1).ToFloat();
|
||||
case 'e':
|
||||
return value_str[value_str.Length - 2] == 'd'
|
||||
? value_str.Remove(value_str.Length - 2).ToDecimal()
|
||||
: throw new Exception("can't parse value:" + value_str);
|
||||
default:
|
||||
if (value_str.Contains('.'))
|
||||
return (object)(value_str.ToDouble());
|
||||
else
|
||||
{
|
||||
try { return (object)(value_str.ToInt()); }
|
||||
catch (FormatException)
|
||||
{
|
||||
Log("r", $"can't parse value: {value_str}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
while (i < text.Length - 1)
|
||||
{
|
||||
c = text[++i];
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case '"':
|
||||
ReadString();
|
||||
break;
|
||||
case '\'':
|
||||
b.Append(c).Append(text[++i]);
|
||||
c = text[++i];
|
||||
if (c != '\'') throw new Exception("after <\'> should be char");
|
||||
else b.Append(c);
|
||||
break;
|
||||
case ';':
|
||||
case ',':
|
||||
string str = b.ToString();
|
||||
b.Clear();
|
||||
return ParseValue(str);
|
||||
case '[':
|
||||
return ReadList();
|
||||
case ']':
|
||||
endOfList = true;
|
||||
break;
|
||||
case '{':
|
||||
return ReadDtsod();
|
||||
case '=':
|
||||
case ':':
|
||||
case '}':
|
||||
case '$':
|
||||
throw new Exception($"DtsodV23.Deserialize() error: unexpected {c}");
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("DtsodV23.Deserialize.ReadValue() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
void SkipComment()
|
||||
{
|
||||
while (text[i] != '\n')
|
||||
if (++i >= text.Length) throw new Exception("DtsodV23.Deserialize() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
}
|
||||
|
||||
internal static readonly Dictionary<Type, Action<dynamic, StringBuilder>> TypeSerializeFuncs = new()
|
||||
{
|
||||
{ typeof(bool), (val, b) => b.Append(val.ToString()) },
|
||||
{ typeof(char), (val, b) => b.Append('\'').Append(val).Append('\'') },
|
||||
{ typeof(string), (val, b) => b.Append('"').Append(val.Replace("\\","\\\\").Replace("\"", "\\\"")).Append('"') },
|
||||
{ typeof(byte), (val, b) => b.Append(val.ToString()).Append('b') },
|
||||
{ typeof(sbyte), (val, b) => b.Append(val.ToString()).Append("sb") },
|
||||
{ typeof(short), (val, b) => b.Append(val.ToString()).Append('s') },
|
||||
{ typeof(ushort), (val, b) => b.Append(val.ToString()).Append("us") },
|
||||
{ typeof(int), (val, b) => b.Append(val.ToString()) },
|
||||
{ typeof(uint), (val, b) => b.Append(val.ToString()).Append("ui") },
|
||||
{ typeof(long), (val, b) => b.Append(val.ToString()).Append('l') },
|
||||
{ typeof(ulong), (val, b) => b.Append(val.ToString()).Append("ul") },
|
||||
{ typeof(float), (val, b) => b.Append(val.ToString(CultureInfo.InvariantCulture)).Append('f') },
|
||||
{ typeof(double), (val, b) => b.Append(val.ToString(CultureInfo.InvariantCulture)) },
|
||||
{ typeof(decimal), (val, b) => b.Append(val.ToString(CultureInfo.InvariantCulture)).Append("de") }
|
||||
};
|
||||
short tabscount = -1;
|
||||
protected StringBuilder Serialize(DtsodV23 dtsod, StringBuilder b = null)
|
||||
{
|
||||
tabscount++;
|
||||
if (b is null) b = new StringBuilder();
|
||||
foreach (var pair in dtsod)
|
||||
{
|
||||
b.Append('\t', tabscount).Append(pair.Key).Append(": ");
|
||||
SerializeType(pair.Value);
|
||||
b.Append(";\n");
|
||||
|
||||
void SerializeType(dynamic value)
|
||||
{
|
||||
if (value is null) b.Append("null");
|
||||
else if (value is IList _list)
|
||||
{
|
||||
b.Append('[');
|
||||
foreach (object el in _list)
|
||||
{
|
||||
SerializeType(el);
|
||||
b.Append(',');
|
||||
}
|
||||
b.Remove(b.Length - 1, 1).Append(']');
|
||||
}
|
||||
else if (value is DtsodV23 _dtsod)
|
||||
{
|
||||
b.Append("{\n");
|
||||
Serialize(_dtsod, b);
|
||||
b.Append('}');
|
||||
}
|
||||
else TypeSerializeFuncs[value.GetType()].Invoke(value, b);
|
||||
}
|
||||
}
|
||||
tabscount--;
|
||||
return b;
|
||||
}
|
||||
|
||||
public override string ToString() => Serialize(this).ToString();
|
||||
}
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
// v23
|
||||
// в процессе создания v30 появились идеи по улучшению 20-ой серии
|
||||
// новый парсер (опять)
|
||||
// улучшена сериализация и десериализация листов
|
||||
|
||||
public class DtsodV23 : DtsodDict<string, dynamic>, IDtsod
|
||||
{
|
||||
|
||||
public DtsodVersion Version { get; } = DtsodVersion.V30;
|
||||
public IDictionary<string, dynamic> ToDictionary() => this;
|
||||
|
||||
public DtsodV23() : base() {}
|
||||
public DtsodV23(IDictionary<string, dynamic> dict) : base(dict) {}
|
||||
public DtsodV23(string serialized) => Append(Deserialize(serialized));
|
||||
|
||||
static DtsodV23 Deserialize(string _text)
|
||||
{
|
||||
char[] text = _text.ToArray();
|
||||
char c;
|
||||
int i = -1; // ++i в ReadName
|
||||
StringBuilder b = new();
|
||||
Dictionary<string, dynamic> output = new();
|
||||
bool partOfDollarList = false;
|
||||
while (i < text.Length)
|
||||
{
|
||||
string name = ReadName();
|
||||
if (name == "") goto end;
|
||||
dynamic value = ReadValue(out bool _);
|
||||
if (partOfDollarList)
|
||||
{
|
||||
if (!output.TryGetValue(name, out var dollarList))
|
||||
{
|
||||
dollarList = new List<dynamic>();
|
||||
output.Add(name, dollarList);
|
||||
}
|
||||
dollarList.Add(value);
|
||||
}
|
||||
else output.Add(name, value);
|
||||
}
|
||||
end:return new DtsodV23(output);
|
||||
|
||||
string ReadName()
|
||||
{
|
||||
while (i < text.Length - 1)
|
||||
{
|
||||
c = text[++i];
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case ':':
|
||||
string _name = b.ToString();
|
||||
b.Clear();
|
||||
return _name;
|
||||
case '$':
|
||||
partOfDollarList = true;
|
||||
break;
|
||||
case '=':
|
||||
case '"':
|
||||
case '\'':
|
||||
case ';':
|
||||
case '[':
|
||||
case ']':
|
||||
case '{':
|
||||
case '}':
|
||||
throw new Exception($"DtsodV23.Deserialize() error: unexpected {c}");
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return b.Length == 0
|
||||
? ""
|
||||
: throw new Exception("DtsodV23.Deserialize.ReadName() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
dynamic ReadValue(out bool endOfList)
|
||||
{
|
||||
endOfList = false;
|
||||
|
||||
void ReadString()
|
||||
{
|
||||
bool prevIsBackslash = false;
|
||||
b.Append('"');
|
||||
c = text[++i];
|
||||
while (c != '"' || prevIsBackslash)
|
||||
{
|
||||
prevIsBackslash = c == '\\' && !prevIsBackslash;
|
||||
b.Append(c);
|
||||
if (++i >= text.Length) throw new Exception("DtsodV23.Deserialize() error: end of text\ntext:\n" + text);
|
||||
c = text[i];
|
||||
}
|
||||
b.Append('"');
|
||||
}
|
||||
|
||||
DtsodV23 ReadDtsod()
|
||||
{
|
||||
short bracketBalance = 1;
|
||||
c = text[++i]; //пропускает начальный символ '{'
|
||||
while (bracketBalance != 0)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case '{':
|
||||
bracketBalance++;
|
||||
b.Append(c);
|
||||
break;
|
||||
case '}':
|
||||
bracketBalance--;
|
||||
if (bracketBalance != 0)
|
||||
b.Append(c);
|
||||
break;
|
||||
case '"':
|
||||
ReadString();
|
||||
break;
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
|
||||
if (++i >= text.Length) throw new Exception("DtsodV23.Deserialize() error: end of text\ntext:\n" + text);
|
||||
c = text[i];
|
||||
}
|
||||
|
||||
var __text = b.ToString();
|
||||
b.Clear();
|
||||
return Deserialize(__text);
|
||||
}
|
||||
|
||||
List<dynamic> ReadList()
|
||||
{
|
||||
List<dynamic> list = new();
|
||||
while (true)
|
||||
{
|
||||
list.Add(ReadValue(out bool _eol));
|
||||
if (_eol) break;
|
||||
}
|
||||
|
||||
b.Clear();
|
||||
return list;
|
||||
}
|
||||
|
||||
dynamic ParseValue(string value_str)
|
||||
{
|
||||
switch (value_str)
|
||||
{
|
||||
case "true":
|
||||
case "false":
|
||||
return value_str.ToBool();
|
||||
case "null":
|
||||
return null;
|
||||
default:
|
||||
if (value_str.Contains('"'))
|
||||
return value_str.Substring(1, value_str.Length - 2).Replace("\\\\","\\").Replace("\\\"","\"");
|
||||
else if (value_str.Contains('\''))
|
||||
return value_str[1];
|
||||
else switch (value_str[value_str.Length - 1])
|
||||
{
|
||||
case 's':
|
||||
return value_str[value_str.Length - 2] == 'u'
|
||||
? value_str.Remove(value_str.Length - 2).ToUShort()
|
||||
: value_str.Remove(value_str.Length - 1).ToShort();
|
||||
case 'u':
|
||||
return value_str.Remove(value_str.Length - 1).ToUInt();
|
||||
case 'i':
|
||||
return value_str[value_str.Length - 2] == 'u'
|
||||
? value_str.Remove(value_str.Length - 2).ToUInt()
|
||||
: value_str.Remove(value_str.Length - 1).ToInt();
|
||||
case 'l':
|
||||
return value_str[value_str.Length - 2] == 'u'
|
||||
? value_str.Remove(value_str.Length - 2).ToULong()
|
||||
: value_str.Remove(value_str.Length - 1).ToLong();
|
||||
case 'b':
|
||||
return value_str[value_str.Length - 2] == 's'
|
||||
? value_str.Remove(value_str.Length - 2).ToSByte()
|
||||
: value_str.Remove(value_str.Length - 1).ToByte();
|
||||
case 'f':
|
||||
return value_str.Remove(value_str.Length - 1).ToFloat();
|
||||
case 'e':
|
||||
return value_str[value_str.Length - 2] == 'd'
|
||||
? value_str.Remove(value_str.Length - 2).ToDecimal()
|
||||
: throw new Exception("can't parse value:" + value_str);
|
||||
default:
|
||||
if (value_str.Contains('.'))
|
||||
return (object)(value_str.ToDouble());
|
||||
else
|
||||
{
|
||||
try { return (object)(value_str.ToInt()); }
|
||||
catch (FormatException)
|
||||
{
|
||||
Log("r", $"can't parse value: {value_str}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
while (i < text.Length - 1)
|
||||
{
|
||||
c = text[++i];
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case '"':
|
||||
ReadString();
|
||||
break;
|
||||
case '\'':
|
||||
b.Append(c).Append(text[++i]);
|
||||
c = text[++i];
|
||||
if (c != '\'') throw new Exception("after <\'> should be char");
|
||||
else b.Append(c);
|
||||
break;
|
||||
case ';':
|
||||
case ',':
|
||||
string str = b.ToString();
|
||||
b.Clear();
|
||||
return ParseValue(str);
|
||||
case '[':
|
||||
return ReadList();
|
||||
case ']':
|
||||
endOfList = true;
|
||||
break;
|
||||
case '{':
|
||||
return ReadDtsod();
|
||||
case '=':
|
||||
case ':':
|
||||
case '}':
|
||||
case '$':
|
||||
throw new Exception($"DtsodV23.Deserialize() error: unexpected {c}");
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("DtsodV23.Deserialize.ReadValue() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
void SkipComment()
|
||||
{
|
||||
while (text[i] != '\n')
|
||||
if (++i >= text.Length) throw new Exception("DtsodV23.Deserialize() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
}
|
||||
|
||||
internal static readonly Dictionary<Type, Action<dynamic, StringBuilder>> TypeSerializeFuncs = new()
|
||||
{
|
||||
{ typeof(bool), (val, b) => b.Append(val.ToString()) },
|
||||
{ typeof(char), (val, b) => b.Append('\'').Append(val).Append('\'') },
|
||||
{ typeof(string), (val, b) => b.Append('"').Append(val.Replace("\\","\\\\").Replace("\"", "\\\"")).Append('"') },
|
||||
{ typeof(byte), (val, b) => b.Append(val.ToString()).Append('b') },
|
||||
{ typeof(sbyte), (val, b) => b.Append(val.ToString()).Append("sb") },
|
||||
{ typeof(short), (val, b) => b.Append(val.ToString()).Append('s') },
|
||||
{ typeof(ushort), (val, b) => b.Append(val.ToString()).Append("us") },
|
||||
{ typeof(int), (val, b) => b.Append(val.ToString()) },
|
||||
{ typeof(uint), (val, b) => b.Append(val.ToString()).Append("ui") },
|
||||
{ typeof(long), (val, b) => b.Append(val.ToString()).Append('l') },
|
||||
{ typeof(ulong), (val, b) => b.Append(val.ToString()).Append("ul") },
|
||||
{ typeof(float), (val, b) => b.Append(val.ToString(CultureInfo.InvariantCulture)).Append('f') },
|
||||
{ typeof(double), (val, b) => b.Append(val.ToString(CultureInfo.InvariantCulture)) },
|
||||
{ typeof(decimal), (val, b) => b.Append(val.ToString(CultureInfo.InvariantCulture)).Append("de") }
|
||||
};
|
||||
short tabscount = -1;
|
||||
protected StringBuilder Serialize(DtsodV23 dtsod, StringBuilder b = null)
|
||||
{
|
||||
tabscount++;
|
||||
if (b is null) b = new StringBuilder();
|
||||
foreach (var pair in dtsod)
|
||||
{
|
||||
b.Append('\t', tabscount).Append(pair.Key).Append(": ");
|
||||
SerializeType(pair.Value);
|
||||
b.Append(";\n");
|
||||
|
||||
void SerializeType(dynamic value)
|
||||
{
|
||||
if (value is null) b.Append("null");
|
||||
else if (value is IList _list)
|
||||
{
|
||||
b.Append('[');
|
||||
foreach (object el in _list)
|
||||
{
|
||||
SerializeType(el);
|
||||
b.Append(',');
|
||||
}
|
||||
b.Remove(b.Length - 1, 1).Append(']');
|
||||
}
|
||||
else if (value is DtsodV23 _dtsod)
|
||||
{
|
||||
b.Append("{\n");
|
||||
Serialize(_dtsod, b);
|
||||
b.Append('}');
|
||||
}
|
||||
else TypeSerializeFuncs[value.GetType()].Invoke(value, b);
|
||||
}
|
||||
}
|
||||
tabscount--;
|
||||
return b;
|
||||
}
|
||||
|
||||
public override string ToString() => Serialize(this).ToString();
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public enum DtsodVersion : byte
|
||||
{
|
||||
V21 = 21,
|
||||
V22 = 22,
|
||||
V23 = 23,
|
||||
V30 = 30
|
||||
}
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public enum DtsodVersion : byte
|
||||
{
|
||||
V21 = 21,
|
||||
V22 = 22,
|
||||
V23 = 23,
|
||||
V30 = 30
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public static class DtsodVersionConverter
|
||||
{
|
||||
public static IDtsod Convert(IDtsod src, DtsodVersion targetVersion)
|
||||
=> targetVersion switch
|
||||
{
|
||||
DtsodVersion.V21 => new DtsodV21(src.ToDictionary()),
|
||||
DtsodVersion.V22 => throw new NotImplementedException("Converting dtsods to V22 isn't implemented"),
|
||||
DtsodVersion.V23 => new DtsodV23(src.ToDictionary()),
|
||||
DtsodVersion.V30 => new DtsodV30(src.ToDictionary()),
|
||||
_ => throw new Exception($"DtsodVersionConverter.Convert() error: unknown target version <{targetVersion}>"),
|
||||
};
|
||||
}
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public static class DtsodVersionConverter
|
||||
{
|
||||
public static IDtsod Convert(IDtsod src, DtsodVersion targetVersion)
|
||||
=> targetVersion switch
|
||||
{
|
||||
DtsodVersion.V21 => new DtsodV21(src.ToDictionary()),
|
||||
DtsodVersion.V22 => throw new NotImplementedException("Converting dtsods to V22 isn't implemented"),
|
||||
DtsodVersion.V23 => new DtsodV23(src.ToDictionary()),
|
||||
DtsodVersion.V30 => new DtsodV30(src.ToDictionary()),
|
||||
_ => throw new Exception($"DtsodVersionConverter.Convert() error: unknown target version <{targetVersion}>"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public interface IDtsod
|
||||
{
|
||||
public DtsodVersion Version { get; }
|
||||
|
||||
public IDictionary<string, dynamic> ToDictionary();
|
||||
}
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public interface IDtsod
|
||||
{
|
||||
public DtsodVersion Version { get; }
|
||||
|
||||
public IDictionary<string, dynamic> ToDictionary();
|
||||
}
|
||||
|
||||
@@ -1,65 +1,65 @@
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public class DtsodDict<TKey, TVal> : IDictionary<TKey, TVal>
|
||||
{
|
||||
// да, вместо собственной реализации интерфейса это ссылки на Dictionary
|
||||
readonly Dictionary<TKey, TVal> baseDict;
|
||||
|
||||
public DtsodDict() => baseDict = new();
|
||||
public DtsodDict(IDictionary<TKey, TVal> srcDict) => baseDict = new(srcDict);
|
||||
|
||||
|
||||
public virtual TVal this[TKey key]
|
||||
{
|
||||
get => TryGetValue(key, out TVal value) ? value : throw new Exception($"Dtsod[{key}] key not found");
|
||||
set
|
||||
{
|
||||
if (!TrySetValue(key, value)) throw new KeyNotFoundException($"DtsodDict[{key}] key not found");
|
||||
}
|
||||
}
|
||||
|
||||
public virtual bool TryGetValue(TKey key, out TVal value) => baseDict.TryGetValue(key, out value);
|
||||
|
||||
public virtual bool TrySetValue(TKey key, TVal value)
|
||||
{
|
||||
if (ContainsKey(key))
|
||||
{
|
||||
baseDict[key] = value;
|
||||
return true;
|
||||
}
|
||||
else return false;
|
||||
}
|
||||
public virtual void Append(ICollection<KeyValuePair<TKey, TVal>> anotherDtsod)
|
||||
{
|
||||
foreach (KeyValuePair<TKey, TVal> pair in anotherDtsod)
|
||||
Add(pair.Key, pair.Value);
|
||||
}
|
||||
|
||||
public virtual void Add(TKey key, TVal value) => baseDict.Add(key, value);
|
||||
|
||||
public virtual void Add(KeyValuePair<TKey, TVal> pair)
|
||||
=> ((ICollection<KeyValuePair<TKey, TVal>>)baseDict).Add(pair);
|
||||
|
||||
|
||||
public int Count => baseDict.Count;
|
||||
public ICollection<TKey> Keys => baseDict.Keys;
|
||||
public ICollection<TVal> Values => baseDict.Values;
|
||||
public bool IsReadOnly { get; } = false;
|
||||
|
||||
public virtual void Clear() => baseDict.Clear();
|
||||
|
||||
public virtual bool ContainsKey(TKey key) => baseDict.ContainsKey(key);
|
||||
|
||||
bool ICollection<KeyValuePair<TKey, TVal>>.Contains(KeyValuePair<TKey, TVal> pair)
|
||||
=> ((ICollection<KeyValuePair<TKey, TVal>>)baseDict).Contains(pair);
|
||||
|
||||
void ICollection<KeyValuePair<TKey, TVal>>.CopyTo(KeyValuePair<TKey, TVal>[] array, int arrayIndex)
|
||||
=> ((ICollection<KeyValuePair<TKey, TVal>>)baseDict).CopyTo(array, arrayIndex);
|
||||
|
||||
public virtual bool Remove(TKey key) => baseDict.Remove(key);
|
||||
bool ICollection<KeyValuePair<TKey, TVal>>.Remove(KeyValuePair<TKey, TVal> pair)
|
||||
=> ((ICollection<KeyValuePair<TKey, TVal>>)baseDict).Remove(pair);
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator() => baseDict.GetEnumerator();
|
||||
public IEnumerator<KeyValuePair<TKey, TVal>> GetEnumerator() => baseDict.GetEnumerator();
|
||||
}
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public class DtsodDict<TKey, TVal> : IDictionary<TKey, TVal>
|
||||
{
|
||||
// да, вместо собственной реализации интерфейса это ссылки на Dictionary
|
||||
readonly Dictionary<TKey, TVal> baseDict;
|
||||
|
||||
public DtsodDict() => baseDict = new();
|
||||
public DtsodDict(IDictionary<TKey, TVal> srcDict) => baseDict = new(srcDict);
|
||||
|
||||
|
||||
public virtual TVal this[TKey key]
|
||||
{
|
||||
get => TryGetValue(key, out TVal value) ? value : throw new Exception($"Dtsod[{key}] key not found");
|
||||
set
|
||||
{
|
||||
if (!TrySetValue(key, value)) throw new KeyNotFoundException($"DtsodDict[{key}] key not found");
|
||||
}
|
||||
}
|
||||
|
||||
public virtual bool TryGetValue(TKey key, out TVal value) => baseDict.TryGetValue(key, out value);
|
||||
|
||||
public virtual bool TrySetValue(TKey key, TVal value)
|
||||
{
|
||||
if (ContainsKey(key))
|
||||
{
|
||||
baseDict[key] = value;
|
||||
return true;
|
||||
}
|
||||
else return false;
|
||||
}
|
||||
public virtual void Append(ICollection<KeyValuePair<TKey, TVal>> anotherDtsod)
|
||||
{
|
||||
foreach (KeyValuePair<TKey, TVal> pair in anotherDtsod)
|
||||
Add(pair.Key, pair.Value);
|
||||
}
|
||||
|
||||
public virtual void Add(TKey key, TVal value) => baseDict.Add(key, value);
|
||||
|
||||
public virtual void Add(KeyValuePair<TKey, TVal> pair)
|
||||
=> ((ICollection<KeyValuePair<TKey, TVal>>)baseDict).Add(pair);
|
||||
|
||||
|
||||
public int Count => baseDict.Count;
|
||||
public ICollection<TKey> Keys => baseDict.Keys;
|
||||
public ICollection<TVal> Values => baseDict.Values;
|
||||
public bool IsReadOnly { get; } = false;
|
||||
|
||||
public virtual void Clear() => baseDict.Clear();
|
||||
|
||||
public virtual bool ContainsKey(TKey key) => baseDict.ContainsKey(key);
|
||||
|
||||
bool ICollection<KeyValuePair<TKey, TVal>>.Contains(KeyValuePair<TKey, TVal> pair)
|
||||
=> ((ICollection<KeyValuePair<TKey, TVal>>)baseDict).Contains(pair);
|
||||
|
||||
void ICollection<KeyValuePair<TKey, TVal>>.CopyTo(KeyValuePair<TKey, TVal>[] array, int arrayIndex)
|
||||
=> ((ICollection<KeyValuePair<TKey, TVal>>)baseDict).CopyTo(array, arrayIndex);
|
||||
|
||||
public virtual bool Remove(TKey key) => baseDict.Remove(key);
|
||||
bool ICollection<KeyValuePair<TKey, TVal>>.Remove(KeyValuePair<TKey, TVal> pair)
|
||||
=> ((ICollection<KeyValuePair<TKey, TVal>>)baseDict).Remove(pair);
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator() => baseDict.GetEnumerator();
|
||||
public IEnumerator<KeyValuePair<TKey, TVal>> GetEnumerator() => baseDict.GetEnumerator();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public class DtsodSerializableAttribute : Attribute
|
||||
{
|
||||
public DtsodVersion Version;
|
||||
public DtsodSerializableAttribute(DtsodVersion ver) => Version = ver;
|
||||
}
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public class DtsodSerializableAttribute : Attribute
|
||||
{
|
||||
public DtsodVersion Version;
|
||||
public DtsodSerializableAttribute(DtsodVersion ver) => Version = ver;
|
||||
}
|
||||
|
||||
@@ -1,297 +1,297 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public class DtsodV30 : DtsodDict<string, dynamic>, IDtsod
|
||||
{
|
||||
public DtsodVersion Version { get; } = DtsodVersion.V30;
|
||||
|
||||
public IDictionary<string, dynamic> ToDictionary() => this;
|
||||
|
||||
public DtsodV30() : base() => UpdateLazy();
|
||||
public DtsodV30(IDictionary<string, dynamic> dict) : base(dict) => UpdateLazy();
|
||||
public DtsodV30(string serialized) : this() => Append(Deserialize(serialized));
|
||||
|
||||
static IDictionary<string, dynamic> Deserialize(string text)
|
||||
{
|
||||
char c;
|
||||
int i = -1; // ++i в ReadType
|
||||
StringBuilder b = new();
|
||||
|
||||
|
||||
Type ReadType()
|
||||
{
|
||||
|
||||
while (i < text.Length - 1)
|
||||
{
|
||||
c = text[++i];
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case ':':
|
||||
string _type = b.ToString();
|
||||
b.Clear();
|
||||
return TypeHelper.Instance.TypeFromString(_type);
|
||||
case '=':
|
||||
case '"':
|
||||
case '\'':
|
||||
case ';':
|
||||
case '[':
|
||||
case ']':
|
||||
case '{':
|
||||
case '}':
|
||||
throw new Exception($"DtsodV30.Deserialize() error: unexpected {c}");
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("DtsodV30.Deserialize.ReadType() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
string ReadName()
|
||||
{
|
||||
while (i < text.Length - 1)
|
||||
{
|
||||
c = text[++i];
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case '=':
|
||||
string _name = b.ToString();
|
||||
b.Clear();
|
||||
return _name;
|
||||
case ':':
|
||||
case '"':
|
||||
case '\'':
|
||||
case ';':
|
||||
case '[':
|
||||
case ']':
|
||||
case '{':
|
||||
case '}':
|
||||
throw new Exception($"DtsodV30.Deserialize() error: unexpected {c}");
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("DtsodV30.Deserialize.ReadName() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
object ReadValue(ref bool endoflist)
|
||||
{
|
||||
void ReadString()
|
||||
{
|
||||
c = text[++i]; //пропускает начальный символ '"'
|
||||
while ((c != '"' && c != '\'') || (text[i - 1] == '\\' && text[i - 2] != '\\'))
|
||||
{
|
||||
b.Append(c);
|
||||
if (++i >= text.Length) throw new Exception("DtsodV30.Deserialize() error: end of text\ntext:\n" + text);
|
||||
c = text[i];
|
||||
}
|
||||
}
|
||||
|
||||
List<object> ReadList()
|
||||
{
|
||||
List<object> list = new();
|
||||
bool _endoflist = false;
|
||||
while (!_endoflist)
|
||||
list.Add(CreateInstance(ReadType(), ReadValue(ref _endoflist)));
|
||||
b.Clear();
|
||||
return list;
|
||||
}
|
||||
|
||||
IDictionary<string, dynamic> ReadDictionary()
|
||||
{
|
||||
short bracketBalance = 1;
|
||||
c = text[++i]; //пропускает начальный символ '{'
|
||||
while (bracketBalance != 0)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case '{':
|
||||
bracketBalance++;
|
||||
b.Append(c);
|
||||
break;
|
||||
case '}':
|
||||
bracketBalance--;
|
||||
if (bracketBalance != 0)
|
||||
b.Append(c);
|
||||
break;
|
||||
case '"':
|
||||
case '\'':
|
||||
b.Append('"');
|
||||
ReadString();
|
||||
b.Append('"');
|
||||
break;
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
|
||||
if (++i >= text.Length) throw new Exception("DtsodV30.Deserialize() error: end of text\ntext:\n" + text);
|
||||
c = text[i];
|
||||
}
|
||||
|
||||
b.Clear();
|
||||
return Deserialize(b.ToString());
|
||||
}
|
||||
|
||||
while (i < text.Length-1)
|
||||
{
|
||||
c = text[++i];
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case '"':
|
||||
case '\'':
|
||||
ReadString();
|
||||
break;
|
||||
case ';': // один параметр
|
||||
case ',': // для листов
|
||||
string str = b.ToString();
|
||||
b.Clear();
|
||||
return str == "null" ? null : str;
|
||||
case '[':
|
||||
return ReadList();
|
||||
case ']':
|
||||
endoflist = true;
|
||||
goto case ',';
|
||||
case '{':
|
||||
return ReadDictionary();
|
||||
case '=':
|
||||
case ':':
|
||||
case '}':
|
||||
throw new Exception($"DtsodV30.Deserialize() error: unexpected {c}");
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("DtsodV30.Deserialize.ReadValue() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
void SkipComment()
|
||||
{
|
||||
while (text[i] != '\n')
|
||||
if (++i >= text.Length) throw new Exception("DtsodV30.Deserialize() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
object CreateInstance(Type type, object ctor_arg)
|
||||
{
|
||||
if (TypeHelper.Instance.BaseTypeConstructors.TryGetValue(type, out Func<string, dynamic> ctor))
|
||||
return (object)ctor.Invoke((string)ctor_arg);
|
||||
else if (type.CustomAttributes.Any(a => a.AttributeType == typeof(DtsodSerializableAttribute)))
|
||||
return Activator.CreateInstance(type, ((IDictionary<string, object>)ctor_arg).Values.ToArray());
|
||||
else if (typeof(ICollection).IsAssignableFrom(type))
|
||||
{
|
||||
var method_As = typeof(TypeHelper).GetMethod("As",
|
||||
System.Reflection.BindingFlags.Static |
|
||||
System.Reflection.BindingFlags.NonPublic)
|
||||
.MakeGenericMethod(type.GetGenericArguments()[0]);
|
||||
object collection = type.GetConstructor(Type.EmptyTypes).Invoke(null);
|
||||
var method_Add = type.GetMethod("Add");
|
||||
Log(method_Add.Name);
|
||||
foreach (object el in (IEnumerable)ctor_arg)
|
||||
{
|
||||
var pel = method_As.Invoke(null, new object[] { el });
|
||||
method_Add.Invoke(collection, new object[] { pel });
|
||||
}
|
||||
return collection;
|
||||
}
|
||||
else throw new Exception($"can't create instance of {type.FullName}");
|
||||
}
|
||||
|
||||
Dictionary<string, dynamic> output = new();
|
||||
Type type;
|
||||
string name;
|
||||
object value;
|
||||
|
||||
for (; i < text.Length; i++)
|
||||
{
|
||||
type = ReadType();
|
||||
name = ReadName();
|
||||
bool _ = false;
|
||||
value = ReadValue(ref _);
|
||||
output.Add(name, CreateInstance(type, value));
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
public override void Append(ICollection<KeyValuePair<string, dynamic>> anotherDtsod) => base.Append(anotherDtsod);//UpdateLazy();
|
||||
|
||||
public override void Add(string key, dynamic value) => base.Add(key, (object)value);//UpdateLazy();
|
||||
|
||||
protected static string Serialize(IDictionary<string, dynamic> dtsod, ushort tabsCount = 0)
|
||||
{
|
||||
StringBuilder b = new();
|
||||
foreach (KeyValuePair<string, dynamic> pair in dtsod)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void SerializeObject(string name, dynamic inst)
|
||||
{
|
||||
Type type = inst.GetType();
|
||||
b.Append(TypeHelper.Instance.TypeToString(type)).Append(':')
|
||||
.Append(name).Append('=');
|
||||
if (TypeHelper.Instance.BaseTypeNames.ContainsKey(type))
|
||||
{
|
||||
if (type == typeof(decimal) || type == typeof(double) || type == typeof(float))
|
||||
b.Append(inst.ToString(CultureInfo.InvariantCulture));
|
||||
else b.Append(inst.ToString());
|
||||
}
|
||||
else if (typeof(IDictionary<string, dynamic>).IsAssignableFrom(type))
|
||||
b.Append("\n{\n").Append(Serialize(inst, tabsCount++)).Append("};\n");
|
||||
else if (type.CustomAttributes.Any(a => a.AttributeType == typeof(DtsodSerializableAttribute)))
|
||||
{
|
||||
var props = type.GetProperties().Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(DtsodSerializableAttribute)));
|
||||
foreach (var prop in props)
|
||||
{
|
||||
var propval = prop.GetValue(inst);
|
||||
|
||||
}
|
||||
}
|
||||
else throw new Exception($"can't serialize type {type.FullName}");
|
||||
}
|
||||
|
||||
return b.ToString();
|
||||
}
|
||||
|
||||
protected Lazy<string> serialized;
|
||||
protected void UpdateLazy() => serialized = new(() => Serialize(this));
|
||||
public override string ToString() => serialized.Value;
|
||||
}
|
||||
using System.Globalization;
|
||||
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public class DtsodV30 : DtsodDict<string, dynamic>, IDtsod
|
||||
{
|
||||
public DtsodVersion Version { get; } = DtsodVersion.V30;
|
||||
|
||||
public IDictionary<string, dynamic> ToDictionary() => this;
|
||||
|
||||
public DtsodV30() : base() => UpdateLazy();
|
||||
public DtsodV30(IDictionary<string, dynamic> dict) : base(dict) => UpdateLazy();
|
||||
public DtsodV30(string serialized) : this() => Append(Deserialize(serialized));
|
||||
|
||||
static IDictionary<string, dynamic> Deserialize(string text)
|
||||
{
|
||||
char c;
|
||||
int i = -1; // ++i в ReadType
|
||||
StringBuilder b = new();
|
||||
|
||||
|
||||
Type ReadType()
|
||||
{
|
||||
|
||||
while (i < text.Length - 1)
|
||||
{
|
||||
c = text[++i];
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case ':':
|
||||
string _type = b.ToString();
|
||||
b.Clear();
|
||||
return TypeHelper.Instance.TypeFromString(_type);
|
||||
case '=':
|
||||
case '"':
|
||||
case '\'':
|
||||
case ';':
|
||||
case '[':
|
||||
case ']':
|
||||
case '{':
|
||||
case '}':
|
||||
throw new Exception($"DtsodV30.Deserialize() error: unexpected {c}");
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("DtsodV30.Deserialize.ReadType() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
string ReadName()
|
||||
{
|
||||
while (i < text.Length - 1)
|
||||
{
|
||||
c = text[++i];
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case '=':
|
||||
string _name = b.ToString();
|
||||
b.Clear();
|
||||
return _name;
|
||||
case ':':
|
||||
case '"':
|
||||
case '\'':
|
||||
case ';':
|
||||
case '[':
|
||||
case ']':
|
||||
case '{':
|
||||
case '}':
|
||||
throw new Exception($"DtsodV30.Deserialize() error: unexpected {c}");
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("DtsodV30.Deserialize.ReadName() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
object ReadValue(ref bool endoflist)
|
||||
{
|
||||
void ReadString()
|
||||
{
|
||||
c = text[++i]; //пропускает начальный символ '"'
|
||||
while ((c != '"' && c != '\'') || (text[i - 1] == '\\' && text[i - 2] != '\\'))
|
||||
{
|
||||
b.Append(c);
|
||||
if (++i >= text.Length) throw new Exception("DtsodV30.Deserialize() error: end of text\ntext:\n" + text);
|
||||
c = text[i];
|
||||
}
|
||||
}
|
||||
|
||||
List<object> ReadList()
|
||||
{
|
||||
List<object> list = new();
|
||||
bool _endoflist = false;
|
||||
while (!_endoflist)
|
||||
list.Add(CreateInstance(ReadType(), ReadValue(ref _endoflist)));
|
||||
b.Clear();
|
||||
return list;
|
||||
}
|
||||
|
||||
IDictionary<string, dynamic> ReadDictionary()
|
||||
{
|
||||
short bracketBalance = 1;
|
||||
c = text[++i]; //пропускает начальный символ '{'
|
||||
while (bracketBalance != 0)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case '{':
|
||||
bracketBalance++;
|
||||
b.Append(c);
|
||||
break;
|
||||
case '}':
|
||||
bracketBalance--;
|
||||
if (bracketBalance != 0)
|
||||
b.Append(c);
|
||||
break;
|
||||
case '"':
|
||||
case '\'':
|
||||
b.Append('"');
|
||||
ReadString();
|
||||
b.Append('"');
|
||||
break;
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
|
||||
if (++i >= text.Length) throw new Exception("DtsodV30.Deserialize() error: end of text\ntext:\n" + text);
|
||||
c = text[i];
|
||||
}
|
||||
|
||||
b.Clear();
|
||||
return Deserialize(b.ToString());
|
||||
}
|
||||
|
||||
while (i < text.Length-1)
|
||||
{
|
||||
c = text[++i];
|
||||
switch (c)
|
||||
{
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '#':
|
||||
SkipComment();
|
||||
break;
|
||||
case '"':
|
||||
case '\'':
|
||||
ReadString();
|
||||
break;
|
||||
case ';': // один параметр
|
||||
case ',': // для листов
|
||||
string str = b.ToString();
|
||||
b.Clear();
|
||||
return str == "null" ? null : str;
|
||||
case '[':
|
||||
return ReadList();
|
||||
case ']':
|
||||
endoflist = true;
|
||||
goto case ',';
|
||||
case '{':
|
||||
return ReadDictionary();
|
||||
case '=':
|
||||
case ':':
|
||||
case '}':
|
||||
throw new Exception($"DtsodV30.Deserialize() error: unexpected {c}");
|
||||
default:
|
||||
b.Append(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("DtsodV30.Deserialize.ReadValue() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
void SkipComment()
|
||||
{
|
||||
while (text[i] != '\n')
|
||||
if (++i >= text.Length) throw new Exception("DtsodV30.Deserialize() error: end of text\ntext:\n" + text);
|
||||
}
|
||||
|
||||
object CreateInstance(Type type, object ctor_arg)
|
||||
{
|
||||
if (TypeHelper.Instance.BaseTypeConstructors.TryGetValue(type, out Func<string, dynamic> ctor))
|
||||
return (object)ctor.Invoke((string)ctor_arg);
|
||||
else if (type.CustomAttributes.Any(a => a.AttributeType == typeof(DtsodSerializableAttribute)))
|
||||
return Activator.CreateInstance(type, ((IDictionary<string, object>)ctor_arg).Values.ToArray());
|
||||
else if (typeof(ICollection).IsAssignableFrom(type))
|
||||
{
|
||||
var method_As = typeof(TypeHelper).GetMethod("As",
|
||||
System.Reflection.BindingFlags.Static |
|
||||
System.Reflection.BindingFlags.NonPublic)
|
||||
.MakeGenericMethod(type.GetGenericArguments()[0]);
|
||||
object collection = type.GetConstructor(Type.EmptyTypes).Invoke(null);
|
||||
var method_Add = type.GetMethod("Add");
|
||||
Log(method_Add.Name);
|
||||
foreach (object el in (IEnumerable)ctor_arg)
|
||||
{
|
||||
var pel = method_As.Invoke(null, new object[] { el });
|
||||
method_Add.Invoke(collection, new object[] { pel });
|
||||
}
|
||||
return collection;
|
||||
}
|
||||
else throw new Exception($"can't create instance of {type.FullName}");
|
||||
}
|
||||
|
||||
Dictionary<string, dynamic> output = new();
|
||||
Type type;
|
||||
string name;
|
||||
object value;
|
||||
|
||||
for (; i < text.Length; i++)
|
||||
{
|
||||
type = ReadType();
|
||||
name = ReadName();
|
||||
bool _ = false;
|
||||
value = ReadValue(ref _);
|
||||
output.Add(name, CreateInstance(type, value));
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
public override void Append(ICollection<KeyValuePair<string, dynamic>> anotherDtsod) => base.Append(anotherDtsod);//UpdateLazy();
|
||||
|
||||
public override void Add(string key, dynamic value) => base.Add(key, (object)value);//UpdateLazy();
|
||||
|
||||
protected static string Serialize(IDictionary<string, dynamic> dtsod, ushort tabsCount = 0)
|
||||
{
|
||||
StringBuilder b = new();
|
||||
foreach (KeyValuePair<string, dynamic> pair in dtsod)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void SerializeObject(string name, dynamic inst)
|
||||
{
|
||||
Type type = inst.GetType();
|
||||
b.Append(TypeHelper.Instance.TypeToString(type)).Append(':')
|
||||
.Append(name).Append('=');
|
||||
if (TypeHelper.Instance.BaseTypeNames.ContainsKey(type))
|
||||
{
|
||||
if (type == typeof(decimal) || type == typeof(double) || type == typeof(float))
|
||||
b.Append(inst.ToString(CultureInfo.InvariantCulture));
|
||||
else b.Append(inst.ToString());
|
||||
}
|
||||
else if (typeof(IDictionary<string, dynamic>).IsAssignableFrom(type))
|
||||
b.Append("\n{\n").Append(Serialize(inst, tabsCount++)).Append("};\n");
|
||||
else if (type.CustomAttributes.Any(a => a.AttributeType == typeof(DtsodSerializableAttribute)))
|
||||
{
|
||||
var props = type.GetProperties().Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(DtsodSerializableAttribute)));
|
||||
foreach (var prop in props)
|
||||
{
|
||||
var propval = prop.GetValue(inst);
|
||||
|
||||
}
|
||||
}
|
||||
else throw new Exception($"can't serialize type {type.FullName}");
|
||||
}
|
||||
|
||||
return b.ToString();
|
||||
}
|
||||
|
||||
protected Lazy<string> serialized;
|
||||
protected void UpdateLazy() => serialized = new(() => Serialize(this));
|
||||
public override string ToString() => serialized.Value;
|
||||
}
|
||||
|
||||
@@ -1,114 +1,114 @@
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public class TypeHelper
|
||||
{
|
||||
static Lazy<TypeHelper> _inst = new();
|
||||
public static TypeHelper Instance => _inst.Value;
|
||||
|
||||
internal readonly Dictionary<Type, Func<string, dynamic>> BaseTypeConstructors = new()
|
||||
{
|
||||
{ typeof(bool), (inp) => inp.ToBool() },
|
||||
{ typeof(char), (inp) => inp.ToChar() },
|
||||
{ typeof(string), (inp) => inp.ToString() },
|
||||
{ typeof(byte), (inp) => inp.ToByte() },
|
||||
{ typeof(sbyte), (inp) => inp.ToSByte() },
|
||||
{ typeof(short), (inp) => inp.ToShort() },
|
||||
{ typeof(ushort), (inp) => inp.ToUShort() },
|
||||
{ typeof(int), (inp) => inp.ToInt() },
|
||||
{ typeof(uint), (inp) => inp.ToUInt() },
|
||||
{ typeof(long), (inp) => inp.ToLong() },
|
||||
{ typeof(ulong), (inp) => inp.ToULong() },
|
||||
{ typeof(float), (inp) => inp.ToFloat() },
|
||||
{ typeof(double), (inp) => inp.ToDouble() },
|
||||
{ typeof(decimal), (inp) => inp.ToDecimal() }
|
||||
};
|
||||
|
||||
internal Dictionary<Type, string> BaseTypeNames = new()
|
||||
{
|
||||
{ typeof(bool), "bool" },
|
||||
{ typeof(char), "char" },
|
||||
{ typeof(string), "string" },
|
||||
{ typeof(byte), "byte" },
|
||||
{ typeof(sbyte), "sbyte" },
|
||||
{ typeof(short), "short" },
|
||||
{ typeof(ushort), "ushort" },
|
||||
{ typeof(int), "int" },
|
||||
{ typeof(uint), "uint" },
|
||||
{ typeof(long), "long" },
|
||||
{ typeof(ulong), "ulong" },
|
||||
{ typeof(float), "float" },
|
||||
{ typeof(double), "double" },
|
||||
{ typeof(decimal), "decimal" }
|
||||
};
|
||||
|
||||
private DtsodDict<string, Type> ST_extensions = new()
|
||||
{
|
||||
{ "List<bool>", typeof(List<bool>) },
|
||||
{ "List<char>", typeof(List<char>) },
|
||||
{ "List<string>", typeof(List<string>) },
|
||||
{ "List<byte>", typeof(List<byte>) },
|
||||
{ "List<sbyte>", typeof(List<sbyte>) },
|
||||
{ "List<short>", typeof(List<short>) },
|
||||
{ "List<ushort>", typeof(List<ushort>) },
|
||||
{ "List<int>", typeof(List<int>) },
|
||||
{ "List<uint>", typeof(List<uint>) },
|
||||
{ "List<long>", typeof(List<long>) },
|
||||
{ "List<ulong>", typeof(List<ulong>) },
|
||||
{ "List<float>", typeof(List<float>) },
|
||||
{ "List<double>", typeof(List<double>) },
|
||||
{ "List<decimal>", typeof(List<decimal>) },
|
||||
};
|
||||
private DtsodDict<Type, string> TS_extensions = new()
|
||||
{
|
||||
{ typeof(List<bool>), "List<bool>" },
|
||||
{ typeof(List<char>), "List<char>" },
|
||||
{ typeof(List<string>), "List<string>" },
|
||||
{ typeof(List<byte>), "List<byte>" },
|
||||
{ typeof(List<sbyte>), "List<sbyte>" },
|
||||
{ typeof(List<short>), "List<short>" },
|
||||
{ typeof(List<ushort>), "List<ushort>" },
|
||||
{ typeof(List<int>), "List<int>" },
|
||||
{ typeof(List<uint>), "List<uint>" },
|
||||
{ typeof(List<long>), "List<long>" },
|
||||
{ typeof(List<ulong>), "List<ulong>" },
|
||||
{ typeof(List<float>), "List<float>" },
|
||||
{ typeof(List<double>), "List<double>" },
|
||||
{ typeof(List<decimal>), "List<decimal>" },
|
||||
};
|
||||
|
||||
public TypeHelper Extend(string name, Type type)
|
||||
{
|
||||
ST_extensions.Add(name, type);
|
||||
TS_extensions.Add(type, name);
|
||||
return this;
|
||||
}
|
||||
|
||||
public string TypeToString(Type t) =>
|
||||
BaseTypeNames.TryGetValue(t, out string name)
|
||||
? name
|
||||
: TS_extensions.TryGetValue(t, out name)
|
||||
? name
|
||||
: t.FullName;
|
||||
public Type TypeFromString(string str) => str switch
|
||||
{
|
||||
"bool" => typeof(bool),
|
||||
"char" => typeof(char),
|
||||
"string" => typeof(string),
|
||||
"byte" => typeof(byte),
|
||||
"sbyte" => typeof(sbyte),
|
||||
"short" => typeof(short),
|
||||
"ushort" => typeof(ushort),
|
||||
"int" => typeof(int),
|
||||
"uint" => typeof(uint),
|
||||
"long" => typeof(long),
|
||||
"ulong" => typeof(ulong),
|
||||
"float" => typeof(float),
|
||||
"double" => typeof(double),
|
||||
"decimal" => typeof(decimal),
|
||||
_ => ST_extensions.TryGetValue(str, out var t)
|
||||
? t
|
||||
: Type.GetType(str, false)
|
||||
?? throw new Exception($"DtsodV30.Deserialize.ParseType() error: type {str} doesn't exists")
|
||||
};
|
||||
static internal T As<T>(object inst) where T : class => inst as T;
|
||||
}
|
||||
namespace DTLib.Dtsod;
|
||||
|
||||
public class TypeHelper
|
||||
{
|
||||
static Lazy<TypeHelper> _inst = new();
|
||||
public static TypeHelper Instance => _inst.Value;
|
||||
|
||||
internal readonly Dictionary<Type, Func<string, dynamic>> BaseTypeConstructors = new()
|
||||
{
|
||||
{ typeof(bool), (inp) => inp.ToBool() },
|
||||
{ typeof(char), (inp) => inp.ToChar() },
|
||||
{ typeof(string), (inp) => inp.ToString() },
|
||||
{ typeof(byte), (inp) => inp.ToByte() },
|
||||
{ typeof(sbyte), (inp) => inp.ToSByte() },
|
||||
{ typeof(short), (inp) => inp.ToShort() },
|
||||
{ typeof(ushort), (inp) => inp.ToUShort() },
|
||||
{ typeof(int), (inp) => inp.ToInt() },
|
||||
{ typeof(uint), (inp) => inp.ToUInt() },
|
||||
{ typeof(long), (inp) => inp.ToLong() },
|
||||
{ typeof(ulong), (inp) => inp.ToULong() },
|
||||
{ typeof(float), (inp) => inp.ToFloat() },
|
||||
{ typeof(double), (inp) => inp.ToDouble() },
|
||||
{ typeof(decimal), (inp) => inp.ToDecimal() }
|
||||
};
|
||||
|
||||
internal Dictionary<Type, string> BaseTypeNames = new()
|
||||
{
|
||||
{ typeof(bool), "bool" },
|
||||
{ typeof(char), "char" },
|
||||
{ typeof(string), "string" },
|
||||
{ typeof(byte), "byte" },
|
||||
{ typeof(sbyte), "sbyte" },
|
||||
{ typeof(short), "short" },
|
||||
{ typeof(ushort), "ushort" },
|
||||
{ typeof(int), "int" },
|
||||
{ typeof(uint), "uint" },
|
||||
{ typeof(long), "long" },
|
||||
{ typeof(ulong), "ulong" },
|
||||
{ typeof(float), "float" },
|
||||
{ typeof(double), "double" },
|
||||
{ typeof(decimal), "decimal" }
|
||||
};
|
||||
|
||||
private DtsodDict<string, Type> ST_extensions = new()
|
||||
{
|
||||
{ "List<bool>", typeof(List<bool>) },
|
||||
{ "List<char>", typeof(List<char>) },
|
||||
{ "List<string>", typeof(List<string>) },
|
||||
{ "List<byte>", typeof(List<byte>) },
|
||||
{ "List<sbyte>", typeof(List<sbyte>) },
|
||||
{ "List<short>", typeof(List<short>) },
|
||||
{ "List<ushort>", typeof(List<ushort>) },
|
||||
{ "List<int>", typeof(List<int>) },
|
||||
{ "List<uint>", typeof(List<uint>) },
|
||||
{ "List<long>", typeof(List<long>) },
|
||||
{ "List<ulong>", typeof(List<ulong>) },
|
||||
{ "List<float>", typeof(List<float>) },
|
||||
{ "List<double>", typeof(List<double>) },
|
||||
{ "List<decimal>", typeof(List<decimal>) },
|
||||
};
|
||||
private DtsodDict<Type, string> TS_extensions = new()
|
||||
{
|
||||
{ typeof(List<bool>), "List<bool>" },
|
||||
{ typeof(List<char>), "List<char>" },
|
||||
{ typeof(List<string>), "List<string>" },
|
||||
{ typeof(List<byte>), "List<byte>" },
|
||||
{ typeof(List<sbyte>), "List<sbyte>" },
|
||||
{ typeof(List<short>), "List<short>" },
|
||||
{ typeof(List<ushort>), "List<ushort>" },
|
||||
{ typeof(List<int>), "List<int>" },
|
||||
{ typeof(List<uint>), "List<uint>" },
|
||||
{ typeof(List<long>), "List<long>" },
|
||||
{ typeof(List<ulong>), "List<ulong>" },
|
||||
{ typeof(List<float>), "List<float>" },
|
||||
{ typeof(List<double>), "List<double>" },
|
||||
{ typeof(List<decimal>), "List<decimal>" },
|
||||
};
|
||||
|
||||
public TypeHelper Extend(string name, Type type)
|
||||
{
|
||||
ST_extensions.Add(name, type);
|
||||
TS_extensions.Add(type, name);
|
||||
return this;
|
||||
}
|
||||
|
||||
public string TypeToString(Type t) =>
|
||||
BaseTypeNames.TryGetValue(t, out string name)
|
||||
? name
|
||||
: TS_extensions.TryGetValue(t, out name)
|
||||
? name
|
||||
: t.FullName;
|
||||
public Type TypeFromString(string str) => str switch
|
||||
{
|
||||
"bool" => typeof(bool),
|
||||
"char" => typeof(char),
|
||||
"string" => typeof(string),
|
||||
"byte" => typeof(byte),
|
||||
"sbyte" => typeof(sbyte),
|
||||
"short" => typeof(short),
|
||||
"ushort" => typeof(ushort),
|
||||
"int" => typeof(int),
|
||||
"uint" => typeof(uint),
|
||||
"long" => typeof(long),
|
||||
"ulong" => typeof(ulong),
|
||||
"float" => typeof(float),
|
||||
"double" => typeof(double),
|
||||
"decimal" => typeof(decimal),
|
||||
_ => ST_extensions.TryGetValue(str, out var t)
|
||||
? t
|
||||
: Type.GetType(str, false)
|
||||
?? throw new Exception($"DtsodV30.Deserialize.ParseType() error: type {str} doesn't exists")
|
||||
};
|
||||
static internal T As<T>(object inst) where T : class => inst as T;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
namespace DTLib;
|
||||
|
||||
// по идее это нужно, чтоб делать так: SomeEvent?.Invoke().Wait()
|
||||
public delegate Task EventHandlerAsyncDelegate();
|
||||
public delegate Task EventHandlerAsyncDelegate<T>(T e);
|
||||
public delegate Task EventHandlerAsyncDelegate<T0, T1>(T0 e0, T1 e1);
|
||||
public delegate Task EventHandlerAsyncDelegate<T0, T1, T2>(T0 e0, T1 e1, T2 e2);
|
||||
public delegate Task EventHandlerAsyncDelegate<T0, T1, T2, T3>(T0 e0, T1 e1, T2 e2, T3 e3);
|
||||
namespace DTLib;
|
||||
|
||||
// по идее это нужно, чтоб делать так: SomeEvent?.Invoke().Wait()
|
||||
public delegate Task EventHandlerAsyncDelegate();
|
||||
public delegate Task EventHandlerAsyncDelegate<T>(T e);
|
||||
public delegate Task EventHandlerAsyncDelegate<T0, T1>(T0 e0, T1 e1);
|
||||
public delegate Task EventHandlerAsyncDelegate<T0, T1, T2>(T0 e0, T1 e1, T2 e2);
|
||||
public delegate Task EventHandlerAsyncDelegate<T0, T1, T2, T3>(T0 e0, T1 e1, T2 e2, T3 e3);
|
||||
|
||||
@@ -1,70 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
public class CompressedArray
|
||||
{
|
||||
public class Array1D<T> where T : IComparable<T>
|
||||
{
|
||||
byte[] Description;
|
||||
T[] Memory;
|
||||
|
||||
public Array1D() { }
|
||||
public Array1D(T[] sourceArray) => CompressArray(sourceArray);
|
||||
|
||||
public void CompressArray(T[] sourceArray)
|
||||
{
|
||||
var listMem = new List<T>();
|
||||
var listDesc = new List<byte>();
|
||||
T prevElement = sourceArray[0];
|
||||
listMem.Add(sourceArray[0]);
|
||||
listDesc.Add(1);
|
||||
byte repeats = 1;
|
||||
for (int i = 1; i < sourceArray.Length; i++)
|
||||
{
|
||||
if (prevElement.CompareTo(sourceArray[i]) == 0)
|
||||
repeats++;
|
||||
else
|
||||
{
|
||||
listMem.Add(sourceArray[i]);
|
||||
listDesc.Add(1);
|
||||
if (repeats > 1)
|
||||
{
|
||||
listDesc[listDesc.Count - 2] = repeats;
|
||||
repeats = 1;
|
||||
}
|
||||
}
|
||||
prevElement = sourceArray[i];
|
||||
}
|
||||
Memory = listMem.ToArray();
|
||||
Description = listDesc.ToArray();
|
||||
ColoredConsole.Write("b", "listMem.Count: ", "c", listMem.Count.ToString(), "b", " listDesc.Count: ", "c", listDesc.Count + "\n");
|
||||
for (short i = 0; i < listDesc.Count; i++)
|
||||
{
|
||||
ColoredConsole.Write("y", $"{Description[i]}:{Memory[i]}\n");
|
||||
}
|
||||
}
|
||||
|
||||
// блокирует обращение к памяти из нескольких потоков
|
||||
Mutex storageUsing = new();
|
||||
|
||||
// возвращает элемент по индексу так, как если бы шло обращение к обычном массиву
|
||||
public T GetElement(int index)
|
||||
{
|
||||
storageUsing.WaitOne();
|
||||
T output = default;
|
||||
int sum = 0;
|
||||
for (int i = 0; i < Description.Length; i++)
|
||||
{
|
||||
if (sum < index)
|
||||
sum += Description[i];
|
||||
else output = sum == index ? Memory[i] : Memory[i - 1];
|
||||
}
|
||||
storageUsing.ReleaseMutex();
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
public class CompressedArray
|
||||
{
|
||||
public class Array1D<T> where T : IComparable<T>
|
||||
{
|
||||
byte[] Description;
|
||||
T[] Memory;
|
||||
|
||||
public Array1D() { }
|
||||
public Array1D(T[] sourceArray) => CompressArray(sourceArray);
|
||||
|
||||
public void CompressArray(T[] sourceArray)
|
||||
{
|
||||
var listMem = new List<T>();
|
||||
var listDesc = new List<byte>();
|
||||
T prevElement = sourceArray[0];
|
||||
listMem.Add(sourceArray[0]);
|
||||
listDesc.Add(1);
|
||||
byte repeats = 1;
|
||||
for (int i = 1; i < sourceArray.Length; i++)
|
||||
{
|
||||
if (prevElement.CompareTo(sourceArray[i]) == 0)
|
||||
repeats++;
|
||||
else
|
||||
{
|
||||
listMem.Add(sourceArray[i]);
|
||||
listDesc.Add(1);
|
||||
if (repeats > 1)
|
||||
{
|
||||
listDesc[listDesc.Count - 2] = repeats;
|
||||
repeats = 1;
|
||||
}
|
||||
}
|
||||
prevElement = sourceArray[i];
|
||||
}
|
||||
Memory = listMem.ToArray();
|
||||
Description = listDesc.ToArray();
|
||||
ColoredConsole.Write("b", "listMem.Count: ", "c", listMem.Count.ToString(), "b", " listDesc.Count: ", "c", listDesc.Count + "\n");
|
||||
for (short i = 0; i < listDesc.Count; i++)
|
||||
{
|
||||
ColoredConsole.Write("y", $"{Description[i]}:{Memory[i]}\n");
|
||||
}
|
||||
}
|
||||
|
||||
// блокирует обращение к памяти из нескольких потоков
|
||||
Mutex storageUsing = new();
|
||||
|
||||
// возвращает элемент по индексу так, как если бы шло обращение к обычном массиву
|
||||
public T GetElement(int index)
|
||||
{
|
||||
storageUsing.WaitOne();
|
||||
T output = default;
|
||||
int sum = 0;
|
||||
for (int i = 0; i < Description.Length; i++)
|
||||
{
|
||||
if (sum < index)
|
||||
sum += Description[i];
|
||||
else output = sum == index ? Memory[i] : Memory[i - 1];
|
||||
}
|
||||
storageUsing.ReleaseMutex();
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,69 +1,69 @@
|
||||
using DTLib.Dtsod;
|
||||
using DTLib.Filesystem;
|
||||
using System.Collections.Generic;
|
||||
using static DTLib.PublicLog;
|
||||
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
public class Container : List<IDrawable>, IDrawable
|
||||
{
|
||||
public (ushort x, ushort y) AnchorPoint { get; set; }
|
||||
public ushort Width { get; set; }
|
||||
public ushort Height { get; set; }
|
||||
public char[] Textmap { get; private set; }
|
||||
public char[] Colormap { get; private set; }
|
||||
public string Name { get; private set; }
|
||||
|
||||
public Container(string name, string layout_file)
|
||||
{
|
||||
Name=name;
|
||||
ParseLayoutFile(layout_file);
|
||||
}
|
||||
|
||||
void ParseLayoutFile(string layout_file)
|
||||
{
|
||||
DtsodV22 layout = new(File.ReadAllText(layout_file));
|
||||
AnchorPoint=(layout[Name]["anchor"][0], layout[Name]["anchor"][1]);
|
||||
Width=layout[Name]["width"];
|
||||
Height=layout[Name]["height"];
|
||||
foreach(string element_name in layout[Name]["children"].Keys)
|
||||
{
|
||||
switch(layout[Name]["children"][element_name]["type"])
|
||||
{
|
||||
case "label":
|
||||
Add(new Label(element_name,
|
||||
layout[Name]["children"][element_name]["resdir"]+$"\\{element_name}.textmap",
|
||||
layout[Name]["children"][element_name]["resdir"]+$"\\{element_name}.colormap")
|
||||
{
|
||||
AnchorPoint=(layout[Name]["children"][element_name]["anchor"][0],
|
||||
layout[Name]["children"][element_name]["anchor"][1])
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void GenTextmap()
|
||||
{
|
||||
Textmap=new char[Width*Height];
|
||||
for(int i = 0; i<Textmap.Length; i++)
|
||||
Textmap[i]=' ';
|
||||
foreach(IDrawable element in this)
|
||||
{
|
||||
element.GenTextmap();
|
||||
Log("m", $"Length: {element.Textmap.Length} calculated: {element.Width*element.Height}\n");
|
||||
for(ushort y = 0; y<element.Height; y++)
|
||||
for(ushort x = 0; x<element.Width; x++)
|
||||
{
|
||||
//Textmap[(element.AnchorPoint.y + y) * Width + element.AnchorPoint.x + x] = element.Textmap[y * element.Width + x];
|
||||
Textmap[(y)*Width+x]=element.Textmap[y*element.Width+x];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void GenColormap()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
using DTLib.Dtsod;
|
||||
using DTLib.Filesystem;
|
||||
using System.Collections.Generic;
|
||||
using static DTLib.PublicLog;
|
||||
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
public class Container : List<IDrawable>, IDrawable
|
||||
{
|
||||
public (ushort x, ushort y) AnchorPoint { get; set; }
|
||||
public ushort Width { get; set; }
|
||||
public ushort Height { get; set; }
|
||||
public char[] Textmap { get; private set; }
|
||||
public char[] Colormap { get; private set; }
|
||||
public string Name { get; private set; }
|
||||
|
||||
public Container(string name, string layout_file)
|
||||
{
|
||||
Name=name;
|
||||
ParseLayoutFile(layout_file);
|
||||
}
|
||||
|
||||
void ParseLayoutFile(string layout_file)
|
||||
{
|
||||
DtsodV22 layout = new(File.ReadAllText(layout_file));
|
||||
AnchorPoint=(layout[Name]["anchor"][0], layout[Name]["anchor"][1]);
|
||||
Width=layout[Name]["width"];
|
||||
Height=layout[Name]["height"];
|
||||
foreach(string element_name in layout[Name]["children"].Keys)
|
||||
{
|
||||
switch(layout[Name]["children"][element_name]["type"])
|
||||
{
|
||||
case "label":
|
||||
Add(new Label(element_name,
|
||||
layout[Name]["children"][element_name]["resdir"]+$"\\{element_name}.textmap",
|
||||
layout[Name]["children"][element_name]["resdir"]+$"\\{element_name}.colormap")
|
||||
{
|
||||
AnchorPoint=(layout[Name]["children"][element_name]["anchor"][0],
|
||||
layout[Name]["children"][element_name]["anchor"][1])
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void GenTextmap()
|
||||
{
|
||||
Textmap=new char[Width*Height];
|
||||
for(int i = 0; i<Textmap.Length; i++)
|
||||
Textmap[i]=' ';
|
||||
foreach(IDrawable element in this)
|
||||
{
|
||||
element.GenTextmap();
|
||||
Log("m", $"Length: {element.Textmap.Length} calculated: {element.Width*element.Height}\n");
|
||||
for(ushort y = 0; y<element.Height; y++)
|
||||
for(ushort x = 0; x<element.Width; x++)
|
||||
{
|
||||
//Textmap[(element.AnchorPoint.y + y) * Width + element.AnchorPoint.x + x] = element.Textmap[y * element.Width + x];
|
||||
Textmap[(y)*Width+x]=element.Textmap[y*element.Width+x];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void GenColormap()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
public class Control : Label
|
||||
{
|
||||
|
||||
public new void GenColormap()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public new void GenTextmap()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
public class Control : Label
|
||||
{
|
||||
|
||||
public new void GenColormap()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public new void GenTextmap()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
public interface IDrawable
|
||||
{
|
||||
public (ushort x, ushort y) AnchorPoint { get; set; }
|
||||
public ushort Width { get; }
|
||||
public ushort Height { get; }
|
||||
public char[] Textmap { get; }
|
||||
public char[] Colormap { get; }
|
||||
public string Name { get; }
|
||||
|
||||
public void GenTextmap();
|
||||
|
||||
public void GenColormap();
|
||||
|
||||
}
|
||||
}
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
public interface IDrawable
|
||||
{
|
||||
public (ushort x, ushort y) AnchorPoint { get; set; }
|
||||
public ushort Width { get; }
|
||||
public ushort Height { get; }
|
||||
public char[] Textmap { get; }
|
||||
public char[] Colormap { get; }
|
||||
public string Name { get; }
|
||||
|
||||
public void GenTextmap();
|
||||
|
||||
public void GenColormap();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,35 +1,35 @@
|
||||
using DTLib.Filesystem;
|
||||
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
public class Label : IDrawable
|
||||
{
|
||||
public (ushort x, ushort y) AnchorPoint { get; set; } = (0, 0);
|
||||
public ushort Width { get; private set; }
|
||||
public ushort Height { get; private set; }
|
||||
public char[] Textmap { get; private set; }
|
||||
public char[] Colormap { get; private set; }
|
||||
|
||||
public string TextmapFile { get; set; }
|
||||
public string ColormapFile { get; set; }
|
||||
public string Name { get; init; }
|
||||
|
||||
public Label() { }
|
||||
|
||||
public Label(string name, string textmapFile, string colormapFile)
|
||||
{
|
||||
TextmapFile=textmapFile;
|
||||
ColormapFile=colormapFile;
|
||||
Name=name;
|
||||
}
|
||||
|
||||
public void GenColormap() => Colormap=File.ReadAllText(ColormapFile).ToCharArray();
|
||||
|
||||
public void GenTextmap()
|
||||
{
|
||||
Textmap=File.ReadAllText(TextmapFile).ToCharArray();
|
||||
Width=12;
|
||||
Height=3;
|
||||
}
|
||||
}
|
||||
}
|
||||
using DTLib.Filesystem;
|
||||
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
public class Label : IDrawable
|
||||
{
|
||||
public (ushort x, ushort y) AnchorPoint { get; set; } = (0, 0);
|
||||
public ushort Width { get; private set; }
|
||||
public ushort Height { get; private set; }
|
||||
public char[] Textmap { get; private set; }
|
||||
public char[] Colormap { get; private set; }
|
||||
|
||||
public string TextmapFile { get; set; }
|
||||
public string ColormapFile { get; set; }
|
||||
public string Name { get; init; }
|
||||
|
||||
public Label() { }
|
||||
|
||||
public Label(string name, string textmapFile, string colormapFile)
|
||||
{
|
||||
TextmapFile=textmapFile;
|
||||
ColormapFile=colormapFile;
|
||||
Name=name;
|
||||
}
|
||||
|
||||
public void GenColormap() => Colormap=File.ReadAllText(ColormapFile).ToCharArray();
|
||||
|
||||
public void GenTextmap()
|
||||
{
|
||||
Textmap=File.ReadAllText(TextmapFile).ToCharArray();
|
||||
Width=12;
|
||||
Height=3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
using DTLib.Filesystem;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
//
|
||||
// создание gui из текста в консоли
|
||||
//
|
||||
public class Window : Container
|
||||
{
|
||||
|
||||
public Window(string layout_file) : base("window", layout_file)
|
||||
{
|
||||
Console.Clear();
|
||||
Console.SetWindowSize(Width+1, Height+1);
|
||||
Console.SetBufferSize(Width+1, Height+1);
|
||||
Console.OutputEncoding=Encoding.Unicode;
|
||||
Console.InputEncoding=Encoding.Unicode;
|
||||
Console.CursorVisible=false;
|
||||
}
|
||||
|
||||
// выводит все символы
|
||||
public void RenderFile(string file)
|
||||
{
|
||||
Console.Clear();
|
||||
Console.WriteLine(File.ReadAllText(file));
|
||||
}
|
||||
|
||||
public void Render()
|
||||
{
|
||||
GenTextmap();
|
||||
Console.WriteLine(SimpleConverter.MergeToString(Textmap));
|
||||
}
|
||||
}
|
||||
}
|
||||
using DTLib.Filesystem;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
//
|
||||
// создание gui из текста в консоли
|
||||
//
|
||||
public class Window : Container
|
||||
{
|
||||
|
||||
public Window(string layout_file) : base("window", layout_file)
|
||||
{
|
||||
Console.Clear();
|
||||
Console.SetWindowSize(Width+1, Height+1);
|
||||
Console.SetBufferSize(Width+1, Height+1);
|
||||
Console.OutputEncoding=Encoding.Unicode;
|
||||
Console.InputEncoding=Encoding.Unicode;
|
||||
Console.CursorVisible=false;
|
||||
}
|
||||
|
||||
// выводит все символы
|
||||
public void RenderFile(string file)
|
||||
{
|
||||
Console.Clear();
|
||||
Console.WriteLine(File.ReadAllText(file));
|
||||
}
|
||||
|
||||
public void Render()
|
||||
{
|
||||
GenTextmap();
|
||||
Console.WriteLine(SimpleConverter.MergeToString(Textmap));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,186 +1,186 @@
|
||||
using DTLib.Filesystem;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
//
|
||||
// создание gui из текста в консоли
|
||||
//
|
||||
public class WindowOld
|
||||
{
|
||||
public int WindowWidth { get; private set; }
|
||||
public int WindowHeight { get; private set; }
|
||||
public char[,] Text;
|
||||
public char[,] nowText;
|
||||
public char[,] TextColors;
|
||||
public char[,] nowTextColors;
|
||||
|
||||
public Container WindowContainer;
|
||||
|
||||
public WindowOld(int windowWidth, int windowHeight)
|
||||
{
|
||||
WindowWidth=windowWidth;
|
||||
WindowHeight=windowHeight;
|
||||
Text=new char[windowWidth, windowHeight];
|
||||
TextColors=new char[windowWidth, windowHeight];
|
||||
nowText=TextColors;
|
||||
nowTextColors=new char[windowWidth, windowHeight];
|
||||
Console.WindowWidth=WindowWidth+1;
|
||||
Console.WindowHeight=WindowHeight+1;
|
||||
Console.BufferWidth=WindowWidth+1;
|
||||
Console.BufferHeight=WindowHeight+1;
|
||||
Console.OutputEncoding=Encoding.Unicode;
|
||||
Console.InputEncoding=Encoding.Unicode;
|
||||
Console.CursorVisible=false;
|
||||
// заполнение массивов
|
||||
for(sbyte y = 0; y<WindowHeight; y++)
|
||||
{
|
||||
for(sbyte x = 0; x<WindowWidth; x++)
|
||||
{
|
||||
Text[x, y]=' ';
|
||||
TextColors[x, y]='w';
|
||||
}
|
||||
}
|
||||
nowText=TextColors;
|
||||
}
|
||||
|
||||
/*// считывает массив символов из файла
|
||||
// ширина и высота текста должны быть как указанные при инициализации объекта этого класса
|
||||
public void ReadFromFile(string path)
|
||||
{
|
||||
var r = new StreamReader(path, SimpleConverter.UTF8);
|
||||
char[] s = new char[1];
|
||||
// считывание текста
|
||||
sbyte y = 0, x = 0;
|
||||
r.Read(s, 0, 1);
|
||||
while (!r.EndOfStream && y < WindowHeight)
|
||||
{
|
||||
if (x == WindowWidth)
|
||||
{
|
||||
r.Read(s, 0, 1);
|
||||
x = 0;
|
||||
y++;
|
||||
}
|
||||
else
|
||||
{
|
||||
Text[x, y] = s[0];
|
||||
x++;
|
||||
}
|
||||
r.Read(s, 0, 1);
|
||||
}
|
||||
r.Read(s, 0, 1);
|
||||
// считывание цвета
|
||||
// если не находит цвет в файле, оставляет старый
|
||||
if (s[0] == '\n')
|
||||
{
|
||||
r.Read(s, 0, 1);
|
||||
y = 0;
|
||||
x = 0;
|
||||
while (!r.EndOfStream && y < WindowHeight)
|
||||
{
|
||||
if (x == WindowWidth)
|
||||
{
|
||||
r.Read(s, 0, 1);
|
||||
x = 0;
|
||||
y++;
|
||||
}
|
||||
else
|
||||
{
|
||||
TextColors[x, y] = s[0];
|
||||
x++;
|
||||
}
|
||||
r.Read(s, 0, 1);
|
||||
}
|
||||
}
|
||||
r.Close();
|
||||
}*/
|
||||
|
||||
public void ResetCursor() => Console.SetCursorPosition(0, WindowHeight);
|
||||
|
||||
// заменяет символ выведенный, использовать после ShowAll()
|
||||
public void ChangeChar(sbyte x, sbyte y, char ch)
|
||||
{
|
||||
Text[x, y]=ch;
|
||||
nowText[x, y]=ch;
|
||||
Console.SetCursorPosition(x, y);
|
||||
ColoredConsole.Write(TextColors[x, y].ToString(), ch.ToString());
|
||||
}
|
||||
|
||||
public void ChangeColor(sbyte x, sbyte y, char color)
|
||||
{
|
||||
TextColors[x, y]=color;
|
||||
nowTextColors[x, y]=color;
|
||||
Console.SetCursorPosition(x, y);
|
||||
ColoredConsole.Write(color.ToString(), Text[x, y].ToString());
|
||||
}
|
||||
|
||||
public void ChangeCharAndColor(sbyte x, sbyte y, char color, char ch)
|
||||
{
|
||||
Text[x, y]=ch;
|
||||
nowText[x, y]=ch;
|
||||
TextColors[x, y]=color;
|
||||
nowTextColors[x, y]=color;
|
||||
Console.SetCursorPosition(x, y);
|
||||
ColoredConsole.Write(color.ToString(), ch.ToString());
|
||||
}
|
||||
|
||||
public void ChangeLine(sbyte x, sbyte y, char color, string line)
|
||||
{
|
||||
Console.SetCursorPosition(x, y);
|
||||
for(sbyte i = 0; i<line.Length; i++)
|
||||
{
|
||||
Text[x+i, y]=line[i];
|
||||
nowText[x+i, y]=line[i];
|
||||
TextColors[x+i, y]=color;
|
||||
nowTextColors[x+i, y]=color;
|
||||
}
|
||||
ColoredConsole.Write(color.ToString(), line);
|
||||
}
|
||||
|
||||
// выводит все символы
|
||||
public void ShowAll()
|
||||
{
|
||||
var l = new List<string>();
|
||||
for(sbyte y = 0; y<WindowHeight; y++)
|
||||
{
|
||||
for(sbyte x = 0; x<WindowWidth; x++)
|
||||
{
|
||||
l.Add(TextColors[x, y].ToString());
|
||||
l.Add(Text[x, y].ToString());
|
||||
nowText[x, y]=Text[x, y];
|
||||
nowTextColors[x, y]=TextColors[x, y];
|
||||
}
|
||||
l.Add("w");
|
||||
l.Add("\n");
|
||||
}
|
||||
ColoredConsole.Write(l.ToArray());
|
||||
//Console.WriteLine();
|
||||
}
|
||||
|
||||
public void UpdateAll()
|
||||
{
|
||||
for(sbyte y = 0; y<WindowHeight; y++)
|
||||
{
|
||||
for(sbyte x = 0; x<WindowWidth; x++)
|
||||
{
|
||||
Console.SetCursorPosition(x, y);
|
||||
if(TextColors[x, y]!=nowTextColors[x, y]||Text[x, y]!=nowText[x, y])
|
||||
{
|
||||
ColoredConsole.Write(TextColors[x, y].ToString(), Text[x, y].ToString());
|
||||
nowText[x, y]=Text[x, y];
|
||||
nowTextColors[x, y]=TextColors[x, y];
|
||||
}
|
||||
}
|
||||
Console.Write('\n');
|
||||
}
|
||||
}
|
||||
|
||||
public void RenderFile(string file)
|
||||
{
|
||||
Console.Clear();
|
||||
Console.WriteLine(File.ReadAllText(file));
|
||||
}
|
||||
}
|
||||
}
|
||||
using DTLib.Filesystem;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace DTLib.ConsoleGUI
|
||||
{
|
||||
//
|
||||
// создание gui из текста в консоли
|
||||
//
|
||||
public class WindowOld
|
||||
{
|
||||
public int WindowWidth { get; private set; }
|
||||
public int WindowHeight { get; private set; }
|
||||
public char[,] Text;
|
||||
public char[,] nowText;
|
||||
public char[,] TextColors;
|
||||
public char[,] nowTextColors;
|
||||
|
||||
public Container WindowContainer;
|
||||
|
||||
public WindowOld(int windowWidth, int windowHeight)
|
||||
{
|
||||
WindowWidth=windowWidth;
|
||||
WindowHeight=windowHeight;
|
||||
Text=new char[windowWidth, windowHeight];
|
||||
TextColors=new char[windowWidth, windowHeight];
|
||||
nowText=TextColors;
|
||||
nowTextColors=new char[windowWidth, windowHeight];
|
||||
Console.WindowWidth=WindowWidth+1;
|
||||
Console.WindowHeight=WindowHeight+1;
|
||||
Console.BufferWidth=WindowWidth+1;
|
||||
Console.BufferHeight=WindowHeight+1;
|
||||
Console.OutputEncoding=Encoding.Unicode;
|
||||
Console.InputEncoding=Encoding.Unicode;
|
||||
Console.CursorVisible=false;
|
||||
// заполнение массивов
|
||||
for(sbyte y = 0; y<WindowHeight; y++)
|
||||
{
|
||||
for(sbyte x = 0; x<WindowWidth; x++)
|
||||
{
|
||||
Text[x, y]=' ';
|
||||
TextColors[x, y]='w';
|
||||
}
|
||||
}
|
||||
nowText=TextColors;
|
||||
}
|
||||
|
||||
/*// считывает массив символов из файла
|
||||
// ширина и высота текста должны быть как указанные при инициализации объекта этого класса
|
||||
public void ReadFromFile(string path)
|
||||
{
|
||||
var r = new StreamReader(path, SimpleConverter.UTF8);
|
||||
char[] s = new char[1];
|
||||
// считывание текста
|
||||
sbyte y = 0, x = 0;
|
||||
r.Read(s, 0, 1);
|
||||
while (!r.EndOfStream && y < WindowHeight)
|
||||
{
|
||||
if (x == WindowWidth)
|
||||
{
|
||||
r.Read(s, 0, 1);
|
||||
x = 0;
|
||||
y++;
|
||||
}
|
||||
else
|
||||
{
|
||||
Text[x, y] = s[0];
|
||||
x++;
|
||||
}
|
||||
r.Read(s, 0, 1);
|
||||
}
|
||||
r.Read(s, 0, 1);
|
||||
// считывание цвета
|
||||
// если не находит цвет в файле, оставляет старый
|
||||
if (s[0] == '\n')
|
||||
{
|
||||
r.Read(s, 0, 1);
|
||||
y = 0;
|
||||
x = 0;
|
||||
while (!r.EndOfStream && y < WindowHeight)
|
||||
{
|
||||
if (x == WindowWidth)
|
||||
{
|
||||
r.Read(s, 0, 1);
|
||||
x = 0;
|
||||
y++;
|
||||
}
|
||||
else
|
||||
{
|
||||
TextColors[x, y] = s[0];
|
||||
x++;
|
||||
}
|
||||
r.Read(s, 0, 1);
|
||||
}
|
||||
}
|
||||
r.Close();
|
||||
}*/
|
||||
|
||||
public void ResetCursor() => Console.SetCursorPosition(0, WindowHeight);
|
||||
|
||||
// заменяет символ выведенный, использовать после ShowAll()
|
||||
public void ChangeChar(sbyte x, sbyte y, char ch)
|
||||
{
|
||||
Text[x, y]=ch;
|
||||
nowText[x, y]=ch;
|
||||
Console.SetCursorPosition(x, y);
|
||||
ColoredConsole.Write(TextColors[x, y].ToString(), ch.ToString());
|
||||
}
|
||||
|
||||
public void ChangeColor(sbyte x, sbyte y, char color)
|
||||
{
|
||||
TextColors[x, y]=color;
|
||||
nowTextColors[x, y]=color;
|
||||
Console.SetCursorPosition(x, y);
|
||||
ColoredConsole.Write(color.ToString(), Text[x, y].ToString());
|
||||
}
|
||||
|
||||
public void ChangeCharAndColor(sbyte x, sbyte y, char color, char ch)
|
||||
{
|
||||
Text[x, y]=ch;
|
||||
nowText[x, y]=ch;
|
||||
TextColors[x, y]=color;
|
||||
nowTextColors[x, y]=color;
|
||||
Console.SetCursorPosition(x, y);
|
||||
ColoredConsole.Write(color.ToString(), ch.ToString());
|
||||
}
|
||||
|
||||
public void ChangeLine(sbyte x, sbyte y, char color, string line)
|
||||
{
|
||||
Console.SetCursorPosition(x, y);
|
||||
for(sbyte i = 0; i<line.Length; i++)
|
||||
{
|
||||
Text[x+i, y]=line[i];
|
||||
nowText[x+i, y]=line[i];
|
||||
TextColors[x+i, y]=color;
|
||||
nowTextColors[x+i, y]=color;
|
||||
}
|
||||
ColoredConsole.Write(color.ToString(), line);
|
||||
}
|
||||
|
||||
// выводит все символы
|
||||
public void ShowAll()
|
||||
{
|
||||
var l = new List<string>();
|
||||
for(sbyte y = 0; y<WindowHeight; y++)
|
||||
{
|
||||
for(sbyte x = 0; x<WindowWidth; x++)
|
||||
{
|
||||
l.Add(TextColors[x, y].ToString());
|
||||
l.Add(Text[x, y].ToString());
|
||||
nowText[x, y]=Text[x, y];
|
||||
nowTextColors[x, y]=TextColors[x, y];
|
||||
}
|
||||
l.Add("w");
|
||||
l.Add("\n");
|
||||
}
|
||||
ColoredConsole.Write(l.ToArray());
|
||||
//Console.WriteLine();
|
||||
}
|
||||
|
||||
public void UpdateAll()
|
||||
{
|
||||
for(sbyte y = 0; y<WindowHeight; y++)
|
||||
{
|
||||
for(sbyte x = 0; x<WindowWidth; x++)
|
||||
{
|
||||
Console.SetCursorPosition(x, y);
|
||||
if(TextColors[x, y]!=nowTextColors[x, y]||Text[x, y]!=nowText[x, y])
|
||||
{
|
||||
ColoredConsole.Write(TextColors[x, y].ToString(), Text[x, y].ToString());
|
||||
nowText[x, y]=Text[x, y];
|
||||
nowTextColors[x, y]=TextColors[x, y];
|
||||
}
|
||||
}
|
||||
Console.Write('\n');
|
||||
}
|
||||
}
|
||||
|
||||
public void RenderFile(string file)
|
||||
{
|
||||
Console.Clear();
|
||||
Console.WriteLine(File.ReadAllText(file));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,127 +1,127 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
public class MyDict<TKey, TVal>
|
||||
{
|
||||
object locker = new object();
|
||||
List<TVal> values;
|
||||
List<TKey> keys;
|
||||
List<int> hashes;
|
||||
int count;
|
||||
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
// lock (count)
|
||||
lock (locker) return count;
|
||||
}
|
||||
}
|
||||
|
||||
public ReadOnlyCollection<TVal> Values
|
||||
{
|
||||
get
|
||||
{
|
||||
ReadOnlyCollectionBuilder<TVal> b;
|
||||
lock (locker) b = new(values);
|
||||
return b.ToReadOnlyCollection();
|
||||
}
|
||||
}
|
||||
|
||||
public ReadOnlyCollection<TKey> Keys
|
||||
{
|
||||
get
|
||||
{
|
||||
ReadOnlyCollectionBuilder<TKey> b;
|
||||
lock (locker) b = new(keys);
|
||||
return b.ToReadOnlyCollection();
|
||||
}
|
||||
}
|
||||
|
||||
public MyDict()
|
||||
{
|
||||
|
||||
values = new();
|
||||
keys = new();
|
||||
hashes = new();
|
||||
count = 0;
|
||||
}
|
||||
|
||||
public MyDict(IList<TKey> _keys, IList<TVal> _values)
|
||||
{
|
||||
if (_keys.Count != _values.Count) throw new Exception("_keys.Count != _values.Count");
|
||||
keys = (List<TKey>)_keys;
|
||||
values = (List<TVal>)_values;
|
||||
count = _keys.Count;
|
||||
hashes = new();
|
||||
for (int i = 0; i < count; i++)
|
||||
hashes.Add(keys[i].GetHashCode());
|
||||
}
|
||||
|
||||
public TVal this[TKey key]
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (locker) return values[hashes.IndexOf(key.GetHashCode())];
|
||||
}
|
||||
set
|
||||
{
|
||||
lock (locker) values[hashes.IndexOf(key.GetHashCode())] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public (TKey, TVal) GetByIndex(int index)
|
||||
{
|
||||
(TKey k, TVal v) output;
|
||||
lock (locker)
|
||||
{
|
||||
output.k = keys[index];
|
||||
output.v = values[index];
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public void Add(TKey key, TVal val)
|
||||
{
|
||||
// lock (keys) lock (values) lock (count)
|
||||
lock (locker)
|
||||
{
|
||||
keys.Add(key);
|
||||
values.Add(val);
|
||||
hashes.Add(key.GetHashCode());
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
public void Remove(TKey key)
|
||||
{
|
||||
var hash = key.GetHashCode();
|
||||
lock (locker)
|
||||
{
|
||||
var num = hashes.IndexOf(hash);
|
||||
keys.RemoveAt(num);
|
||||
values.RemoveAt(num);
|
||||
hashes.RemoveAt(num);
|
||||
count--;
|
||||
}
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
lock (locker)
|
||||
{
|
||||
hashes.Clear();
|
||||
keys.Clear();
|
||||
values.Clear();
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
public class MyDict<TKey, TVal>
|
||||
{
|
||||
object locker = new object();
|
||||
List<TVal> values;
|
||||
List<TKey> keys;
|
||||
List<int> hashes;
|
||||
int count;
|
||||
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
// lock (count)
|
||||
lock (locker) return count;
|
||||
}
|
||||
}
|
||||
|
||||
public ReadOnlyCollection<TVal> Values
|
||||
{
|
||||
get
|
||||
{
|
||||
ReadOnlyCollectionBuilder<TVal> b;
|
||||
lock (locker) b = new(values);
|
||||
return b.ToReadOnlyCollection();
|
||||
}
|
||||
}
|
||||
|
||||
public ReadOnlyCollection<TKey> Keys
|
||||
{
|
||||
get
|
||||
{
|
||||
ReadOnlyCollectionBuilder<TKey> b;
|
||||
lock (locker) b = new(keys);
|
||||
return b.ToReadOnlyCollection();
|
||||
}
|
||||
}
|
||||
|
||||
public MyDict()
|
||||
{
|
||||
|
||||
values = new();
|
||||
keys = new();
|
||||
hashes = new();
|
||||
count = 0;
|
||||
}
|
||||
|
||||
public MyDict(IList<TKey> _keys, IList<TVal> _values)
|
||||
{
|
||||
if (_keys.Count != _values.Count) throw new Exception("_keys.Count != _values.Count");
|
||||
keys = (List<TKey>)_keys;
|
||||
values = (List<TVal>)_values;
|
||||
count = _keys.Count;
|
||||
hashes = new();
|
||||
for (int i = 0; i < count; i++)
|
||||
hashes.Add(keys[i].GetHashCode());
|
||||
}
|
||||
|
||||
public TVal this[TKey key]
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (locker) return values[hashes.IndexOf(key.GetHashCode())];
|
||||
}
|
||||
set
|
||||
{
|
||||
lock (locker) values[hashes.IndexOf(key.GetHashCode())] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public (TKey, TVal) GetByIndex(int index)
|
||||
{
|
||||
(TKey k, TVal v) output;
|
||||
lock (locker)
|
||||
{
|
||||
output.k = keys[index];
|
||||
output.v = values[index];
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public void Add(TKey key, TVal val)
|
||||
{
|
||||
// lock (keys) lock (values) lock (count)
|
||||
lock (locker)
|
||||
{
|
||||
keys.Add(key);
|
||||
values.Add(val);
|
||||
hashes.Add(key.GetHashCode());
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
public void Remove(TKey key)
|
||||
{
|
||||
var hash = key.GetHashCode();
|
||||
lock (locker)
|
||||
{
|
||||
var num = hashes.IndexOf(hash);
|
||||
keys.RemoveAt(num);
|
||||
values.RemoveAt(num);
|
||||
hashes.RemoveAt(num);
|
||||
count--;
|
||||
}
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
lock (locker)
|
||||
{
|
||||
hashes.Clear();
|
||||
keys.Clear();
|
||||
values.Clear();
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,100 +1,100 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DTLib.Reactive
|
||||
{
|
||||
public class ReactiveListener<T> : ReactiveProvider<T>
|
||||
{
|
||||
public ReactiveListener() { }
|
||||
public ReactiveListener(ReactiveStream<T> stream) : base(stream) { }
|
||||
public ReactiveListener(ICollection<ReactiveStream<T>> streams) : base(streams) { }
|
||||
|
||||
|
||||
public event Action<ReactiveStream<T>, T> ElementAddedEvent;
|
||||
void ElementAdded(ReactiveStream<T> stream, TimeSignedObject<T> e) => ElementAdded(stream, e.Value);
|
||||
void ElementAdded(ReactiveStream<T> stream, T e) =>
|
||||
Task.Run(() => ElementAddedEvent?.Invoke(stream, e));
|
||||
|
||||
public override void Join(ReactiveStream<T> stream)
|
||||
{
|
||||
base.Join(stream);
|
||||
lock (Streams) stream.ElementAddedEvent += ElementAdded;
|
||||
}
|
||||
|
||||
public override void Leave(ReactiveStream<T> stream)
|
||||
{
|
||||
base.Leave(stream);
|
||||
lock (Streams) stream.ElementAddedEvent -= ElementAdded;
|
||||
}
|
||||
|
||||
public T GetFirst()
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
TimeSignedObject<T> rezult = null;
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
if (stream.Count != 0)
|
||||
{
|
||||
TimeSignedObject<T> e = stream[0];
|
||||
if (rezult is null) rezult = e;
|
||||
else if (rezult.Time > e.Time) rezult = e;
|
||||
}
|
||||
return rezult.Value;
|
||||
}
|
||||
public T GetLast()
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
TimeSignedObject<T> rezult = null;
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
if (stream.Count != 0)
|
||||
{
|
||||
TimeSignedObject<T> e = stream[stream.Count - 1];
|
||||
if (rezult is null) rezult = e;
|
||||
else if (rezult.Time < e.Time) rezult = e;
|
||||
}
|
||||
return rezult.Value;
|
||||
}
|
||||
|
||||
public T FindOne(Func<T, bool> condition)
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
foreach (TimeSignedObject<T> el in stream)
|
||||
if (condition(el.Value))
|
||||
return el.Value;
|
||||
return default;
|
||||
}
|
||||
|
||||
public TimeSignedObject<T> FindOne(Func<TimeSignedObject<T>, bool> condition)
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
foreach (TimeSignedObject<T> el in stream)
|
||||
if (condition(el))
|
||||
return el;
|
||||
return default;
|
||||
}
|
||||
|
||||
public List<T> FindAll(Func<T, bool> condition)
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
List<T> rezults = new();
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
foreach (TimeSignedObject<T> el in stream)
|
||||
if (condition(el.Value))
|
||||
rezults.Add(el.Value);
|
||||
return rezults;
|
||||
}
|
||||
|
||||
public List<TimeSignedObject<T>> FindAll(Func<TimeSignedObject<T>, bool> condition)
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
List<TimeSignedObject<T>> rezults = new();
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
foreach (TimeSignedObject<T> el in stream)
|
||||
if (condition(el))
|
||||
rezults.Add(el);
|
||||
return rezults;
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DTLib.Reactive
|
||||
{
|
||||
public class ReactiveListener<T> : ReactiveProvider<T>
|
||||
{
|
||||
public ReactiveListener() { }
|
||||
public ReactiveListener(ReactiveStream<T> stream) : base(stream) { }
|
||||
public ReactiveListener(ICollection<ReactiveStream<T>> streams) : base(streams) { }
|
||||
|
||||
|
||||
public event Action<ReactiveStream<T>, T> ElementAddedEvent;
|
||||
void ElementAdded(ReactiveStream<T> stream, TimeSignedObject<T> e) => ElementAdded(stream, e.Value);
|
||||
void ElementAdded(ReactiveStream<T> stream, T e) =>
|
||||
Task.Run(() => ElementAddedEvent?.Invoke(stream, e));
|
||||
|
||||
public override void Join(ReactiveStream<T> stream)
|
||||
{
|
||||
base.Join(stream);
|
||||
lock (Streams) stream.ElementAddedEvent += ElementAdded;
|
||||
}
|
||||
|
||||
public override void Leave(ReactiveStream<T> stream)
|
||||
{
|
||||
base.Leave(stream);
|
||||
lock (Streams) stream.ElementAddedEvent -= ElementAdded;
|
||||
}
|
||||
|
||||
public T GetFirst()
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
TimeSignedObject<T> rezult = null;
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
if (stream.Count != 0)
|
||||
{
|
||||
TimeSignedObject<T> e = stream[0];
|
||||
if (rezult is null) rezult = e;
|
||||
else if (rezult.Time > e.Time) rezult = e;
|
||||
}
|
||||
return rezult.Value;
|
||||
}
|
||||
public T GetLast()
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
TimeSignedObject<T> rezult = null;
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
if (stream.Count != 0)
|
||||
{
|
||||
TimeSignedObject<T> e = stream[stream.Count - 1];
|
||||
if (rezult is null) rezult = e;
|
||||
else if (rezult.Time < e.Time) rezult = e;
|
||||
}
|
||||
return rezult.Value;
|
||||
}
|
||||
|
||||
public T FindOne(Func<T, bool> condition)
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
foreach (TimeSignedObject<T> el in stream)
|
||||
if (condition(el.Value))
|
||||
return el.Value;
|
||||
return default;
|
||||
}
|
||||
|
||||
public TimeSignedObject<T> FindOne(Func<TimeSignedObject<T>, bool> condition)
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
foreach (TimeSignedObject<T> el in stream)
|
||||
if (condition(el))
|
||||
return el;
|
||||
return default;
|
||||
}
|
||||
|
||||
public List<T> FindAll(Func<T, bool> condition)
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
List<T> rezults = new();
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
foreach (TimeSignedObject<T> el in stream)
|
||||
if (condition(el.Value))
|
||||
rezults.Add(el.Value);
|
||||
return rezults;
|
||||
}
|
||||
|
||||
public List<TimeSignedObject<T>> FindAll(Func<TimeSignedObject<T>, bool> condition)
|
||||
{
|
||||
if (Streams.Count == 0) throw new Exception("ReactiveListener is not connected to any streams");
|
||||
List<TimeSignedObject<T>> rezults = new();
|
||||
foreach (ReactiveStream<T> stream in Streams)
|
||||
foreach (TimeSignedObject<T> el in stream)
|
||||
if (condition(el))
|
||||
rezults.Add(el);
|
||||
return rezults;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,35 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace DTLib.Reactive
|
||||
{
|
||||
public abstract class ReactiveProvider<T>
|
||||
{
|
||||
protected List<ReactiveStream<T>> Streams
|
||||
{
|
||||
get
|
||||
{ lock (_streams) return _streams; }
|
||||
set
|
||||
{ lock (_streams) _streams = value; }
|
||||
}
|
||||
private List<ReactiveStream<T>> _streams = new();
|
||||
|
||||
public ReactiveProvider() { }
|
||||
public ReactiveProvider(ReactiveStream<T> stream) => Streams.Add(stream);
|
||||
public ReactiveProvider(ICollection<ReactiveStream<T>> streams) => Streams = streams.ToList();
|
||||
|
||||
public virtual void Join(ReactiveStream<T> stream)
|
||||
{
|
||||
if (IsConnetcedTo(stream)) throw new Exception("ReactiveListener is already connected to the stream");
|
||||
Streams.Add(stream);
|
||||
}
|
||||
|
||||
public virtual void Leave(ReactiveStream<T> stream)
|
||||
{
|
||||
if (!Streams.Remove(stream)) throw new Exception("ReactiveListener is not connected to the stream");
|
||||
}
|
||||
|
||||
public bool IsConnetcedTo(ReactiveStream<T> stream) => Streams.Contains(stream);
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace DTLib.Reactive
|
||||
{
|
||||
public abstract class ReactiveProvider<T>
|
||||
{
|
||||
protected List<ReactiveStream<T>> Streams
|
||||
{
|
||||
get
|
||||
{ lock (_streams) return _streams; }
|
||||
set
|
||||
{ lock (_streams) _streams = value; }
|
||||
}
|
||||
private List<ReactiveStream<T>> _streams = new();
|
||||
|
||||
public ReactiveProvider() { }
|
||||
public ReactiveProvider(ReactiveStream<T> stream) => Streams.Add(stream);
|
||||
public ReactiveProvider(ICollection<ReactiveStream<T>> streams) => Streams = streams.ToList();
|
||||
|
||||
public virtual void Join(ReactiveStream<T> stream)
|
||||
{
|
||||
if (IsConnetcedTo(stream)) throw new Exception("ReactiveListener is already connected to the stream");
|
||||
Streams.Add(stream);
|
||||
}
|
||||
|
||||
public virtual void Leave(ReactiveStream<T> stream)
|
||||
{
|
||||
if (!Streams.Remove(stream)) throw new Exception("ReactiveListener is not connected to the stream");
|
||||
}
|
||||
|
||||
public bool IsConnetcedTo(ReactiveStream<T> stream) => Streams.Contains(stream);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DTLib.Reactive
|
||||
{
|
||||
public class ReactiveSender<T> : ReactiveProvider<T>
|
||||
{
|
||||
|
||||
public ReactiveSender() { }
|
||||
public ReactiveSender(ReactiveStream<T> stream) : base(stream) { }
|
||||
public ReactiveSender(ICollection<ReactiveStream<T>> streams) : base(streams) { }
|
||||
|
||||
public void Send(T e)
|
||||
{
|
||||
foreach (ReactiveStream<T> s in Streams)
|
||||
s.Add(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DTLib.Reactive
|
||||
{
|
||||
public class ReactiveSender<T> : ReactiveProvider<T>
|
||||
{
|
||||
|
||||
public ReactiveSender() { }
|
||||
public ReactiveSender(ReactiveStream<T> stream) : base(stream) { }
|
||||
public ReactiveSender(ICollection<ReactiveStream<T>> streams) : base(streams) { }
|
||||
|
||||
public void Send(T e)
|
||||
{
|
||||
foreach (ReactiveStream<T> s in Streams)
|
||||
s.Add(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,74 +1,74 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DTLib.Reactive
|
||||
{
|
||||
public class ReactiveStream<T> : IEnumerable<TimeSignedObject<T>>, IList<TimeSignedObject<T>>
|
||||
{
|
||||
public ReactiveStream() { }
|
||||
|
||||
List<TimeSignedObject<T>> _storage = new();
|
||||
List<TimeSignedObject<T>> Storage
|
||||
{
|
||||
get
|
||||
{ lock (_storage) return _storage; }
|
||||
}
|
||||
|
||||
public int Count => Storage.Count;
|
||||
|
||||
public TimeSignedObject<T> this[int index]
|
||||
{
|
||||
get => Storage[index];
|
||||
set => throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public event Action<ReactiveStream<T>, TimeSignedObject<T>> ElementAddedEvent;
|
||||
public void Add(TimeSignedObject<T> elem)
|
||||
{
|
||||
Storage.Add(elem);
|
||||
ElementAddedEvent?.Invoke(this, elem);
|
||||
}
|
||||
public void Add(T elem) => Add(new TimeSignedObject<T>(elem));
|
||||
|
||||
public void Clear() => Storage.Clear();
|
||||
public int IndexOf(TimeSignedObject<T> item) => Storage.IndexOf(item);
|
||||
public bool Contains(TimeSignedObject<T> item) => Storage.Contains(item);
|
||||
|
||||
public IEnumerator<TimeSignedObject<T>> GetEnumerator() => new Enumerator(Storage);
|
||||
IEnumerator IEnumerable.GetEnumerator() => new Enumerator(Storage);
|
||||
|
||||
struct Enumerator : IEnumerator<TimeSignedObject<T>>
|
||||
{
|
||||
public Enumerator(List<TimeSignedObject<T>> storage)
|
||||
{
|
||||
_storage = storage;
|
||||
_index = storage.Count - 1;
|
||||
}
|
||||
|
||||
List<TimeSignedObject<T>> _storage;
|
||||
int _index;
|
||||
public TimeSignedObject<T> Current => _storage[_index];
|
||||
object IEnumerator.Current => Current;
|
||||
|
||||
public void Dispose() => _storage = null;
|
||||
|
||||
public bool MoveNext()
|
||||
{
|
||||
if (_index < 0)
|
||||
return false;
|
||||
_index--;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Reset() => _index = _storage.Count - 1;
|
||||
}
|
||||
|
||||
bool ICollection<TimeSignedObject<T>>.IsReadOnly { get; } = false;
|
||||
|
||||
public void Insert(int index, TimeSignedObject<T> item) => throw new NotImplementedException();
|
||||
public void RemoveAt(int index) => throw new NotImplementedException();
|
||||
public void CopyTo(TimeSignedObject<T>[] array, int arrayIndex) => throw new NotImplementedException();
|
||||
public bool Remove(TimeSignedObject<T> item) => throw new NotImplementedException();
|
||||
}
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DTLib.Reactive
|
||||
{
|
||||
public class ReactiveStream<T> : IEnumerable<TimeSignedObject<T>>, IList<TimeSignedObject<T>>
|
||||
{
|
||||
public ReactiveStream() { }
|
||||
|
||||
List<TimeSignedObject<T>> _storage = new();
|
||||
List<TimeSignedObject<T>> Storage
|
||||
{
|
||||
get
|
||||
{ lock (_storage) return _storage; }
|
||||
}
|
||||
|
||||
public int Count => Storage.Count;
|
||||
|
||||
public TimeSignedObject<T> this[int index]
|
||||
{
|
||||
get => Storage[index];
|
||||
set => throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public event Action<ReactiveStream<T>, TimeSignedObject<T>> ElementAddedEvent;
|
||||
public void Add(TimeSignedObject<T> elem)
|
||||
{
|
||||
Storage.Add(elem);
|
||||
ElementAddedEvent?.Invoke(this, elem);
|
||||
}
|
||||
public void Add(T elem) => Add(new TimeSignedObject<T>(elem));
|
||||
|
||||
public void Clear() => Storage.Clear();
|
||||
public int IndexOf(TimeSignedObject<T> item) => Storage.IndexOf(item);
|
||||
public bool Contains(TimeSignedObject<T> item) => Storage.Contains(item);
|
||||
|
||||
public IEnumerator<TimeSignedObject<T>> GetEnumerator() => new Enumerator(Storage);
|
||||
IEnumerator IEnumerable.GetEnumerator() => new Enumerator(Storage);
|
||||
|
||||
struct Enumerator : IEnumerator<TimeSignedObject<T>>
|
||||
{
|
||||
public Enumerator(List<TimeSignedObject<T>> storage)
|
||||
{
|
||||
_storage = storage;
|
||||
_index = storage.Count - 1;
|
||||
}
|
||||
|
||||
List<TimeSignedObject<T>> _storage;
|
||||
int _index;
|
||||
public TimeSignedObject<T> Current => _storage[_index];
|
||||
object IEnumerator.Current => Current;
|
||||
|
||||
public void Dispose() => _storage = null;
|
||||
|
||||
public bool MoveNext()
|
||||
{
|
||||
if (_index < 0)
|
||||
return false;
|
||||
_index--;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Reset() => _index = _storage.Count - 1;
|
||||
}
|
||||
|
||||
bool ICollection<TimeSignedObject<T>>.IsReadOnly { get; } = false;
|
||||
|
||||
public void Insert(int index, TimeSignedObject<T> item) => throw new NotImplementedException();
|
||||
public void RemoveAt(int index) => throw new NotImplementedException();
|
||||
public void CopyTo(TimeSignedObject<T>[] array, int arrayIndex) => throw new NotImplementedException();
|
||||
public bool Remove(TimeSignedObject<T> item) => throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
using System;
|
||||
|
||||
namespace DTLib.Reactive
|
||||
{
|
||||
public class TimeSignedObject<T>
|
||||
{
|
||||
public T Value { get; init; }
|
||||
public long Time { get; init; }
|
||||
|
||||
public TimeSignedObject(T value)
|
||||
{
|
||||
Value = value;
|
||||
Time = DateTime.Now.Ticks;
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
|
||||
namespace DTLib.Reactive
|
||||
{
|
||||
public class TimeSignedObject<T>
|
||||
{
|
||||
public T Value { get; init; }
|
||||
public long Time { get; init; }
|
||||
|
||||
public TimeSignedObject(T value)
|
||||
{
|
||||
Value = value;
|
||||
Time = DateTime.Now.Ticks;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,37 +1,37 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// Вычисление псевдослучайного числа из множества параметров.
|
||||
// Работает медленнее чем класс System.Random, но выдаёт более случайные значения
|
||||
//
|
||||
public class SecureRandom
|
||||
{
|
||||
private RNGCryptoServiceProvider crypt = new();
|
||||
|
||||
// получение массива случайных байтов
|
||||
public byte[] GenBytes(uint length)
|
||||
{
|
||||
byte[] output = new byte[length];
|
||||
crypt.GetNonZeroBytes(output);
|
||||
return output;
|
||||
}
|
||||
|
||||
// получение случайного числа от 0 до 2147483647
|
||||
/*public int NextInt(uint from, int to)
|
||||
{
|
||||
int output = 0;
|
||||
int rez = 0;
|
||||
while (true)
|
||||
{
|
||||
rez = output * 10 + NextBytes(1)[0];
|
||||
if (rez < to && rez > from)
|
||||
{
|
||||
output = rez;
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// Вычисление псевдослучайного числа из множества параметров.
|
||||
// Работает медленнее чем класс System.Random, но выдаёт более случайные значения
|
||||
//
|
||||
public class SecureRandom
|
||||
{
|
||||
private RNGCryptoServiceProvider crypt = new();
|
||||
|
||||
// получение массива случайных байтов
|
||||
public byte[] GenBytes(uint length)
|
||||
{
|
||||
byte[] output = new byte[length];
|
||||
crypt.GetNonZeroBytes(output);
|
||||
return output;
|
||||
}
|
||||
|
||||
// получение случайного числа от 0 до 2147483647
|
||||
/*public int NextInt(uint from, int to)
|
||||
{
|
||||
int output = 0;
|
||||
int rez = 0;
|
||||
while (true)
|
||||
{
|
||||
rez = output * 10 + NextBytes(1)[0];
|
||||
if (rez < to && rez > from)
|
||||
{
|
||||
output = rez;
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace DTLib.Experimental;
|
||||
|
||||
public static class Tester
|
||||
{
|
||||
public static void LogOperationTime(string op_name, int repeats, Action operation)
|
||||
{
|
||||
Stopwatch clock = new();
|
||||
clock.Start();
|
||||
for (int i = 0; i < repeats; i++)
|
||||
operation();
|
||||
clock.Stop();
|
||||
LogNoTime("c",$"operation {op_name} took {clock.ElapsedTicks / repeats} ticks");
|
||||
}
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace DTLib.Experimental;
|
||||
|
||||
public static class Tester
|
||||
{
|
||||
public static void LogOperationTime(string op_name, int repeats, Action operation)
|
||||
{
|
||||
Stopwatch clock = new();
|
||||
clock.Start();
|
||||
for (int i = 0; i < repeats; i++)
|
||||
operation();
|
||||
clock.Stop();
|
||||
LogNoTime("c",$"operation {op_name} took {clock.ElapsedTicks / repeats} ticks");
|
||||
}
|
||||
}
|
||||
@@ -1,53 +1,53 @@
|
||||
global using System;
|
||||
global using System.Collections;
|
||||
global using System.Collections.Generic;
|
||||
global using System.Linq;
|
||||
global using System.Text;
|
||||
global using System.Threading.Tasks;
|
||||
global using DTLib.Extensions;
|
||||
global using DTLib.Filesystem;
|
||||
global using static DTLib.PublicLog;
|
||||
|
||||
namespace DTLib.Extensions;
|
||||
|
||||
public static class BaseConverter
|
||||
{
|
||||
// сокращение конвертации
|
||||
public static bool ToBool<T>(this T input) => Convert.ToBoolean(input);
|
||||
public static char ToChar<T>(this T input) => Convert.ToChar(input);
|
||||
public static byte ToByte<T>(this T input) => Convert.ToByte(input);
|
||||
public static sbyte ToSByte<T>(this T input) => Convert.ToSByte(input);
|
||||
public static short ToShort<T>(this T input) => Convert.ToInt16(input);
|
||||
public static ushort ToUShort<T>(this T input) => Convert.ToUInt16(input);
|
||||
public static int ToInt<T>(this T input) => Convert.ToInt32(input);
|
||||
public static uint ToUInt<T>(this T input) => Convert.ToUInt32(input);
|
||||
public static long ToLong<T>(this T input) => Convert.ToInt64(input);
|
||||
public static ulong ToULong<T>(this T input) => Convert.ToUInt64(input);
|
||||
public static float ToFloat(this string input) => float.Parse(input, System.Globalization.CultureInfo.InvariantCulture);
|
||||
public static double ToDouble<T>(this T input) => Convert.ToDouble(input, System.Globalization.CultureInfo.InvariantCulture);
|
||||
public static decimal ToDecimal<T>(this T input) => Convert.ToDecimal(input, System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
public static int ToInt(this byte[] bytes)
|
||||
{
|
||||
int output = 0;
|
||||
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)
|
||||
{
|
||||
output.Add(ToByte(num % 256));
|
||||
num = (num / 256).Truncate();
|
||||
}
|
||||
output.Reverse();
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
// Math.Truncate принимает как decimal, так и doublе,
|
||||
// из-за чего вызов метода так: Math.Truncate(10/3) выдаст ошибку "неоднозначный вызов"
|
||||
public static int Truncate<T>(this T number) => Math.Truncate(number.ToDouble()).ToInt();
|
||||
}
|
||||
global using System;
|
||||
global using System.Collections;
|
||||
global using System.Collections.Generic;
|
||||
global using System.Linq;
|
||||
global using System.Text;
|
||||
global using System.Threading.Tasks;
|
||||
global using DTLib.Extensions;
|
||||
global using DTLib.Filesystem;
|
||||
global using static DTLib.PublicLog;
|
||||
|
||||
namespace DTLib.Extensions;
|
||||
|
||||
public static class BaseConverter
|
||||
{
|
||||
// сокращение конвертации
|
||||
public static bool ToBool<T>(this T input) => Convert.ToBoolean(input);
|
||||
public static char ToChar<T>(this T input) => Convert.ToChar(input);
|
||||
public static byte ToByte<T>(this T input) => Convert.ToByte(input);
|
||||
public static sbyte ToSByte<T>(this T input) => Convert.ToSByte(input);
|
||||
public static short ToShort<T>(this T input) => Convert.ToInt16(input);
|
||||
public static ushort ToUShort<T>(this T input) => Convert.ToUInt16(input);
|
||||
public static int ToInt<T>(this T input) => Convert.ToInt32(input);
|
||||
public static uint ToUInt<T>(this T input) => Convert.ToUInt32(input);
|
||||
public static long ToLong<T>(this T input) => Convert.ToInt64(input);
|
||||
public static ulong ToULong<T>(this T input) => Convert.ToUInt64(input);
|
||||
public static float ToFloat(this string input) => float.Parse(input, System.Globalization.CultureInfo.InvariantCulture);
|
||||
public static double ToDouble<T>(this T input) => Convert.ToDouble(input, System.Globalization.CultureInfo.InvariantCulture);
|
||||
public static decimal ToDecimal<T>(this T input) => Convert.ToDecimal(input, System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
public static int ToInt(this byte[] bytes)
|
||||
{
|
||||
int output = 0;
|
||||
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)
|
||||
{
|
||||
output.Add(ToByte(num % 256));
|
||||
num = (num / 256).Truncate();
|
||||
}
|
||||
output.Reverse();
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
// Math.Truncate принимает как decimal, так и doublе,
|
||||
// из-за чего вызов метода так: Math.Truncate(10/3) выдаст ошибку "неоднозначный вызов"
|
||||
public static int Truncate<T>(this T number) => Math.Truncate(number.ToDouble()).ToInt();
|
||||
}
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
namespace DTLib.Extensions;
|
||||
|
||||
public static class Collections
|
||||
{
|
||||
|
||||
public static void ForEach<T>(this IEnumerable<T> en, Action<T> act)
|
||||
{
|
||||
foreach (T elem in en)
|
||||
act(elem);
|
||||
}
|
||||
|
||||
// массив в лист
|
||||
public static List<T> ToList<T>(this T[] input)
|
||||
{
|
||||
var list = new List<T>();
|
||||
list.AddRange(input);
|
||||
return list;
|
||||
}
|
||||
|
||||
// удаление нескольких элементов массива
|
||||
public static T[] RemoveRange<T>(this T[] input, int startIndex, int count)
|
||||
{
|
||||
var 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 bool Contains<T>(this T[] array, T value)
|
||||
{
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
if (array[i].Equals(value))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
namespace DTLib.Extensions;
|
||||
|
||||
public static class Collections
|
||||
{
|
||||
|
||||
public static void ForEach<T>(this IEnumerable<T> en, Action<T> act)
|
||||
{
|
||||
foreach (T elem in en)
|
||||
act(elem);
|
||||
}
|
||||
|
||||
// массив в лист
|
||||
public static List<T> ToList<T>(this T[] input)
|
||||
{
|
||||
var list = new List<T>();
|
||||
list.AddRange(input);
|
||||
return list;
|
||||
}
|
||||
|
||||
// удаление нескольких элементов массива
|
||||
public static T[] RemoveRange<T>(this T[] input, int startIndex, int count)
|
||||
{
|
||||
var 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 bool Contains<T>(this T[] array, T value)
|
||||
{
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
if (array[i].Equals(value))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
// включает init и record из c# 9.0
|
||||
namespace System.Runtime.CompilerServices;
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public class IsExternalInit { }
|
||||
using System.ComponentModel;
|
||||
|
||||
// включает init и record из c# 9.0
|
||||
namespace System.Runtime.CompilerServices;
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public class IsExternalInit { }
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
namespace DTLib.Extensions;
|
||||
|
||||
public static class IfMethod
|
||||
{
|
||||
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);
|
||||
|
||||
public static void If<T>(this T input, bool condition, Action<T> if_true, Action<T> if_false)
|
||||
{
|
||||
if (condition) if_true(input);
|
||||
else if_false(input);
|
||||
}
|
||||
|
||||
public static T If<T>(this T input, bool condition, Func<T, T> if_true) =>
|
||||
condition ? if_true(input) : input;
|
||||
|
||||
public static void If<T>(this T input, bool condition, Action<T> if_true)
|
||||
{
|
||||
if (condition) if_true(input);
|
||||
}
|
||||
}
|
||||
namespace DTLib.Extensions;
|
||||
|
||||
public static class IfMethod
|
||||
{
|
||||
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);
|
||||
|
||||
public static void If<T>(this T input, bool condition, Action<T> if_true, Action<T> if_false)
|
||||
{
|
||||
if (condition) if_true(input);
|
||||
else if_false(input);
|
||||
}
|
||||
|
||||
public static T If<T>(this T input, bool condition, Func<T, T> if_true) =>
|
||||
condition ? if_true(input) : input;
|
||||
|
||||
public static void If<T>(this T input, bool condition, Action<T> if_true)
|
||||
{
|
||||
if (condition) if_true(input);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,147 +1,147 @@
|
||||
namespace DTLib.Extensions;
|
||||
|
||||
public static class StringConverter
|
||||
{
|
||||
public static Encoding UTF8 = new UTF8Encoding(false);
|
||||
public static byte[] ToBytes(this string str) => UTF8.GetBytes(str);
|
||||
public static string BytesToString(this byte[] bytes) => UTF8.GetString(bytes);
|
||||
|
||||
// хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
|
||||
public static string HashToString(this byte[] hash)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
for (int i = 0; i < hash.Length; i++)
|
||||
{
|
||||
builder.Append(hash[i].ToString("x2"));
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
|
||||
// эти методы работают как надо, в отличии от стандартных, которые иногда дуркуют
|
||||
public static bool StartsWith(this byte[] source, byte[] startsWith)
|
||||
{
|
||||
for (int i = 0; i < startsWith.Length; i++)
|
||||
{
|
||||
if (source[i] != startsWith[i])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool EndsWith(this byte[] source, byte[] endsWith)
|
||||
{
|
||||
for (int i = 0; i < endsWith.Length; i++)
|
||||
{
|
||||
if (source[source.Length - endsWith.Length + i] != endsWith[i])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool StartsWith(this string s, char c) => s[0] == c;
|
||||
public static bool EndsWith(this string s, char c) => s[s.Length - 1] == c;
|
||||
|
||||
public static string MergeToString(params object[] parts)
|
||||
{
|
||||
StringBuilder builder = new();
|
||||
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)
|
||||
{
|
||||
builder.Append(elem.ToString());
|
||||
builder.Append(separator);
|
||||
}
|
||||
if (builder.Length == 0)
|
||||
return "";
|
||||
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)
|
||||
builder.Append(elem.ToString());
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
public static string Multiply(this string input, int howMany)
|
||||
{
|
||||
StringBuilder b = new();
|
||||
for (int i = 0; i < howMany; i++)
|
||||
b.Append(input);
|
||||
return b.ToString();
|
||||
}
|
||||
public static string Multiply(this char input, int howMany)
|
||||
{
|
||||
StringBuilder b = new();
|
||||
for (int i = 0; i < howMany; i++)
|
||||
b.Append(input);
|
||||
return b.ToString();
|
||||
}
|
||||
|
||||
|
||||
// делает что надо в отличии от String.Split(), который не убирает char c из начала
|
||||
public static List<string> SplitToList(this string s, char c)
|
||||
{
|
||||
char[] ar = s.ToCharArray();
|
||||
StringBuilder b = new();
|
||||
List<string> o = new();
|
||||
if (ar[0] != c)
|
||||
b.Append(ar[0]);
|
||||
for (int i = 1; i < ar.Length; i++)
|
||||
if (ar[i] == c)
|
||||
{
|
||||
if (b.Length > 0)
|
||||
o.Add(b.ToString());
|
||||
b.Clear();
|
||||
}
|
||||
else b.Append(ar[i]);
|
||||
if (b.Length > 0) o.Add(b.ToString());
|
||||
return o;
|
||||
}
|
||||
|
||||
// правильно реагирует на кавычки
|
||||
public static List<string> SplitToList(this string s, char c, char quot)
|
||||
{
|
||||
List<string> output = new();
|
||||
List<string> list = s.SplitToList(c);
|
||||
bool q_open = false;
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
string _s = list[i];
|
||||
if (q_open)
|
||||
{
|
||||
if (_s.EndsWith(quot))
|
||||
{
|
||||
q_open = false;
|
||||
_s = _s.Remove(_s.Length - 1);
|
||||
}
|
||||
output[output.Count - 1] += c + _s;
|
||||
}
|
||||
else if (_s.StartsWith(quot))
|
||||
{
|
||||
q_open = true;
|
||||
_s = _s.Remove(0, 1);
|
||||
}
|
||||
output.Add(_s);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
// разбивает на части указанной длины
|
||||
public static List<string> SplitToList(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));
|
||||
return parts;
|
||||
}
|
||||
}
|
||||
namespace DTLib.Extensions;
|
||||
|
||||
public static class StringConverter
|
||||
{
|
||||
public static Encoding UTF8 = new UTF8Encoding(false);
|
||||
public static byte[] ToBytes(this string str) => UTF8.GetBytes(str);
|
||||
public static string BytesToString(this byte[] bytes) => UTF8.GetString(bytes);
|
||||
|
||||
// хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
|
||||
public static string HashToString(this byte[] hash)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
for (int i = 0; i < hash.Length; i++)
|
||||
{
|
||||
builder.Append(hash[i].ToString("x2"));
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
|
||||
// эти методы работают как надо, в отличии от стандартных, которые иногда дуркуют
|
||||
public static bool StartsWith(this byte[] source, byte[] startsWith)
|
||||
{
|
||||
for (int i = 0; i < startsWith.Length; i++)
|
||||
{
|
||||
if (source[i] != startsWith[i])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool EndsWith(this byte[] source, byte[] endsWith)
|
||||
{
|
||||
for (int i = 0; i < endsWith.Length; i++)
|
||||
{
|
||||
if (source[source.Length - endsWith.Length + i] != endsWith[i])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool StartsWith(this string s, char c) => s[0] == c;
|
||||
public static bool EndsWith(this string s, char c) => s[s.Length - 1] == c;
|
||||
|
||||
public static string MergeToString(params object[] parts)
|
||||
{
|
||||
StringBuilder builder = new();
|
||||
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)
|
||||
{
|
||||
builder.Append(elem.ToString());
|
||||
builder.Append(separator);
|
||||
}
|
||||
if (builder.Length == 0)
|
||||
return "";
|
||||
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)
|
||||
builder.Append(elem.ToString());
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
public static string Multiply(this string input, int howMany)
|
||||
{
|
||||
StringBuilder b = new();
|
||||
for (int i = 0; i < howMany; i++)
|
||||
b.Append(input);
|
||||
return b.ToString();
|
||||
}
|
||||
public static string Multiply(this char input, int howMany)
|
||||
{
|
||||
StringBuilder b = new();
|
||||
for (int i = 0; i < howMany; i++)
|
||||
b.Append(input);
|
||||
return b.ToString();
|
||||
}
|
||||
|
||||
|
||||
// делает что надо в отличии от String.Split(), который не убирает char c из начала
|
||||
public static List<string> SplitToList(this string s, char c)
|
||||
{
|
||||
char[] ar = s.ToCharArray();
|
||||
StringBuilder b = new();
|
||||
List<string> o = new();
|
||||
if (ar[0] != c)
|
||||
b.Append(ar[0]);
|
||||
for (int i = 1; i < ar.Length; i++)
|
||||
if (ar[i] == c)
|
||||
{
|
||||
if (b.Length > 0)
|
||||
o.Add(b.ToString());
|
||||
b.Clear();
|
||||
}
|
||||
else b.Append(ar[i]);
|
||||
if (b.Length > 0) o.Add(b.ToString());
|
||||
return o;
|
||||
}
|
||||
|
||||
// правильно реагирует на кавычки
|
||||
public static List<string> SplitToList(this string s, char c, char quot)
|
||||
{
|
||||
List<string> output = new();
|
||||
List<string> list = s.SplitToList(c);
|
||||
bool q_open = false;
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
string _s = list[i];
|
||||
if (q_open)
|
||||
{
|
||||
if (_s.EndsWith(quot))
|
||||
{
|
||||
q_open = false;
|
||||
_s = _s.Remove(_s.Length - 1);
|
||||
}
|
||||
output[output.Count - 1] += c + _s;
|
||||
}
|
||||
else if (_s.StartsWith(quot))
|
||||
{
|
||||
q_open = true;
|
||||
_s = _s.Remove(0, 1);
|
||||
}
|
||||
output.Add(_s);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
// разбивает на части указанной длины
|
||||
public static List<string> SplitToList(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));
|
||||
return parts;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,120 +1,120 @@
|
||||
namespace DTLib.Filesystem;
|
||||
|
||||
public static class Directory
|
||||
{
|
||||
public static bool Exists(string dir) => System.IO.Directory.Exists(dir);
|
||||
|
||||
// создает папку, если её не существует
|
||||
public static void Create(string dir)
|
||||
{
|
||||
if (!Directory.Exists(dir))
|
||||
{
|
||||
// проверяет существование папки, в которой нужно создать dir
|
||||
if (dir.Contains('\\') && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
|
||||
Create(dir.Remove(dir.LastIndexOf('\\')));
|
||||
System.IO.Directory.CreateDirectory(dir);
|
||||
}
|
||||
}
|
||||
// копирует все файлы и папки
|
||||
public static void Copy(string source_dir, string new_dir, bool owerwrite = false)
|
||||
{
|
||||
Create(new_dir);
|
||||
var subdirs = new List<string>();
|
||||
List<string> files = GetAllFiles(source_dir, ref subdirs);
|
||||
for (int i = 0; i < subdirs.Count; i++)
|
||||
Create(subdirs[i].Replace(source_dir, new_dir));
|
||||
for (int i = 0; i < files.Count; i++)
|
||||
File.Copy(files[i], files[i].Replace(source_dir, new_dir), owerwrite);
|
||||
}
|
||||
|
||||
// копирует все файлы и папки и выдаёт список конфликтующих файлов
|
||||
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>();
|
||||
List<string> files = GetAllFiles(source_dir, ref subdirs);
|
||||
Create(new_dir);
|
||||
for (int i = 0; i < subdirs.Count; i++)
|
||||
Create(subdirs[i].Replace(source_dir, new_dir));
|
||||
for (int i = 0; i < files.Count; i++)
|
||||
{
|
||||
string newfile = files[i].Replace(source_dir, new_dir);
|
||||
if (File.Exists(newfile))
|
||||
conflicts.Add(newfile);
|
||||
File.Copy(files[i], newfile, owerwrite);
|
||||
}
|
||||
}
|
||||
|
||||
// удаляет папку со всеми подпапками и файлами
|
||||
public static void Delete(string dir)
|
||||
{
|
||||
var subdirs = new List<string>();
|
||||
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]}");
|
||||
if (Directory.Exists(subdirs[i]))
|
||||
System.IO.Directory.Delete(subdirs[i], true);
|
||||
}
|
||||
PublicLog.Log($"deleting {dir}");
|
||||
if (Directory.Exists(dir))
|
||||
System.IO.Directory.Delete(dir, true);
|
||||
}
|
||||
|
||||
public static string[] GetFiles(string dir) => System.IO.Directory.GetFiles(dir);
|
||||
public static string[] GetFiles(string dir, string searchPattern) => System.IO.Directory.GetFiles(dir, searchPattern);
|
||||
public static string[] GetDirectories(string dir) => System.IO.Directory.GetDirectories(dir);
|
||||
|
||||
// выдает список всех файлов
|
||||
public static List<string> GetAllFiles(string dir)
|
||||
{
|
||||
var all_files = new List<string>();
|
||||
string[] cur_files = Directory.GetFiles(dir);
|
||||
for (int i = 0; i < cur_files.Length; i++)
|
||||
all_files.Add(cur_files[i]);
|
||||
string[] cur_subdirs = Directory.GetDirectories(dir);
|
||||
for (int i = 0; i < cur_subdirs.Length; i++)
|
||||
all_files.AddRange(GetAllFiles(cur_subdirs[i]));
|
||||
return all_files;
|
||||
}
|
||||
|
||||
// выдает список всех файлов и подпапок в папке
|
||||
public static List<string> GetAllFiles(string dir, ref List<string> all_subdirs)
|
||||
{
|
||||
var all_files = new List<string>();
|
||||
string[] cur_files = Directory.GetFiles(dir);
|
||||
for (int i = 0; i < cur_files.Length; i++)
|
||||
all_files.Add(cur_files[i]);
|
||||
string[] cur_subdirs = Directory.GetDirectories(dir);
|
||||
for (int i = 0; i < cur_subdirs.Length; i++)
|
||||
{
|
||||
all_subdirs.Add(cur_subdirs[i]);
|
||||
all_files.AddRange(GetAllFiles(cur_subdirs[i], ref all_subdirs));
|
||||
}
|
||||
return all_files;
|
||||
}
|
||||
|
||||
public static string GetCurrent() => System.IO.Directory.GetCurrentDirectory();
|
||||
|
||||
public static void CreateSymlink(string sourceName, string symlinkName)
|
||||
{
|
||||
if (symlinkName.Contains("\\"))
|
||||
Directory.Create(symlinkName.Remove(symlinkName.LastIndexOf('\\')));
|
||||
if (!Symlink.CreateSymbolicLink(symlinkName, sourceName, Symlink.SymlinkTarget.Directory))
|
||||
throw new InvalidOperationException($"some error occured while creating symlink\nDirectory.CreateSymlink({symlinkName}, {sourceName})");
|
||||
}
|
||||
|
||||
// copies directory with symlinks instead of files
|
||||
public static int SymCopy(string srcdir, string newdir)
|
||||
{
|
||||
List<string> files = Directory.GetAllFiles(srcdir);
|
||||
if (!srcdir.EndsWith('\\')) srcdir += '\\';
|
||||
if (!newdir.EndsWith('\\')) newdir += '\\';
|
||||
int i = 0;
|
||||
for (; i < files.Count; i++)
|
||||
File.CreateSymlink(files[i], files[i].Replace(srcdir, newdir));
|
||||
return i;
|
||||
}
|
||||
}
|
||||
namespace DTLib.Filesystem;
|
||||
|
||||
public static class Directory
|
||||
{
|
||||
public static bool Exists(string dir) => System.IO.Directory.Exists(dir);
|
||||
|
||||
// создает папку, если её не существует
|
||||
public static void Create(string dir)
|
||||
{
|
||||
if (!Directory.Exists(dir))
|
||||
{
|
||||
// проверяет существование папки, в которой нужно создать dir
|
||||
if (dir.Contains('\\') && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
|
||||
Create(dir.Remove(dir.LastIndexOf('\\')));
|
||||
System.IO.Directory.CreateDirectory(dir);
|
||||
}
|
||||
}
|
||||
// копирует все файлы и папки
|
||||
public static void Copy(string source_dir, string new_dir, bool owerwrite = false)
|
||||
{
|
||||
Create(new_dir);
|
||||
var subdirs = new List<string>();
|
||||
List<string> files = GetAllFiles(source_dir, ref subdirs);
|
||||
for (int i = 0; i < subdirs.Count; i++)
|
||||
Create(subdirs[i].Replace(source_dir, new_dir));
|
||||
for (int i = 0; i < files.Count; i++)
|
||||
File.Copy(files[i], files[i].Replace(source_dir, new_dir), owerwrite);
|
||||
}
|
||||
|
||||
// копирует все файлы и папки и выдаёт список конфликтующих файлов
|
||||
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>();
|
||||
List<string> files = GetAllFiles(source_dir, ref subdirs);
|
||||
Create(new_dir);
|
||||
for (int i = 0; i < subdirs.Count; i++)
|
||||
Create(subdirs[i].Replace(source_dir, new_dir));
|
||||
for (int i = 0; i < files.Count; i++)
|
||||
{
|
||||
string newfile = files[i].Replace(source_dir, new_dir);
|
||||
if (File.Exists(newfile))
|
||||
conflicts.Add(newfile);
|
||||
File.Copy(files[i], newfile, owerwrite);
|
||||
}
|
||||
}
|
||||
|
||||
// удаляет папку со всеми подпапками и файлами
|
||||
public static void Delete(string dir)
|
||||
{
|
||||
var subdirs = new List<string>();
|
||||
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]}");
|
||||
if (Directory.Exists(subdirs[i]))
|
||||
System.IO.Directory.Delete(subdirs[i], true);
|
||||
}
|
||||
PublicLog.Log($"deleting {dir}");
|
||||
if (Directory.Exists(dir))
|
||||
System.IO.Directory.Delete(dir, true);
|
||||
}
|
||||
|
||||
public static string[] GetFiles(string dir) => System.IO.Directory.GetFiles(dir);
|
||||
public static string[] GetFiles(string dir, string searchPattern) => System.IO.Directory.GetFiles(dir, searchPattern);
|
||||
public static string[] GetDirectories(string dir) => System.IO.Directory.GetDirectories(dir);
|
||||
|
||||
// выдает список всех файлов
|
||||
public static List<string> GetAllFiles(string dir)
|
||||
{
|
||||
var all_files = new List<string>();
|
||||
string[] cur_files = Directory.GetFiles(dir);
|
||||
for (int i = 0; i < cur_files.Length; i++)
|
||||
all_files.Add(cur_files[i]);
|
||||
string[] cur_subdirs = Directory.GetDirectories(dir);
|
||||
for (int i = 0; i < cur_subdirs.Length; i++)
|
||||
all_files.AddRange(GetAllFiles(cur_subdirs[i]));
|
||||
return all_files;
|
||||
}
|
||||
|
||||
// выдает список всех файлов и подпапок в папке
|
||||
public static List<string> GetAllFiles(string dir, ref List<string> all_subdirs)
|
||||
{
|
||||
var all_files = new List<string>();
|
||||
string[] cur_files = Directory.GetFiles(dir);
|
||||
for (int i = 0; i < cur_files.Length; i++)
|
||||
all_files.Add(cur_files[i]);
|
||||
string[] cur_subdirs = Directory.GetDirectories(dir);
|
||||
for (int i = 0; i < cur_subdirs.Length; i++)
|
||||
{
|
||||
all_subdirs.Add(cur_subdirs[i]);
|
||||
all_files.AddRange(GetAllFiles(cur_subdirs[i], ref all_subdirs));
|
||||
}
|
||||
return all_files;
|
||||
}
|
||||
|
||||
public static string GetCurrent() => System.IO.Directory.GetCurrentDirectory();
|
||||
|
||||
public static void CreateSymlink(string sourceName, string symlinkName)
|
||||
{
|
||||
if (symlinkName.Contains("\\"))
|
||||
Directory.Create(symlinkName.Remove(symlinkName.LastIndexOf('\\')));
|
||||
if (!Symlink.CreateSymbolicLink(symlinkName, sourceName, Symlink.SymlinkTarget.Directory))
|
||||
throw new InvalidOperationException($"some error occured while creating symlink\nDirectory.CreateSymlink({symlinkName}, {sourceName})");
|
||||
}
|
||||
|
||||
// copies directory with symlinks instead of files
|
||||
public static int SymCopy(string srcdir, string newdir)
|
||||
{
|
||||
List<string> files = Directory.GetAllFiles(srcdir);
|
||||
if (!srcdir.EndsWith('\\')) srcdir += '\\';
|
||||
if (!newdir.EndsWith('\\')) newdir += '\\';
|
||||
int i = 0;
|
||||
for (; i < files.Count; i++)
|
||||
File.CreateSymlink(files[i], files[i].Replace(srcdir, newdir));
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,83 +1,83 @@
|
||||
namespace DTLib.Filesystem;
|
||||
|
||||
public static class File
|
||||
{
|
||||
public static int GetSize(string file) => new System.IO.FileInfo(file).Length.ToInt();
|
||||
|
||||
public static bool Exists(string file) => System.IO.File.Exists(file);
|
||||
|
||||
// если файл не существует, создаёт файл, создаёт папки из его пути
|
||||
public static void Create(string file, bool delete_old = false)
|
||||
{
|
||||
if (delete_old && File.Exists(file))
|
||||
File.Delete(file);
|
||||
if (!File.Exists(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");
|
||||
Create(newPath);
|
||||
WriteAllBytes(newPath, ReadAllBytes(srcPath));
|
||||
}
|
||||
|
||||
public static void Delete(string file) => System.IO.File.Delete(file);
|
||||
|
||||
public static byte[] ReadAllBytes(string file)
|
||||
{
|
||||
using System.IO.FileStream stream = File.OpenRead(file);
|
||||
int size = GetSize(file);
|
||||
byte[] output = new byte[size];
|
||||
stream.Read(output, 0, size);
|
||||
stream.Close();
|
||||
return output;
|
||||
}
|
||||
|
||||
public static string ReadAllText(string file) => ReadAllBytes(file).BytesToString();
|
||||
|
||||
public static void WriteAllBytes(string file, byte[] content)
|
||||
{
|
||||
using System.IO.FileStream stream = File.OpenWrite(file);
|
||||
stream.Write(content, 0, content.Length);
|
||||
stream.Close();
|
||||
}
|
||||
|
||||
public static void WriteAllText(string file, string content) => WriteAllBytes(file, content.ToBytes());
|
||||
|
||||
public static void AppendAllBytes(string file, byte[] content)
|
||||
{
|
||||
using System.IO.FileStream stream = File.OpenAppend(file);
|
||||
stream.Write(content, 0, content.Length);
|
||||
stream.Close();
|
||||
}
|
||||
|
||||
public static void AppendAllText(string file, string content) => AppendAllBytes(file, content.ToBytes());
|
||||
|
||||
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);
|
||||
return System.IO.File.Open(file, System.IO.FileMode.OpenOrCreate);
|
||||
}
|
||||
public static System.IO.FileStream OpenAppend(string file)
|
||||
{
|
||||
File.Create(file);
|
||||
return System.IO.File.Open(file, System.IO.FileMode.Append);
|
||||
}
|
||||
|
||||
public static void CreateSymlink(string sourceName, string symlinkName)
|
||||
{
|
||||
if (symlinkName.Contains("\\"))
|
||||
Directory.Create(symlinkName.Remove(symlinkName.LastIndexOf('\\')));
|
||||
if (!Symlink.CreateSymbolicLink(symlinkName, sourceName, Symlink.SymlinkTarget.File))
|
||||
throw new InvalidOperationException($"some error occured while creating symlink\nFile.CreateSymlink({symlinkName}, {sourceName})");
|
||||
}
|
||||
}
|
||||
namespace DTLib.Filesystem;
|
||||
|
||||
public static class File
|
||||
{
|
||||
public static int GetSize(string file) => new System.IO.FileInfo(file).Length.ToInt();
|
||||
|
||||
public static bool Exists(string file) => System.IO.File.Exists(file);
|
||||
|
||||
// если файл не существует, создаёт файл, создаёт папки из его пути
|
||||
public static void Create(string file, bool delete_old = false)
|
||||
{
|
||||
if (delete_old && File.Exists(file))
|
||||
File.Delete(file);
|
||||
if (!File.Exists(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");
|
||||
Create(newPath);
|
||||
WriteAllBytes(newPath, ReadAllBytes(srcPath));
|
||||
}
|
||||
|
||||
public static void Delete(string file) => System.IO.File.Delete(file);
|
||||
|
||||
public static byte[] ReadAllBytes(string file)
|
||||
{
|
||||
using System.IO.FileStream stream = File.OpenRead(file);
|
||||
int size = GetSize(file);
|
||||
byte[] output = new byte[size];
|
||||
stream.Read(output, 0, size);
|
||||
stream.Close();
|
||||
return output;
|
||||
}
|
||||
|
||||
public static string ReadAllText(string file) => ReadAllBytes(file).BytesToString();
|
||||
|
||||
public static void WriteAllBytes(string file, byte[] content)
|
||||
{
|
||||
using System.IO.FileStream stream = File.OpenWrite(file);
|
||||
stream.Write(content, 0, content.Length);
|
||||
stream.Close();
|
||||
}
|
||||
|
||||
public static void WriteAllText(string file, string content) => WriteAllBytes(file, content.ToBytes());
|
||||
|
||||
public static void AppendAllBytes(string file, byte[] content)
|
||||
{
|
||||
using System.IO.FileStream stream = File.OpenAppend(file);
|
||||
stream.Write(content, 0, content.Length);
|
||||
stream.Close();
|
||||
}
|
||||
|
||||
public static void AppendAllText(string file, string content) => AppendAllBytes(file, content.ToBytes());
|
||||
|
||||
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);
|
||||
return System.IO.File.Open(file, System.IO.FileMode.OpenOrCreate);
|
||||
}
|
||||
public static System.IO.FileStream OpenAppend(string file)
|
||||
{
|
||||
File.Create(file);
|
||||
return System.IO.File.Open(file, System.IO.FileMode.Append);
|
||||
}
|
||||
|
||||
public static void CreateSymlink(string sourceName, string symlinkName)
|
||||
{
|
||||
if (symlinkName.Contains("\\"))
|
||||
Directory.Create(symlinkName.Remove(symlinkName.LastIndexOf('\\')));
|
||||
if (!Symlink.CreateSymbolicLink(symlinkName, sourceName, Symlink.SymlinkTarget.File))
|
||||
throw new InvalidOperationException($"some error occured while creating symlink\nFile.CreateSymlink({symlinkName}, {sourceName})");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,65 +1,65 @@
|
||||
namespace DTLib.Filesystem;
|
||||
|
||||
//
|
||||
// некоторые старые методы, которые хорошо бы вырезать
|
||||
//
|
||||
public static class OldFilework
|
||||
{
|
||||
// записывает текст в файл и закрывает файл
|
||||
/*public static void LogToFile(string logfile, string msg)
|
||||
{
|
||||
lock (new object())
|
||||
{
|
||||
File.AppendAllText(logfile, msg);
|
||||
}
|
||||
}*/
|
||||
|
||||
// чтение параметров из конфига
|
||||
public static string ReadFromConfig(string configfile, string key)
|
||||
{
|
||||
lock (new object())
|
||||
{
|
||||
key += ": ";
|
||||
using var reader = new System.IO.StreamReader(configfile);
|
||||
while (!reader.EndOfStream)
|
||||
{
|
||||
string st = reader.ReadLine();
|
||||
if (st.StartsWith(key))
|
||||
{
|
||||
string value = "";
|
||||
for (int i = key.Length; i < st.Length; i++)
|
||||
{
|
||||
if (st[i] == '#')
|
||||
return value;
|
||||
if (st[i] == '%')
|
||||
{
|
||||
bool stop = false;
|
||||
string placeholder = "";
|
||||
i++;
|
||||
while (!stop)
|
||||
{
|
||||
if (st[i] == '%')
|
||||
{
|
||||
stop = true;
|
||||
value += ReadFromConfig(configfile, placeholder);
|
||||
}
|
||||
else
|
||||
{
|
||||
placeholder += st[i];
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
value += st[i];
|
||||
}
|
||||
reader.Close();
|
||||
//if (value == "") throw new System.Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
|
||||
return value;
|
||||
}
|
||||
}
|
||||
reader.Close();
|
||||
throw new Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace DTLib.Filesystem;
|
||||
|
||||
//
|
||||
// некоторые старые методы, которые хорошо бы вырезать
|
||||
//
|
||||
public static class OldFilework
|
||||
{
|
||||
// записывает текст в файл и закрывает файл
|
||||
/*public static void LogToFile(string logfile, string msg)
|
||||
{
|
||||
lock (new object())
|
||||
{
|
||||
File.AppendAllText(logfile, msg);
|
||||
}
|
||||
}*/
|
||||
|
||||
// чтение параметров из конфига
|
||||
public static string ReadFromConfig(string configfile, string key)
|
||||
{
|
||||
lock (new object())
|
||||
{
|
||||
key += ": ";
|
||||
using var reader = new System.IO.StreamReader(configfile);
|
||||
while (!reader.EndOfStream)
|
||||
{
|
||||
string st = reader.ReadLine();
|
||||
if (st.StartsWith(key))
|
||||
{
|
||||
string value = "";
|
||||
for (int i = key.Length; i < st.Length; i++)
|
||||
{
|
||||
if (st[i] == '#')
|
||||
return value;
|
||||
if (st[i] == '%')
|
||||
{
|
||||
bool stop = false;
|
||||
string placeholder = "";
|
||||
i++;
|
||||
while (!stop)
|
||||
{
|
||||
if (st[i] == '%')
|
||||
{
|
||||
stop = true;
|
||||
value += ReadFromConfig(configfile, placeholder);
|
||||
}
|
||||
else
|
||||
{
|
||||
placeholder += st[i];
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
value += st[i];
|
||||
}
|
||||
reader.Close();
|
||||
//if (value == "") throw new System.Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
|
||||
return value;
|
||||
}
|
||||
}
|
||||
reader.Close();
|
||||
throw new Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
20
DTLib/Filesystem/Path.cs
Normal file
20
DTLib/Filesystem/Path.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
namespace DTLib.Filesystem;
|
||||
|
||||
static public class Path
|
||||
{
|
||||
|
||||
public static string CorrectSeparator(string path)
|
||||
{
|
||||
if (System.IO.Path.PathSeparator == '\\')
|
||||
{
|
||||
if (path.Contains('/'))
|
||||
path = path.Replace('/', '\\');
|
||||
}
|
||||
else if (System.IO.Path.PathSeparator == '/')
|
||||
{
|
||||
if (path.Contains('\\'))
|
||||
path = path.Replace('\\', '/');
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace DTLib.Filesystem;
|
||||
|
||||
internal class Symlink
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
internal static extern bool CreateSymbolicLink(string symlinkName, string sourceName, SymlinkTarget type);
|
||||
|
||||
internal enum SymlinkTarget
|
||||
{
|
||||
File,
|
||||
Directory
|
||||
}
|
||||
}
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace DTLib.Filesystem;
|
||||
|
||||
internal class Symlink
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
internal static extern bool CreateSymbolicLink(string symlinkName, string sourceName, SymlinkTarget type);
|
||||
|
||||
internal enum SymlinkTarget
|
||||
{
|
||||
File,
|
||||
Directory
|
||||
}
|
||||
}
|
||||
|
||||
114
DTLib/Hasher.cs
114
DTLib/Hasher.cs
@@ -1,57 +1,57 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DTLib;
|
||||
|
||||
//
|
||||
// хеширует массивы байтов алшоритмом SHA256 и файлы алгоримом XXHash32
|
||||
//
|
||||
public class Hasher
|
||||
{
|
||||
readonly HashAlgorithm sha256 = SHA256.Create();
|
||||
readonly HashAlgorithm xxh32 = XXHash32.Create();
|
||||
|
||||
public Hasher() { }
|
||||
|
||||
// хеш массива
|
||||
public byte[] Hash(byte[] input) => sha256.ComputeHash(input);
|
||||
|
||||
// хеш из двух массивов
|
||||
public byte[] Hash(byte[] input, byte[] salt)
|
||||
{
|
||||
var rez = new List<byte>();
|
||||
rez.AddRange(input);
|
||||
rez.AddRange(salt);
|
||||
return sha256.ComputeHash(rez.ToArray());
|
||||
}
|
||||
|
||||
// хеш двух массивов зацикленный
|
||||
public byte[] HashCycled(byte[] input, byte[] salt, ushort cycles)
|
||||
{
|
||||
for (uint i = 0; i < cycles; i++)
|
||||
{
|
||||
input = Hash(input, salt);
|
||||
}
|
||||
return input;
|
||||
}
|
||||
// хеш зацикленный
|
||||
public byte[] HashCycled(byte[] input, ushort cycles)
|
||||
{
|
||||
for (uint i = 0; i < cycles; i++)
|
||||
{
|
||||
input = Hash(input);
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
// хеш файла
|
||||
public byte[] HashFile(string filename)
|
||||
{
|
||||
using System.IO.FileStream fileStream = File.OpenRead(filename);
|
||||
//var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
|
||||
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}");
|
||||
fileStream.Close();
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DTLib;
|
||||
|
||||
//
|
||||
// хеширует массивы байтов алшоритмом SHA256 и файлы алгоримом XXHash32
|
||||
//
|
||||
public class Hasher
|
||||
{
|
||||
readonly HashAlgorithm sha256 = SHA256.Create();
|
||||
readonly HashAlgorithm xxh32 = XXHash32.Create();
|
||||
|
||||
public Hasher() { }
|
||||
|
||||
// хеш массива
|
||||
public byte[] Hash(byte[] input) => sha256.ComputeHash(input);
|
||||
|
||||
// хеш из двух массивов
|
||||
public byte[] Hash(byte[] input, byte[] salt)
|
||||
{
|
||||
var rez = new List<byte>();
|
||||
rez.AddRange(input);
|
||||
rez.AddRange(salt);
|
||||
return sha256.ComputeHash(rez.ToArray());
|
||||
}
|
||||
|
||||
// хеш двух массивов зацикленный
|
||||
public byte[] HashCycled(byte[] input, byte[] salt, ushort cycles)
|
||||
{
|
||||
for (uint i = 0; i < cycles; i++)
|
||||
{
|
||||
input = Hash(input, salt);
|
||||
}
|
||||
return input;
|
||||
}
|
||||
// хеш зацикленный
|
||||
public byte[] HashCycled(byte[] input, ushort cycles)
|
||||
{
|
||||
for (uint i = 0; i < cycles; i++)
|
||||
{
|
||||
input = Hash(input);
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
// хеш файла
|
||||
public byte[] HashFile(string filename)
|
||||
{
|
||||
using System.IO.FileStream fileStream = File.OpenRead(filename);
|
||||
//var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
|
||||
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}");
|
||||
fileStream.Close();
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
namespace DTLib.Loggers;
|
||||
|
||||
// вывод лога в консоль и файл
|
||||
public class AsyncLogger : BaseLogger
|
||||
{
|
||||
public AsyncLogger(string logfile) : base(logfile) { }
|
||||
|
||||
public AsyncLogger(string dir, string programName) : base(dir, programName) { }
|
||||
|
||||
readonly object consolelocker = new();
|
||||
public override void Log(params string[] msg)
|
||||
{
|
||||
lock (statelocker) if (!IsEnabled) return;
|
||||
// добавление даты
|
||||
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
|
||||
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
|
||||
// перенос строки
|
||||
msg[msg.Length - 1] += '\n';
|
||||
// вывод в консоль
|
||||
lock (consolelocker)
|
||||
ColoredConsole.Write(msg);
|
||||
// вывод в файл
|
||||
if (msg.Length == 1)
|
||||
lock (Logfile) File.AppendAllText(Logfile, msg[0]);
|
||||
else
|
||||
{
|
||||
StringBuilder strB = new();
|
||||
for (ushort i = 0; i < msg.Length; i++)
|
||||
strB.Append(msg[++i]);
|
||||
lock (Logfile) File.AppendAllText(Logfile, strB.ToString());
|
||||
}
|
||||
}
|
||||
public void LogAsync(params string[] msg) => Task.Run(() => Log(msg));
|
||||
}
|
||||
namespace DTLib.Loggers;
|
||||
|
||||
// вывод лога в консоль и файл
|
||||
public class AsyncLogger : BaseLogger
|
||||
{
|
||||
public AsyncLogger(string logfile) : base(logfile) { }
|
||||
|
||||
public AsyncLogger(string dir, string programName) : base(dir, programName) { }
|
||||
|
||||
readonly object consolelocker = new();
|
||||
public override void Log(params string[] msg)
|
||||
{
|
||||
lock (statelocker) if (!IsEnabled) return;
|
||||
// добавление даты
|
||||
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
|
||||
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
|
||||
// перенос строки
|
||||
msg[msg.Length - 1] += '\n';
|
||||
// вывод в консоль
|
||||
lock (consolelocker)
|
||||
ColoredConsole.Write(msg);
|
||||
// вывод в файл
|
||||
if (msg.Length == 1)
|
||||
lock (Logfile) File.AppendAllText(Logfile, msg[0]);
|
||||
else
|
||||
{
|
||||
StringBuilder strB = new();
|
||||
for (ushort i = 0; i < msg.Length; i++)
|
||||
strB.Append(msg[++i]);
|
||||
lock (Logfile) File.AppendAllText(Logfile, strB.ToString());
|
||||
}
|
||||
}
|
||||
public void LogAsync(params string[] msg) => Task.Run(() => Log(msg));
|
||||
}
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
namespace DTLib.Loggers;
|
||||
|
||||
public abstract class BaseLogger
|
||||
{
|
||||
public string Logfile { get; init; }
|
||||
public BaseLogger() { }
|
||||
public BaseLogger(string logfile) => (Logfile, WriteToFile) = (logfile,true);
|
||||
public BaseLogger(string dir, string programName)
|
||||
: this($"{dir}\\{programName}_{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_')) { }
|
||||
|
||||
|
||||
public bool IsEnabled { get; private set; } = false;
|
||||
public bool WriteToFile { get; private set; } = false;
|
||||
protected readonly object statelocker = new();
|
||||
public void Disable() { lock (statelocker) IsEnabled = false; }
|
||||
public void Enable() { lock (statelocker) IsEnabled = true; }
|
||||
|
||||
public abstract void Log(params string[] msg);
|
||||
}
|
||||
namespace DTLib.Loggers;
|
||||
|
||||
public abstract class BaseLogger
|
||||
{
|
||||
public string Logfile { get; init; }
|
||||
public BaseLogger() { }
|
||||
public BaseLogger(string logfile) => (Logfile, WriteToFile) = (logfile,true);
|
||||
public BaseLogger(string dir, string programName)
|
||||
: this($"{dir}\\{programName}_{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_')) { }
|
||||
|
||||
|
||||
public bool IsEnabled { get; private set; } = false;
|
||||
public bool WriteToFile { get; private set; } = false;
|
||||
protected readonly object statelocker = new();
|
||||
public void Disable() { lock (statelocker) IsEnabled = false; }
|
||||
public void Enable() { lock (statelocker) IsEnabled = true; }
|
||||
|
||||
public abstract void Log(params string[] msg);
|
||||
}
|
||||
|
||||
@@ -1,37 +1,37 @@
|
||||
namespace DTLib.Loggers;
|
||||
|
||||
// вывод лога в консоль и файл
|
||||
public class DefaultLogger : BaseLogger
|
||||
{
|
||||
public DefaultLogger() => Logfile = "";
|
||||
public DefaultLogger(string logfile) : base(logfile) { }
|
||||
|
||||
public DefaultLogger(string dir, string programName) : base(dir, programName) { }
|
||||
|
||||
public override void Log(params string[] msg)
|
||||
{
|
||||
lock (Logfile) if (!IsEnabled) return;
|
||||
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
|
||||
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
|
||||
LogNoTime(msg);
|
||||
}
|
||||
|
||||
public void LogNoTime(params string[] msg)
|
||||
{
|
||||
lock (Logfile) if (!IsEnabled) return;
|
||||
msg[msg.Length - 1] += '\n';
|
||||
ColoredConsole.Write(msg);
|
||||
if (WriteToFile)
|
||||
{
|
||||
if (msg.Length == 1)
|
||||
lock (Logfile) File.AppendAllText(Logfile, msg[0]);
|
||||
else
|
||||
{
|
||||
StringBuilder strB = new();
|
||||
for (ushort i = 0; i < msg.Length; i++)
|
||||
strB.Append(msg[++i]);
|
||||
lock (Logfile) File.AppendAllText(Logfile, strB.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace DTLib.Loggers;
|
||||
|
||||
// вывод лога в консоль и файл
|
||||
public class DefaultLogger : BaseLogger
|
||||
{
|
||||
public DefaultLogger() => Logfile = "";
|
||||
public DefaultLogger(string logfile) : base(logfile) { }
|
||||
|
||||
public DefaultLogger(string dir, string programName) : base(dir, programName) { }
|
||||
|
||||
public override void Log(params string[] msg)
|
||||
{
|
||||
lock (Logfile) if (!IsEnabled) return;
|
||||
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
|
||||
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
|
||||
LogNoTime(msg);
|
||||
}
|
||||
|
||||
public void LogNoTime(params string[] msg)
|
||||
{
|
||||
lock (Logfile) if (!IsEnabled) return;
|
||||
msg[msg.Length - 1] += '\n';
|
||||
ColoredConsole.Write(msg);
|
||||
if (WriteToFile)
|
||||
{
|
||||
if (msg.Length == 1)
|
||||
lock (Logfile) File.AppendAllText(Logfile, msg[0]);
|
||||
else
|
||||
{
|
||||
StringBuilder strB = new();
|
||||
for (ushort i = 0; i < msg.Length; i++)
|
||||
strB.Append(msg[++i]);
|
||||
lock (Logfile) File.AppendAllText(Logfile, strB.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,206 +1,206 @@
|
||||
using System.Net.Sockets;
|
||||
using DTLib.Dtsod;
|
||||
|
||||
namespace DTLib.Network;
|
||||
|
||||
//
|
||||
// передача файлов по сети
|
||||
//
|
||||
public class FSP
|
||||
{
|
||||
Socket MainSocket { get; init; }
|
||||
public static bool debug = false;
|
||||
public FSP(Socket _mainSocket) => MainSocket = _mainSocket;
|
||||
|
||||
public uint BytesDownloaded = 0;
|
||||
public uint BytesUploaded = 0;
|
||||
public uint Filesize = 0;
|
||||
|
||||
// скачивает файл с помощью FSP протокола
|
||||
public void DownloadFile(string filePath_server, string filePath_client)
|
||||
{
|
||||
lock (MainSocket)
|
||||
{
|
||||
Debug("b", $"requesting file download: {filePath_server}");
|
||||
MainSocket.SendPackage("requesting file download".ToBytes());
|
||||
MainSocket.SendPackage(filePath_server.ToBytes());
|
||||
}
|
||||
DownloadFile(filePath_client);
|
||||
}
|
||||
|
||||
public void DownloadFile(string filePath_client)
|
||||
{
|
||||
using System.IO.Stream fileStream = File.OpenWrite(filePath_client);
|
||||
Download_SharedCode(fileStream, true);
|
||||
fileStream.Close();
|
||||
Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes");
|
||||
}
|
||||
|
||||
public byte[] DownloadFileToMemory(string filePath_server)
|
||||
{
|
||||
lock (MainSocket)
|
||||
{
|
||||
Debug("b", $"requesting file download: {filePath_server}");
|
||||
MainSocket.SendPackage("requesting file download".ToBytes());
|
||||
MainSocket.SendPackage(filePath_server.ToBytes());
|
||||
}
|
||||
return DownloadFileToMemory();
|
||||
}
|
||||
|
||||
public byte[] DownloadFileToMemory()
|
||||
{
|
||||
using var fileStream = new System.IO.MemoryStream();
|
||||
Download_SharedCode(fileStream, false);
|
||||
byte[] output = fileStream.GetBuffer();
|
||||
fileStream.Close();
|
||||
Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes");
|
||||
return output;
|
||||
}
|
||||
|
||||
void Download_SharedCode(System.IO.Stream fileStream, bool requiresFlushing)
|
||||
{
|
||||
lock (MainSocket)
|
||||
{
|
||||
BytesDownloaded = 0;
|
||||
Filesize = MainSocket.GetPackage().BytesToString().ToUInt();
|
||||
MainSocket.SendPackage("ready".ToBytes());
|
||||
int packagesCount = 0;
|
||||
byte[] buffer = new byte[5120];
|
||||
int fullPackagesCount = (Filesize / buffer.Length).Truncate();
|
||||
// получение полных пакетов файла
|
||||
for (byte n = 0; packagesCount < fullPackagesCount; packagesCount++)
|
||||
{
|
||||
buffer = MainSocket.GetPackage();
|
||||
BytesDownloaded += (uint)buffer.Length;
|
||||
fileStream.Write(buffer, 0, buffer.Length);
|
||||
if (requiresFlushing)
|
||||
{
|
||||
if (n == 100)
|
||||
{
|
||||
fileStream.Flush();
|
||||
n = 0;
|
||||
}
|
||||
else
|
||||
n++;
|
||||
}
|
||||
}
|
||||
// получение остатка
|
||||
if ((Filesize - fileStream.Position) > 0)
|
||||
{
|
||||
MainSocket.SendPackage("remain request".ToBytes());
|
||||
buffer = MainSocket.GetPackage();
|
||||
BytesDownloaded += (uint)buffer.Length;
|
||||
fileStream.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
}
|
||||
if (requiresFlushing)
|
||||
fileStream.Flush();
|
||||
}
|
||||
|
||||
// отдаёт файл с помощью FSP протокола
|
||||
public void UploadFile(string filePath)
|
||||
{
|
||||
BytesUploaded = 0;
|
||||
Debug("b", $"uploading file {filePath}");
|
||||
using System.IO.FileStream fileStream = File.OpenRead(filePath);
|
||||
Filesize = File.GetSize(filePath).ToUInt();
|
||||
lock (MainSocket)
|
||||
{
|
||||
MainSocket.SendPackage(Filesize.ToString().ToBytes());
|
||||
MainSocket.GetAnswer("ready");
|
||||
byte[] buffer = new byte[5120];
|
||||
int packagesCount = 0;
|
||||
int fullPackagesCount = (Filesize / buffer.Length).Truncate();
|
||||
// отправка полных пакетов файла
|
||||
for (; packagesCount < fullPackagesCount; packagesCount++)
|
||||
{
|
||||
fileStream.Read(buffer, 0, buffer.Length);
|
||||
MainSocket.SendPackage(buffer);
|
||||
BytesUploaded += (uint)buffer.Length;
|
||||
}
|
||||
// отправка остатка
|
||||
if ((Filesize - fileStream.Position) > 0)
|
||||
{
|
||||
MainSocket.GetAnswer("remain request");
|
||||
buffer = new byte[(Filesize - fileStream.Position).ToInt()];
|
||||
fileStream.Read(buffer, 0, buffer.Length);
|
||||
MainSocket.SendPackage(buffer);
|
||||
BytesUploaded += (uint)buffer.Length;
|
||||
}
|
||||
}
|
||||
fileStream.Close();
|
||||
Debug("g", $" uploaded {BytesUploaded} of {Filesize} bytes");
|
||||
}
|
||||
|
||||
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", ">");
|
||||
var manifest = new DtsodV22(DownloadFileToMemory(dirOnServer + "manifest.dtsod").BytesToString());
|
||||
Debug("g", $"found {manifest.Values.Count} files in manifest");
|
||||
var hasher = new Hasher();
|
||||
foreach (string fileOnServer in manifest.Keys)
|
||||
{
|
||||
string fileOnClient = dirOnClient + fileOnServer;
|
||||
Debug("b", "file <", "c", fileOnClient, "b", ">... ");
|
||||
if (!File.Exists(fileOnClient))
|
||||
{
|
||||
DebugNoTime("y", "doesn't exist");
|
||||
DownloadFile(dirOnServer + fileOnServer, fileOnClient);
|
||||
}
|
||||
else if (overwrite && hasher.HashFile(fileOnClient).HashToString() != manifest[fileOnServer])
|
||||
{
|
||||
DebugNoTime("y", "outdated");
|
||||
DownloadFile(dirOnServer + fileOnServer, fileOnClient);
|
||||
}
|
||||
else
|
||||
DebugNoTime("g", "without changes");
|
||||
}
|
||||
// удаление лишних файлов
|
||||
if (delete_excess)
|
||||
{
|
||||
foreach (string file in Directory.GetAllFiles(dirOnClient))
|
||||
{
|
||||
if (!manifest.ContainsKey(file.Remove(0, dirOnClient.Length)))
|
||||
{
|
||||
Debug("y", $"deleting excess file: {file}");
|
||||
File.Delete(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void CreateManifest(string dir)
|
||||
{
|
||||
if (!dir.EndsWith("\\"))
|
||||
dir += "\\";
|
||||
Log($"b", $"creating manifest of {dir}");
|
||||
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))
|
||||
{
|
||||
string file = _file.Remove(0, dir.Length);
|
||||
manifestBuilder.Append(file);
|
||||
manifestBuilder.Append(": \"");
|
||||
byte[] hash = hasher.HashFile(dir + file);
|
||||
manifestBuilder.Append(hash.HashToString());
|
||||
manifestBuilder.Append("\";\n");
|
||||
}
|
||||
Debug($"g", $" manifest of {dir} created");
|
||||
File.WriteAllText(dir + "manifest.dtsod", manifestBuilder.ToString());
|
||||
}
|
||||
|
||||
static void Debug(params string[] msg)
|
||||
{
|
||||
if (debug) Log(msg);
|
||||
}
|
||||
static void DebugNoTime(params string[] msg)
|
||||
{
|
||||
if (debug) LogNoTime(msg);
|
||||
}
|
||||
}
|
||||
using System.Net.Sockets;
|
||||
using DTLib.Dtsod;
|
||||
|
||||
namespace DTLib.Network;
|
||||
|
||||
//
|
||||
// передача файлов по сети
|
||||
//
|
||||
public class FSP
|
||||
{
|
||||
Socket MainSocket { get; init; }
|
||||
public static bool debug = false;
|
||||
public FSP(Socket _mainSocket) => MainSocket = _mainSocket;
|
||||
|
||||
public uint BytesDownloaded = 0;
|
||||
public uint BytesUploaded = 0;
|
||||
public uint Filesize = 0;
|
||||
|
||||
// скачивает файл с помощью FSP протокола
|
||||
public void DownloadFile(string filePath_server, string filePath_client)
|
||||
{
|
||||
lock (MainSocket)
|
||||
{
|
||||
Debug("b", $"requesting file download: {filePath_server}");
|
||||
MainSocket.SendPackage("requesting file download".ToBytes());
|
||||
MainSocket.SendPackage(filePath_server.ToBytes());
|
||||
}
|
||||
DownloadFile(filePath_client);
|
||||
}
|
||||
|
||||
public void DownloadFile(string filePath_client)
|
||||
{
|
||||
using System.IO.Stream fileStream = File.OpenWrite(filePath_client);
|
||||
Download_SharedCode(fileStream, true);
|
||||
fileStream.Close();
|
||||
Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes");
|
||||
}
|
||||
|
||||
public byte[] DownloadFileToMemory(string filePath_server)
|
||||
{
|
||||
lock (MainSocket)
|
||||
{
|
||||
Debug("b", $"requesting file download: {filePath_server}");
|
||||
MainSocket.SendPackage("requesting file download".ToBytes());
|
||||
MainSocket.SendPackage(filePath_server.ToBytes());
|
||||
}
|
||||
return DownloadFileToMemory();
|
||||
}
|
||||
|
||||
public byte[] DownloadFileToMemory()
|
||||
{
|
||||
using var fileStream = new System.IO.MemoryStream();
|
||||
Download_SharedCode(fileStream, false);
|
||||
byte[] output = fileStream.GetBuffer();
|
||||
fileStream.Close();
|
||||
Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes");
|
||||
return output;
|
||||
}
|
||||
|
||||
void Download_SharedCode(System.IO.Stream fileStream, bool requiresFlushing)
|
||||
{
|
||||
lock (MainSocket)
|
||||
{
|
||||
BytesDownloaded = 0;
|
||||
Filesize = MainSocket.GetPackage().BytesToString().ToUInt();
|
||||
MainSocket.SendPackage("ready".ToBytes());
|
||||
int packagesCount = 0;
|
||||
byte[] buffer = new byte[5120];
|
||||
int fullPackagesCount = (Filesize / buffer.Length).Truncate();
|
||||
// получение полных пакетов файла
|
||||
for (byte n = 0; packagesCount < fullPackagesCount; packagesCount++)
|
||||
{
|
||||
buffer = MainSocket.GetPackage();
|
||||
BytesDownloaded += (uint)buffer.Length;
|
||||
fileStream.Write(buffer, 0, buffer.Length);
|
||||
if (requiresFlushing)
|
||||
{
|
||||
if (n == 100)
|
||||
{
|
||||
fileStream.Flush();
|
||||
n = 0;
|
||||
}
|
||||
else
|
||||
n++;
|
||||
}
|
||||
}
|
||||
// получение остатка
|
||||
if ((Filesize - fileStream.Position) > 0)
|
||||
{
|
||||
MainSocket.SendPackage("remain request".ToBytes());
|
||||
buffer = MainSocket.GetPackage();
|
||||
BytesDownloaded += (uint)buffer.Length;
|
||||
fileStream.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
}
|
||||
if (requiresFlushing)
|
||||
fileStream.Flush();
|
||||
}
|
||||
|
||||
// отдаёт файл с помощью FSP протокола
|
||||
public void UploadFile(string filePath)
|
||||
{
|
||||
BytesUploaded = 0;
|
||||
Debug("b", $"uploading file {filePath}");
|
||||
using System.IO.FileStream fileStream = File.OpenRead(filePath);
|
||||
Filesize = File.GetSize(filePath).ToUInt();
|
||||
lock (MainSocket)
|
||||
{
|
||||
MainSocket.SendPackage(Filesize.ToString().ToBytes());
|
||||
MainSocket.GetAnswer("ready");
|
||||
byte[] buffer = new byte[5120];
|
||||
int packagesCount = 0;
|
||||
int fullPackagesCount = (Filesize / buffer.Length).Truncate();
|
||||
// отправка полных пакетов файла
|
||||
for (; packagesCount < fullPackagesCount; packagesCount++)
|
||||
{
|
||||
fileStream.Read(buffer, 0, buffer.Length);
|
||||
MainSocket.SendPackage(buffer);
|
||||
BytesUploaded += (uint)buffer.Length;
|
||||
}
|
||||
// отправка остатка
|
||||
if ((Filesize - fileStream.Position) > 0)
|
||||
{
|
||||
MainSocket.GetAnswer("remain request");
|
||||
buffer = new byte[(Filesize - fileStream.Position).ToInt()];
|
||||
fileStream.Read(buffer, 0, buffer.Length);
|
||||
MainSocket.SendPackage(buffer);
|
||||
BytesUploaded += (uint)buffer.Length;
|
||||
}
|
||||
}
|
||||
fileStream.Close();
|
||||
Debug("g", $" uploaded {BytesUploaded} of {Filesize} bytes");
|
||||
}
|
||||
|
||||
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", ">");
|
||||
var manifest = new DtsodV22(DownloadFileToMemory(dirOnServer + "manifest.dtsod").BytesToString());
|
||||
Debug("g", $"found {manifest.Values.Count} files in manifest");
|
||||
var hasher = new Hasher();
|
||||
foreach (string fileOnServer in manifest.Keys)
|
||||
{
|
||||
string fileOnClient = dirOnClient + fileOnServer;
|
||||
Debug("b", "file <", "c", fileOnClient, "b", ">... ");
|
||||
if (!File.Exists(fileOnClient))
|
||||
{
|
||||
DebugNoTime("y", "doesn't exist");
|
||||
DownloadFile(dirOnServer + fileOnServer, fileOnClient);
|
||||
}
|
||||
else if (overwrite && hasher.HashFile(fileOnClient).HashToString() != manifest[fileOnServer])
|
||||
{
|
||||
DebugNoTime("y", "outdated");
|
||||
DownloadFile(dirOnServer + fileOnServer, fileOnClient);
|
||||
}
|
||||
else
|
||||
DebugNoTime("g", "without changes");
|
||||
}
|
||||
// удаление лишних файлов
|
||||
if (delete_excess)
|
||||
{
|
||||
foreach (string file in Directory.GetAllFiles(dirOnClient))
|
||||
{
|
||||
if (!manifest.ContainsKey(file.Remove(0, dirOnClient.Length)))
|
||||
{
|
||||
Debug("y", $"deleting excess file: {file}");
|
||||
File.Delete(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void CreateManifest(string dir)
|
||||
{
|
||||
if (!dir.EndsWith("\\"))
|
||||
dir += "\\";
|
||||
Log($"b", $"creating manifest of {dir}");
|
||||
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))
|
||||
{
|
||||
string file = _file.Remove(0, dir.Length);
|
||||
manifestBuilder.Append(file);
|
||||
manifestBuilder.Append(": \"");
|
||||
byte[] hash = hasher.HashFile(dir + file);
|
||||
manifestBuilder.Append(hash.HashToString());
|
||||
manifestBuilder.Append("\";\n");
|
||||
}
|
||||
Debug($"g", $" manifest of {dir} created");
|
||||
File.WriteAllText(dir + "manifest.dtsod", manifestBuilder.ToString());
|
||||
}
|
||||
|
||||
static void Debug(params string[] msg)
|
||||
{
|
||||
if (debug) Log(msg);
|
||||
}
|
||||
static void DebugNoTime(params string[] msg)
|
||||
{
|
||||
if (debug) LogNoTime(msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net.Http;
|
||||
|
||||
namespace DTLib.Network;
|
||||
|
||||
//
|
||||
// пара почти никогда не используемых методов
|
||||
//
|
||||
public static class OldNetwork
|
||||
{
|
||||
|
||||
|
||||
// получает с сайта публичный ip
|
||||
public static string GetPublicIP() => new HttpClient().GetStringAsync("https://ifconfig.me/ip").GetAwaiter().GetResult();
|
||||
|
||||
// пингует айпи с помощью встроенной в винду проги, возвращает задержку
|
||||
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;
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
using System.Diagnostics;
|
||||
using System.Net.Http;
|
||||
|
||||
namespace DTLib.Network;
|
||||
|
||||
//
|
||||
// пара почти никогда не используемых методов
|
||||
//
|
||||
public static class OldNetwork
|
||||
{
|
||||
|
||||
|
||||
// получает с сайта публичный ip
|
||||
public static string GetPublicIP() => new HttpClient().GetStringAsync("https://ifconfig.me/ip").GetAwaiter().GetResult();
|
||||
|
||||
// пингует айпи с помощью встроенной в винду проги, возвращает задержку
|
||||
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;
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,67 +1,67 @@
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
|
||||
namespace DTLib.Network;
|
||||
|
||||
//
|
||||
// отправка/получение пакетов
|
||||
//
|
||||
public static class Package
|
||||
{
|
||||
// принимает пакет
|
||||
public static byte[] GetPackage(this Socket socket)
|
||||
{
|
||||
int packageSize = 0;
|
||||
byte[] data = new byte[2];
|
||||
// цикл выполняется пока не пройдёт 2000 мс
|
||||
for (ushort s = 0; s < 400; s += 1)
|
||||
{
|
||||
if (packageSize == 0 && socket.Available >= 2)
|
||||
{
|
||||
socket.Receive(data, data.Length, 0);
|
||||
packageSize = data.ToInt();
|
||||
}
|
||||
if (packageSize != 0 && socket.Available >= packageSize)
|
||||
{
|
||||
data = new byte[packageSize];
|
||||
socket.Receive(data, data.Length, 0);
|
||||
return data;
|
||||
}
|
||||
else
|
||||
Thread.Sleep(5);
|
||||
}
|
||||
throw new Exception($"GetPackage() error: timeout. socket.Available={socket.Available}");
|
||||
}
|
||||
|
||||
// отправляет пакет
|
||||
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");
|
||||
var list = new List<byte>();
|
||||
byte[] packageSize = data.Length.ToBytes();
|
||||
if (packageSize.Length == 1)
|
||||
list.Add(0);
|
||||
list.AddRange(packageSize);
|
||||
list.AddRange(data);
|
||||
socket.Send(list.ToArray());
|
||||
}
|
||||
public static void SendPackage(this Socket socket, string data) => SendPackage(socket, data.ToBytes());
|
||||
|
||||
// получает пакет и выбрасывает исключение, если пакет не соответствует образцу
|
||||
public static void GetAnswer(this Socket socket, string answer)
|
||||
{
|
||||
string rec = socket.GetPackage().BytesToString();
|
||||
if (rec != answer)
|
||||
throw new Exception($"GetAnswer() error: invalid answer: <{rec}>");
|
||||
}
|
||||
|
||||
public static byte[] RequestPackage(this Socket socket, byte[] request)
|
||||
{
|
||||
socket.SendPackage(request);
|
||||
return socket.GetPackage();
|
||||
}
|
||||
public static byte[] RequestPackage(this Socket socket, string request) => socket.RequestPackage(request.ToBytes());
|
||||
}
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
|
||||
namespace DTLib.Network;
|
||||
|
||||
//
|
||||
// отправка/получение пакетов
|
||||
//
|
||||
public static class Package
|
||||
{
|
||||
// принимает пакет
|
||||
public static byte[] GetPackage(this Socket socket)
|
||||
{
|
||||
int packageSize = 0;
|
||||
byte[] data = new byte[2];
|
||||
// цикл выполняется пока не пройдёт 2000 мс
|
||||
for (ushort s = 0; s < 400; s += 1)
|
||||
{
|
||||
if (packageSize == 0 && socket.Available >= 2)
|
||||
{
|
||||
socket.Receive(data, data.Length, 0);
|
||||
packageSize = data.ToInt();
|
||||
}
|
||||
if (packageSize != 0 && socket.Available >= packageSize)
|
||||
{
|
||||
data = new byte[packageSize];
|
||||
socket.Receive(data, data.Length, 0);
|
||||
return data;
|
||||
}
|
||||
else
|
||||
Thread.Sleep(5);
|
||||
}
|
||||
throw new Exception($"GetPackage() error: timeout. socket.Available={socket.Available}");
|
||||
}
|
||||
|
||||
// отправляет пакет
|
||||
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");
|
||||
var list = new List<byte>();
|
||||
byte[] packageSize = data.Length.ToBytes();
|
||||
if (packageSize.Length == 1)
|
||||
list.Add(0);
|
||||
list.AddRange(packageSize);
|
||||
list.AddRange(data);
|
||||
socket.Send(list.ToArray());
|
||||
}
|
||||
public static void SendPackage(this Socket socket, string data) => SendPackage(socket, data.ToBytes());
|
||||
|
||||
// получает пакет и выбрасывает исключение, если пакет не соответствует образцу
|
||||
public static void GetAnswer(this Socket socket, string answer)
|
||||
{
|
||||
string rec = socket.GetPackage().BytesToString();
|
||||
if (rec != answer)
|
||||
throw new Exception($"GetAnswer() error: invalid answer: <{rec}>");
|
||||
}
|
||||
|
||||
public static byte[] RequestPackage(this Socket socket, byte[] request)
|
||||
{
|
||||
socket.SendPackage(request);
|
||||
return socket.GetPackage();
|
||||
}
|
||||
public static byte[] RequestPackage(this Socket socket, string request) => socket.RequestPackage(request.ToBytes());
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
namespace DTLib;
|
||||
|
||||
//
|
||||
// вывод логов со всех классов в библиотеке
|
||||
//
|
||||
public static class PublicLog
|
||||
{
|
||||
public delegate void LogDelegate(params string[] msg);
|
||||
// вот к этому объекту подключайте методы для вывода логов
|
||||
public static event LogDelegate LogEvent;
|
||||
public static void Log(params string[] msg) => LogEvent?.Invoke(msg);
|
||||
|
||||
public static event LogDelegate LogNoTimeEvent;
|
||||
public static void LogNoTime(params string[] msg) => LogNoTimeEvent?.Invoke(msg);
|
||||
}
|
||||
namespace DTLib;
|
||||
|
||||
//
|
||||
// вывод логов со всех классов в библиотеке
|
||||
//
|
||||
public static class PublicLog
|
||||
{
|
||||
public delegate void LogDelegate(params string[] msg);
|
||||
// вот к этому объекту подключайте методы для вывода логов
|
||||
public static event LogDelegate LogEvent;
|
||||
public static void Log(params string[] msg) => LogEvent?.Invoke(msg);
|
||||
|
||||
public static event LogDelegate LogNoTimeEvent;
|
||||
public static void LogNoTime(params string[] msg) => LogNoTimeEvent?.Invoke(msg);
|
||||
}
|
||||
|
||||
@@ -1,39 +1,39 @@
|
||||
using System.Threading;
|
||||
|
||||
namespace DTLib;
|
||||
|
||||
//
|
||||
// простой и понятный класс для выполнения каких-либо действий в отдельном потоке раз в некоторое время
|
||||
//
|
||||
public class Timer
|
||||
{
|
||||
Task TimerTask;
|
||||
bool Repeat;
|
||||
CancellationTokenSource кансель = new();
|
||||
|
||||
// таймер сразу запускается
|
||||
public Timer(bool repeat, int delay, Action method)
|
||||
{
|
||||
Repeat = repeat;
|
||||
TimerTask = new Task(() =>
|
||||
{
|
||||
do
|
||||
{
|
||||
if (кансель.Token.IsCancellationRequested)
|
||||
return;
|
||||
Task.Delay(delay).Wait();
|
||||
method();
|
||||
} while (Repeat);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public void Start() => TimerTask.Start();
|
||||
|
||||
// завершение потока
|
||||
public void Stop()
|
||||
{
|
||||
Repeat = false;
|
||||
кансель.Cancel();
|
||||
}
|
||||
}
|
||||
using System.Threading;
|
||||
|
||||
namespace DTLib;
|
||||
|
||||
//
|
||||
// простой и понятный класс для выполнения каких-либо действий в отдельном потоке раз в некоторое время
|
||||
//
|
||||
public class Timer
|
||||
{
|
||||
Task TimerTask;
|
||||
bool Repeat;
|
||||
CancellationTokenSource кансель = new();
|
||||
|
||||
// таймер сразу запускается
|
||||
public Timer(bool repeat, int delay, Action method)
|
||||
{
|
||||
Repeat = repeat;
|
||||
TimerTask = new Task(() =>
|
||||
{
|
||||
do
|
||||
{
|
||||
if (кансель.Token.IsCancellationRequested)
|
||||
return;
|
||||
Task.Delay(delay).Wait();
|
||||
method();
|
||||
} while (Repeat);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public void Start() => TimerTask.Start();
|
||||
|
||||
// завершение потока
|
||||
public void Stop()
|
||||
{
|
||||
Repeat = false;
|
||||
кансель.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
346
DTLib/XXHash.cs
346
DTLib/XXHash.cs
@@ -1,173 +1,173 @@
|
||||
using System.Security.Cryptography;
|
||||
namespace DTLib;
|
||||
|
||||
// честно взятый с гитхаба алгоритм хеширования
|
||||
// выдаёт хеш в виде массива четырёх байтов
|
||||
sealed class XXHash32 : HashAlgorithm
|
||||
{
|
||||
private const uint PRIME32_1 = 2654435761U;
|
||||
private const uint PRIME32_2 = 2246822519U;
|
||||
private const uint PRIME32_3 = 3266489917U;
|
||||
private const uint PRIME32_4 = 668265263U;
|
||||
private const uint PRIME32_5 = 374761393U;
|
||||
private static readonly Func<byte[], int, uint> FuncGetLittleEndianUInt32;
|
||||
private static readonly Func<uint, uint> FuncGetFinalHashUInt32;
|
||||
private uint _Seed32;
|
||||
private uint _ACC32_1;
|
||||
private uint _ACC32_2;
|
||||
private uint _ACC32_3;
|
||||
private uint _ACC32_4;
|
||||
private uint _Hash32;
|
||||
private int _RemainingLength;
|
||||
private long _TotalLength = 0;
|
||||
private int _CurrentIndex;
|
||||
private byte[] _CurrentArray;
|
||||
|
||||
static XXHash32()
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* array = x)
|
||||
{
|
||||
return *(uint*)(array + i);
|
||||
}
|
||||
}
|
||||
});
|
||||
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => (i & 0x000000FFU) << 24 | (i & 0x0000FF00U) << 8 | (i & 0x00FF0000U) >> 8 | (i & 0xFF000000U) >> 24);
|
||||
}
|
||||
else
|
||||
{
|
||||
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* array = x)
|
||||
{
|
||||
return (uint)(array[i++] | (array[i++] << 8) | (array[i++] << 16) | (array[i] << 24));
|
||||
}
|
||||
}
|
||||
});
|
||||
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => i);
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an instance of <see cref="XXHash32"/> class by default seed(0).
|
||||
/// <returns></returns>
|
||||
public static new XXHash32 Create() => new();
|
||||
|
||||
/// Initializes a new instance of the <see cref="XXHash32"/> class by default seed(0).
|
||||
public XXHash32() => Initialize(0);
|
||||
|
||||
/// Initializes a new instance of the <see cref="XXHash32"/> class, and sets the <see cref="Seed"/> to the specified value.
|
||||
/// <param name="seed">Represent the seed to be used for xxHash32 computing.</param>
|
||||
public XXHash32(uint seed) => Initialize(seed);
|
||||
|
||||
/// Gets the <see cref="uint"/> value of the computed hash code.
|
||||
/// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
||||
public uint HashUInt32 => State == 0 ? _Hash32 : throw new InvalidOperationException("Hash computation has not yet completed.");
|
||||
|
||||
/// Gets or sets the value of seed used by xxHash32 algorithm.
|
||||
/// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
||||
public uint Seed
|
||||
{
|
||||
get => _Seed32;
|
||||
set
|
||||
{
|
||||
if (value != _Seed32)
|
||||
{
|
||||
if (State != 0)
|
||||
throw new InvalidOperationException("Hash computation has not yet completed.");
|
||||
_Seed32 = value;
|
||||
Initialize();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes this instance for new hash computing.
|
||||
public override void Initialize()
|
||||
{
|
||||
_ACC32_1 = _Seed32 + PRIME32_1 + PRIME32_2;
|
||||
_ACC32_2 = _Seed32 + PRIME32_2;
|
||||
_ACC32_3 = _Seed32 + 0;
|
||||
_ACC32_4 = _Seed32 - PRIME32_1;
|
||||
}
|
||||
|
||||
/// Routes data written to the object into the hash algorithm for computing the hash.
|
||||
/// <param name="array">The input to compute the hash code for.</param>
|
||||
/// <param name="ibStart">The offset into the byte array from which to begin using data.</param>
|
||||
/// <param name="cbSize">The number of bytes in the byte array to use as data.</param>
|
||||
protected override void HashCore(byte[] array, int ibStart, int cbSize)
|
||||
{
|
||||
if (State != 1)
|
||||
State = 1;
|
||||
int size = cbSize - ibStart;
|
||||
_RemainingLength = size & 15;
|
||||
if (cbSize >= 16)
|
||||
{
|
||||
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);
|
||||
}
|
||||
_TotalLength += cbSize;
|
||||
if (_RemainingLength != 0)
|
||||
{
|
||||
_CurrentArray = array;
|
||||
_CurrentIndex = ibStart;
|
||||
}
|
||||
}
|
||||
|
||||
/// Finalizes the hash computation after the last data is processed by the cryptographic stream object.
|
||||
/// <returns>The computed hash code.</returns>
|
||||
protected override byte[] HashFinal()
|
||||
{
|
||||
_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(_Hash32 + FuncGetLittleEndianUInt32(_CurrentArray, _CurrentIndex) * PRIME32_3, 17) * PRIME32_4;
|
||||
_CurrentIndex += 4;
|
||||
_RemainingLength -= 4;
|
||||
}
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* arrayPtr = _CurrentArray)
|
||||
{
|
||||
while (_RemainingLength-- >= 1)
|
||||
{
|
||||
_Hash32 = RotateLeft32(_Hash32 + arrayPtr[_CurrentIndex++] * PRIME32_5, 11) * PRIME32_1;
|
||||
}
|
||||
}
|
||||
}
|
||||
_Hash32 = (_Hash32 ^ (_Hash32 >> 15)) * PRIME32_2;
|
||||
_Hash32 = (_Hash32 ^ (_Hash32 >> 13)) * PRIME32_3;
|
||||
_Hash32 ^= _Hash32 >> 16;
|
||||
_TotalLength = State = 0;
|
||||
return BitConverter.GetBytes(FuncGetFinalHashUInt32(_Hash32));
|
||||
}
|
||||
|
||||
private static uint Round32(uint input, uint value) => RotateLeft32(input + (value * PRIME32_2), 13) * PRIME32_1;
|
||||
|
||||
private static uint RotateLeft32(uint value, int count) => (value << count) | (value >> (32 - count));
|
||||
|
||||
private void Initialize(uint seed)
|
||||
{
|
||||
HashSizeValue = 32;
|
||||
_Seed32 = seed;
|
||||
Initialize();
|
||||
}
|
||||
}
|
||||
using System.Security.Cryptography;
|
||||
namespace DTLib;
|
||||
|
||||
// честно взятый с гитхаба алгоритм хеширования
|
||||
// выдаёт хеш в виде массива четырёх байтов
|
||||
sealed class XXHash32 : HashAlgorithm
|
||||
{
|
||||
private const uint PRIME32_1 = 2654435761U;
|
||||
private const uint PRIME32_2 = 2246822519U;
|
||||
private const uint PRIME32_3 = 3266489917U;
|
||||
private const uint PRIME32_4 = 668265263U;
|
||||
private const uint PRIME32_5 = 374761393U;
|
||||
private static readonly Func<byte[], int, uint> FuncGetLittleEndianUInt32;
|
||||
private static readonly Func<uint, uint> FuncGetFinalHashUInt32;
|
||||
private uint _Seed32;
|
||||
private uint _ACC32_1;
|
||||
private uint _ACC32_2;
|
||||
private uint _ACC32_3;
|
||||
private uint _ACC32_4;
|
||||
private uint _Hash32;
|
||||
private int _RemainingLength;
|
||||
private long _TotalLength = 0;
|
||||
private int _CurrentIndex;
|
||||
private byte[] _CurrentArray;
|
||||
|
||||
static XXHash32()
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* array = x)
|
||||
{
|
||||
return *(uint*)(array + i);
|
||||
}
|
||||
}
|
||||
});
|
||||
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => (i & 0x000000FFU) << 24 | (i & 0x0000FF00U) << 8 | (i & 0x00FF0000U) >> 8 | (i & 0xFF000000U) >> 24);
|
||||
}
|
||||
else
|
||||
{
|
||||
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* array = x)
|
||||
{
|
||||
return (uint)(array[i++] | (array[i++] << 8) | (array[i++] << 16) | (array[i] << 24));
|
||||
}
|
||||
}
|
||||
});
|
||||
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => i);
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an instance of <see cref="XXHash32"/> class by default seed(0).
|
||||
/// <returns></returns>
|
||||
public static new XXHash32 Create() => new();
|
||||
|
||||
/// Initializes a new instance of the <see cref="XXHash32"/> class by default seed(0).
|
||||
public XXHash32() => Initialize(0);
|
||||
|
||||
/// Initializes a new instance of the <see cref="XXHash32"/> class, and sets the <see cref="Seed"/> to the specified value.
|
||||
/// <param name="seed">Represent the seed to be used for xxHash32 computing.</param>
|
||||
public XXHash32(uint seed) => Initialize(seed);
|
||||
|
||||
/// Gets the <see cref="uint"/> value of the computed hash code.
|
||||
/// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
||||
public uint HashUInt32 => State == 0 ? _Hash32 : throw new InvalidOperationException("Hash computation has not yet completed.");
|
||||
|
||||
/// Gets or sets the value of seed used by xxHash32 algorithm.
|
||||
/// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
||||
public uint Seed
|
||||
{
|
||||
get => _Seed32;
|
||||
set
|
||||
{
|
||||
if (value != _Seed32)
|
||||
{
|
||||
if (State != 0)
|
||||
throw new InvalidOperationException("Hash computation has not yet completed.");
|
||||
_Seed32 = value;
|
||||
Initialize();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes this instance for new hash computing.
|
||||
public override void Initialize()
|
||||
{
|
||||
_ACC32_1 = _Seed32 + PRIME32_1 + PRIME32_2;
|
||||
_ACC32_2 = _Seed32 + PRIME32_2;
|
||||
_ACC32_3 = _Seed32 + 0;
|
||||
_ACC32_4 = _Seed32 - PRIME32_1;
|
||||
}
|
||||
|
||||
/// Routes data written to the object into the hash algorithm for computing the hash.
|
||||
/// <param name="array">The input to compute the hash code for.</param>
|
||||
/// <param name="ibStart">The offset into the byte array from which to begin using data.</param>
|
||||
/// <param name="cbSize">The number of bytes in the byte array to use as data.</param>
|
||||
protected override void HashCore(byte[] array, int ibStart, int cbSize)
|
||||
{
|
||||
if (State != 1)
|
||||
State = 1;
|
||||
int size = cbSize - ibStart;
|
||||
_RemainingLength = size & 15;
|
||||
if (cbSize >= 16)
|
||||
{
|
||||
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);
|
||||
}
|
||||
_TotalLength += cbSize;
|
||||
if (_RemainingLength != 0)
|
||||
{
|
||||
_CurrentArray = array;
|
||||
_CurrentIndex = ibStart;
|
||||
}
|
||||
}
|
||||
|
||||
/// Finalizes the hash computation after the last data is processed by the cryptographic stream object.
|
||||
/// <returns>The computed hash code.</returns>
|
||||
protected override byte[] HashFinal()
|
||||
{
|
||||
_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(_Hash32 + FuncGetLittleEndianUInt32(_CurrentArray, _CurrentIndex) * PRIME32_3, 17) * PRIME32_4;
|
||||
_CurrentIndex += 4;
|
||||
_RemainingLength -= 4;
|
||||
}
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* arrayPtr = _CurrentArray)
|
||||
{
|
||||
while (_RemainingLength-- >= 1)
|
||||
{
|
||||
_Hash32 = RotateLeft32(_Hash32 + arrayPtr[_CurrentIndex++] * PRIME32_5, 11) * PRIME32_1;
|
||||
}
|
||||
}
|
||||
}
|
||||
_Hash32 = (_Hash32 ^ (_Hash32 >> 15)) * PRIME32_2;
|
||||
_Hash32 = (_Hash32 ^ (_Hash32 >> 13)) * PRIME32_3;
|
||||
_Hash32 ^= _Hash32 >> 16;
|
||||
_TotalLength = State = 0;
|
||||
return BitConverter.GetBytes(FuncGetFinalHashUInt32(_Hash32));
|
||||
}
|
||||
|
||||
private static uint Round32(uint input, uint value) => RotateLeft32(input + (value * PRIME32_2), 13) * PRIME32_1;
|
||||
|
||||
private static uint RotateLeft32(uint value, int count) => (value << count) | (value >> (32 - count));
|
||||
|
||||
private void Initialize(uint seed)
|
||||
{
|
||||
HashSizeValue = 32;
|
||||
_Seed32 = seed;
|
||||
Initialize();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user