REFACTORING
This commit is contained in:
parent
c71d2b8356
commit
2defc3ae5e
6
Color.cs
6
Color.cs
@ -8,7 +8,8 @@ namespace DTLib
|
|||||||
{
|
{
|
||||||
public RGBA(byte[] arrayRGBA) : this(arrayRGBA[0], arrayRGBA[1], arrayRGBA[2], arrayRGBA[3])
|
public RGBA(byte[] arrayRGBA) : this(arrayRGBA[0], arrayRGBA[1], arrayRGBA[2], arrayRGBA[3])
|
||||||
{
|
{
|
||||||
if (arrayRGBA.Length != 4) throw new Exception("Color.RGBA(byte[] arrayRGBA) error: arrayRGBA.Length != 4\n");
|
if(arrayRGBA.Length!=4)
|
||||||
|
throw new Exception("Color.RGBA(byte[] arrayRGBA) error: arrayRGBA.Length != 4\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -16,7 +17,8 @@ namespace DTLib
|
|||||||
{
|
{
|
||||||
public RGB(byte[] arrayRGB) : this(arrayRGB[0], arrayRGB[1], arrayRGB[2])
|
public RGB(byte[] arrayRGB) : this(arrayRGB[0], arrayRGB[1], arrayRGB[2])
|
||||||
{
|
{
|
||||||
if (arrayRGB.Length != 3) throw new Exception("Color.RGB(byte[] arrayRGB) error: arrayRGB.Length != 3\n");
|
if(arrayRGB.Length!=3)
|
||||||
|
throw new Exception("Color.RGB(byte[] arrayRGB) error: arrayRGB.Length != 3\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -10,9 +10,7 @@ namespace DTLib
|
|||||||
public static class ColoredConsole
|
public static class ColoredConsole
|
||||||
{
|
{
|
||||||
// парсит название цвета в ConsoleColor
|
// парсит название цвета в ConsoleColor
|
||||||
public static ConsoleColor ParseColor(string color)
|
public static ConsoleColor ParseColor(string color) => color switch
|
||||||
{
|
|
||||||
return color switch
|
|
||||||
{
|
{
|
||||||
//case "magneta":
|
//case "magneta":
|
||||||
"m" => ConsoleColor.Magenta,
|
"m" => ConsoleColor.Magenta,
|
||||||
@ -34,40 +32,43 @@ namespace DTLib
|
|||||||
"black" => ConsoleColor.Black,
|
"black" => ConsoleColor.Black,
|
||||||
_ => throw new Exception($"ColoredConsole.ParseColor({color}) error: incorrect color"),
|
_ => throw new Exception($"ColoredConsole.ParseColor({color}) error: incorrect color"),
|
||||||
};
|
};
|
||||||
}
|
|
||||||
|
|
||||||
// вывод цветного текста
|
// вывод цветного текста
|
||||||
public static void Write(params string[] input)
|
public static void Write(params string[] input)
|
||||||
{
|
{
|
||||||
if (input.Length == 1)
|
if(input.Length==1)
|
||||||
{
|
{
|
||||||
if (Console.ForegroundColor != ConsoleColor.Gray) Console.ForegroundColor = ConsoleColor.Gray;
|
if(Console.ForegroundColor!=ConsoleColor.Gray)
|
||||||
|
Console.ForegroundColor=ConsoleColor.Gray;
|
||||||
Console.Write(input[0]);
|
Console.Write(input[0]);
|
||||||
}
|
}
|
||||||
else if (input.Length % 2 == 0)
|
else if(input.Length%2==0)
|
||||||
{
|
{
|
||||||
StringBuilder strB = new();
|
StringBuilder strB = new();
|
||||||
for (ushort i = 0; i < input.Length; i++)
|
for(ushort i = 0; i<input.Length; i++)
|
||||||
{
|
{
|
||||||
var c = ParseColor(input[i]);
|
ConsoleColor c = ParseColor(input[i]);
|
||||||
if (Console.ForegroundColor != c)
|
if(Console.ForegroundColor!=c)
|
||||||
{
|
{
|
||||||
Console.Write(strB.ToString());
|
Console.Write(strB.ToString());
|
||||||
Console.ForegroundColor = c;
|
Console.ForegroundColor=c;
|
||||||
strB.Clear();
|
strB.Clear();
|
||||||
}
|
}
|
||||||
strB.Append(input[++i]);
|
strB.Append(input[++i]);
|
||||||
}
|
}
|
||||||
if (strB.Length > 0) Console.Write(strB.ToString());
|
if(strB.Length>0)
|
||||||
|
Console.Write(strB.ToString());
|
||||||
}
|
}
|
||||||
else throw new Exception("ColoredConsole.Write() error: every text string must have color string before");
|
else
|
||||||
|
throw new Exception("ColoredConsole.Write() error: every text string must have color string before");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ввод цветного текста
|
// ввод цветного текста
|
||||||
public static string Read(string color)
|
public static string Read(string color)
|
||||||
{
|
{
|
||||||
var c = ParseColor(color);
|
ConsoleColor c = ParseColor(color);
|
||||||
if (Console.ForegroundColor != c) Console.ForegroundColor = c;
|
if(Console.ForegroundColor!=c)
|
||||||
|
Console.ForegroundColor=c;
|
||||||
return Console.ReadLine();
|
return Console.ReadLine();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -12,10 +12,7 @@ namespace DTLib
|
|||||||
T[] Memory;
|
T[] Memory;
|
||||||
|
|
||||||
public Array1D() { }
|
public Array1D() { }
|
||||||
public Array1D(T[] sourceArray)
|
public Array1D(T[] sourceArray) => CompressArray(sourceArray);
|
||||||
{
|
|
||||||
CompressArray(sourceArray);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void CompressArray(T[] sourceArray)
|
public void CompressArray(T[] sourceArray)
|
||||||
{
|
{
|
||||||
@ -25,25 +22,26 @@ namespace DTLib
|
|||||||
listMem.Add(sourceArray[0]);
|
listMem.Add(sourceArray[0]);
|
||||||
listDesc.Add(1);
|
listDesc.Add(1);
|
||||||
byte repeats = 1;
|
byte repeats = 1;
|
||||||
for (int i = 1; i < sourceArray.Length; i++)
|
for(int i = 1; i<sourceArray.Length; i++)
|
||||||
{
|
{
|
||||||
if (prevElement.CompareTo(sourceArray[i]) == 0) repeats++;
|
if(prevElement.CompareTo(sourceArray[i])==0)
|
||||||
|
repeats++;
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
listMem.Add(sourceArray[i]);
|
listMem.Add(sourceArray[i]);
|
||||||
listDesc.Add(1);
|
listDesc.Add(1);
|
||||||
if (repeats > 1)
|
if(repeats>1)
|
||||||
{
|
{
|
||||||
listDesc[listDesc.Count - 2] = repeats;
|
listDesc[listDesc.Count-2]=repeats;
|
||||||
repeats = 1;
|
repeats=1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
prevElement = sourceArray[i];
|
prevElement=sourceArray[i];
|
||||||
}
|
}
|
||||||
Memory = listMem.ToArray();
|
Memory=listMem.ToArray();
|
||||||
Description = listDesc.ToArray();
|
Description=listDesc.ToArray();
|
||||||
ColoredConsole.Write("b", "listMem.Count: ", "c", listMem.Count.ToString(), "b", " listDesc.Count: ", "c", listDesc.Count + "\n");
|
ColoredConsole.Write("b", "listMem.Count: ", "c", listMem.Count.ToString(), "b", " listDesc.Count: ", "c", listDesc.Count+"\n");
|
||||||
for (short i = 0; i < listDesc.Count; i++)
|
for(short i = 0; i<listDesc.Count; i++)
|
||||||
{
|
{
|
||||||
ColoredConsole.Write("y", $"{Description[i]}:{Memory[i]}\n");
|
ColoredConsole.Write("y", $"{Description[i]}:{Memory[i]}\n");
|
||||||
}
|
}
|
||||||
@ -58,11 +56,14 @@ namespace DTLib
|
|||||||
storageUsing.WaitOne();
|
storageUsing.WaitOne();
|
||||||
T output = default;
|
T output = default;
|
||||||
int sum = 0;
|
int sum = 0;
|
||||||
for (int i = 0; i < Description.Length; i++)
|
for(int i = 0; i<Description.Length; i++)
|
||||||
{
|
{
|
||||||
if (sum < index) sum += Description[i];
|
if(sum<index)
|
||||||
else if (sum == index) output = Memory[i];
|
sum+=Description[i];
|
||||||
else output = Memory[i - 1];
|
else if(sum==index)
|
||||||
|
output=Memory[i];
|
||||||
|
else
|
||||||
|
output=Memory[i-1];
|
||||||
}
|
}
|
||||||
storageUsing.ReleaseMutex();
|
storageUsing.ReleaseMutex();
|
||||||
return output;
|
return output;
|
||||||
|
|||||||
@ -16,26 +16,26 @@ namespace DTLib.ConsoleGUI
|
|||||||
|
|
||||||
public Container(string name, string layout_file)
|
public Container(string name, string layout_file)
|
||||||
{
|
{
|
||||||
Name = name;
|
Name=name;
|
||||||
ParseLayoutFile(layout_file);
|
ParseLayoutFile(layout_file);
|
||||||
}
|
}
|
||||||
|
|
||||||
void ParseLayoutFile(string layout_file)
|
void ParseLayoutFile(string layout_file)
|
||||||
{
|
{
|
||||||
DtsodV23 layout = new(File.ReadAllText(layout_file));
|
DtsodV23 layout = new(File.ReadAllText(layout_file));
|
||||||
AnchorPoint = (layout[Name]["anchor"][0], layout[Name]["anchor"][1]);
|
AnchorPoint=(layout[Name]["anchor"][0], layout[Name]["anchor"][1]);
|
||||||
Width = layout[Name]["width"];
|
Width=layout[Name]["width"];
|
||||||
Height = layout[Name]["height"];
|
Height=layout[Name]["height"];
|
||||||
foreach (string element_name in layout[Name]["children"].Keys)
|
foreach(string element_name in layout[Name]["children"].Keys)
|
||||||
{
|
{
|
||||||
switch (layout[Name]["children"][element_name]["type"])
|
switch(layout[Name]["children"][element_name]["type"])
|
||||||
{
|
{
|
||||||
case "label":
|
case "label":
|
||||||
this.Add(new Label(element_name,
|
Add(new Label(element_name,
|
||||||
layout[Name]["children"][element_name]["resdir"] + $"\\{element_name}.textmap",
|
layout[Name]["children"][element_name]["resdir"]+$"\\{element_name}.textmap",
|
||||||
layout[Name]["children"][element_name]["resdir"] + $"\\{element_name}.colormap")
|
layout[Name]["children"][element_name]["resdir"]+$"\\{element_name}.colormap")
|
||||||
{
|
{
|
||||||
AnchorPoint = (layout[Name]["children"][element_name]["anchor"][0],
|
AnchorPoint=(layout[Name]["children"][element_name]["anchor"][0],
|
||||||
layout[Name]["children"][element_name]["anchor"][1])
|
layout[Name]["children"][element_name]["anchor"][1])
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
@ -45,18 +45,18 @@ namespace DTLib.ConsoleGUI
|
|||||||
|
|
||||||
public void GenTextmap()
|
public void GenTextmap()
|
||||||
{
|
{
|
||||||
Textmap = new char[Width * Height];
|
Textmap=new char[Width*Height];
|
||||||
for (int i = 0; i < Textmap.Length; i++)
|
for(int i = 0; i<Textmap.Length; i++)
|
||||||
Textmap[i] = ' ';
|
Textmap[i]=' ';
|
||||||
foreach (var element in this)
|
foreach(IDrawable element in this)
|
||||||
{
|
{
|
||||||
element.GenTextmap();
|
element.GenTextmap();
|
||||||
Log("m", $"Length: {element.Textmap.Length} calculated: {element.Width * element.Height}\n");
|
Log("m", $"Length: {element.Textmap.Length} calculated: {element.Width*element.Height}\n");
|
||||||
for (ushort y = 0; y < element.Height; y++)
|
for(ushort y = 0; y<element.Height; y++)
|
||||||
for (ushort x = 0; x < element.Width; x++)
|
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[(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];
|
Textmap[(y)*Width+x]=element.Textmap[y*element.Width+x];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,21 +18,18 @@ namespace DTLib.ConsoleGUI
|
|||||||
|
|
||||||
public Label(string name, string textmapFile, string colormapFile)
|
public Label(string name, string textmapFile, string colormapFile)
|
||||||
{
|
{
|
||||||
TextmapFile = textmapFile;
|
TextmapFile=textmapFile;
|
||||||
ColormapFile = colormapFile;
|
ColormapFile=colormapFile;
|
||||||
Name = name;
|
Name=name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void GenColormap()
|
public void GenColormap() => Colormap=File.ReadAllText(ColormapFile).ToCharArray();
|
||||||
{
|
|
||||||
Colormap = File.ReadAllText(ColormapFile).ToCharArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void GenTextmap()
|
public void GenTextmap()
|
||||||
{
|
{
|
||||||
Textmap = File.ReadAllText(TextmapFile).ToCharArray();
|
Textmap=File.ReadAllText(TextmapFile).ToCharArray();
|
||||||
Width = 12;
|
Width=12;
|
||||||
Height = 3;
|
Height=3;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -13,11 +13,11 @@ namespace DTLib.ConsoleGUI
|
|||||||
public Window(string layout_file) : base("window", layout_file)
|
public Window(string layout_file) : base("window", layout_file)
|
||||||
{
|
{
|
||||||
Console.Clear();
|
Console.Clear();
|
||||||
Console.SetWindowSize(Width + 1, Height + 1);
|
Console.SetWindowSize(Width+1, Height+1);
|
||||||
Console.SetBufferSize(Width + 1, Height + 1);
|
Console.SetBufferSize(Width+1, Height+1);
|
||||||
Console.OutputEncoding = Encoding.Unicode;
|
Console.OutputEncoding=Encoding.Unicode;
|
||||||
Console.InputEncoding = Encoding.Unicode;
|
Console.InputEncoding=Encoding.Unicode;
|
||||||
Console.CursorVisible = false;
|
Console.CursorVisible=false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// выводит все символы
|
// выводит все символы
|
||||||
|
|||||||
@ -21,29 +21,29 @@ namespace DTLib.ConsoleGUI
|
|||||||
|
|
||||||
public WindowOld(int windowWidth, int windowHeight)
|
public WindowOld(int windowWidth, int windowHeight)
|
||||||
{
|
{
|
||||||
WindowWidth = windowWidth;
|
WindowWidth=windowWidth;
|
||||||
WindowHeight = windowHeight;
|
WindowHeight=windowHeight;
|
||||||
Text = new char[windowWidth, windowHeight];
|
Text=new char[windowWidth, windowHeight];
|
||||||
TextColors = new char[windowWidth, windowHeight];
|
TextColors=new char[windowWidth, windowHeight];
|
||||||
nowText = TextColors;
|
nowText=TextColors;
|
||||||
nowTextColors = new char[windowWidth, windowHeight];
|
nowTextColors=new char[windowWidth, windowHeight];
|
||||||
Console.WindowWidth = WindowWidth + 1;
|
Console.WindowWidth=WindowWidth+1;
|
||||||
Console.WindowHeight = WindowHeight + 1;
|
Console.WindowHeight=WindowHeight+1;
|
||||||
Console.BufferWidth = WindowWidth + 1;
|
Console.BufferWidth=WindowWidth+1;
|
||||||
Console.BufferHeight = WindowHeight + 1;
|
Console.BufferHeight=WindowHeight+1;
|
||||||
Console.OutputEncoding = Encoding.Unicode;
|
Console.OutputEncoding=Encoding.Unicode;
|
||||||
Console.InputEncoding = Encoding.Unicode;
|
Console.InputEncoding=Encoding.Unicode;
|
||||||
Console.CursorVisible = false;
|
Console.CursorVisible=false;
|
||||||
// заполнение массивов
|
// заполнение массивов
|
||||||
for (sbyte y = 0; y < WindowHeight; y++)
|
for(sbyte y = 0; y<WindowHeight; y++)
|
||||||
{
|
{
|
||||||
for (sbyte x = 0; x < WindowWidth; x++)
|
for(sbyte x = 0; x<WindowWidth; x++)
|
||||||
{
|
{
|
||||||
Text[x, y] = ' ';
|
Text[x, y]=' ';
|
||||||
TextColors[x, y] = 'w';
|
TextColors[x, y]='w';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
nowText = TextColors;
|
nowText=TextColors;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*// считывает массив символов из файла
|
/*// считывает массив символов из файла
|
||||||
@ -97,34 +97,31 @@ namespace DTLib.ConsoleGUI
|
|||||||
r.Close();
|
r.Close();
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
public void ResetCursor()
|
public void ResetCursor() => Console.SetCursorPosition(0, WindowHeight);
|
||||||
{
|
|
||||||
Console.SetCursorPosition(0, WindowHeight);
|
|
||||||
}
|
|
||||||
|
|
||||||
// заменяет символ выведенный, использовать после ShowAll()
|
// заменяет символ выведенный, использовать после ShowAll()
|
||||||
public void ChangeChar(sbyte x, sbyte y, char ch)
|
public void ChangeChar(sbyte x, sbyte y, char ch)
|
||||||
{
|
{
|
||||||
Text[x, y] = ch;
|
Text[x, y]=ch;
|
||||||
nowText[x, y] = ch;
|
nowText[x, y]=ch;
|
||||||
Console.SetCursorPosition(x, y);
|
Console.SetCursorPosition(x, y);
|
||||||
ColoredConsole.Write(TextColors[x, y].ToString(), ch.ToString());
|
ColoredConsole.Write(TextColors[x, y].ToString(), ch.ToString());
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ChangeColor(sbyte x, sbyte y, char color)
|
public void ChangeColor(sbyte x, sbyte y, char color)
|
||||||
{
|
{
|
||||||
TextColors[x, y] = color;
|
TextColors[x, y]=color;
|
||||||
nowTextColors[x, y] = color;
|
nowTextColors[x, y]=color;
|
||||||
Console.SetCursorPosition(x, y);
|
Console.SetCursorPosition(x, y);
|
||||||
ColoredConsole.Write(color.ToString(), Text[x, y].ToString());
|
ColoredConsole.Write(color.ToString(), Text[x, y].ToString());
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ChangeCharAndColor(sbyte x, sbyte y, char color, char ch)
|
public void ChangeCharAndColor(sbyte x, sbyte y, char color, char ch)
|
||||||
{
|
{
|
||||||
Text[x, y] = ch;
|
Text[x, y]=ch;
|
||||||
nowText[x, y] = ch;
|
nowText[x, y]=ch;
|
||||||
TextColors[x, y] = color;
|
TextColors[x, y]=color;
|
||||||
nowTextColors[x, y] = color;
|
nowTextColors[x, y]=color;
|
||||||
Console.SetCursorPosition(x, y);
|
Console.SetCursorPosition(x, y);
|
||||||
ColoredConsole.Write(color.ToString(), ch.ToString());
|
ColoredConsole.Write(color.ToString(), ch.ToString());
|
||||||
}
|
}
|
||||||
@ -132,12 +129,12 @@ namespace DTLib.ConsoleGUI
|
|||||||
public void ChangeLine(sbyte x, sbyte y, char color, string line)
|
public void ChangeLine(sbyte x, sbyte y, char color, string line)
|
||||||
{
|
{
|
||||||
Console.SetCursorPosition(x, y);
|
Console.SetCursorPosition(x, y);
|
||||||
for (sbyte i = 0; i < line.Length; i++)
|
for(sbyte i = 0; i<line.Length; i++)
|
||||||
{
|
{
|
||||||
Text[x + i, y] = line[i];
|
Text[x+i, y]=line[i];
|
||||||
nowText[x + i, y] = line[i];
|
nowText[x+i, y]=line[i];
|
||||||
TextColors[x + i, y] = color;
|
TextColors[x+i, y]=color;
|
||||||
nowTextColors[x + i, y] = color;
|
nowTextColors[x+i, y]=color;
|
||||||
}
|
}
|
||||||
ColoredConsole.Write(color.ToString(), line);
|
ColoredConsole.Write(color.ToString(), line);
|
||||||
}
|
}
|
||||||
@ -146,14 +143,14 @@ namespace DTLib.ConsoleGUI
|
|||||||
public void ShowAll()
|
public void ShowAll()
|
||||||
{
|
{
|
||||||
var l = new List<string>();
|
var l = new List<string>();
|
||||||
for (sbyte y = 0; y < WindowHeight; y++)
|
for(sbyte y = 0; y<WindowHeight; y++)
|
||||||
{
|
{
|
||||||
for (sbyte x = 0; x < WindowWidth; x++)
|
for(sbyte x = 0; x<WindowWidth; x++)
|
||||||
{
|
{
|
||||||
l.Add(TextColors[x, y].ToString());
|
l.Add(TextColors[x, y].ToString());
|
||||||
l.Add(Text[x, y].ToString());
|
l.Add(Text[x, y].ToString());
|
||||||
nowText[x, y] = Text[x, y];
|
nowText[x, y]=Text[x, y];
|
||||||
nowTextColors[x, y] = TextColors[x, y];
|
nowTextColors[x, y]=TextColors[x, y];
|
||||||
}
|
}
|
||||||
l.Add("w");
|
l.Add("w");
|
||||||
l.Add("\n");
|
l.Add("\n");
|
||||||
@ -164,16 +161,16 @@ namespace DTLib.ConsoleGUI
|
|||||||
|
|
||||||
public void UpdateAll()
|
public void UpdateAll()
|
||||||
{
|
{
|
||||||
for (sbyte y = 0; y < WindowHeight; y++)
|
for(sbyte y = 0; y<WindowHeight; y++)
|
||||||
{
|
{
|
||||||
for (sbyte x = 0; x < WindowWidth; x++)
|
for(sbyte x = 0; x<WindowWidth; x++)
|
||||||
{
|
{
|
||||||
Console.SetCursorPosition(x, y);
|
Console.SetCursorPosition(x, y);
|
||||||
if (TextColors[x, y] != nowTextColors[x, y] || Text[x, y] != nowText[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());
|
ColoredConsole.Write(TextColors[x, y].ToString(), Text[x, y].ToString());
|
||||||
nowText[x, y] = Text[x, y];
|
nowText[x, y]=Text[x, y];
|
||||||
nowTextColors[x, y] = TextColors[x, y];
|
nowTextColors[x, y]=TextColors[x, y];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Console.Write('\n');
|
Console.Write('\n');
|
||||||
|
|||||||
@ -24,8 +24,8 @@ namespace DTLib.Dtsod
|
|||||||
//public Dictionary<string, dynamic> Values { get; set; }
|
//public Dictionary<string, dynamic> Values { get; set; }
|
||||||
public DtsodV21(string text)
|
public DtsodV21(string text)
|
||||||
{
|
{
|
||||||
Text = text;
|
Text=text;
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -34,13 +34,17 @@ namespace DTLib.Dtsod
|
|||||||
{
|
{
|
||||||
get
|
get
|
||||||
{
|
{
|
||||||
if (TryGetValue(key, out dynamic value)) return value;
|
if(TryGetValue(key, out dynamic value))
|
||||||
else throw new Exception($"Dtsod[{key}] key not found");
|
return value;
|
||||||
|
else
|
||||||
|
throw new Exception($"Dtsod[{key}] key not found");
|
||||||
}
|
}
|
||||||
set
|
set
|
||||||
{
|
{
|
||||||
if (TrySetValue(key, value)) return;
|
if(TrySetValue(key, value))
|
||||||
else throw new Exception($"Dtsod[{key}] key not found");
|
return;
|
||||||
|
else
|
||||||
|
throw new Exception($"Dtsod[{key}] key not found");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -49,12 +53,12 @@ namespace DTLib.Dtsod
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
value = base[key];
|
value=base[key];
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
catch (KeyNotFoundException)
|
catch(KeyNotFoundException)
|
||||||
{
|
{
|
||||||
value = null;
|
value=null;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -62,10 +66,10 @@ namespace DTLib.Dtsod
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
base[key] = value;
|
base[key]=value;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
catch (KeyNotFoundException)
|
catch(KeyNotFoundException)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -94,7 +98,8 @@ namespace DTLib.Dtsod
|
|||||||
{
|
{
|
||||||
Dictionary<string, dynamic> parsed = new();
|
Dictionary<string, dynamic> parsed = new();
|
||||||
int i = 0;
|
int i = 0;
|
||||||
for (; i < text.Length; i++) ReadName();
|
for(; i<text.Length; i++)
|
||||||
|
ReadName();
|
||||||
DebugNoTime("g", $"Parse returns {parsed.Keys.Count} keys\n");
|
DebugNoTime("g", $"Parse returns {parsed.Keys.Count} keys\n");
|
||||||
return parsed;
|
return parsed;
|
||||||
|
|
||||||
@ -112,9 +117,9 @@ namespace DTLib.Dtsod
|
|||||||
StringBuilder defaultNameBuilder = new();
|
StringBuilder defaultNameBuilder = new();
|
||||||
|
|
||||||
DebugNoTime("m", "ReadName\n");
|
DebugNoTime("m", "ReadName\n");
|
||||||
for (; i < text.Length; i++)
|
for(; i<text.Length; i++)
|
||||||
{
|
{
|
||||||
switch (text[i])
|
switch(text[i])
|
||||||
{
|
{
|
||||||
case ' ':
|
case ' ':
|
||||||
case '\t':
|
case '\t':
|
||||||
@ -124,29 +129,32 @@ namespace DTLib.Dtsod
|
|||||||
case ':':
|
case ':':
|
||||||
i++;
|
i++;
|
||||||
string name = defaultNameBuilder.ToString();
|
string name = defaultNameBuilder.ToString();
|
||||||
value = ReadValue();
|
value=ReadValue();
|
||||||
DebugNoTime("c", $"parsed.Add({name}, {value} { value.GetType() })\n");
|
DebugNoTime("c", $"parsed.Add({name}, {value} { value.GetType() })\n");
|
||||||
if (isListElem)
|
if(isListElem)
|
||||||
{
|
{
|
||||||
if (!parsed.ContainsKey(name)) parsed.Add(name, new List<dynamic>());
|
if(!parsed.ContainsKey(name))
|
||||||
|
parsed.Add(name, new List<dynamic>());
|
||||||
parsed[name].Add(value);
|
parsed[name].Add(value);
|
||||||
}
|
}
|
||||||
else parsed.Add(name, value);
|
else
|
||||||
|
parsed.Add(name, value);
|
||||||
return;
|
return;
|
||||||
// строка, начинающаяся с # будет считаться комментом
|
// строка, начинающаяся с # будет считаться комментом
|
||||||
case '#':
|
case '#':
|
||||||
//ReadCommentLine();
|
//ReadCommentLine();
|
||||||
break;
|
break;
|
||||||
case '}':
|
case '}':
|
||||||
throw new Exception("Parse.ReadName() error: unexpected '}' at " + i + " char");
|
throw new Exception("Parse.ReadName() error: unexpected '}' at "+i+" char");
|
||||||
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
|
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
|
||||||
case '$':
|
case '$':
|
||||||
DebugNoTime("w", text[i].ToString());
|
DebugNoTime("w", text[i].ToString());
|
||||||
if (defaultNameBuilder.ToString().Length != 0) throw new Exception("Parse.ReadName() error: unexpected '$' at " + i + " char");
|
if(defaultNameBuilder.ToString().Length!=0)
|
||||||
isListElem = true;
|
throw new Exception("Parse.ReadName() error: unexpected '$' at "+i+" char");
|
||||||
|
isListElem=true;
|
||||||
break;
|
break;
|
||||||
case ';':
|
case ';':
|
||||||
throw new Exception("Parse.ReadName() error: unexpected ';' at " + i + " char");
|
throw new Exception("Parse.ReadName() error: unexpected ';' at "+i+" char");
|
||||||
default:
|
default:
|
||||||
DebugNoTime("w", text[i].ToString());
|
DebugNoTime("w", text[i].ToString());
|
||||||
defaultNameBuilder.Append(text[i]);
|
defaultNameBuilder.Append(text[i]);
|
||||||
@ -165,14 +173,14 @@ namespace DTLib.Dtsod
|
|||||||
i++;
|
i++;
|
||||||
StringBuilder valueBuilder = new();
|
StringBuilder valueBuilder = new();
|
||||||
valueBuilder.Append('"');
|
valueBuilder.Append('"');
|
||||||
for (; text[i] != '"' || text[i - 1] == '\\'; i++)
|
for(; text[i]!='"'||text[i-1]=='\\'; i++)
|
||||||
{
|
{
|
||||||
DebugNoTime("gray", text[i].ToString());
|
DebugNoTime("gray", text[i].ToString());
|
||||||
valueBuilder.Append(text[i]);
|
valueBuilder.Append(text[i]);
|
||||||
}
|
}
|
||||||
valueBuilder.Append('"');
|
valueBuilder.Append('"');
|
||||||
DebugNoTime("gray", text[i].ToString());
|
DebugNoTime("gray", text[i].ToString());
|
||||||
type = ValueType.String;
|
type=ValueType.String;
|
||||||
return valueBuilder.ToString();
|
return valueBuilder.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -181,10 +189,10 @@ namespace DTLib.Dtsod
|
|||||||
i++;
|
i++;
|
||||||
List<dynamic> output = new();
|
List<dynamic> output = new();
|
||||||
StringBuilder valueBuilder = new();
|
StringBuilder valueBuilder = new();
|
||||||
for (; text[i] != ']'; i++)
|
for(; text[i]!=']'; i++)
|
||||||
{
|
{
|
||||||
DebugNoTime("c", text[i].ToString());
|
DebugNoTime("c", text[i].ToString());
|
||||||
switch (text[i])
|
switch(text[i])
|
||||||
{
|
{
|
||||||
case ' ':
|
case ' ':
|
||||||
case '\t':
|
case '\t':
|
||||||
@ -201,13 +209,13 @@ namespace DTLib.Dtsod
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (valueBuilder.Length > 0)
|
if(valueBuilder.Length>0)
|
||||||
{
|
{
|
||||||
ParseValueToRightType(valueBuilder.ToString());
|
ParseValueToRightType(valueBuilder.ToString());
|
||||||
output.Add(value);
|
output.Add(value);
|
||||||
}
|
}
|
||||||
DebugNoTime("c", text[i].ToString());
|
DebugNoTime("c", text[i].ToString());
|
||||||
type = ValueType.List;
|
type=ValueType.List;
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -216,10 +224,10 @@ namespace DTLib.Dtsod
|
|||||||
StringBuilder valueBuilder = new();
|
StringBuilder valueBuilder = new();
|
||||||
int balance = 1;
|
int balance = 1;
|
||||||
i++;
|
i++;
|
||||||
for (; balance != 0; i++)
|
for(; balance!=0; i++)
|
||||||
{
|
{
|
||||||
DebugNoTime("y", text[i].ToString());
|
DebugNoTime("y", text[i].ToString());
|
||||||
switch (text[i])
|
switch(text[i])
|
||||||
{
|
{
|
||||||
case '"':
|
case '"':
|
||||||
valueBuilder.Append(ReadString());
|
valueBuilder.Append(ReadString());
|
||||||
@ -227,7 +235,8 @@ namespace DTLib.Dtsod
|
|||||||
case '}':
|
case '}':
|
||||||
balance--;
|
balance--;
|
||||||
DebugNoTime("b", $"\nbalance -- = {balance}\n");
|
DebugNoTime("b", $"\nbalance -- = {balance}\n");
|
||||||
if (balance != 0) valueBuilder.Append(text[i]);
|
if(balance!=0)
|
||||||
|
valueBuilder.Append(text[i]);
|
||||||
break;
|
break;
|
||||||
case '{':
|
case '{':
|
||||||
balance++;
|
balance++;
|
||||||
@ -240,7 +249,7 @@ namespace DTLib.Dtsod
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
i--; // i++ в for выполняется даже когда balance == 0, то есть text[i] получается == ;, что ломает всё
|
i--; // i++ в for выполняется даже когда balance == 0, то есть text[i] получается == ;, что ломает всё
|
||||||
type = ValueType.Complex;
|
type=ValueType.Complex;
|
||||||
return Parse(valueBuilder.ToString());
|
return Parse(valueBuilder.ToString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -248,51 +257,54 @@ namespace DTLib.Dtsod
|
|||||||
{
|
{
|
||||||
|
|
||||||
DebugNoTime("b", $"\nParseValueToRightType({stringValue})\n");
|
DebugNoTime("b", $"\nParseValueToRightType({stringValue})\n");
|
||||||
switch (stringValue)
|
switch(stringValue)
|
||||||
{
|
{
|
||||||
|
|
||||||
// bool
|
// bool
|
||||||
case "true":
|
case "true":
|
||||||
case "false":
|
case "false":
|
||||||
value = stringValue.ToBool();
|
value=stringValue.ToBool();
|
||||||
break;
|
break;
|
||||||
// null
|
// null
|
||||||
case "null":
|
case "null":
|
||||||
value = null;
|
value=null;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
if (stringValue.Contains('"')) value = stringValue.Remove(stringValue.Length - 1).Remove(0, 1);
|
if(stringValue.Contains('"'))
|
||||||
|
value=stringValue.Remove(stringValue.Length-1).Remove(0, 1);
|
||||||
// double
|
// double
|
||||||
else if (stringValue.Contains('.')) value = stringValue.ToDouble();
|
else if(stringValue.Contains('.'))
|
||||||
|
value=stringValue.ToDouble();
|
||||||
// ushort; ulong; uint
|
// ushort; ulong; uint
|
||||||
else if (stringValue.Length > 2 && stringValue[stringValue.Length - 2] == 'u')
|
else if(stringValue.Length>2&&stringValue[stringValue.Length-2]=='u')
|
||||||
{
|
{
|
||||||
switch (stringValue[stringValue.Length - 1])
|
switch(stringValue[stringValue.Length-1])
|
||||||
{
|
{
|
||||||
case 's':
|
case 's':
|
||||||
value = stringValue.Remove(stringValue.Length - 2).ToUShort();
|
value=stringValue.Remove(stringValue.Length-2).ToUShort();
|
||||||
break;
|
break;
|
||||||
case 'i':
|
case 'i':
|
||||||
value = stringValue.Remove(stringValue.Length - 2).ToUInt();
|
value=stringValue.Remove(stringValue.Length-2).ToUInt();
|
||||||
break;
|
break;
|
||||||
case 'l':
|
case 'l':
|
||||||
value = stringValue.Remove(stringValue.Length - 2).ToULong();
|
value=stringValue.Remove(stringValue.Length-2).ToULong();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new Exception($"Dtsod.Parse.ReadValue() error: value= wrong type <u{stringValue[stringValue.Length - 1]}>");
|
throw new Exception($"Dtsod.Parse.ReadValue() error: value= wrong type <u{stringValue[stringValue.Length-1]}>");
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// short; long; int
|
// short; long; int
|
||||||
else switch (stringValue[stringValue.Length - 1])
|
else
|
||||||
|
switch(stringValue[stringValue.Length-1])
|
||||||
{
|
{
|
||||||
case 's':
|
case 's':
|
||||||
value = stringValue.Remove(stringValue.Length - 1).ToShort();
|
value=stringValue.Remove(stringValue.Length-1).ToShort();
|
||||||
break;
|
break;
|
||||||
case 'l':
|
case 'l':
|
||||||
value = stringValue.Remove(stringValue.Length - 1).ToLong();
|
value=stringValue.Remove(stringValue.Length-1).ToLong();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
value = stringValue.ToShort();
|
value=stringValue.ToShort();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@ -301,10 +313,10 @@ namespace DTLib.Dtsod
|
|||||||
|
|
||||||
StringBuilder defaultValueBuilder = new();
|
StringBuilder defaultValueBuilder = new();
|
||||||
DebugNoTime("m", "\nReadValue\n");
|
DebugNoTime("m", "\nReadValue\n");
|
||||||
for (; i < text.Length; i++)
|
for(; i<text.Length; i++)
|
||||||
{
|
{
|
||||||
DebugNoTime("b", text[i].ToString());
|
DebugNoTime("b", text[i].ToString());
|
||||||
switch (text[i])
|
switch(text[i])
|
||||||
{
|
{
|
||||||
case ' ':
|
case ' ':
|
||||||
case '\t':
|
case '\t':
|
||||||
@ -312,10 +324,10 @@ namespace DTLib.Dtsod
|
|||||||
case '\n':
|
case '\n':
|
||||||
break;
|
break;
|
||||||
case '"':
|
case '"':
|
||||||
value = ReadString();
|
value=ReadString();
|
||||||
break;
|
break;
|
||||||
case ';':
|
case ';':
|
||||||
switch (type)
|
switch(type)
|
||||||
{
|
{
|
||||||
case ValueType.String:
|
case ValueType.String:
|
||||||
ParseValueToRightType(value);
|
ParseValueToRightType(value);
|
||||||
@ -326,10 +338,10 @@ namespace DTLib.Dtsod
|
|||||||
};
|
};
|
||||||
return value;
|
return value;
|
||||||
case '[':
|
case '[':
|
||||||
value = ReadList();
|
value=ReadList();
|
||||||
break;
|
break;
|
||||||
case '{':
|
case '{':
|
||||||
value = ReadComplex();
|
value=ReadComplex();
|
||||||
break;
|
break;
|
||||||
// строка, начинающаяся с # будет считаться комментом
|
// строка, начинающаяся с # будет считаться комментом
|
||||||
case '#':
|
case '#':
|
||||||
@ -347,11 +359,13 @@ namespace DTLib.Dtsod
|
|||||||
|
|
||||||
void Debug(params string[] msg)
|
void Debug(params string[] msg)
|
||||||
{
|
{
|
||||||
if (debug) Log(msg);
|
if(debug)
|
||||||
|
Log(msg);
|
||||||
}
|
}
|
||||||
void DebugNoTime(params string[] msg)
|
void DebugNoTime(params string[] msg)
|
||||||
{
|
{
|
||||||
if (debug) LogNoTime(msg);
|
if(debug)
|
||||||
|
LogNoTime(msg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -34,15 +34,15 @@ namespace DTLib.Dtsod
|
|||||||
public bool IsList;
|
public bool IsList;
|
||||||
public ValueStruct(ValueTypes type, dynamic value, bool isList)
|
public ValueStruct(ValueTypes type, dynamic value, bool isList)
|
||||||
{
|
{
|
||||||
Value = value;
|
Value=value;
|
||||||
Type = type;
|
Type=type;
|
||||||
IsList = isList;
|
IsList=isList;
|
||||||
}
|
}
|
||||||
public ValueStruct(ValueTypes type, dynamic value)
|
public ValueStruct(ValueTypes type, dynamic value)
|
||||||
{
|
{
|
||||||
Value = value;
|
Value=value;
|
||||||
Type = type;
|
Type=type;
|
||||||
IsList = false;
|
IsList=false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -50,14 +50,14 @@ namespace DTLib.Dtsod
|
|||||||
|
|
||||||
public DtsodV23(string text)
|
public DtsodV23(string text)
|
||||||
{
|
{
|
||||||
foreach (KeyValuePair<string, ValueStruct> pair in Parse(text))
|
foreach(KeyValuePair<string, ValueStruct> pair in Parse(text))
|
||||||
Add(pair.Key, pair.Value);
|
Add(pair.Key, pair.Value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public DtsodV23(Dictionary<string, DtsodV23.ValueStruct> dict)
|
public DtsodV23(Dictionary<string, DtsodV23.ValueStruct> dict)
|
||||||
{
|
{
|
||||||
foreach (KeyValuePair<string, ValueStruct> pair in dict)
|
foreach(KeyValuePair<string, ValueStruct> pair in dict)
|
||||||
Add(pair.Key, pair.Value);
|
Add(pair.Key, pair.Value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,13 +66,17 @@ namespace DTLib.Dtsod
|
|||||||
{
|
{
|
||||||
get
|
get
|
||||||
{
|
{
|
||||||
if (TryGetValue(key, out dynamic value)) return value;
|
if(TryGetValue(key, out dynamic value))
|
||||||
else throw new Exception($"Dtsod[{key}] key not found");
|
return value;
|
||||||
|
else
|
||||||
|
throw new Exception($"Dtsod[{key}] key not found");
|
||||||
}
|
}
|
||||||
set
|
set
|
||||||
{
|
{
|
||||||
if (TrySetValue(key, value)) return;
|
if(TrySetValue(key, value))
|
||||||
else throw new Exception($"Dtsod[{key}] key not found");
|
return;
|
||||||
|
else
|
||||||
|
throw new Exception($"Dtsod[{key}] key not found");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -81,12 +85,12 @@ namespace DTLib.Dtsod
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
value = base[key].Value;
|
value=base[key].Value;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
catch (KeyNotFoundException)
|
catch(KeyNotFoundException)
|
||||||
{
|
{
|
||||||
value = null;
|
value=null;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -95,12 +99,14 @@ namespace DTLib.Dtsod
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
bool isList;
|
bool isList;
|
||||||
if (value is IList) isList = true;
|
if(value is IList)
|
||||||
else isList = false;
|
isList=true;
|
||||||
base[key] = new(base[key].Type, value, isList);
|
else
|
||||||
|
isList=false;
|
||||||
|
base[key]=new(base[key].Type, value, isList);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
catch (KeyNotFoundException)
|
catch(KeyNotFoundException)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -110,7 +116,8 @@ namespace DTLib.Dtsod
|
|||||||
{
|
{
|
||||||
Dictionary<string, ValueStruct> parsed = new();
|
Dictionary<string, ValueStruct> parsed = new();
|
||||||
int i = 0;
|
int i = 0;
|
||||||
for (; i < text.Length; i++) ReadName();
|
for(; i<text.Length; i++)
|
||||||
|
ReadName();
|
||||||
DebugNoTime("g", $"Parse returns {parsed.Keys.Count} keys\n");
|
DebugNoTime("g", $"Parse returns {parsed.Keys.Count} keys\n");
|
||||||
return new DtsodV23(parsed);
|
return new DtsodV23(parsed);
|
||||||
|
|
||||||
@ -128,9 +135,9 @@ namespace DTLib.Dtsod
|
|||||||
StringBuilder defaultNameBuilder = new();
|
StringBuilder defaultNameBuilder = new();
|
||||||
|
|
||||||
DebugNoTime("m", "ReadName\n");
|
DebugNoTime("m", "ReadName\n");
|
||||||
for (; i < text.Length; i++)
|
for(; i<text.Length; i++)
|
||||||
{
|
{
|
||||||
switch (text[i])
|
switch(text[i])
|
||||||
{
|
{
|
||||||
case ' ':
|
case ' ':
|
||||||
case '\t':
|
case '\t':
|
||||||
@ -140,29 +147,32 @@ namespace DTLib.Dtsod
|
|||||||
case ':':
|
case ':':
|
||||||
i++;
|
i++;
|
||||||
string name = defaultNameBuilder.ToString();
|
string name = defaultNameBuilder.ToString();
|
||||||
value = ReadValue(out var type, out var isList);
|
value=ReadValue(out ValueTypes type, out bool isList);
|
||||||
DebugNoTime("c", $"parsed.Add({name},{type} {value} )\n");
|
DebugNoTime("c", $"parsed.Add({name},{type} {value} )\n");
|
||||||
if (isListElem)
|
if(isListElem)
|
||||||
{
|
{
|
||||||
if (!parsed.ContainsKey(name)) parsed.Add(name, new(type, new List<dynamic>(), isList));
|
if(!parsed.ContainsKey(name))
|
||||||
|
parsed.Add(name, new(type, new List<dynamic>(), isList));
|
||||||
parsed[name].Value.Add(value);
|
parsed[name].Value.Add(value);
|
||||||
}
|
}
|
||||||
else parsed.Add(name, new(type, value, isList));
|
else
|
||||||
|
parsed.Add(name, new(type, value, isList));
|
||||||
return;
|
return;
|
||||||
// строка, начинающаяся с # будет считаться комментом
|
// строка, начинающаяся с # будет считаться комментом
|
||||||
case '#':
|
case '#':
|
||||||
//ReadCommentLine();
|
//ReadCommentLine();
|
||||||
break;
|
break;
|
||||||
case '}':
|
case '}':
|
||||||
throw new Exception("Parse.ReadName() error: unexpected '}' at " + i + " char");
|
throw new Exception("Parse.ReadName() error: unexpected '}' at "+i+" char");
|
||||||
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
|
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
|
||||||
case '$':
|
case '$':
|
||||||
DebugNoTime("w", text[i].ToString());
|
DebugNoTime("w", text[i].ToString());
|
||||||
if (defaultNameBuilder.ToString().Length != 0) throw new Exception("Parse.ReadName() error: unexpected '$' at " + i + " char");
|
if(defaultNameBuilder.ToString().Length!=0)
|
||||||
isListElem = true;
|
throw new Exception("Parse.ReadName() error: unexpected '$' at "+i+" char");
|
||||||
|
isListElem=true;
|
||||||
break;
|
break;
|
||||||
case ';':
|
case ';':
|
||||||
throw new Exception("Parse.ReadName() error: unexpected ';' at " + i + " char");
|
throw new Exception("Parse.ReadName() error: unexpected ';' at "+i+" char");
|
||||||
default:
|
default:
|
||||||
DebugNoTime("w", text[i].ToString());
|
DebugNoTime("w", text[i].ToString());
|
||||||
defaultNameBuilder.Append(text[i]);
|
defaultNameBuilder.Append(text[i]);
|
||||||
@ -174,7 +184,7 @@ namespace DTLib.Dtsod
|
|||||||
dynamic ReadValue(out ValueTypes outType, out bool isList)
|
dynamic ReadValue(out ValueTypes outType, out bool isList)
|
||||||
{
|
{
|
||||||
ValueTypes type = ValueTypes.Unknown;
|
ValueTypes type = ValueTypes.Unknown;
|
||||||
isList = false;
|
isList=false;
|
||||||
dynamic value = null;
|
dynamic value = null;
|
||||||
|
|
||||||
string ReadString()
|
string ReadString()
|
||||||
@ -182,14 +192,14 @@ namespace DTLib.Dtsod
|
|||||||
i++;
|
i++;
|
||||||
StringBuilder valueBuilder = new();
|
StringBuilder valueBuilder = new();
|
||||||
valueBuilder.Append('"');
|
valueBuilder.Append('"');
|
||||||
for (; text[i] != '"' || text[i - 1] == '\\'; i++)
|
for(; text[i]!='"'||text[i-1]=='\\'; i++)
|
||||||
{
|
{
|
||||||
DebugNoTime("gray", text[i].ToString());
|
DebugNoTime("gray", text[i].ToString());
|
||||||
valueBuilder.Append(text[i]);
|
valueBuilder.Append(text[i]);
|
||||||
}
|
}
|
||||||
valueBuilder.Append('"');
|
valueBuilder.Append('"');
|
||||||
DebugNoTime("gray", text[i].ToString());
|
DebugNoTime("gray", text[i].ToString());
|
||||||
type = ValueTypes.String;
|
type=ValueTypes.String;
|
||||||
return valueBuilder.ToString();
|
return valueBuilder.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -198,10 +208,10 @@ namespace DTLib.Dtsod
|
|||||||
i++;
|
i++;
|
||||||
List<dynamic> output = new();
|
List<dynamic> output = new();
|
||||||
StringBuilder valueBuilder = new();
|
StringBuilder valueBuilder = new();
|
||||||
for (; text[i] != ']'; i++)
|
for(; text[i]!=']'; i++)
|
||||||
{
|
{
|
||||||
DebugNoTime("c", text[i].ToString());
|
DebugNoTime("c", text[i].ToString());
|
||||||
switch (text[i])
|
switch(text[i])
|
||||||
{
|
{
|
||||||
case ' ':
|
case ' ':
|
||||||
case '\t':
|
case '\t':
|
||||||
@ -218,13 +228,13 @@ namespace DTLib.Dtsod
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (valueBuilder.Length > 0)
|
if(valueBuilder.Length>0)
|
||||||
{
|
{
|
||||||
ParseValueToRightType(valueBuilder.ToString());
|
ParseValueToRightType(valueBuilder.ToString());
|
||||||
output.Add(value);
|
output.Add(value);
|
||||||
}
|
}
|
||||||
DebugNoTime("c", text[i].ToString());
|
DebugNoTime("c", text[i].ToString());
|
||||||
type = ValueTypes.List;
|
type=ValueTypes.List;
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -233,10 +243,10 @@ namespace DTLib.Dtsod
|
|||||||
StringBuilder valueBuilder = new();
|
StringBuilder valueBuilder = new();
|
||||||
int balance = 1;
|
int balance = 1;
|
||||||
i++;
|
i++;
|
||||||
for (; balance != 0; i++)
|
for(; balance!=0; i++)
|
||||||
{
|
{
|
||||||
DebugNoTime("y", text[i].ToString());
|
DebugNoTime("y", text[i].ToString());
|
||||||
switch (text[i])
|
switch(text[i])
|
||||||
{
|
{
|
||||||
case '"':
|
case '"':
|
||||||
valueBuilder.Append(ReadString());
|
valueBuilder.Append(ReadString());
|
||||||
@ -244,7 +254,8 @@ namespace DTLib.Dtsod
|
|||||||
case '}':
|
case '}':
|
||||||
balance--;
|
balance--;
|
||||||
DebugNoTime("b", $"\nbalance -- = {balance}\n");
|
DebugNoTime("b", $"\nbalance -- = {balance}\n");
|
||||||
if (balance != 0) valueBuilder.Append(text[i]);
|
if(balance!=0)
|
||||||
|
valueBuilder.Append(text[i]);
|
||||||
break;
|
break;
|
||||||
case '{':
|
case '{':
|
||||||
balance++;
|
balance++;
|
||||||
@ -257,74 +268,75 @@ namespace DTLib.Dtsod
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
i--; // i++ в for выполняется даже когда balance == 0, то есть text[i] получается == ;, что ломает всё
|
i--; // i++ в for выполняется даже когда balance == 0, то есть text[i] получается == ;, что ломает всё
|
||||||
type = ValueTypes.Complex;
|
type=ValueTypes.Complex;
|
||||||
return Parse(valueBuilder.ToString());
|
return Parse(valueBuilder.ToString());
|
||||||
}
|
}
|
||||||
|
|
||||||
void ParseValueToRightType(string stringValue)
|
void ParseValueToRightType(string stringValue)
|
||||||
{
|
{
|
||||||
DebugNoTime("b", $"\nParseValueToRightType({stringValue})\n");
|
DebugNoTime("b", $"\nParseValueToRightType({stringValue})\n");
|
||||||
switch (stringValue)
|
switch(stringValue)
|
||||||
{
|
{
|
||||||
|
|
||||||
// bool
|
// bool
|
||||||
case "true":
|
case "true":
|
||||||
case "false":
|
case "false":
|
||||||
type = ValueTypes.Bool;
|
type=ValueTypes.Bool;
|
||||||
value = stringValue.ToBool();
|
value=stringValue.ToBool();
|
||||||
break;
|
break;
|
||||||
// null
|
// null
|
||||||
case "null":
|
case "null":
|
||||||
type = ValueTypes.Null;
|
type=ValueTypes.Null;
|
||||||
value = null;
|
value=null;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
if (stringValue.Contains('"'))
|
if(stringValue.Contains('"'))
|
||||||
{
|
{
|
||||||
type = ValueTypes.String;
|
type=ValueTypes.String;
|
||||||
value = stringValue.Remove(stringValue.Length - 1).Remove(0, 1);
|
value=stringValue.Remove(stringValue.Length-1).Remove(0, 1);
|
||||||
}
|
}
|
||||||
// double
|
// double
|
||||||
else if (stringValue.Contains('.'))
|
else if(stringValue.Contains('.'))
|
||||||
{
|
{
|
||||||
type = ValueTypes.Double;
|
type=ValueTypes.Double;
|
||||||
value = stringValue.ToDouble();
|
value=stringValue.ToDouble();
|
||||||
}
|
}
|
||||||
// ushort; ulong; uint
|
// ushort; ulong; uint
|
||||||
else if (stringValue.Length > 2 && stringValue[stringValue.Length - 2] == 'u')
|
else if(stringValue.Length>2&&stringValue[stringValue.Length-2]=='u')
|
||||||
{
|
{
|
||||||
switch (stringValue[stringValue.Length - 1])
|
switch(stringValue[stringValue.Length-1])
|
||||||
{
|
{
|
||||||
case 's':
|
case 's':
|
||||||
type = ValueTypes.UShort;
|
type=ValueTypes.UShort;
|
||||||
value = stringValue.Remove(stringValue.Length - 2).ToUShort();
|
value=stringValue.Remove(stringValue.Length-2).ToUShort();
|
||||||
break;
|
break;
|
||||||
case 'i':
|
case 'i':
|
||||||
type = ValueTypes.UInt;
|
type=ValueTypes.UInt;
|
||||||
value = stringValue.Remove(stringValue.Length - 2).ToUInt();
|
value=stringValue.Remove(stringValue.Length-2).ToUInt();
|
||||||
break;
|
break;
|
||||||
case 'l':
|
case 'l':
|
||||||
type = ValueTypes.ULong;
|
type=ValueTypes.ULong;
|
||||||
value = stringValue.Remove(stringValue.Length - 2).ToULong();
|
value=stringValue.Remove(stringValue.Length-2).ToULong();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new Exception($"Dtsod.Parse.ReadValue() error: value <{stringValue}> has wrong type");
|
throw new Exception($"Dtsod.Parse.ReadValue() error: value <{stringValue}> has wrong type");
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// short; long; int
|
// short; long; int
|
||||||
else switch (stringValue[stringValue.Length - 1])
|
else
|
||||||
|
switch(stringValue[stringValue.Length-1])
|
||||||
{
|
{
|
||||||
case 's':
|
case 's':
|
||||||
type = ValueTypes.Short;
|
type=ValueTypes.Short;
|
||||||
value = stringValue.Remove(stringValue.Length - 1).ToShort();
|
value=stringValue.Remove(stringValue.Length-1).ToShort();
|
||||||
break;
|
break;
|
||||||
case 'l':
|
case 'l':
|
||||||
type = ValueTypes.Long;
|
type=ValueTypes.Long;
|
||||||
value = stringValue.Remove(stringValue.Length - 1).ToLong();
|
value=stringValue.Remove(stringValue.Length-1).ToLong();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
type = ValueTypes.Int;
|
type=ValueTypes.Int;
|
||||||
value = stringValue.ToShort();
|
value=stringValue.ToShort();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@ -333,10 +345,10 @@ namespace DTLib.Dtsod
|
|||||||
|
|
||||||
StringBuilder defaultValueBuilder = new();
|
StringBuilder defaultValueBuilder = new();
|
||||||
DebugNoTime("m", "\nReadValue\n");
|
DebugNoTime("m", "\nReadValue\n");
|
||||||
for (; i < text.Length; i++)
|
for(; i<text.Length; i++)
|
||||||
{
|
{
|
||||||
DebugNoTime("b", text[i].ToString());
|
DebugNoTime("b", text[i].ToString());
|
||||||
switch (text[i])
|
switch(text[i])
|
||||||
{
|
{
|
||||||
case ' ':
|
case ' ':
|
||||||
case '\t':
|
case '\t':
|
||||||
@ -344,16 +356,16 @@ namespace DTLib.Dtsod
|
|||||||
case '\n':
|
case '\n':
|
||||||
break;
|
break;
|
||||||
case '"':
|
case '"':
|
||||||
value = ReadString();
|
value=ReadString();
|
||||||
break;
|
break;
|
||||||
case '[':
|
case '[':
|
||||||
value = ReadList();
|
value=ReadList();
|
||||||
break;
|
break;
|
||||||
case '{':
|
case '{':
|
||||||
value = ReadComplex();
|
value=ReadComplex();
|
||||||
break;
|
break;
|
||||||
case ';':
|
case ';':
|
||||||
switch (type)
|
switch(type)
|
||||||
{
|
{
|
||||||
case ValueTypes.String:
|
case ValueTypes.String:
|
||||||
ParseValueToRightType(value);
|
ParseValueToRightType(value);
|
||||||
@ -362,10 +374,10 @@ namespace DTLib.Dtsod
|
|||||||
ParseValueToRightType(defaultValueBuilder.ToString());
|
ParseValueToRightType(defaultValueBuilder.ToString());
|
||||||
break;
|
break;
|
||||||
case ValueTypes.List:
|
case ValueTypes.List:
|
||||||
isList = true;
|
isList=true;
|
||||||
break;
|
break;
|
||||||
};
|
};
|
||||||
outType = type;
|
outType=type;
|
||||||
return value;
|
return value;
|
||||||
// строка, начинающаяся с # будет считаться комментом
|
// строка, начинающаяся с # будет считаться комментом
|
||||||
case '#':
|
case '#':
|
||||||
@ -386,13 +398,13 @@ namespace DTLib.Dtsod
|
|||||||
string Deconstruct(DtsodV23 dtsod)
|
string Deconstruct(DtsodV23 dtsod)
|
||||||
{
|
{
|
||||||
StringBuilder outBuilder = new();
|
StringBuilder outBuilder = new();
|
||||||
foreach (var key in dtsod.Keys)
|
foreach(string key in dtsod.Keys)
|
||||||
{
|
{
|
||||||
outBuilder.Append('\t', tabCount);
|
outBuilder.Append('\t', tabCount);
|
||||||
outBuilder.Append(key);
|
outBuilder.Append(key);
|
||||||
outBuilder.Append(": ");
|
outBuilder.Append(": ");
|
||||||
dtsod.TryGetValue(key, out ValueStruct value);
|
dtsod.TryGetValue(key, out ValueStruct value);
|
||||||
switch (value.Type)
|
switch(value.Type)
|
||||||
{
|
{
|
||||||
case ValueTypes.List:
|
case ValueTypes.List:
|
||||||
outBuilder.Append("\"list deconstruction is'nt implemented yet\"");
|
outBuilder.Append("\"list deconstruction is'nt implemented yet\"");
|
||||||
@ -455,12 +467,13 @@ namespace DTLib.Dtsod
|
|||||||
|
|
||||||
void DebugNoTime(params string[] msg)
|
void DebugNoTime(params string[] msg)
|
||||||
{
|
{
|
||||||
if (debug) PublicLog.LogNoTime(msg);
|
if(debug)
|
||||||
|
PublicLog.LogNoTime(msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Expand(DtsodV23 newPart)
|
public void Expand(DtsodV23 newPart)
|
||||||
{
|
{
|
||||||
foreach (KeyValuePair<string, ValueStruct> pair in newPart)
|
foreach(KeyValuePair<string, ValueStruct> pair in newPart)
|
||||||
Add(pair.Key, pair.Value);
|
Add(pair.Key, pair.Value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,5 +2,7 @@
|
|||||||
|
|
||||||
namespace DTLib
|
namespace DTLib
|
||||||
{
|
{
|
||||||
|
#pragma warning disable IDE1006 // Стили именования
|
||||||
public delegate Task EventHandlerAsync<TEventArgs>(object sender, TEventArgs e);
|
public delegate Task EventHandlerAsync<TEventArgs>(object sender, TEventArgs e);
|
||||||
|
#pragma warning restore IDE1006 // Стили именования
|
||||||
}
|
}
|
||||||
|
|||||||
@ -10,10 +10,10 @@ namespace DTLib.Filesystem
|
|||||||
// создает папку, если её не существует
|
// создает папку, если её не существует
|
||||||
public static void Create(string dir)
|
public static void Create(string dir)
|
||||||
{
|
{
|
||||||
if (!Directory.Exists(dir))
|
if(!Directory.Exists(dir))
|
||||||
{
|
{
|
||||||
// проверяет существование папки, в которой нужно создать dir
|
// проверяет существование папки, в которой нужно создать dir
|
||||||
if (dir.Contains("\\") && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
|
if(dir.Contains("\\")&&!Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
|
||||||
Create(dir.Remove(dir.LastIndexOf('\\')));
|
Create(dir.Remove(dir.LastIndexOf('\\')));
|
||||||
System.IO.Directory.CreateDirectory(dir);
|
System.IO.Directory.CreateDirectory(dir);
|
||||||
}
|
}
|
||||||
@ -22,13 +22,13 @@ namespace DTLib.Filesystem
|
|||||||
public static void Copy(string source_dir, string new_dir, bool owerwrite = false)
|
public static void Copy(string source_dir, string new_dir, bool owerwrite = false)
|
||||||
{
|
{
|
||||||
Create(new_dir);
|
Create(new_dir);
|
||||||
List<string> subdirs = new List<string>();
|
var subdirs = new List<string>();
|
||||||
List<string> files = GetAllFiles(source_dir, ref subdirs);
|
List<string> files = GetAllFiles(source_dir, ref subdirs);
|
||||||
for (int i = 0; i < subdirs.Count; i++)
|
for(int i = 0; i<subdirs.Count; i++)
|
||||||
{
|
{
|
||||||
Create(subdirs[i].Replace(source_dir, new_dir));
|
Create(subdirs[i].Replace(source_dir, new_dir));
|
||||||
}
|
}
|
||||||
for (int i = 0; i < files.Count; i++)
|
for(int i = 0; i<files.Count; i++)
|
||||||
{
|
{
|
||||||
string f = files[i].Replace(source_dir, new_dir);
|
string f = files[i].Replace(source_dir, new_dir);
|
||||||
File.Copy(files[i], f, owerwrite);
|
File.Copy(files[i], f, owerwrite);
|
||||||
@ -39,18 +39,19 @@ namespace DTLib.Filesystem
|
|||||||
// копирует все файлы и папки и выдаёт список конфликтующих файлов
|
// копирует все файлы и папки и выдаёт список конфликтующих файлов
|
||||||
public static void Copy(string source_dir, string new_dir, out List<string> conflicts, bool owerwrite = false)
|
public static void Copy(string source_dir, string new_dir, out List<string> conflicts, bool owerwrite = false)
|
||||||
{
|
{
|
||||||
conflicts = new List<string>();
|
conflicts=new List<string>();
|
||||||
var subdirs = new List<string>();
|
var subdirs = new List<string>();
|
||||||
var files = GetAllFiles(source_dir, ref subdirs);
|
List<string> files = GetAllFiles(source_dir, ref subdirs);
|
||||||
Create(new_dir);
|
Create(new_dir);
|
||||||
for (int i = 0; i < subdirs.Count; i++)
|
for(int i = 0; i<subdirs.Count; i++)
|
||||||
{
|
{
|
||||||
Create(subdirs[i].Replace(source_dir, new_dir));
|
Create(subdirs[i].Replace(source_dir, new_dir));
|
||||||
}
|
}
|
||||||
for (int i = 0; i < files.Count; i++)
|
for(int i = 0; i<files.Count; i++)
|
||||||
{
|
{
|
||||||
string newfile = files[i].Replace(source_dir, new_dir);
|
string newfile = files[i].Replace(source_dir, new_dir);
|
||||||
if (File.Exists(newfile)) conflicts.Add(newfile);
|
if(File.Exists(newfile))
|
||||||
|
conflicts.Add(newfile);
|
||||||
File.Copy(files[i], newfile, owerwrite);
|
File.Copy(files[i], newfile, owerwrite);
|
||||||
//PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
|
//PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
|
||||||
}
|
}
|
||||||
@ -60,16 +61,18 @@ namespace DTLib.Filesystem
|
|||||||
public static void Delete(string dir)
|
public static void Delete(string dir)
|
||||||
{
|
{
|
||||||
var subdirs = new List<string>();
|
var subdirs = new List<string>();
|
||||||
var files = GetAllFiles(dir, ref subdirs);
|
List<string> files = GetAllFiles(dir, ref subdirs);
|
||||||
for (int i = 0; i < files.Count; i++)
|
for(int i = 0; i<files.Count; i++)
|
||||||
File.Delete(files[i]);
|
File.Delete(files[i]);
|
||||||
for (int i = subdirs.Count - 1; i >= 0; i--)
|
for(int i = subdirs.Count-1; i>=0; i--)
|
||||||
{
|
{
|
||||||
PublicLog.Log($"deleting {subdirs[i]}\n");
|
PublicLog.Log($"deleting {subdirs[i]}\n");
|
||||||
if (Directory.Exists(subdirs[i])) System.IO.Directory.Delete(subdirs[i], true);
|
if(Directory.Exists(subdirs[i]))
|
||||||
|
System.IO.Directory.Delete(subdirs[i], true);
|
||||||
}
|
}
|
||||||
PublicLog.Log($"deleting {dir}\n");
|
PublicLog.Log($"deleting {dir}\n");
|
||||||
if (Directory.Exists(dir)) System.IO.Directory.Delete(dir, true);
|
if(Directory.Exists(dir))
|
||||||
|
System.IO.Directory.Delete(dir, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string[] GetFiles(string dir) => System.IO.Directory.GetFiles(dir);
|
public static string[] GetFiles(string dir) => System.IO.Directory.GetFiles(dir);
|
||||||
@ -79,15 +82,15 @@ namespace DTLib.Filesystem
|
|||||||
// выдает список всех файлов
|
// выдает список всех файлов
|
||||||
public static List<string> GetAllFiles(string dir)
|
public static List<string> GetAllFiles(string dir)
|
||||||
{
|
{
|
||||||
List<string> all_files = new List<string>();
|
var all_files = new List<string>();
|
||||||
string[] cur_files = Directory.GetFiles(dir);
|
string[] cur_files = Directory.GetFiles(dir);
|
||||||
for (int i = 0; i < cur_files.Length; i++)
|
for(int i = 0; i<cur_files.Length; i++)
|
||||||
{
|
{
|
||||||
all_files.Add(cur_files[i]);
|
all_files.Add(cur_files[i]);
|
||||||
//PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
|
//PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
|
||||||
}
|
}
|
||||||
string[] cur_subdirs = Directory.GetDirectories(dir);
|
string[] cur_subdirs = Directory.GetDirectories(dir);
|
||||||
for (int i = 0; i < cur_subdirs.Length; i++)
|
for(int i = 0; i<cur_subdirs.Length; i++)
|
||||||
{
|
{
|
||||||
//PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
|
//PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
|
||||||
all_files.AddRange(GetAllFiles(cur_subdirs[i]));
|
all_files.AddRange(GetAllFiles(cur_subdirs[i]));
|
||||||
@ -98,15 +101,15 @@ namespace DTLib.Filesystem
|
|||||||
// выдает список всех файлов и подпапок в папке
|
// выдает список всех файлов и подпапок в папке
|
||||||
public static List<string> GetAllFiles(string dir, ref List<string> all_subdirs)
|
public static List<string> GetAllFiles(string dir, ref List<string> all_subdirs)
|
||||||
{
|
{
|
||||||
List<string> all_files = new List<string>();
|
var all_files = new List<string>();
|
||||||
string[] cur_files = Directory.GetFiles(dir);
|
string[] cur_files = Directory.GetFiles(dir);
|
||||||
for (int i = 0; i < cur_files.Length; i++)
|
for(int i = 0; i<cur_files.Length; i++)
|
||||||
{
|
{
|
||||||
all_files.Add(cur_files[i]);
|
all_files.Add(cur_files[i]);
|
||||||
//PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
|
//PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
|
||||||
}
|
}
|
||||||
string[] cur_subdirs = Directory.GetDirectories(dir);
|
string[] cur_subdirs = Directory.GetDirectories(dir);
|
||||||
for (int i = 0; i < cur_subdirs.Length; i++)
|
for(int i = 0; i<cur_subdirs.Length; i++)
|
||||||
{
|
{
|
||||||
all_subdirs.Add(cur_subdirs[i]);
|
all_subdirs.Add(cur_subdirs[i]);
|
||||||
//PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
|
//PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
|
||||||
@ -119,13 +122,13 @@ namespace DTLib.Filesystem
|
|||||||
|
|
||||||
public static void GrantAccess(string fullPath)
|
public static void GrantAccess(string fullPath)
|
||||||
{
|
{
|
||||||
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(fullPath);
|
var dirInfo = new System.IO.DirectoryInfo(fullPath);
|
||||||
System.Security.AccessControl.DirectorySecurity dirSecurity = dirInfo.GetAccessControl();
|
System.Security.AccessControl.DirectorySecurity dirSecurity = dirInfo.GetAccessControl();
|
||||||
dirSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
|
dirSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
|
||||||
new System.Security.Principal.SecurityIdentifier(
|
new System.Security.Principal.SecurityIdentifier(
|
||||||
System.Security.Principal.WellKnownSidType.WorldSid, null),
|
System.Security.Principal.WellKnownSidType.WorldSid, null),
|
||||||
System.Security.AccessControl.FileSystemRights.FullControl,
|
System.Security.AccessControl.FileSystemRights.FullControl,
|
||||||
System.Security.AccessControl.InheritanceFlags.ObjectInherit |
|
System.Security.AccessControl.InheritanceFlags.ObjectInherit|
|
||||||
System.Security.AccessControl.InheritanceFlags.ContainerInherit,
|
System.Security.AccessControl.InheritanceFlags.ContainerInherit,
|
||||||
System.Security.AccessControl.PropagationFlags.NoPropagateInherit,
|
System.Security.AccessControl.PropagationFlags.NoPropagateInherit,
|
||||||
System.Security.AccessControl.AccessControlType.Allow));
|
System.Security.AccessControl.AccessControlType.Allow));
|
||||||
|
|||||||
@ -11,18 +11,21 @@ namespace DTLib.Filesystem
|
|||||||
// если файл не существует, создаёт файл, создаёт папки из его пути
|
// если файл не существует, создаёт файл, создаёт папки из его пути
|
||||||
public static void Create(string file, bool delete_old = false)
|
public static void Create(string file, bool delete_old = false)
|
||||||
{
|
{
|
||||||
if (delete_old && File.Exists(file)) File.Delete(file);
|
if(delete_old&&File.Exists(file))
|
||||||
if (!File.Exists(file))
|
File.Delete(file);
|
||||||
|
if(!File.Exists(file))
|
||||||
{
|
{
|
||||||
if (file.Contains("\\")) Directory.Create(file.Remove(file.LastIndexOf('\\')));
|
if(file.Contains("\\"))
|
||||||
using var stream = System.IO.File.Create(file);
|
Directory.Create(file.Remove(file.LastIndexOf('\\')));
|
||||||
|
using System.IO.FileStream stream = System.IO.File.Create(file);
|
||||||
stream.Close();
|
stream.Close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void Copy(string srcPath, string newPath, bool replace = false)
|
public static void Copy(string srcPath, string newPath, bool replace = false)
|
||||||
{
|
{
|
||||||
if (!replace && Exists(newPath)) throw new Exception($"file <{newPath}> alredy exists");
|
if(!replace&&Exists(newPath))
|
||||||
|
throw new Exception($"file <{newPath}> alredy exists");
|
||||||
Create(newPath);
|
Create(newPath);
|
||||||
WriteAllBytes(newPath, ReadAllBytes(srcPath));
|
WriteAllBytes(newPath, ReadAllBytes(srcPath));
|
||||||
}
|
}
|
||||||
@ -31,7 +34,7 @@ namespace DTLib.Filesystem
|
|||||||
|
|
||||||
public static byte[] ReadAllBytes(string file)
|
public static byte[] ReadAllBytes(string file)
|
||||||
{
|
{
|
||||||
using var stream = File.OpenRead(file);
|
using System.IO.FileStream stream = File.OpenRead(file);
|
||||||
int size = GetSize(file);
|
int size = GetSize(file);
|
||||||
byte[] output = new byte[size];
|
byte[] output = new byte[size];
|
||||||
stream.Read(output, 0, size);
|
stream.Read(output, 0, size);
|
||||||
@ -43,7 +46,7 @@ namespace DTLib.Filesystem
|
|||||||
|
|
||||||
public static void WriteAllBytes(string file, byte[] content)
|
public static void WriteAllBytes(string file, byte[] content)
|
||||||
{
|
{
|
||||||
using var stream = File.OpenWrite(file);
|
using System.IO.FileStream stream = File.OpenWrite(file);
|
||||||
stream.Write(content, 0, content.Length);
|
stream.Write(content, 0, content.Length);
|
||||||
stream.Close();
|
stream.Close();
|
||||||
}
|
}
|
||||||
@ -52,7 +55,7 @@ namespace DTLib.Filesystem
|
|||||||
|
|
||||||
public static void AppendAllBytes(string file, byte[] content)
|
public static void AppendAllBytes(string file, byte[] content)
|
||||||
{
|
{
|
||||||
using var stream = File.OpenAppend(file);
|
using System.IO.FileStream stream = File.OpenAppend(file);
|
||||||
stream.Write(content, 0, content.Length);
|
stream.Write(content, 0, content.Length);
|
||||||
stream.Close();
|
stream.Close();
|
||||||
}
|
}
|
||||||
@ -61,7 +64,8 @@ namespace DTLib.Filesystem
|
|||||||
|
|
||||||
public static System.IO.FileStream OpenRead(string file)
|
public static System.IO.FileStream OpenRead(string file)
|
||||||
{
|
{
|
||||||
if (!Exists(file)) throw new Exception($"file not found: <{file}>");
|
if(!Exists(file))
|
||||||
|
throw new Exception($"file not found: <{file}>");
|
||||||
return System.IO.File.OpenRead(file);
|
return System.IO.File.OpenRead(file);
|
||||||
}
|
}
|
||||||
public static System.IO.FileStream OpenWrite(string file)
|
public static System.IO.FileStream OpenWrite(string file)
|
||||||
|
|||||||
@ -10,7 +10,7 @@ namespace DTLib.Filesystem
|
|||||||
// записывает текст в файл и закрывает файл
|
// записывает текст в файл и закрывает файл
|
||||||
public static void LogToFile(string logfile, string msg)
|
public static void LogToFile(string logfile, string msg)
|
||||||
{
|
{
|
||||||
lock (new object())
|
lock(new object())
|
||||||
{
|
{
|
||||||
File.AppendAllText(logfile, msg);
|
File.AppendAllText(logfile, msg);
|
||||||
}
|
}
|
||||||
@ -19,39 +19,41 @@ namespace DTLib.Filesystem
|
|||||||
// чтение параметров из конфига
|
// чтение параметров из конфига
|
||||||
public static string ReadFromConfig(string configfile, string key)
|
public static string ReadFromConfig(string configfile, string key)
|
||||||
{
|
{
|
||||||
lock (new object())
|
lock(new object())
|
||||||
{
|
{
|
||||||
key += ": ";
|
key+=": ";
|
||||||
using var reader = new System.IO.StreamReader(configfile);
|
using var reader = new System.IO.StreamReader(configfile);
|
||||||
while (!reader.EndOfStream)
|
while(!reader.EndOfStream)
|
||||||
{
|
{
|
||||||
string st = reader.ReadLine();
|
string st = reader.ReadLine();
|
||||||
if (st.StartsWith(key))
|
if(st.StartsWith(key))
|
||||||
{
|
{
|
||||||
string value = "";
|
string value = "";
|
||||||
for (int i = key.Length; i < st.Length; i++)
|
for(int i = key.Length; i<st.Length; i++)
|
||||||
{
|
{
|
||||||
if (st[i] == '#') return value;
|
if(st[i]=='#')
|
||||||
if (st[i] == '%')
|
return value;
|
||||||
|
if(st[i]=='%')
|
||||||
{
|
{
|
||||||
bool stop = false;
|
bool stop = false;
|
||||||
string placeholder = "";
|
string placeholder = "";
|
||||||
i++;
|
i++;
|
||||||
while (!stop)
|
while(!stop)
|
||||||
{
|
{
|
||||||
if (st[i] == '%')
|
if(st[i]=='%')
|
||||||
{
|
{
|
||||||
stop = true;
|
stop=true;
|
||||||
value += ReadFromConfig(configfile, placeholder);
|
value+=ReadFromConfig(configfile, placeholder);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
placeholder += st[i];
|
placeholder+=st[i];
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else value += st[i];
|
else
|
||||||
|
value+=st[i];
|
||||||
}
|
}
|
||||||
reader.Close();
|
reader.Close();
|
||||||
//if (value == "") throw new System.Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
|
//if (value == "") throw new System.Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
|
||||||
|
|||||||
14
Hasher.cs
14
Hasher.cs
@ -20,7 +20,7 @@ namespace DTLib
|
|||||||
// хеш из двух массивов
|
// хеш из двух массивов
|
||||||
public byte[] Hash(byte[] input, byte[] salt)
|
public byte[] Hash(byte[] input, byte[] salt)
|
||||||
{
|
{
|
||||||
List<byte> rez = new List<byte>();
|
var rez = new List<byte>();
|
||||||
rez.AddRange(input);
|
rez.AddRange(input);
|
||||||
rez.AddRange(salt);
|
rez.AddRange(salt);
|
||||||
return sha256.ComputeHash(rez.ToArray());
|
return sha256.ComputeHash(rez.ToArray());
|
||||||
@ -29,18 +29,18 @@ namespace DTLib
|
|||||||
// хеш двух массивов зацикленный
|
// хеш двух массивов зацикленный
|
||||||
public byte[] HashCycled(byte[] input, byte[] salt, ushort cycles)
|
public byte[] HashCycled(byte[] input, byte[] salt, ushort cycles)
|
||||||
{
|
{
|
||||||
for (uint i = 0; i < cycles; i++)
|
for(uint i = 0; i<cycles; i++)
|
||||||
{
|
{
|
||||||
input = Hash(input, salt);
|
input=Hash(input, salt);
|
||||||
}
|
}
|
||||||
return input;
|
return input;
|
||||||
}
|
}
|
||||||
// хеш зацикленный
|
// хеш зацикленный
|
||||||
public byte[] HashCycled(byte[] input, ushort cycles)
|
public byte[] HashCycled(byte[] input, ushort cycles)
|
||||||
{
|
{
|
||||||
for (uint i = 0; i < cycles; i++)
|
for(uint i = 0; i<cycles; i++)
|
||||||
{
|
{
|
||||||
input = Hash(input);
|
input=Hash(input);
|
||||||
}
|
}
|
||||||
return input;
|
return input;
|
||||||
}
|
}
|
||||||
@ -48,9 +48,9 @@ namespace DTLib
|
|||||||
// хеш файла
|
// хеш файла
|
||||||
public byte[] HashFile(string filename)
|
public byte[] HashFile(string filename)
|
||||||
{
|
{
|
||||||
using var fileStream = File.OpenRead(filename);
|
using System.IO.FileStream fileStream = File.OpenRead(filename);
|
||||||
//var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
|
//var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
|
||||||
var hash = xxh32.ComputeHash(fileStream);
|
byte[] hash = xxh32.ComputeHash(fileStream);
|
||||||
//var now = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
|
//var now = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
|
||||||
//PublicLog.Log($"xxh32 hash: {hash.HashToString()} time: {now - then}\n");
|
//PublicLog.Log($"xxh32 hash: {hash.HashToString()} time: {now - then}\n");
|
||||||
fileStream.Close();
|
fileStream.Close();
|
||||||
|
|||||||
134
Network/FSP.cs
134
Network/FSP.cs
@ -1,5 +1,6 @@
|
|||||||
using DTLib.Dtsod;
|
using DTLib.Dtsod;
|
||||||
using DTLib.Filesystem;
|
using DTLib.Filesystem;
|
||||||
|
using System;
|
||||||
using System.Net.Sockets;
|
using System.Net.Sockets;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using static DTLib.PublicLog;
|
using static DTLib.PublicLog;
|
||||||
@ -11,9 +12,9 @@ namespace DTLib.Network
|
|||||||
//
|
//
|
||||||
public class FSP
|
public class FSP
|
||||||
{
|
{
|
||||||
Socket mainSocket { get; init; }
|
Socket MainSocket { get; init; }
|
||||||
static public bool debug = false;
|
public static bool debug = false;
|
||||||
public FSP(Socket _mainSocket) => mainSocket = _mainSocket;
|
public FSP(Socket _mainSocket) => MainSocket=_mainSocket;
|
||||||
|
|
||||||
public uint BytesDownloaded = 0;
|
public uint BytesDownloaded = 0;
|
||||||
public uint BytesUploaded = 0;
|
public uint BytesUploaded = 0;
|
||||||
@ -27,9 +28,9 @@ namespace DTLib.Network
|
|||||||
Mutex.Execute(() =>
|
Mutex.Execute(() =>
|
||||||
{
|
{
|
||||||
Debug("b", $"requesting file download: {filePath_server}\n");
|
Debug("b", $"requesting file download: {filePath_server}\n");
|
||||||
mainSocket.SendPackage("requesting file download".ToBytes());
|
MainSocket.SendPackage("requesting file download".ToBytes());
|
||||||
mainSocket.SendPackage(filePath_server.ToBytes());
|
MainSocket.SendPackage(filePath_server.ToBytes());
|
||||||
}, out var exception);
|
}, out Exception exception);
|
||||||
exception?.Throw();
|
exception?.Throw();
|
||||||
DownloadFile(filePath_client);
|
DownloadFile(filePath_client);
|
||||||
}
|
}
|
||||||
@ -47,9 +48,9 @@ namespace DTLib.Network
|
|||||||
Mutex.Execute(() =>
|
Mutex.Execute(() =>
|
||||||
{
|
{
|
||||||
Debug("b", $"requesting file download: {filePath_server}\n");
|
Debug("b", $"requesting file download: {filePath_server}\n");
|
||||||
mainSocket.SendPackage("requesting file download".ToBytes());
|
MainSocket.SendPackage("requesting file download".ToBytes());
|
||||||
mainSocket.SendPackage(filePath_server.ToBytes());
|
MainSocket.SendPackage(filePath_server.ToBytes());
|
||||||
}, out var exception);
|
}, out System.Exception exception);
|
||||||
exception?.Throw();
|
exception?.Throw();
|
||||||
return DownloadFileToMemory();
|
return DownloadFileToMemory();
|
||||||
}
|
}
|
||||||
@ -68,72 +69,74 @@ namespace DTLib.Network
|
|||||||
{
|
{
|
||||||
Mutex.Execute(() =>
|
Mutex.Execute(() =>
|
||||||
{
|
{
|
||||||
BytesDownloaded = 0;
|
BytesDownloaded=0;
|
||||||
Filesize = SimpleConverter.ToString(mainSocket.GetPackage()).ToUInt();
|
Filesize=SimpleConverter.ToString(MainSocket.GetPackage()).ToUInt();
|
||||||
mainSocket.SendPackage("ready".ToBytes());
|
MainSocket.SendPackage("ready".ToBytes());
|
||||||
int packagesCount = 0;
|
int packagesCount = 0;
|
||||||
byte[] buffer = new byte[5120];
|
byte[] buffer = new byte[5120];
|
||||||
int fullPackagesCount = SimpleConverter.Truncate(Filesize / buffer.Length);
|
int fullPackagesCount = SimpleConverter.Truncate(Filesize/buffer.Length);
|
||||||
// получение полных пакетов файла
|
// получение полных пакетов файла
|
||||||
for (byte n = 0; packagesCount < fullPackagesCount; packagesCount++)
|
for(byte n = 0; packagesCount<fullPackagesCount; packagesCount++)
|
||||||
{
|
{
|
||||||
buffer = mainSocket.GetPackage();
|
buffer=MainSocket.GetPackage();
|
||||||
BytesDownloaded += (uint)buffer.Length;
|
BytesDownloaded+=(uint)buffer.Length;
|
||||||
fileStream.Write(buffer, 0, buffer.Length);
|
fileStream.Write(buffer, 0, buffer.Length);
|
||||||
if (requiresFlushing)
|
if(requiresFlushing)
|
||||||
{
|
{
|
||||||
if (n == 100)
|
if(n==100)
|
||||||
{
|
{
|
||||||
fileStream.Flush();
|
fileStream.Flush();
|
||||||
n = 0;
|
n=0;
|
||||||
}
|
}
|
||||||
else n++;
|
else
|
||||||
|
n++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// получение остатка
|
// получение остатка
|
||||||
if ((Filesize - fileStream.Position) > 0)
|
if((Filesize-fileStream.Position)>0)
|
||||||
{
|
{
|
||||||
mainSocket.SendPackage("remain request".ToBytes());
|
MainSocket.SendPackage("remain request".ToBytes());
|
||||||
buffer = mainSocket.GetPackage();
|
buffer=MainSocket.GetPackage();
|
||||||
BytesDownloaded += (uint)buffer.Length;
|
BytesDownloaded+=(uint)buffer.Length;
|
||||||
fileStream.Write(buffer, 0, buffer.Length);
|
fileStream.Write(buffer, 0, buffer.Length);
|
||||||
}
|
}
|
||||||
}, out var exception);
|
}, out System.Exception exception);
|
||||||
exception?.Throw();
|
exception?.Throw();
|
||||||
if (requiresFlushing) fileStream.Flush();
|
if(requiresFlushing)
|
||||||
|
fileStream.Flush();
|
||||||
}
|
}
|
||||||
|
|
||||||
// отдаёт файл с помощью FSP протокола
|
// отдаёт файл с помощью FSP протокола
|
||||||
public void UploadFile(string filePath)
|
public void UploadFile(string filePath)
|
||||||
{
|
{
|
||||||
BytesUploaded = 0;
|
BytesUploaded=0;
|
||||||
Debug("b", $"uploading file {filePath}\n");
|
Debug("b", $"uploading file {filePath}\n");
|
||||||
using var fileStream = File.OpenRead(filePath);
|
using System.IO.FileStream fileStream = File.OpenRead(filePath);
|
||||||
Filesize = File.GetSize(filePath).ToUInt();
|
Filesize=File.GetSize(filePath).ToUInt();
|
||||||
Mutex.Execute(() =>
|
Mutex.Execute(() =>
|
||||||
{
|
{
|
||||||
mainSocket.SendPackage(Filesize.ToString().ToBytes());
|
MainSocket.SendPackage(Filesize.ToString().ToBytes());
|
||||||
mainSocket.GetAnswer("ready");
|
MainSocket.GetAnswer("ready");
|
||||||
byte[] buffer = new byte[5120];
|
byte[] buffer = new byte[5120];
|
||||||
int packagesCount = 0;
|
int packagesCount = 0;
|
||||||
int fullPackagesCount = SimpleConverter.Truncate(Filesize / buffer.Length);
|
int fullPackagesCount = SimpleConverter.Truncate(Filesize/buffer.Length);
|
||||||
// отправка полных пакетов файла
|
// отправка полных пакетов файла
|
||||||
for (; packagesCount < fullPackagesCount; packagesCount++)
|
for(; packagesCount<fullPackagesCount; packagesCount++)
|
||||||
{
|
{
|
||||||
fileStream.Read(buffer, 0, buffer.Length);
|
fileStream.Read(buffer, 0, buffer.Length);
|
||||||
mainSocket.SendPackage(buffer);
|
MainSocket.SendPackage(buffer);
|
||||||
BytesUploaded += (uint)buffer.Length;
|
BytesUploaded+=(uint)buffer.Length;
|
||||||
}
|
}
|
||||||
// отправка остатка
|
// отправка остатка
|
||||||
if ((Filesize - fileStream.Position) > 0)
|
if((Filesize-fileStream.Position)>0)
|
||||||
{
|
{
|
||||||
mainSocket.GetAnswer("remain request");
|
MainSocket.GetAnswer("remain request");
|
||||||
buffer = new byte[(Filesize - fileStream.Position).ToInt()];
|
buffer=new byte[(Filesize-fileStream.Position).ToInt()];
|
||||||
fileStream.Read(buffer, 0, buffer.Length);
|
fileStream.Read(buffer, 0, buffer.Length);
|
||||||
mainSocket.SendPackage(buffer);
|
MainSocket.SendPackage(buffer);
|
||||||
BytesUploaded += (uint)buffer.Length;
|
BytesUploaded+=(uint)buffer.Length;
|
||||||
}
|
}
|
||||||
}, out var exception);
|
}, out System.Exception exception);
|
||||||
exception?.Throw();
|
exception?.Throw();
|
||||||
fileStream.Close();
|
fileStream.Close();
|
||||||
Debug(new string[] { "g", $" uploaded {BytesUploaded} of {Filesize} bytes\n" });
|
Debug(new string[] { "g", $" uploaded {BytesUploaded} of {Filesize} bytes\n" });
|
||||||
@ -141,34 +144,37 @@ namespace DTLib.Network
|
|||||||
|
|
||||||
public void DownloadByManifest(string dirOnServer, string dirOnClient, bool overwrite = false, bool delete_excess = false)
|
public void DownloadByManifest(string dirOnServer, string dirOnClient, bool overwrite = false, bool delete_excess = false)
|
||||||
{
|
{
|
||||||
if (!dirOnClient.EndsWith("\\")) dirOnClient += "\\";
|
if(!dirOnClient.EndsWith("\\"))
|
||||||
if (!dirOnServer.EndsWith("\\")) dirOnServer += "\\";
|
dirOnClient+="\\";
|
||||||
Debug("b", "downloading manifest <", "c", dirOnServer + "manifest.dtsod", "b", ">\n");
|
if(!dirOnServer.EndsWith("\\"))
|
||||||
var manifest = new DtsodV23(SimpleConverter.ToString(DownloadFileToMemory(dirOnServer + "manifest.dtsod")));
|
dirOnServer+="\\";
|
||||||
|
Debug("b", "downloading manifest <", "c", dirOnServer+"manifest.dtsod", "b", ">\n");
|
||||||
|
var manifest = new DtsodV23(SimpleConverter.ToString(DownloadFileToMemory(dirOnServer+"manifest.dtsod")));
|
||||||
Debug("g", $"found {manifest.Values.Count} files in manifest\n");
|
Debug("g", $"found {manifest.Values.Count} files in manifest\n");
|
||||||
var hasher = new Hasher();
|
var hasher = new Hasher();
|
||||||
foreach (string fileOnServer in manifest.Keys)
|
foreach(string fileOnServer in manifest.Keys)
|
||||||
{
|
{
|
||||||
string fileOnClient = dirOnClient + fileOnServer;
|
string fileOnClient = dirOnClient+fileOnServer;
|
||||||
Debug("b", "file <", "c", fileOnClient, "b", ">... ");
|
Debug("b", "file <", "c", fileOnClient, "b", ">... ");
|
||||||
if (!File.Exists(fileOnClient))
|
if(!File.Exists(fileOnClient))
|
||||||
{
|
{
|
||||||
DebugNoTime("y", "doesn't exist\n");
|
DebugNoTime("y", "doesn't exist\n");
|
||||||
DownloadFile(dirOnServer + fileOnServer, fileOnClient);
|
DownloadFile(dirOnServer+fileOnServer, fileOnClient);
|
||||||
}
|
}
|
||||||
else if (overwrite && hasher.HashFile(fileOnClient).HashToString() != manifest[fileOnServer])
|
else if(overwrite&&hasher.HashFile(fileOnClient).HashToString()!=manifest[fileOnServer])
|
||||||
{
|
{
|
||||||
DebugNoTime("y", "outdated\n");
|
DebugNoTime("y", "outdated\n");
|
||||||
DownloadFile(dirOnServer + fileOnServer, fileOnClient);
|
DownloadFile(dirOnServer+fileOnServer, fileOnClient);
|
||||||
}
|
}
|
||||||
else DebugNoTime("g", "without changes\n");
|
else
|
||||||
|
DebugNoTime("g", "without changes\n");
|
||||||
}
|
}
|
||||||
// удаление лишних файлов
|
// удаление лишних файлов
|
||||||
if (delete_excess)
|
if(delete_excess)
|
||||||
{
|
{
|
||||||
foreach (string file in Directory.GetAllFiles(dirOnClient))
|
foreach(string file in Directory.GetAllFiles(dirOnClient))
|
||||||
{
|
{
|
||||||
if (!manifest.ContainsKey(file.Remove(0, dirOnClient.Length)))
|
if(!manifest.ContainsKey(file.Remove(0, dirOnClient.Length)))
|
||||||
{
|
{
|
||||||
Debug("y", $"deleting excess file: {file}\n");
|
Debug("y", $"deleting excess file: {file}\n");
|
||||||
File.Delete(file);
|
File.Delete(file);
|
||||||
@ -179,31 +185,35 @@ namespace DTLib.Network
|
|||||||
|
|
||||||
public static void CreateManifest(string dir)
|
public static void CreateManifest(string dir)
|
||||||
{
|
{
|
||||||
if (!dir.EndsWith("\\")) dir += "\\";
|
if(!dir.EndsWith("\\"))
|
||||||
|
dir+="\\";
|
||||||
Log($"b", $"creating manifest of {dir}\n");
|
Log($"b", $"creating manifest of {dir}\n");
|
||||||
StringBuilder manifestBuilder = new();
|
StringBuilder manifestBuilder = new();
|
||||||
Hasher hasher = new();
|
Hasher hasher = new();
|
||||||
if (Directory.GetFiles(dir).Contains(dir + "manifest.dtsod")) File.Delete(dir + "manifest.dtsod");
|
if(Directory.GetFiles(dir).Contains(dir+"manifest.dtsod"))
|
||||||
foreach (string _file in Directory.GetAllFiles(dir))
|
File.Delete(dir+"manifest.dtsod");
|
||||||
|
foreach(string _file in Directory.GetAllFiles(dir))
|
||||||
{
|
{
|
||||||
string file = _file.Remove(0, dir.Length);
|
string file = _file.Remove(0, dir.Length);
|
||||||
manifestBuilder.Append(file);
|
manifestBuilder.Append(file);
|
||||||
manifestBuilder.Append(": \"");
|
manifestBuilder.Append(": \"");
|
||||||
byte[] hash = hasher.HashFile(dir + file);
|
byte[] hash = hasher.HashFile(dir+file);
|
||||||
manifestBuilder.Append(hash.HashToString());
|
manifestBuilder.Append(hash.HashToString());
|
||||||
manifestBuilder.Append("\";\n");
|
manifestBuilder.Append("\";\n");
|
||||||
}
|
}
|
||||||
Debug($"g", $" manifest of {dir} created\n");
|
Debug($"g", $" manifest of {dir} created\n");
|
||||||
File.WriteAllText(dir + "manifest.dtsod", manifestBuilder.ToString());
|
File.WriteAllText(dir+"manifest.dtsod", manifestBuilder.ToString());
|
||||||
}
|
}
|
||||||
|
|
||||||
static void Debug(params string[] msg)
|
static void Debug(params string[] msg)
|
||||||
{
|
{
|
||||||
if (debug) Log(msg);
|
if(debug)
|
||||||
|
Log(msg);
|
||||||
}
|
}
|
||||||
static void DebugNoTime(params string[] msg)
|
static void DebugNoTime(params string[] msg)
|
||||||
{
|
{
|
||||||
if (debug) LogNoTime(msg);
|
if(debug)
|
||||||
|
LogNoTime(msg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -16,17 +16,17 @@ namespace DTLib.Network
|
|||||||
// пингует айпи с помощью встроенной в винду проги, возвращает задержку
|
// пингует айпи с помощью встроенной в винду проги, возвращает задержку
|
||||||
public static string PingIP(string address)
|
public static string PingIP(string address)
|
||||||
{
|
{
|
||||||
Process proc = new Process();
|
var proc = new Process();
|
||||||
proc.StartInfo.FileName = "cmd.exe";
|
proc.StartInfo.FileName="cmd.exe";
|
||||||
proc.StartInfo.Arguments = "/c @echo off & chcp 65001 >nul & ping -n 5 " + address;
|
proc.StartInfo.Arguments="/c @echo off & chcp 65001 >nul & ping -n 5 "+address;
|
||||||
proc.StartInfo.CreateNoWindow = true;
|
proc.StartInfo.CreateNoWindow=true;
|
||||||
proc.StartInfo.UseShellExecute = false;
|
proc.StartInfo.UseShellExecute=false;
|
||||||
proc.StartInfo.RedirectStandardOutput = true;
|
proc.StartInfo.RedirectStandardOutput=true;
|
||||||
proc.Start();
|
proc.Start();
|
||||||
var outStream = proc.StandardOutput;
|
System.IO.StreamReader outStream = proc.StandardOutput;
|
||||||
var rezult = outStream.ReadToEnd();
|
string rezult = outStream.ReadToEnd();
|
||||||
rezult = rezult.Remove(0, rezult.LastIndexOf('=') + 2);
|
rezult=rezult.Remove(0, rezult.LastIndexOf('=')+2);
|
||||||
return rezult.Remove(rezult.Length - 4);
|
return rezult.Remove(rezult.Length-4);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -16,20 +16,21 @@ namespace DTLib.Network
|
|||||||
int packageSize = 0;
|
int packageSize = 0;
|
||||||
byte[] data = new byte[2];
|
byte[] data = new byte[2];
|
||||||
// цикл выполняется пока не пройдёт 2000 мс
|
// цикл выполняется пока не пройдёт 2000 мс
|
||||||
for (ushort s = 0; s < 400; s += 1)
|
for(ushort s = 0; s<400; s+=1)
|
||||||
{
|
{
|
||||||
if (packageSize == 0 && socket.Available >= 2)
|
if(packageSize==0&&socket.Available>=2)
|
||||||
{
|
{
|
||||||
socket.Receive(data, data.Length, 0);
|
socket.Receive(data, data.Length, 0);
|
||||||
packageSize = data.ToInt();
|
packageSize=data.ToInt();
|
||||||
}
|
}
|
||||||
if (packageSize != 0 && socket.Available >= packageSize)
|
if(packageSize!=0&&socket.Available>=packageSize)
|
||||||
{
|
{
|
||||||
data = new byte[packageSize];
|
data=new byte[packageSize];
|
||||||
socket.Receive(data, data.Length, 0);
|
socket.Receive(data, data.Length, 0);
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
else Thread.Sleep(5);
|
else
|
||||||
|
Thread.Sleep(5);
|
||||||
}
|
}
|
||||||
throw new Exception($"GetPackage() error: timeout. socket.Available={socket.Available}\n");
|
throw new Exception($"GetPackage() error: timeout. socket.Available={socket.Available}\n");
|
||||||
}
|
}
|
||||||
@ -37,11 +38,14 @@ namespace DTLib.Network
|
|||||||
// отправляет пакет
|
// отправляет пакет
|
||||||
public static void SendPackage(this Socket socket, byte[] data)
|
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>65536)
|
||||||
if (data.Length == 0) throw new Exception($"SendPackage() error: package has zero size");
|
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>();
|
var list = new List<byte>();
|
||||||
byte[] packageSize = data.Length.ToBytes();
|
byte[] packageSize = data.Length.ToBytes();
|
||||||
if (packageSize.Length == 1) list.Add(0);
|
if(packageSize.Length==1)
|
||||||
|
list.Add(0);
|
||||||
list.AddRange(packageSize);
|
list.AddRange(packageSize);
|
||||||
list.AddRange(data);
|
list.AddRange(data);
|
||||||
socket.Send(list.ToArray());
|
socket.Send(list.ToArray());
|
||||||
@ -51,8 +55,9 @@ namespace DTLib.Network
|
|||||||
// получает пакет и выбрасывает исключение, если пакет не соответствует образцу
|
// получает пакет и выбрасывает исключение, если пакет не соответствует образцу
|
||||||
public static void GetAnswer(this Socket socket, string answer)
|
public static void GetAnswer(this Socket socket, string answer)
|
||||||
{
|
{
|
||||||
var rec = SimpleConverter.ToString(socket.GetPackage());
|
string rec = SimpleConverter.ToString(socket.GetPackage());
|
||||||
if (rec != answer) throw new Exception($"GetAnswer() error: invalid answer: <{rec}>");
|
if(rec!=answer)
|
||||||
|
throw new Exception($"GetAnswer() error: invalid answer: <{rec}>");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static byte[] RequestPackage(this Socket socket, byte[] request)
|
public static byte[] RequestPackage(this Socket socket, byte[] request)
|
||||||
|
|||||||
@ -11,25 +11,21 @@ namespace DTLib.Reactive
|
|||||||
public ReactiveListener(IEnumerable<ReactiveStream<T>> streams) : base(streams) { }
|
public ReactiveListener(IEnumerable<ReactiveStream<T>> streams) : base(streams) { }
|
||||||
|
|
||||||
public Action<object, T> ElementAddedHandler;
|
public Action<object, T> ElementAddedHandler;
|
||||||
public void SetHandler(Action<object, T> handler) => ReactiveWorkerMutex.Execute(() => { ElementAddedHandler = handler; });
|
public void SetHandler(Action<object, T> handler) => ReactiveWorkerMutex.Execute(() => ElementAddedHandler=handler);
|
||||||
public async Task ElementAdded(object s, T e) => await Task.Run(() => ElementAddedHandler?.Invoke(s, e));
|
public async Task ElementAdded(object s, T e) => await Task.Run(() => ElementAddedHandler?.Invoke(s, e));
|
||||||
|
|
||||||
public override void Join(ReactiveStream<T> stream)
|
public override void Join(ReactiveStream<T> stream) =>
|
||||||
{
|
|
||||||
ReactiveWorkerMutex.Execute(() =>
|
ReactiveWorkerMutex.Execute(() =>
|
||||||
{
|
{
|
||||||
Streams.Add(stream);
|
Streams.Add(stream);
|
||||||
stream.ElementAdded += ElementAdded;
|
stream.ElementAdded+=ElementAdded;
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
public override void Leave(ReactiveStream<T> stream)
|
public override void Leave(ReactiveStream<T> stream) =>
|
||||||
{
|
|
||||||
ReactiveWorkerMutex.Execute(() =>
|
ReactiveWorkerMutex.Execute(() =>
|
||||||
{
|
{
|
||||||
Streams.Remove(stream);
|
Streams.Remove(stream);
|
||||||
stream.ElementAdded -= ElementAdded;
|
stream.ElementAdded-=ElementAdded;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -11,27 +11,18 @@ namespace DTLib.Reactive
|
|||||||
public ReactiveProvider(IEnumerable<ReactiveStream<T>> streams) : base(streams) { }
|
public ReactiveProvider(IEnumerable<ReactiveStream<T>> streams) : base(streams) { }
|
||||||
|
|
||||||
event Action<T> AnnounceEvent;
|
event Action<T> AnnounceEvent;
|
||||||
public void Announce(T e)
|
public void Announce(T e) => ReactiveWorkerMutex.Execute(() => AnnounceEvent.Invoke(e));
|
||||||
{
|
|
||||||
ReactiveWorkerMutex.Execute(() => AnnounceEvent.Invoke(e));
|
|
||||||
}
|
|
||||||
|
|
||||||
public override void Join(ReactiveStream<T> stream)
|
public override void Join(ReactiveStream<T> stream) => ReactiveWorkerMutex.Execute(() =>
|
||||||
{
|
|
||||||
ReactiveWorkerMutex.Execute(() =>
|
|
||||||
{
|
{
|
||||||
Streams.Add(stream);
|
Streams.Add(stream);
|
||||||
AnnounceEvent += stream.Add;
|
AnnounceEvent+=stream.Add;
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
public override void Leave(ReactiveStream<T> stream)
|
public override void Leave(ReactiveStream<T> stream) => ReactiveWorkerMutex.Execute(() =>
|
||||||
{
|
|
||||||
ReactiveWorkerMutex.Execute(() =>
|
|
||||||
{
|
{
|
||||||
Streams.Remove(stream);
|
Streams.Remove(stream);
|
||||||
AnnounceEvent -= stream.Add;
|
AnnounceEvent-=stream.Add;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
using System;
|
using System.Collections.Generic;
|
||||||
using System.Collections.Generic;
|
|
||||||
|
|
||||||
namespace DTLib.Reactive
|
namespace DTLib.Reactive
|
||||||
{
|
{
|
||||||
@ -8,7 +7,7 @@ namespace DTLib.Reactive
|
|||||||
List<T> Storage = new();
|
List<T> Storage = new();
|
||||||
public event EventHandlerAsync<T> ElementAdded;
|
public event EventHandlerAsync<T> ElementAdded;
|
||||||
SafeMutex StorageMutex = new();
|
SafeMutex StorageMutex = new();
|
||||||
public int Length { get { return StorageMutex.Execute(() => Storage.Count); } }
|
public int Length => StorageMutex.Execute(() => Storage.Count);
|
||||||
|
|
||||||
public ReactiveStream() { }
|
public ReactiveStream() { }
|
||||||
|
|
||||||
|
|||||||
@ -12,7 +12,7 @@ namespace DTLib.Reactive
|
|||||||
public ReactiveWorker(ReactiveStream<T> stream) => Join(stream);
|
public ReactiveWorker(ReactiveStream<T> stream) => Join(stream);
|
||||||
|
|
||||||
public ReactiveWorker(IEnumerable<ReactiveStream<T>> streams) =>
|
public ReactiveWorker(IEnumerable<ReactiveStream<T>> streams) =>
|
||||||
ReactiveWorkerMutex.Execute(() => { foreach (var stream in streams) Join(stream); });
|
ReactiveWorkerMutex.Execute(() => { foreach(ReactiveStream<T> stream in streams) Join(stream); });
|
||||||
|
|
||||||
public abstract void Join(ReactiveStream<T> stream);
|
public abstract void Join(ReactiveStream<T> stream);
|
||||||
public abstract void Leave(ReactiveStream<T> stream);
|
public abstract void Leave(ReactiveStream<T> stream);
|
||||||
|
|||||||
15
SafeMutex.cs
15
SafeMutex.cs
@ -13,13 +13,14 @@ namespace DTLib
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
exception = null;
|
exception=null;
|
||||||
Execute(action);
|
Execute(action);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch(Exception ex)
|
||||||
{
|
{
|
||||||
exception = ex;
|
exception=ex;
|
||||||
if (!isReleased) Mutex.ReleaseMutex();
|
if(!isReleased)
|
||||||
|
Mutex.ReleaseMutex();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -28,14 +29,14 @@ namespace DTLib
|
|||||||
Mutex.WaitOne();
|
Mutex.WaitOne();
|
||||||
action();
|
action();
|
||||||
Mutex.ReleaseMutex();
|
Mutex.ReleaseMutex();
|
||||||
isReleased = true;
|
isReleased=true;
|
||||||
}
|
}
|
||||||
public T Execute<T>(Func<T> action)
|
public T Execute<T>(Func<T> action)
|
||||||
{
|
{
|
||||||
Mutex.WaitOne();
|
Mutex.WaitOne();
|
||||||
var rezult = action();
|
T rezult = action();
|
||||||
Mutex.ReleaseMutex();
|
Mutex.ReleaseMutex();
|
||||||
isReleased = true;
|
isReleased=true;
|
||||||
return rezult;
|
return rezult;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -13,18 +13,20 @@ namespace DTLib
|
|||||||
// эти методы работают как надо, в отличии от стандартных, которые иногда дуркуют
|
// эти методы работают как надо, в отличии от стандартных, которые иногда дуркуют
|
||||||
public static bool StartsWith(this byte[] source, byte[] startsWith)
|
public static bool StartsWith(this byte[] source, byte[] startsWith)
|
||||||
{
|
{
|
||||||
for (int i = 0; i < startsWith.Length; i++)
|
for(int i = 0; i<startsWith.Length; i++)
|
||||||
{
|
{
|
||||||
if (source[i] != startsWith[i]) return false;
|
if(source[i]!=startsWith[i])
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool EndsWith(this byte[] source, byte[] endsWith)
|
public static bool EndsWith(this byte[] source, byte[] endsWith)
|
||||||
{
|
{
|
||||||
for (int i = 0; i < endsWith.Length; i++)
|
for(int i = 0; i<endsWith.Length; i++)
|
||||||
{
|
{
|
||||||
if (source[source.Length - endsWith.Length + i] != endsWith[i]) return false;
|
if(source[source.Length-endsWith.Length+i]!=endsWith[i])
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -44,17 +46,18 @@ namespace DTLib
|
|||||||
// удаление нескольких элементов массива
|
// удаление нескольких элементов массива
|
||||||
public static T[] RemoveRange<T>(this T[] input, int startIndex, int count)
|
public static T[] RemoveRange<T>(this T[] input, int startIndex, int count)
|
||||||
{
|
{
|
||||||
List<T> list = input.ToList();
|
var list = input.ToList();
|
||||||
list.RemoveRange(startIndex, count);
|
list.RemoveRange(startIndex, count);
|
||||||
return list.ToArray();
|
return list.ToArray();
|
||||||
}
|
}
|
||||||
public static T[] RemoveRange<T>(this T[] input, int startIndex) => input.RemoveRange(startIndex, input.Length - startIndex);
|
public static T[] RemoveRange<T>(this T[] input, int startIndex) => input.RemoveRange(startIndex, input.Length-startIndex);
|
||||||
|
|
||||||
// метод как у листов
|
// метод как у листов
|
||||||
public static bool Contains<T>(this T[] array, T value)
|
public static bool Contains<T>(this T[] array, T value)
|
||||||
{
|
{
|
||||||
for (int i = 0; i < array.Length; i++)
|
for(int i = 0; i<array.Length; i++)
|
||||||
if (array[i].Equals(value)) return true;
|
if(array[i].Equals(value))
|
||||||
|
return true;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -73,17 +76,18 @@ namespace DTLib
|
|||||||
public static int ToInt(this byte[] bytes)
|
public static int ToInt(this byte[] bytes)
|
||||||
{
|
{
|
||||||
int output = 0;
|
int output = 0;
|
||||||
for (ushort i = 0; i < bytes.Length; i++) output = output * 256 + bytes[i];
|
for(ushort i = 0; i<bytes.Length; i++)
|
||||||
|
output=output*256+bytes[i];
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static byte[] ToBytes(this int num)
|
public static byte[] ToBytes(this int num)
|
||||||
{
|
{
|
||||||
List<byte> output = new();
|
List<byte> output = new();
|
||||||
while (num != 0)
|
while(num!=0)
|
||||||
{
|
{
|
||||||
output.Add(ToByte(num % 256));
|
output.Add(ToByte(num%256));
|
||||||
num = Truncate(num / 256);
|
num=Truncate(num/256);
|
||||||
}
|
}
|
||||||
output.Reverse();
|
output.Reverse();
|
||||||
return output.ToArray();
|
return output.ToArray();
|
||||||
@ -98,7 +102,7 @@ namespace DTLib
|
|||||||
public static string HashToString(this byte[] hash)
|
public static string HashToString(this byte[] hash)
|
||||||
{
|
{
|
||||||
var builder = new StringBuilder();
|
var builder = new StringBuilder();
|
||||||
for (int i = 0; i < hash.Length; i++)
|
for(int i = 0; i<hash.Length; i++)
|
||||||
{
|
{
|
||||||
builder.Append(hash[i].ToString("x2"));
|
builder.Append(hash[i].ToString("x2"));
|
||||||
}
|
}
|
||||||
@ -108,25 +112,25 @@ namespace DTLib
|
|||||||
public static string MergeToString(params object[] parts)
|
public static string MergeToString(params object[] parts)
|
||||||
{
|
{
|
||||||
StringBuilder builder = new();
|
StringBuilder builder = new();
|
||||||
for (int i = 0; i < parts.Length; i++)
|
for(int i = 0; i<parts.Length; i++)
|
||||||
builder.Append(parts[i].ToString());
|
builder.Append(parts[i].ToString());
|
||||||
return builder.ToString();
|
return builder.ToString();
|
||||||
}
|
}
|
||||||
public static string MergeToString<T>(this IEnumerable<T> collection, string separator)
|
public static string MergeToString<T>(this IEnumerable<T> collection, string separator)
|
||||||
{
|
{
|
||||||
StringBuilder builder = new();
|
StringBuilder builder = new();
|
||||||
foreach (T elem in collection)
|
foreach(T elem in collection)
|
||||||
{
|
{
|
||||||
builder.Append(elem.ToString());
|
builder.Append(elem.ToString());
|
||||||
builder.Append(separator);
|
builder.Append(separator);
|
||||||
}
|
}
|
||||||
builder.Remove(builder.Length - separator.Length, separator.Length);
|
builder.Remove(builder.Length-separator.Length, separator.Length);
|
||||||
return builder.ToString();
|
return builder.ToString();
|
||||||
}
|
}
|
||||||
public static string MergeToString<T>(this IEnumerable<T> collection)
|
public static string MergeToString<T>(this IEnumerable<T> collection)
|
||||||
{
|
{
|
||||||
StringBuilder builder = new();
|
StringBuilder builder = new();
|
||||||
foreach (T elem in collection)
|
foreach(T elem in collection)
|
||||||
builder.Append(elem.ToString());
|
builder.Append(elem.ToString());
|
||||||
return builder.ToString();
|
return builder.ToString();
|
||||||
}
|
}
|
||||||
@ -134,7 +138,7 @@ namespace DTLib
|
|||||||
public static string Multiply(this string input, int howMany)
|
public static string Multiply(this string input, int howMany)
|
||||||
{
|
{
|
||||||
StringBuilder b = new();
|
StringBuilder b = new();
|
||||||
for (int i = 0; i < howMany; i++)
|
for(int i = 0; i<howMany; i++)
|
||||||
b.Append(input);
|
b.Append(input);
|
||||||
return b.ToString();
|
return b.ToString();
|
||||||
}
|
}
|
||||||
|
|||||||
8
TImer.cs
8
TImer.cs
@ -14,14 +14,14 @@ namespace DTLib
|
|||||||
// таймер сразу запускается
|
// таймер сразу запускается
|
||||||
public Timer(bool repeat, int delay, Action method)
|
public Timer(bool repeat, int delay, Action method)
|
||||||
{
|
{
|
||||||
Repeat = repeat;
|
Repeat=repeat;
|
||||||
TimerThread = new Thread(() =>
|
TimerThread=new Thread(() =>
|
||||||
{
|
{
|
||||||
do
|
do
|
||||||
{
|
{
|
||||||
Thread.Sleep(delay);
|
Thread.Sleep(delay);
|
||||||
method();
|
method();
|
||||||
} while (Repeat);
|
} while(Repeat);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -30,7 +30,7 @@ namespace DTLib
|
|||||||
// завершение потока
|
// завершение потока
|
||||||
public void Stop()
|
public void Stop()
|
||||||
{
|
{
|
||||||
Repeat = false;
|
Repeat=false;
|
||||||
TimerThread.Abort();
|
TimerThread.Abort();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
112
XXHash.cs
112
XXHash.cs
@ -28,39 +28,39 @@ namespace DTLib
|
|||||||
|
|
||||||
static XXHash32()
|
static XXHash32()
|
||||||
{
|
{
|
||||||
if (BitConverter.IsLittleEndian)
|
if(BitConverter.IsLittleEndian)
|
||||||
{
|
{
|
||||||
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
|
FuncGetLittleEndianUInt32=new Func<byte[], int, uint>((x, i) =>
|
||||||
{
|
{
|
||||||
unsafe
|
unsafe
|
||||||
{
|
{
|
||||||
fixed (byte* array = x)
|
fixed(byte* array = x)
|
||||||
{
|
{
|
||||||
return *(uint*)(array + i);
|
return *(uint*)(array+i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => (i & 0x000000FFU) << 24 | (i & 0x0000FF00U) << 8 | (i & 0x00FF0000U) >> 8 | (i & 0xFF000000U) >> 24);
|
FuncGetFinalHashUInt32=new Func<uint, uint>(i => (i&0x000000FFU)<<24|(i&0x0000FF00U)<<8|(i&0x00FF0000U)>>8|(i&0xFF000000U)>>24);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
|
FuncGetLittleEndianUInt32=new Func<byte[], int, uint>((x, i) =>
|
||||||
{
|
{
|
||||||
unsafe
|
unsafe
|
||||||
{
|
{
|
||||||
fixed (byte* array = x)
|
fixed(byte* array = x)
|
||||||
{
|
{
|
||||||
return (uint)(array[i++] | (array[i++] << 8) | (array[i++] << 16) | (array[i] << 24));
|
return (uint)(array[i++]|(array[i++]<<8)|(array[i++]<<16)|(array[i]<<24));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => i);
|
FuncGetFinalHashUInt32=new Func<uint, uint>(i => i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Creates an instance of <see cref="XXHash32"/> class by default seed(0).
|
// Creates an instance of <see cref="XXHash32"/> class by default seed(0).
|
||||||
// <returns></returns>
|
// <returns></returns>
|
||||||
public static new XXHash32 Create() => new XXHash32();
|
public static new XXHash32 Create() => new();
|
||||||
|
|
||||||
// Initializes a new instance of the <see cref="XXHash32"/> class by default seed(0).
|
// Initializes a new instance of the <see cref="XXHash32"/> class by default seed(0).
|
||||||
public XXHash32() => Initialize(0);
|
public XXHash32() => Initialize(0);
|
||||||
@ -71,7 +71,7 @@ namespace DTLib
|
|||||||
|
|
||||||
// Gets the <see cref="uint"/> value of the computed hash code.
|
// Gets the <see cref="uint"/> value of the computed hash code.
|
||||||
// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
||||||
public uint HashUInt32 => State == 0 ? _Hash32 : throw new InvalidOperationException("Hash computation has not yet completed.");
|
public uint HashUInt32 => State==0 ? _Hash32 : throw new InvalidOperationException("Hash computation has not yet completed.");
|
||||||
|
|
||||||
// Gets or sets the value of seed used by xxHash32 algorithm.
|
// Gets or sets the value of seed used by xxHash32 algorithm.
|
||||||
// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
||||||
@ -80,10 +80,11 @@ namespace DTLib
|
|||||||
get => _Seed32;
|
get => _Seed32;
|
||||||
set
|
set
|
||||||
{
|
{
|
||||||
if (value != _Seed32)
|
if(value!=_Seed32)
|
||||||
{
|
{
|
||||||
if (State != 0) throw new InvalidOperationException("Hash computation has not yet completed.");
|
if(State!=0)
|
||||||
_Seed32 = value;
|
throw new InvalidOperationException("Hash computation has not yet completed.");
|
||||||
|
_Seed32=value;
|
||||||
Initialize();
|
Initialize();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -92,10 +93,10 @@ namespace DTLib
|
|||||||
// Initializes this instance for new hash computing.
|
// Initializes this instance for new hash computing.
|
||||||
public override void Initialize()
|
public override void Initialize()
|
||||||
{
|
{
|
||||||
_ACC32_1 = _Seed32 + PRIME32_1 + PRIME32_2;
|
_ACC32_1=_Seed32+PRIME32_1+PRIME32_2;
|
||||||
_ACC32_2 = _Seed32 + PRIME32_2;
|
_ACC32_2=_Seed32+PRIME32_2;
|
||||||
_ACC32_3 = _Seed32 + 0;
|
_ACC32_3=_Seed32+0;
|
||||||
_ACC32_4 = _Seed32 - PRIME32_1;
|
_ACC32_4=_Seed32-PRIME32_1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Routes data written to the object into the hash algorithm for computing the hash.
|
// Routes data written to the object into the hash algorithm for computing the hash.
|
||||||
@ -104,29 +105,30 @@ namespace DTLib
|
|||||||
// <param name="cbSize">The number of bytes in the byte array to use as 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)
|
protected override void HashCore(byte[] array, int ibStart, int cbSize)
|
||||||
{
|
{
|
||||||
if (State != 1) State = 1;
|
if(State!=1)
|
||||||
var size = cbSize - ibStart;
|
State=1;
|
||||||
_RemainingLength = size & 15;
|
int size = cbSize-ibStart;
|
||||||
if (cbSize >= 16)
|
_RemainingLength=size&15;
|
||||||
|
if(cbSize>=16)
|
||||||
{
|
{
|
||||||
var limit = size - _RemainingLength;
|
int limit = size-_RemainingLength;
|
||||||
do
|
do
|
||||||
{
|
{
|
||||||
_ACC32_1 = Round32(_ACC32_1, FuncGetLittleEndianUInt32(array, ibStart));
|
_ACC32_1=Round32(_ACC32_1, FuncGetLittleEndianUInt32(array, ibStart));
|
||||||
ibStart += 4;
|
ibStart+=4;
|
||||||
_ACC32_2 = Round32(_ACC32_2, FuncGetLittleEndianUInt32(array, ibStart));
|
_ACC32_2=Round32(_ACC32_2, FuncGetLittleEndianUInt32(array, ibStart));
|
||||||
ibStart += 4;
|
ibStart+=4;
|
||||||
_ACC32_3 = Round32(_ACC32_3, FuncGetLittleEndianUInt32(array, ibStart));
|
_ACC32_3=Round32(_ACC32_3, FuncGetLittleEndianUInt32(array, ibStart));
|
||||||
ibStart += 4;
|
ibStart+=4;
|
||||||
_ACC32_4 = Round32(_ACC32_4, FuncGetLittleEndianUInt32(array, ibStart));
|
_ACC32_4=Round32(_ACC32_4, FuncGetLittleEndianUInt32(array, ibStart));
|
||||||
ibStart += 4;
|
ibStart+=4;
|
||||||
} while (ibStart < limit);
|
} while(ibStart<limit);
|
||||||
}
|
}
|
||||||
_TotalLength += cbSize;
|
_TotalLength+=cbSize;
|
||||||
if (_RemainingLength != 0)
|
if(_RemainingLength!=0)
|
||||||
{
|
{
|
||||||
_CurrentArray = array;
|
_CurrentArray=array;
|
||||||
_CurrentIndex = ibStart;
|
_CurrentIndex=ibStart;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -134,46 +136,46 @@ namespace DTLib
|
|||||||
// <returns>The computed hash code.</returns>
|
// <returns>The computed hash code.</returns>
|
||||||
protected override byte[] HashFinal()
|
protected override byte[] HashFinal()
|
||||||
{
|
{
|
||||||
if (_TotalLength >= 16)
|
if(_TotalLength>=16)
|
||||||
{
|
{
|
||||||
_Hash32 = RotateLeft32(_ACC32_1, 1) + RotateLeft32(_ACC32_2, 7) + RotateLeft32(_ACC32_3, 12) + RotateLeft32(_ACC32_4, 18);
|
_Hash32=RotateLeft32(_ACC32_1, 1)+RotateLeft32(_ACC32_2, 7)+RotateLeft32(_ACC32_3, 12)+RotateLeft32(_ACC32_4, 18);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
_Hash32 = _Seed32 + PRIME32_5;
|
_Hash32=_Seed32+PRIME32_5;
|
||||||
}
|
}
|
||||||
_Hash32 += (uint)_TotalLength;
|
_Hash32+=(uint)_TotalLength;
|
||||||
while (_RemainingLength >= 4)
|
while(_RemainingLength>=4)
|
||||||
{
|
{
|
||||||
_Hash32 = RotateLeft32(_Hash32 + FuncGetLittleEndianUInt32(_CurrentArray, _CurrentIndex) * PRIME32_3, 17) * PRIME32_4;
|
_Hash32=RotateLeft32(_Hash32+FuncGetLittleEndianUInt32(_CurrentArray, _CurrentIndex)*PRIME32_3, 17)*PRIME32_4;
|
||||||
_CurrentIndex += 4;
|
_CurrentIndex+=4;
|
||||||
_RemainingLength -= 4;
|
_RemainingLength-=4;
|
||||||
}
|
}
|
||||||
unsafe
|
unsafe
|
||||||
{
|
{
|
||||||
fixed (byte* arrayPtr = _CurrentArray)
|
fixed(byte* arrayPtr = _CurrentArray)
|
||||||
{
|
{
|
||||||
while (_RemainingLength-- >= 1)
|
while(_RemainingLength-->=1)
|
||||||
{
|
{
|
||||||
_Hash32 = RotateLeft32(_Hash32 + arrayPtr[_CurrentIndex++] * PRIME32_5, 11) * PRIME32_1;
|
_Hash32=RotateLeft32(_Hash32+arrayPtr[_CurrentIndex++]*PRIME32_5, 11)*PRIME32_1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_Hash32 = (_Hash32 ^ (_Hash32 >> 15)) * PRIME32_2;
|
_Hash32=(_Hash32^(_Hash32>>15))*PRIME32_2;
|
||||||
_Hash32 = (_Hash32 ^ (_Hash32 >> 13)) * PRIME32_3;
|
_Hash32=(_Hash32^(_Hash32>>13))*PRIME32_3;
|
||||||
_Hash32 ^= _Hash32 >> 16;
|
_Hash32^=_Hash32>>16;
|
||||||
_TotalLength = State = 0;
|
_TotalLength=State=0;
|
||||||
return BitConverter.GetBytes(FuncGetFinalHashUInt32(_Hash32));
|
return BitConverter.GetBytes(FuncGetFinalHashUInt32(_Hash32));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static uint Round32(uint input, uint value) => RotateLeft32(input + (value * PRIME32_2), 13) * PRIME32_1;
|
private static uint Round32(uint input, uint value) => RotateLeft32(input+(value*PRIME32_2), 13)*PRIME32_1;
|
||||||
|
|
||||||
private static uint RotateLeft32(uint value, int count) => (value << count) | (value >> (32 - count));
|
private static uint RotateLeft32(uint value, int count) => (value<<count)|(value>>(32-count));
|
||||||
|
|
||||||
private void Initialize(uint seed)
|
private void Initialize(uint seed)
|
||||||
{
|
{
|
||||||
HashSizeValue = 32;
|
HashSizeValue=32;
|
||||||
_Seed32 = seed;
|
_Seed32=seed;
|
||||||
Initialize();
|
Initialize();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user