diff --git a/Color.cs b/Color.cs deleted file mode 100644 index 6093917..0000000 --- a/Color.cs +++ /dev/null @@ -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"); - } - } - } - -} diff --git a/ColoredConsole.cs b/ColoredConsole.cs index 18b39ba..98b684e 100644 --- a/ColoredConsole.cs +++ b/ColoredConsole.cs @@ -26,8 +26,8 @@ namespace DTLib "b" => ConsoleColor.Blue, //case "cyan": "c" => ConsoleColor.Cyan, - //case "gray": - "gray" => ConsoleColor.Gray, + //case "h": + "h" or "gray" => ConsoleColor.Gray, //case "black": "black" => ConsoleColor.Black, _ => throw new Exception($"ColoredConsole.ParseColor({color}) error: incorrect color"), diff --git a/DTLib.csproj b/DTLib.csproj index ea97a15..1fde41c 100644 --- a/DTLib.csproj +++ b/DTLib.csproj @@ -32,9 +32,11 @@ - + + + @@ -59,7 +61,7 @@ - + diff --git a/DefaultLogger.cs b/DefaultLogger.cs index 7072a2a..71a5f9f 100644 --- a/DefaultLogger.cs +++ b/DefaultLogger.cs @@ -1,6 +1,6 @@ -using System; +using DTLib.Filesystem; +using System; using System.Text; -using DTLib.Filesystem; namespace DTLib { @@ -12,8 +12,13 @@ namespace DTLib 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) { + 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); @@ -21,17 +26,16 @@ namespace DTLib public void LogNoTime(params string[] msg) { - lock (Logfile) + lock (Logfile) if (!isEnabled) return; + ColoredConsole.Write(msg); + if (msg.Length == 1) + lock (Logfile) File.AppendAllText(Logfile, msg[0]); + else { - ColoredConsole.Write(msg); - if (msg.Length == 1) File.AppendAllText(Logfile, msg[0]); - else - { - StringBuilder strB = new(); - for (ushort i = 0; i < msg.Length; i++) - strB.Append(msg[++i]); - File.AppendAllText(Logfile, strB.ToString()); - } + StringBuilder strB = new(); + for (ushort i = 0; i < msg.Length; i++) + strB.Append(msg[++i]); + lock (Logfile) File.AppendAllText(Logfile, strB.ToString()); } } } diff --git a/Dtsod/DtsodV21.cs b/Dtsod/DtsodV21.cs index 499cab4..20c73e1 100644 --- a/Dtsod/DtsodV21.cs +++ b/Dtsod/DtsodV21.cs @@ -1,4 +1,5 @@ -using System; +using DTLib.Extensions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -29,6 +30,13 @@ namespace DTLib.Dtsod foreach (KeyValuePair pair in Parse(text)) Add(pair.Key, pair.Value); } + public DtsodV21(Dictionary rawDict) + { + Text = ""; + foreach (KeyValuePair pair in rawDict) + Add(pair.Key, pair.Value); + } + // выдаёт Exception public new dynamic this[string key] @@ -89,14 +97,14 @@ namespace DTLib.Dtsod // СЛОМАНО /*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() { bool isListElem = false; - dynamic value = null; + dynamic value; StringBuilder defaultNameBuilder = new(); DebugNoTime("m", "ReadName\n"); @@ -113,7 +121,8 @@ namespace DTLib.Dtsod i++; string name = defaultNameBuilder.ToString(); 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 (!parsed.ContainsKey(name)) @@ -158,11 +167,11 @@ namespace DTLib.Dtsod valueBuilder.Append('"'); for (; text[i] != '"' || text[i - 1] == '\\'; i++) { - DebugNoTime("gray", text[i].ToString()); + DebugNoTime("h", text[i].ToString()); valueBuilder.Append(text[i]); } valueBuilder.Append('"'); - DebugNoTime("gray", text[i].ToString()); + DebugNoTime("h", text[i].ToString()); type = ValueType.String; return valueBuilder.ToString(); } diff --git a/Dtsod/DtsodV22.cs b/Dtsod/DtsodV22.cs index 051201b..0755976 100644 --- a/Dtsod/DtsodV22.cs +++ b/Dtsod/DtsodV22.cs @@ -1,4 +1,5 @@ -using System; +using DTLib.Extensions; +using System; using System.Collections; using System.Collections.Generic; using System.Linq; @@ -35,12 +36,6 @@ namespace DTLib.Dtsod Type = type; IsList = isList; } - public ValueStruct(ValueTypes type, dynamic value) - { - Value = value; - Type = type; - IsList = false; - } } public enum ValueTypes @@ -122,14 +117,14 @@ namespace DTLib.Dtsod // СЛОМАНО /*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() { bool isListElem = false; - dynamic value = null; + dynamic value; StringBuilder defaultNameBuilder = new(); DebugNoTime("m", "ReadName\n"); @@ -192,11 +187,11 @@ namespace DTLib.Dtsod valueBuilder.Append('"'); for (; text[i] != '"' || text[i - 1] == '\\'; i++) { - DebugNoTime("gray", text[i].ToString()); + DebugNoTime("h", text[i].ToString()); valueBuilder.Append(text[i]); } valueBuilder.Append('"'); - DebugNoTime("gray", text[i].ToString()); + DebugNoTime("h", text[i].ToString()); type = ValueTypes.String; return valueBuilder.ToString(); } @@ -405,33 +400,34 @@ namespace DTLib.Dtsod switch (value.Type) { case ValueTypes.List: - outBuilder.Append("\"list deconstruction is'nt implemented yet\""); + outBuilder.Append('[').Append(ToStringConverter.MergeToString((IEnumerable)value.Value, ",")).Append(']'); + //outBuilder.Append("\"list deconstruction is'nt implemented yet\""); break; case ValueTypes.Complex: - outBuilder.Append("\n"); + outBuilder.Append('\n'); outBuilder.Append('\t', tabCount); outBuilder.Append("{\n"); tabCount++; outBuilder.Append(Deconstruct(value.Value)); tabCount--; outBuilder.Append('\t', tabCount); - outBuilder.Append("}"); + outBuilder.Append('}'); break; case ValueTypes.String: - outBuilder.Append("\""); + outBuilder.Append('\"'); outBuilder.Append(value.Value.ToString()); - outBuilder.Append("\""); + outBuilder.Append('\"'); break; case ValueTypes.Short: outBuilder.Append(value.Value.ToString()); - outBuilder.Append("s"); + outBuilder.Append('s'); break; case ValueTypes.Int: outBuilder.Append(value.Value.ToString()); break; case ValueTypes.Long: outBuilder.Append(value.Value.ToString()); - outBuilder.Append("l"); + outBuilder.Append('l'); break; case ValueTypes.UShort: outBuilder.Append(value.Value.ToString()); diff --git a/Extensions/BaseConverter.cs b/Extensions/BaseConverter.cs new file mode 100644 index 0000000..951e64e --- /dev/null +++ b/Extensions/BaseConverter.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; + +namespace DTLib.Extensions +{ + public static class BaseConverter + { + // сокращение конвертации + public static int ToInt(this T input) => Convert.ToInt32(input); + public static uint ToUInt(this T input) => Convert.ToUInt32(input); + public static long ToLong(this T input) => Convert.ToInt64(input); + public static ulong ToULong(this T input) => Convert.ToUInt64(input); + public static short ToShort(this T input) => Convert.ToInt16(input); + public static ushort ToUShort(this T input) => Convert.ToUInt16(input); + public static double ToDouble(this T input) => Convert.ToDouble(input, System.Globalization.CultureInfo.InvariantCulture); + public static byte ToByte(this T input) => Convert.ToByte(input); + public static sbyte ToSByte(this T input) => Convert.ToSByte(input); + public static bool ToBool(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 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(this T number) => Math.Truncate(number.ToDouble()).ToInt(); + } +} \ No newline at end of file diff --git a/Extensions/Collections.cs b/Extensions/Collections.cs new file mode 100644 index 0000000..d71aad1 --- /dev/null +++ b/Extensions/Collections.cs @@ -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(this IEnumerable en, Action act) + { + foreach (T elem in en) + act(elem); + } + + // массив в лист + public static List ToList(this T[] input) + { + var list = new List(); + list.AddRange(input); + return list; + } + + // удаление нескольких элементов массива + public static T[] RemoveRange(this T[] input, int startIndex, int count) + { + var list = input.ToList(); + list.RemoveRange(startIndex, count); + return list.ToArray(); + } + public static T[] RemoveRange(this T[] input, int startIndex) => input.RemoveRange(startIndex, input.Length - startIndex); + + + // метод как у листов + public static bool Contains(this T[] array, T value) + { + for (int i = 0; i < array.Length; i++) + if (array[i].Equals(value)) + return true; + return false; + } + } +} diff --git a/Extensions/FrameworkFix.cs b/Extensions/FrameworkFix.cs new file mode 100644 index 0000000..5c286ad --- /dev/null +++ b/Extensions/FrameworkFix.cs @@ -0,0 +1,8 @@ +using System.ComponentModel; + +// включает init и record из c# 9.0 +namespace System.Runtime.CompilerServices +{ + [EditorBrowsable(EditorBrowsableState.Never)] + public class IsExternalInit { } +} \ No newline at end of file diff --git a/FrameworkFix.cs b/Extensions/ToStringConverter.cs similarity index 52% rename from FrameworkFix.cs rename to Extensions/ToStringConverter.cs index eb95206..f6b0f43 100644 --- a/FrameworkFix.cs +++ b/Extensions/ToStringConverter.cs @@ -1,22 +1,25 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; +using System.Collections.Generic; using System.Text; -// включает init и record из c# 9.0 -namespace System.Runtime.CompilerServices +namespace DTLib.Extensions { - [EditorBrowsable(EditorBrowsableState.Never)] - public class IsExternalInit { } -} - -namespace DTLib -{ - // - // содержит методы расширения для различных операций и преобразований - // - public static class FrameworkFix + public static class ToStringConverter { + 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) @@ -40,85 +43,7 @@ namespace DTLib } 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; - - // Math.Truncate принимает как decimal, так и doublе, - // из-за чего вызов метода так: Math.Truncate(10/3) выдаст ошибку "неоднозначный вызов" - public static int Truncate(this T number) => Math.Truncate(number.ToDouble()).ToInt(); - - // массив в лист - public static List ToList(this T[] input) - { - var list = new List(); - list.AddRange(input); - return list; - } - - // удаление нескольких элементов массива - public static T[] RemoveRange(this T[] input, int startIndex, int count) - { - var list = input.ToList(); - list.RemoveRange(startIndex, count); - return list.ToArray(); - } - public static T[] RemoveRange(this T[] input, int startIndex) => input.RemoveRange(startIndex, input.Length - startIndex); - - // метод как у листов - public static bool Contains(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(this T input) => Convert.ToInt32(input); - public static uint ToUInt(this T input) => Convert.ToUInt32(input); - public static long ToLong(this T input) => Convert.ToInt64(input); - public static ulong ToULong(this T input) => Convert.ToUInt64(input); - public static short ToShort(this T input) => Convert.ToInt16(input); - public static ushort ToUShort(this T input) => Convert.ToUInt16(input); - public static double ToDouble(this T input) => Convert.ToDouble(input, System.Globalization.CultureInfo.InvariantCulture); - public static byte ToByte(this T input) => Convert.ToByte(input); - public static sbyte ToSByte(this T input) => Convert.ToSByte(input); - public static bool ToBool(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 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 bool EndsWith(this string s, char c) => s[s.Length - 1] == c; public static string MergeToString(params object[] parts) { @@ -163,13 +88,6 @@ namespace DTLib return b.ToString(); } - public static void Throw(this Exception ex) => throw ex; - - public static void ForEach(this IEnumerable en, Action act) - { - foreach (T elem in en) - act(elem); - } // делает что надо в отличии от String.Split(), который не убирает char c из начала public static List SplitToList(this string s, char c) @@ -186,10 +104,8 @@ namespace DTLib o.Add(b.ToString()); b.Clear(); } - else - b.Append(ar[i]); - if (b.Length > 0) - o.Add(b.ToString()); + else b.Append(ar[i]); + if (b.Length > 0) o.Add(b.ToString()); return o; } @@ -207,25 +123,22 @@ namespace DTLib if (_s.EndsWith(quot)) { q_open = false; - _s=_s.Remove(_s.Length - 1); + _s = _s.Remove(_s.Length - 1); } output[output.Count - 1] += c + _s; } - else + else if (_s.StartsWith(quot)) { - if (_s.StartsWith(quot)) - { - q_open = true; - _s = _s.Remove(0, 1); - } - output.Add(_s); + q_open = true; + _s = _s.Remove(0, 1); } + output.Add(_s); } return output; } // разбивает на части указанной длины - public static List Split(this string s, int length) + public static List SplitToList(this string s, int length) { List parts = new(); int max = (s.Length / length).Truncate(); @@ -235,25 +148,9 @@ namespace DTLib return parts; } - public static T If(this T input, bool condition, Func if_true, Func if_false) => - condition ? if_true(input) : if_false(input); - public static void If(this T input, bool condition, Action if_true, Action if_false) - { - if (condition) if_true(input); - else if_false(input); - } - public static T If(this T input, bool condition, Func if_true) => - condition ? if_true(input) : input; - public static void If(this T input, bool condition, Action if_true) - { - if (condition) if_true(input); - } - public static string AddZeroes(this T number, int length) { var str = number.ToString(); - //var diff = str.Length -length ; - //if (diff > 0) return Multiply('0', str.Length - length) + str; } } diff --git a/Filesystem/Directory.cs b/Filesystem/Directory.cs index 330b635..0465697 100644 --- a/Filesystem/Directory.cs +++ b/Filesystem/Directory.cs @@ -1,9 +1,9 @@ -using System; +using DTLib.Extensions; +using System; using System.Collections.Generic; namespace DTLib.Filesystem { - public static class Directory { public static bool Exists(string dir) => System.IO.Directory.Exists(dir); diff --git a/Filesystem/File.cs b/Filesystem/File.cs index f53d14e..9896ceb 100644 --- a/Filesystem/File.cs +++ b/Filesystem/File.cs @@ -1,4 +1,5 @@ -using System; +using DTLib.Extensions; +using System; namespace DTLib.Filesystem { diff --git a/Network/FSP.cs b/Network/FSP.cs index 4309351..7884da2 100644 --- a/Network/FSP.cs +++ b/Network/FSP.cs @@ -1,7 +1,8 @@ -using System.Net.Sockets; -using System.Text; -using DTLib.Dtsod; +using DTLib.Dtsod; +using DTLib.Extensions; using DTLib.Filesystem; +using System.Net.Sockets; +using System.Text; using static DTLib.PublicLog; namespace DTLib.Network diff --git a/Network/Package.cs b/Network/Package.cs index 508ffed..50def44 100644 --- a/Network/Package.cs +++ b/Network/Package.cs @@ -1,4 +1,5 @@ -using System; +using DTLib.Extensions; +using System; using System.Collections.Generic; using System.Net.Sockets; using System.Threading;