forked from TheLazzoro/W3G-NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryReaderExtension.cs
More file actions
82 lines (73 loc) · 2.31 KB
/
BinaryReaderExtension.cs
File metadata and controls
82 lines (73 loc) · 2.31 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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace W3GNET.Extensions
{
internal static class BinaryReaderExtension
{
internal static void SkipBytes(this BinaryReader reader, uint count)
{
var stream = reader.BaseStream;
if (stream.CanSeek)
{
stream.Seek(Math.Min(count, stream.Length - stream.Position), SeekOrigin.Current);
}
else
{
for (int i = 0; i < count; i++)
{
if (stream.Length <= stream.Position)
{
return;
}
_ = reader.ReadByte();
}
}
}
/// <summary>
/// Copies the content of the current stream, returns a new stream, and resets the reader's position.
/// </summary>
internal static Stream SliceFromCurrentOffset(this BinaryReader reader, int length)
{
long position = reader.BaseStream.Position;
var output = reader.ReadBytes(length);
reader.BaseStream.Position = position;
return new MemoryStream(output);
}
internal static string ReadZeroTermString(this BinaryReader reader, StringEncoding encoding)
{
List<byte> bytes = new List<byte>();
byte b;
while (true && reader.BaseStream.Position < reader.BaseStream.Length)
{
b = reader.ReadByte();
if (b == 0)
break;
bytes.Add(b);
}
var str = string.Empty;
if (encoding == StringEncoding.UTF8)
{
str = Encoding.Default.GetString(bytes.ToArray());
}
else if (encoding == StringEncoding.HEX)
{
str = BitConverter.ToString(bytes.ToArray()).Replace("-", "");
}
else if (encoding == StringEncoding.ASCII)
{
str = System.Text.Encoding.ASCII.GetString(bytes.ToArray()).Trim();
}
return str;
}
}
internal enum StringEncoding
{
UTF8,
HEX,
ASCII,
}
}