FrameworcFix splitted to different files

This commit is contained in:
Timerix22 2021-12-12 16:19:18 +03:00
parent 5e8f9d8485
commit e9d490ebe3
14 changed files with 185 additions and 203 deletions

View File

@ -1,26 +0,0 @@
using System;
namespace DTLib
{
public abstract class Color
{
public record RGBA(byte R, byte G, byte B, byte A)
{
public RGBA(byte[] arrayRGBA) : this(arrayRGBA[0], arrayRGBA[1], arrayRGBA[2], arrayRGBA[3])
{
if (arrayRGBA.Length != 4)
throw new Exception("Color.RGBA(byte[] arrayRGBA) error: arrayRGBA.Length != 4\n");
}
}
public record RGB(byte R, byte G, byte B)
{
public RGB(byte[] arrayRGB) : this(arrayRGB[0], arrayRGB[1], arrayRGB[2])
{
if (arrayRGB.Length != 3)
throw new Exception("Color.RGB(byte[] arrayRGB) error: arrayRGB.Length != 3\n");
}
}
}
}

View File

@ -26,8 +26,8 @@ namespace DTLib
"b" => ConsoleColor.Blue, "b" => ConsoleColor.Blue,
//case "cyan": //case "cyan":
"c" => ConsoleColor.Cyan, "c" => ConsoleColor.Cyan,
//case "gray": //case "h":
"gray" => ConsoleColor.Gray, "h" or "gray" => ConsoleColor.Gray,
//case "black": //case "black":
"black" => ConsoleColor.Black, "black" => ConsoleColor.Black,
_ => throw new Exception($"ColoredConsole.ParseColor({color}) error: incorrect color"), _ => throw new Exception($"ColoredConsole.ParseColor({color}) error: incorrect color"),

View File

@ -32,9 +32,11 @@
<Reference Include="System.Data" /> <Reference Include="System.Data" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Color.cs" />
<Compile Include="CompressedArray.cs" /> <Compile Include="CompressedArray.cs" />
<Compile Include="DefaultLogger.cs" /> <Compile Include="DefaultLogger.cs" />
<Compile Include="Extensions\Collections.cs" />
<Compile Include="Extensions\BaseConverter.cs" />
<Compile Include="Extensions\ToStringConverter.cs" />
<Compile Include="Filesystem\Symlink.cs" /> <Compile Include="Filesystem\Symlink.cs" />
<Compile Include="MyDict.cs" /> <Compile Include="MyDict.cs" />
<Compile Include="Dtsod\DtsodV21.cs" /> <Compile Include="Dtsod\DtsodV21.cs" />
@ -59,7 +61,7 @@
<Compile Include="Reactive\ReactiveProvider.cs" /> <Compile Include="Reactive\ReactiveProvider.cs" />
<Compile Include="Reactive\TimeSignedObject.cs" /> <Compile Include="Reactive\TimeSignedObject.cs" />
<Compile Include="SecureRandom.cs" /> <Compile Include="SecureRandom.cs" />
<Compile Include="FrameworkFix.cs" /> <Compile Include="Extensions\FrameworkFix.cs" />
<Compile Include="TImer.cs" /> <Compile Include="TImer.cs" />
<Compile Include="XXHash.cs" /> <Compile Include="XXHash.cs" />
</ItemGroup> </ItemGroup>

View File

@ -1,6 +1,6 @@
using System; using DTLib.Filesystem;
using System;
using System.Text; using System.Text;
using DTLib.Filesystem;
namespace DTLib namespace DTLib
{ {
@ -12,8 +12,13 @@ namespace DTLib
public string Logfile { get; set; } public string Logfile { get; set; }
private bool isEnabled=false;
public void Enable() { lock (Logfile) isEnabled = true; }
public void Disable() { lock (Logfile) isEnabled = false; }
public void Log(params string[] msg) public void Log(params string[] msg)
{ {
lock (Logfile) if (!isEnabled) return;
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0]; if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1]; else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
LogNoTime(msg); LogNoTime(msg);
@ -21,17 +26,16 @@ namespace DTLib
public void LogNoTime(params string[] msg) public void LogNoTime(params string[] msg)
{ {
lock (Logfile) lock (Logfile) if (!isEnabled) return;
{
ColoredConsole.Write(msg); ColoredConsole.Write(msg);
if (msg.Length == 1) File.AppendAllText(Logfile, msg[0]); if (msg.Length == 1)
lock (Logfile) File.AppendAllText(Logfile, msg[0]);
else else
{ {
StringBuilder strB = new(); StringBuilder strB = new();
for (ushort i = 0; i < msg.Length; i++) for (ushort i = 0; i < msg.Length; i++)
strB.Append(msg[++i]); strB.Append(msg[++i]);
File.AppendAllText(Logfile, strB.ToString()); lock (Logfile) File.AppendAllText(Logfile, strB.ToString());
}
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using DTLib.Extensions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -29,6 +30,13 @@ namespace DTLib.Dtsod
foreach (KeyValuePair<string, dynamic> pair in Parse(text)) foreach (KeyValuePair<string, dynamic> pair in Parse(text))
Add(pair.Key, pair.Value); Add(pair.Key, pair.Value);
} }
public DtsodV21(Dictionary<string, dynamic> rawDict)
{
Text = "";
foreach (KeyValuePair<string, dynamic> pair in rawDict)
Add(pair.Key, pair.Value);
}
// выдаёт Exception // выдаёт Exception
public new dynamic this[string key] public new dynamic this[string key]
@ -89,14 +97,14 @@ namespace DTLib.Dtsod
// СЛОМАНО // СЛОМАНО
/*void ReadCommentLine() /*void ReadCommentLine()
{ {
for (; i < text.Length && text[i] != '\n'; i++) DebugNoTime("gray", text[i].ToString()); for (; i < text.Length && text[i] != '\n'; i++) DebugNoTime("h", text[i].ToString());
}*/ }*/
void ReadName() void ReadName()
{ {
bool isListElem = false; bool isListElem = false;
dynamic value = null; dynamic value;
StringBuilder defaultNameBuilder = new(); StringBuilder defaultNameBuilder = new();
DebugNoTime("m", "ReadName\n"); DebugNoTime("m", "ReadName\n");
@ -113,7 +121,8 @@ namespace DTLib.Dtsod
i++; i++;
string name = defaultNameBuilder.ToString(); string name = defaultNameBuilder.ToString();
value = ReadValue(); value = ReadValue();
DebugNoTime("c", $"parsed.Add({name}, {value} { value.GetType() })\n"); // если value это null, эта строка выдавала ошибку
//DebugNoTime("c", $"parsed.Add({name}, {value} { value.GetType() })\n");
if (isListElem) if (isListElem)
{ {
if (!parsed.ContainsKey(name)) if (!parsed.ContainsKey(name))
@ -158,11 +167,11 @@ namespace DTLib.Dtsod
valueBuilder.Append('"'); valueBuilder.Append('"');
for (; text[i] != '"' || text[i - 1] == '\\'; i++) for (; text[i] != '"' || text[i - 1] == '\\'; i++)
{ {
DebugNoTime("gray", text[i].ToString()); DebugNoTime("h", text[i].ToString());
valueBuilder.Append(text[i]); valueBuilder.Append(text[i]);
} }
valueBuilder.Append('"'); valueBuilder.Append('"');
DebugNoTime("gray", text[i].ToString()); DebugNoTime("h", text[i].ToString());
type = ValueType.String; type = ValueType.String;
return valueBuilder.ToString(); return valueBuilder.ToString();
} }

View File

@ -1,4 +1,5 @@
using System; using DTLib.Extensions;
using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -35,12 +36,6 @@ namespace DTLib.Dtsod
Type = type; Type = type;
IsList = isList; IsList = isList;
} }
public ValueStruct(ValueTypes type, dynamic value)
{
Value = value;
Type = type;
IsList = false;
}
} }
public enum ValueTypes public enum ValueTypes
@ -122,14 +117,14 @@ namespace DTLib.Dtsod
// СЛОМАНО // СЛОМАНО
/*void ReadCommentLine() /*void ReadCommentLine()
{ {
for (; i < text.Length && text[i] != '\n'; i++) Debug("gray", text[i].ToString()); for (; i < text.Length && text[i] != '\n'; i++) Debug("h", text[i].ToString());
}*/ }*/
void ReadName() void ReadName()
{ {
bool isListElem = false; bool isListElem = false;
dynamic value = null; dynamic value;
StringBuilder defaultNameBuilder = new(); StringBuilder defaultNameBuilder = new();
DebugNoTime("m", "ReadName\n"); DebugNoTime("m", "ReadName\n");
@ -192,11 +187,11 @@ namespace DTLib.Dtsod
valueBuilder.Append('"'); valueBuilder.Append('"');
for (; text[i] != '"' || text[i - 1] == '\\'; i++) for (; text[i] != '"' || text[i - 1] == '\\'; i++)
{ {
DebugNoTime("gray", text[i].ToString()); DebugNoTime("h", text[i].ToString());
valueBuilder.Append(text[i]); valueBuilder.Append(text[i]);
} }
valueBuilder.Append('"'); valueBuilder.Append('"');
DebugNoTime("gray", text[i].ToString()); DebugNoTime("h", text[i].ToString());
type = ValueTypes.String; type = ValueTypes.String;
return valueBuilder.ToString(); return valueBuilder.ToString();
} }
@ -405,33 +400,34 @@ namespace DTLib.Dtsod
switch (value.Type) switch (value.Type)
{ {
case ValueTypes.List: case ValueTypes.List:
outBuilder.Append("\"list deconstruction is'nt implemented yet\""); outBuilder.Append('[').Append(ToStringConverter.MergeToString((IEnumerable<object>)value.Value, ",")).Append(']');
//outBuilder.Append("\"list deconstruction is'nt implemented yet\"");
break; break;
case ValueTypes.Complex: case ValueTypes.Complex:
outBuilder.Append("\n"); outBuilder.Append('\n');
outBuilder.Append('\t', tabCount); outBuilder.Append('\t', tabCount);
outBuilder.Append("{\n"); outBuilder.Append("{\n");
tabCount++; tabCount++;
outBuilder.Append(Deconstruct(value.Value)); outBuilder.Append(Deconstruct(value.Value));
tabCount--; tabCount--;
outBuilder.Append('\t', tabCount); outBuilder.Append('\t', tabCount);
outBuilder.Append("}"); outBuilder.Append('}');
break; break;
case ValueTypes.String: case ValueTypes.String:
outBuilder.Append("\""); outBuilder.Append('\"');
outBuilder.Append(value.Value.ToString()); outBuilder.Append(value.Value.ToString());
outBuilder.Append("\""); outBuilder.Append('\"');
break; break;
case ValueTypes.Short: case ValueTypes.Short:
outBuilder.Append(value.Value.ToString()); outBuilder.Append(value.Value.ToString());
outBuilder.Append("s"); outBuilder.Append('s');
break; break;
case ValueTypes.Int: case ValueTypes.Int:
outBuilder.Append(value.Value.ToString()); outBuilder.Append(value.Value.ToString());
break; break;
case ValueTypes.Long: case ValueTypes.Long:
outBuilder.Append(value.Value.ToString()); outBuilder.Append(value.Value.ToString());
outBuilder.Append("l"); outBuilder.Append('l');
break; break;
case ValueTypes.UShort: case ValueTypes.UShort:
outBuilder.Append(value.Value.ToString()); outBuilder.Append(value.Value.ToString());

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
namespace DTLib.Extensions
{
public static class BaseConverter
{
// сокращение конвертации
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 short ToShort<T>(this T input) => Convert.ToInt16(input);
public static ushort ToUShort<T>(this T input) => Convert.ToUInt16(input);
public static double ToDouble<T>(this T input) => Convert.ToDouble(input, System.Globalization.CultureInfo.InvariantCulture);
public static byte ToByte<T>(this T input) => Convert.ToByte(input);
public static sbyte ToSByte<T>(this T input) => Convert.ToSByte(input);
public static bool ToBool<T>(this T input) => Convert.ToBoolean(input);
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();
}
}

45
Extensions/Collections.cs Normal file
View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
}
}
}

View File

@ -0,0 +1,8 @@
using System.ComponentModel;
// включает init и record из c# 9.0
namespace System.Runtime.CompilerServices
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class IsExternalInit { }
}

View File

@ -1,22 +1,25 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text; using System.Text;
// включает init и record из c# 9.0 namespace DTLib.Extensions
namespace System.Runtime.CompilerServices
{ {
[EditorBrowsable(EditorBrowsableState.Never)] public static class ToStringConverter
public class IsExternalInit { }
}
namespace DTLib
{
//
// содержит методы расширения для различных операций и преобразований
//
public static class FrameworkFix
{ {
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) public static bool StartsWith(this byte[] source, byte[] startsWith)
@ -40,85 +43,7 @@ namespace DTLib
} }
public static bool StartsWith(this string s, char c) => s[0] == c; 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 bool EndsWith(this string s, char c) => s[s.Length - 1] == c;
// Math.Truncate принимает как decimal, так и doublе,
// из-за чего вызов метода так: Math.Truncate(10/3) выдаст ошибку "неоднозначный вызов"
public static int Truncate<T>(this T number) => Math.Truncate(number.ToDouble()).ToInt();
// массив в лист
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;
}
// сокращение конвертации
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 short ToShort<T>(this T input) => Convert.ToInt16(input);
public static ushort ToUShort<T>(this T input) => Convert.ToUInt16(input);
public static double ToDouble<T>(this T input) => Convert.ToDouble(input, System.Globalization.CultureInfo.InvariantCulture);
public static byte ToByte<T>(this T input) => Convert.ToByte(input);
public static sbyte ToSByte<T>(this T input) => Convert.ToSByte(input);
public static bool ToBool<T>(this T input) => Convert.ToBoolean(input);
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 = Truncate(num / 256);
}
output.Reverse();
return output.ToArray();
}
public static byte[] ToBytes(this string str) => UTF8.GetBytes(str);
public static Encoding UTF8 = new UTF8Encoding(false);
// байты в кодировке UTF8 в строку
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 string MergeToString(params object[] parts) public static string MergeToString(params object[] parts)
{ {
@ -163,13 +88,6 @@ namespace DTLib
return b.ToString(); return b.ToString();
} }
public static void Throw(this Exception ex) => throw ex;
public static void ForEach<T>(this IEnumerable<T> en, Action<T> act)
{
foreach (T elem in en)
act(elem);
}
// делает что надо в отличии от String.Split(), который не убирает char c из начала // делает что надо в отличии от String.Split(), который не убирает char c из начала
public static List<string> SplitToList(this string s, char c) public static List<string> SplitToList(this string s, char c)
@ -186,10 +104,8 @@ namespace DTLib
o.Add(b.ToString()); o.Add(b.ToString());
b.Clear(); b.Clear();
} }
else else b.Append(ar[i]);
b.Append(ar[i]); if (b.Length > 0) o.Add(b.ToString());
if (b.Length > 0)
o.Add(b.ToString());
return o; return o;
} }
@ -207,25 +123,22 @@ namespace DTLib
if (_s.EndsWith(quot)) if (_s.EndsWith(quot))
{ {
q_open = false; q_open = false;
_s=_s.Remove(_s.Length - 1); _s = _s.Remove(_s.Length - 1);
} }
output[output.Count - 1] += c + _s; output[output.Count - 1] += c + _s;
} }
else else if (_s.StartsWith(quot))
{
if (_s.StartsWith(quot))
{ {
q_open = true; q_open = true;
_s = _s.Remove(0, 1); _s = _s.Remove(0, 1);
} }
output.Add(_s); output.Add(_s);
} }
}
return output; return output;
} }
// разбивает на части указанной длины // разбивает на части указанной длины
public static List<string> Split(this string s, int length) public static List<string> SplitToList(this string s, int length)
{ {
List<string> parts = new(); List<string> parts = new();
int max = (s.Length / length).Truncate(); int max = (s.Length / length).Truncate();
@ -235,25 +148,9 @@ namespace DTLib
return parts; return parts;
} }
public static T If<T>(this T input, bool condition, Func<T, T> if_true, Func<T, T> if_false) =>
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);
}
public static string AddZeroes<T>(this T number, int length) public static string AddZeroes<T>(this T number, int length)
{ {
var str = number.ToString(); var str = number.ToString();
//var diff = str.Length -length ;
//if (diff > 0)
return Multiply('0', str.Length - length) + str; return Multiply('0', str.Length - length) + str;
} }
} }

View File

@ -1,9 +1,9 @@
using System; using DTLib.Extensions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace DTLib.Filesystem namespace DTLib.Filesystem
{ {
public static class Directory public static class Directory
{ {
public static bool Exists(string dir) => System.IO.Directory.Exists(dir); public static bool Exists(string dir) => System.IO.Directory.Exists(dir);

View File

@ -1,4 +1,5 @@
using System; using DTLib.Extensions;
using System;
namespace DTLib.Filesystem namespace DTLib.Filesystem
{ {

View File

@ -1,7 +1,8 @@
using System.Net.Sockets; using DTLib.Dtsod;
using System.Text; using DTLib.Extensions;
using DTLib.Dtsod;
using DTLib.Filesystem; using DTLib.Filesystem;
using System.Net.Sockets;
using System.Text;
using static DTLib.PublicLog; using static DTLib.PublicLog;
namespace DTLib.Network namespace DTLib.Network

View File

@ -1,4 +1,5 @@
using System; using DTLib.Extensions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Sockets; using System.Net.Sockets;
using System.Threading; using System.Threading;