-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExtensionMethods.cs
59 lines (53 loc) · 1.72 KB
/
ExtensionMethods.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
using System.Net.Sockets;
using System.Text;
using ScreenLogicConnect.Messages;
namespace ScreenLogicConnect;
static class ExtensionMethods
{
public static void SendHLMessage(this NetworkStream stream, HLMessage msg)
{
var arr = msg.AsByteArray();
System.Diagnostics.Debug.WriteLine($" sent {arr.Length}");
stream.Write(arr);
}
public static void WritePrefixLength(this BinaryWriter bw, string val)
{
bw.Write(val.Length);
bw.Write(Encoding.ASCII.GetBytes(val));
var boundaryBufferLen = HLMessageTypeHelper.AlignToNext4Boundary(val.Length);
for (int i = 0; i < boundaryBufferLen; i++)
{
bw.Write((byte)0);
}
}
public static void WritePrefixLength(this BinaryWriter bw, ReadOnlySpan<byte> val)
{
bw.Write(val.Length);
bw.Write(val);
}
public static void Write(this BinaryWriter bw, HLTime hlTime)
{
bw.Write(hlTime.year);
bw.Write(hlTime.month);
bw.Write(hlTime.dayOfWeek);
bw.Write(hlTime.day);
bw.Write(hlTime.hour);
bw.Write(hlTime.minute);
bw.Write(hlTime.second);
bw.Write(hlTime.millisecond);
}
public static async Task<TResult?> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout) where TResult : notnull
{
using var timeoutCancellationTokenSource = new CancellationTokenSource();
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
return await task;
}
else
{
return default;
}
}
}