-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMemoryStreamExtensions.cs
More file actions
40 lines (34 loc) · 1.12 KB
/
Copy pathMemoryStreamExtensions.cs
File metadata and controls
40 lines (34 loc) · 1.12 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
using System.IO;
using System.Text;
namespace SboxCllGui;
public static class MemoryStreamExtensions
{
public static void WriteInt32(this MemoryStream ms, int value)
{
var data = BitConverter.GetBytes(value);
ms.Write(data, 0, data.Length);
}
public static void WriteLengthPrependedAsciiString(this MemoryStream ms, string? value)
{
if (value == null) value = "";
var bytes = Encoding.ASCII.GetBytes(value);
ms.WriteInt32(bytes.Length);
ms.Write(bytes, 0, bytes.Length);
}
public static int? ReadInt32(this MemoryStream ms)
{
if (ms.Position + 4 > ms.Length) return null;
var buf = new byte[4];
ms.ReadExactly(buf, 0, 4);
return BitConverter.ToInt32(buf, 0);
}
public static string? ReadLengthPrependedAsciiString(this MemoryStream ms)
{
var len = ms.ReadInt32();
if (len == null || len < 0) return null;
if (ms.Position + len > ms.Length) return null;
var buf = new byte[len.Value];
ms.ReadExactly(buf, 0, len.Value);
return Encoding.ASCII.GetString(buf);
}
}