-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtils.cs
75 lines (65 loc) · 2.1 KB
/
Utils.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace P3TableExporter
{
public static class Utils
{
// Annoyingly, there's no easy way to read a null-terminated ASCII string in .NET
// (or maybe I'm just a moron), so we have to do it manually.
public static string ReadNullTerminatedString(BinaryReader reader, Encoding encoding)
{
using BinaryReader stringReader = new BinaryReader(reader.BaseStream, encoding, true);
StringBuilder sb = new StringBuilder();
while (stringReader.BaseStream.Position < stringReader.BaseStream.Length)
{
char c = stringReader.ReadChar();
if (c == 0)
break;
sb.Append(c);
}
return sb.ToString();
}
public static void ReadPadding(BinaryReader reader, int padTo)
{
int padLength = padTo - (int)(reader.BaseStream.Position % padTo);
if (padLength != padTo)
{
reader.BaseStream.Seek(padLength, SeekOrigin.Current);
}
}
public static void WritePadding(BinaryWriter writer, int padTo, byte padValue = 0)
{
int padLength = padTo - (int)(writer.BaseStream.Position % padTo);
if (padLength != padTo)
{
Span<byte> padding = new byte[padLength];
padding.Fill(padValue);
writer.Write(padding);
}
}
public static int PowerOfTwo(int x)
{
if (x < 0) return 0;
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
}
public static int NearestMultipleOf(int x, int multipleOf)
{
return x + (x % multipleOf);
}
public static byte[] SwapEndian(byte[] bytes)
{
Array.Reverse(bytes);
return bytes;
}
}
}