forked from RevenantX/LiteEntitySystem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSyncString.cs
More file actions
72 lines (63 loc) · 2.22 KB
/
SyncString.cs
File metadata and controls
72 lines (63 loc) · 2.22 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
using System;
using System.Runtime.CompilerServices;
using System.Text;
using LiteEntitySystem.Internal;
namespace LiteEntitySystem.Extensions
{
public class SyncString : SyncableField
{
private static readonly UTF8Encoding Encoding = new UTF8Encoding(false, true);
private byte[] _stringData;
private string _string;
private int _size;
private RemoteCallSpan<byte> _setStringClientCall;
public string Value
{
get => _string;
set
{
if (_string == value)
return;
_string = value;
Utils.ResizeOrCreate(ref _stringData, Encoding.GetMaxByteCount(_string.Length));
_size = Encoding.GetBytes(_string, 0, _string.Length, _stringData, 0);
ExecuteRPC(_setStringClientCall, _stringData);
}
}
public override void RegisterRPC(in SyncableRPCRegistrator r)
{
r.CreateClientAction(this, SetNewString, ref _setStringClientCall);
}
public override string ToString()
{
return _string;
}
public static implicit operator string(SyncString s)
{
return s.Value;
}
private void SetNewString(ReadOnlySpan<byte> data)
{
_string = Encoding.GetString(data);
}
public override unsafe void FullSyncRead(ReadOnlySpan<byte> dataSpan, ref int position)
{
fixed (byte* data = dataSpan)
{
int length = *(ushort*)(data + position);
Utils.ResizeOrCreate(ref _stringData, length);
_string = Encoding.GetString(data + position + sizeof(ushort), length);
position += sizeof(ushort) + length;
}
}
public override unsafe void FullSyncWrite(Span<byte> dataSpan, ref int position)
{
fixed (byte* data = dataSpan, stringData = _stringData)
{
*(ushort*)(data + position) = (ushort)_size;
Unsafe.CopyBlock(data + position + sizeof(ushort), stringData, (uint)_size);
}
position += sizeof(ushort) + _size;
}
}
}