-
Notifications
You must be signed in to change notification settings - Fork 3
/
JobInfo.cs
105 lines (87 loc) · 3.26 KB
/
JobInfo.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/* FIXME: This require a refactor to not use byte arrays and not considering
any transmission over the network as this has been unneeded for a while now */
namespace RoboBot
{
public class JobInfo
{
public class BadJobException<T> : Exception
{
public override string Message { get; }
public T Property { get; }
public BadJobException(string message, T property) : base(message)
{
Message = message;
Property = property;
}
}
public const int AddonNameSize = 40;
public const int MaxAddons = 5;
public bool HasAddons { get; }
public byte AddonsCount { get; } // ignored if (!hasAddons)
public byte[][] AddonsFileNames { get; } // ignored if (!hasAddons)
public static JobInfo NoAddons = new JobInfo();
public static JobInfo CreateFromStrings(byte addonsCount, List<string> addonsFileNames)
{
byte[][] addonsNamesConverted = new byte[addonsCount][];
for (int i = 0; i < addonsCount; i++)
{
addonsNamesConverted[i] = Encoding.ASCII.GetBytes(addonsFileNames[i]);
}
return new JobInfo(addonsCount, addonsNamesConverted);
}
public JobInfo(byte addonsCount, byte[][] addonsFileNames)
{
HasAddons = true;
AddonsCount = addonsCount != 0 ? addonsCount : throw new BadJobException<byte>("AddonsCount can't be 0 if it contains addons", addonsCount);
if (addonsFileNames.Any(addon => addon.Length > AddonNameSize))
throw new BadJobException<byte[][]>("An addon file name can't be greater than 40 bytes", addonsFileNames);
AddonsFileNames = addonsFileNames;
}
public JobInfo()
{
HasAddons = false;
}
public byte[] ToBytes()
{
byte[] bytes = new byte[202];
if (HasAddons)
{
bytes[0] = 1;
bytes[1] = AddonsCount;
int curByte = 2;
byte[] blankBytes = new byte[40];
for (int i = 0; i < MaxAddons; i++)
{
if (i >= AddonsFileNames.Length)
blankBytes.CopyTo(bytes, curByte);
else
AddonsFileNames[i].CopyTo(bytes, curByte);
curByte += AddonNameSize;
}
return bytes;
}
bytes[0] = 0;
return bytes;
}
public static JobInfo FromBytes(ref byte[] bytes)
{
if (bytes[0] == 1)
{
byte addonsCount = bytes[1];
byte[][] addonFileNames = new byte[addonsCount][];
int curByte = 2;
for (int i = 0; i < addonsCount; i++)
{
addonFileNames[i] = bytes.Skip(curByte).Take(AddonNameSize).ToArray();
curByte += AddonNameSize;
}
return new JobInfo(addonsCount, addonFileNames);
}
return new JobInfo();
}
}
}