-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathByteReader.cs
More file actions
126 lines (98 loc) · 3.07 KB
/
ByteReader.cs
File metadata and controls
126 lines (98 loc) · 3.07 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KSSHServer
{
public class ByteReader : IDisposable
{
private readonly char[] _ListSeparator = new char[] {','};
private MemoryStream _Stream;
public bool IsEOF
{
get
{
if(disposedValue)
throw new ObjectDisposedException("ByteReader");
return _Stream.Position == _Stream.Length;
}
private set {}
}
public ByteReader(byte[] data)
{
_Stream = new MemoryStream(data);
}
public byte[] GetBytes(int length)
{
if(disposedValue)
throw new ObjectDisposedException("ByteReader");
byte[] data = new byte[length];
_Stream.Read(data, 0, length);
return data;
}
public byte[] GetMPInt()
{
UInt32 size = GetUInt32();
if(size == 0)
return new byte[1];
byte[] data = GetBytes((int) size);
if (data[0] == 0)
return data.Skip(1).ToArray();
return data;
}
public UInt32 GetUInt32()
{
byte[] data = GetBytes(4); // 4 bytes = UInt32
if(BitConverter.IsLittleEndian)
data = data.Reverse().ToArray();
return BitConverter.ToUInt32(data, 0);
}
public string GetString()
{
return GetString(Encoding.ASCII);
}
public string GetString(Encoding encoding)
{
int length = (int)GetUInt32();
if (length == 0)
return string.Empty;
return encoding.GetString(GetBytes(length));
}
public List<string> GetNameList()
{
return new List<string>(GetString().Split(_ListSeparator, StringSplitOptions.RemoveEmptyEntries));
}
public bool GetBoolean()
{
return (GetByte() != 0);
}
public byte GetByte()
{
if(disposedValue)
throw new ObjectDisposedException("ByteReader");
return (byte)_Stream.ReadByte();
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_Stream.Dispose();
_Stream = null;
}
disposedValue = true;
}
}
void IDisposable.Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
}
#endregion
}
}