-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathSerializationHelper.cs
More file actions
394 lines (362 loc) · 13 KB
/
SerializationHelper.cs
File metadata and controls
394 lines (362 loc) · 13 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace EosSharp.Core.Helpers
{
public class SerializationHelper
{
/// <summary>
/// Is a big Number negative
/// </summary>
/// <param name="bin">big number in byte array</param>
/// <returns></returns>
public static bool IsNegative(byte[] bin)
{
return (bin[bin.Length - 1] & 0x80) != 0;
}
/// <summary>
/// Negate a big number
/// </summary>
/// <param name="bin">big number in byte array</param>
public static void Negate(byte[] bin)
{
int carry = 1;
for (int i = 0; i < bin.Length; ++i)
{
int x = (~bin[i] & 0xff) + carry;
bin[i] = (byte)x;
carry = x >> 8;
}
}
/// <summary>
/// Convert an unsigned decimal number as string to a big number
/// </summary>
/// <param name="size">Size in bytes of the big number</param>
/// <param name="s">decimal encoded as string</param>
/// <returns></returns>
public static byte[] DecimalToBinary(uint size, string s)
{
byte[] result = new byte[size];
for (int i = 0; i < s.Length; ++i)
{
char srcDigit = s[i];
if (srcDigit < '0' || srcDigit > '9')
throw new Exception("invalid number");
int carry = srcDigit - '0';
for (int j = 0; j < size; ++j)
{
int x = result[j] * 10 + carry;
result[j] = (byte)x;
carry = x >> 8;
}
if (carry != 0)
throw new Exception("number is out of range");
}
return result;
}
/// <summary>
/// Convert an signed decimal number as string to a big number
/// </summary>
/// <param name="size">Size in bytes of the big number</param>
/// <param name="s">decimal encoded as string</param>
/// <returns></returns>
public static byte[] SignedDecimalToBinary(uint size, string s)
{
bool negative = s[0] == '-';
if (negative)
s = s.Substring(0, 1);
byte[] result = DecimalToBinary(size, s);
if (negative)
Negate(result);
return result;
}
/// <summary>
/// Convert big number to an unsigned decimal number
/// </summary>
/// <param name="bin">big number as byte array</param>
/// <param name="minDigits">0-pad result to this many digits</param>
/// <returns></returns>
public static string BinaryToDecimal(byte[] bin, int minDigits = 1)
{
var result = new List<char>(minDigits);
for (int i = 0; i < minDigits; i++)
{
result.Add('0');
}
for (int i = bin.Length - 1; i >= 0; --i)
{
int carry = bin[i];
for (int j = 0; j < result.Count; ++j)
{
int x = ((result[j] - '0') << 8) + carry;
result[j] = (char)('0' + (x % 10));
carry = (x / 10) | 0;
}
while (carry != 0)
{
result.Add((char)('0' + carry % 10));
carry = (carry / 10) | 0;
}
}
result.Reverse();
return string.Join("", result);
}
/// <summary>
/// Convert big number to an signed decimal number
/// </summary>
/// <param name="bin">big number as byte array</param>
/// <param name="minDigits">0-pad result to this many digits</param>
/// <returns></returns>
public static string SignedBinaryToDecimal(byte[] bin, int minDigits = 1)
{
if (IsNegative(bin))
{
Negate(bin);
return '-' + BinaryToDecimal(bin, minDigits);
}
return BinaryToDecimal(bin, minDigits);
}
/// <summary>
/// Convert base64 with fc prefix to byte array
/// </summary>
/// <param name="s">string to convert</param>
/// <returns></returns>
public static byte[] Base64FcStringToByteArray(string s)
{
//fc adds extra '='
if((s.Length & 3) == 1 && s[s.Length - 1] == '=')
{
return Convert.FromBase64String(s.Substring(0, s.Length - 1));
}
return Convert.FromBase64String(s);
}
/// <summary>
/// Convert ascii char to symbol value
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static byte CharToSymbol(char c)
{
if (c >= 'a' && c <= 'z')
return (byte)(c - 'a' + 6);
if (c >= '1' && c <= '5')
return (byte)(c - '1' + 1);
return 0;
}
/// <summary>
/// Convert snake case string to pascal case
/// </summary>
/// <param name="s">string to convert</param>
/// <returns></returns>
public static string SnakeCaseToPascalCase(string s)
{
var result = s.ToLower().Replace("_", " ");
TextInfo info = CultureInfo.CurrentCulture.TextInfo;
result = info.ToTitleCase(result).Replace(" ", string.Empty);
return result;
}
/// <summary>
/// Convert pascal case string to snake case
/// </summary>
/// <param name="s">string to convert</param>
/// <returns></returns>
public static string PascalCaseToSnakeCase(string s)
{
if (string.IsNullOrEmpty(s))
{
return s;
}
var builder = new StringBuilder();
bool first = true;
foreach(var c in s)
{
if(char.IsUpper(c))
{
if (!first)
builder.Append('_');
builder.Append(char.ToLower(c));
}
else
{
builder.Append(c);
}
if (first)
first = false;
}
return builder.ToString();
}
/// <summary>
/// Serialize object to byte array
/// </summary>
/// <param name="obj">object to serialize</param>
/// <returns></returns>
public static byte[] ObjectToByteArray(object obj)
{
if (obj == null)
return null;
return Encoding.UTF8.GetBytes(JsonSerializer.Serialize(obj, GetJsonSerializerOptions()));
}
private static JsonSerializerOptions GetJsonSerializerOptions()
{
return new JsonSerializerOptions()
{
PropertyNamingPolicy = null,
WriteIndented = true,
AllowTrailingCommas = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
}
/// <summary>
/// Encode byte array to hexadecimal string
/// </summary>
/// <param name="ba">byte array to convert</param>
/// <returns></returns>
public static string ByteArrayToHexString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
/// <summary>
/// Decode hexadecimal string to byte array
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
public static byte[] HexStringToByteArray(string hex)
{
var l = hex.Length / 2;
var result = new byte[l];
for (var i = 0; i < l; ++i)
result[i] = (byte)Convert.ToInt32(hex.Substring(i * 2, 2), 16);
return result;
}
/// <summary>
/// Serialize object to hexadecimal encoded string
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ObjectToHexString(object obj)
{
return ByteArrayToHexString(ObjectToByteArray(obj));
}
/// <summary>
/// Combina multiple arrays into one
/// </summary>
/// <param name="arrays"></param>
/// <returns></returns>
public static byte[] Combine(IEnumerable<byte[]> arrays)
{
byte[] ret = new byte[arrays.Sum(x => x != null ? x.Length : 0)];
int offset = 0;
foreach (byte[] data in arrays)
{
if (data == null) continue;
Buffer.BlockCopy(data, 0, ret, offset, data.Length);
offset += data.Length;
}
return ret;
}
/// <summary>
/// Convert DateTime to `time_point` (miliseconds since epoch)
/// </summary>
/// <param name="value">date to convert</param>
/// <returns></returns>
public static UInt64 DateToTimePoint(DateTime value)
{
var span = (value - new DateTime(1970, 1, 1));
return (UInt64)(span.Ticks / TimeSpan.TicksPerMillisecond);
}
/// <summary>
/// Convert `time_point` (miliseconds since epoch) to DateTime
/// </summary>
/// <param name="ticks">time_point ticks to convert</param>
/// <returns></returns>
public static DateTime TimePointToDate(long ticks)
{
return new DateTime(ticks + new DateTime(1970, 1, 1).Ticks);
}
/// <summary>
/// Convert DateTime to `time_point_sec` (seconds since epoch)
/// </summary>
/// <param name="value">date to convert</param>
/// <returns></returns>
public static UInt32 DateToTimePointSec(DateTime value)
{
var span = (value - new DateTime(1970, 1, 1));
return (UInt32)((span.Ticks / TimeSpan.TicksPerSecond) & 0xffffffff);
}
/// <summary>
/// Convert `time_point_sec` (seconds since epoch) to DateTime
/// </summary>
/// <param name="secs">time_point_sec to convert</param>
/// <returns></returns>
public static DateTime TimePointSecToDate(UInt32 secs)
{
return new DateTime(secs * TimeSpan.TicksPerSecond + new DateTime(1970, 1, 1).Ticks);
}
/// <summary>
/// Convert DateTime to `block_timestamp_type` (half-seconds since a different epoch)
/// </summary>
/// <param name="value">date to convert</param>
/// <returns></returns>
public static UInt32 DateToBlockTimestamp(DateTime value)
{
var span = (value - new DateTime(1970, 1, 1));
return (UInt32)((UInt64)Math.Round((double)(span.Ticks / TimeSpan.TicksPerMillisecond - 946684800000) / 500) & 0xffffffff);
}
/// <summary>
/// Convert `block_timestamp_type` (half-seconds since a different epoch) to DateTime
/// </summary>
/// <param name="slot">block_timestamp slot to convert</param>
/// <returns></returns>
public static DateTime BlockTimestampToDate(UInt32 slot)
{
return new DateTime(slot * TimeSpan.TicksPerMillisecond * 500 + 946684800000 + new DateTime(1970, 1, 1).Ticks);
}
/// <summary>
/// Convert Name into unsigned long
/// </summary>
/// <param name="name"></param>
/// <returns>Converted value</returns>
public static UInt64 ConvertNameToLong(string name)
{
return BitConverter.ToUInt64(ConvertNameToBytes(name), 0);
}
/// <summary>
/// Convert Name into bytes
/// </summary>
/// <param name="name"></param>
/// <returns>Converted value bytes</returns>
public static byte[] ConvertNameToBytes(string name)
{
var a = new byte[8];
Int32 bit = 63;
for (int i = 0; i < name.Length; ++i)
{
var c = SerializationHelper.CharToSymbol(name[i]);
if (bit < 5)
c = (byte)(c << 1);
for (int j = 4; j >= 0; --j)
{
if (bit >= 0)
{
a[(int)Math.Floor((decimal)(bit / 8))] |= (byte)(((c >> j) & 1) << (bit % 8));
--bit;
}
}
}
return a;
}
public static string ReverseHex(string h)
{
return h.Substring(6, 2) + h.Substring(4, 2) + h.Substring(2, 2) + h.Substring(0, 2);
}
}
}