fix(SyncDictionary): Clear after Callback (#3789)

This commit is contained in:
MrGadget 2024-03-21 23:02:54 -04:00
parent 05d68f91af
commit 877067af76
2 changed files with 16 additions and 2 deletions

View File

@ -195,12 +195,14 @@ public override void OnDeserializeDelta(NetworkReader reader)
case Operation.OP_CLEAR: case Operation.OP_CLEAR:
if (apply) if (apply)
{ {
objects.Clear();
// add dirty + changes. // add dirty + changes.
// ClientToServer needs to set dirty in server OnDeserialize. // ClientToServer needs to set dirty in server OnDeserialize.
// no access check: server OnDeserialize can always // no access check: server OnDeserialize can always
// write, even for ClientToServer (for broadcasting). // write, even for ClientToServer (for broadcasting).
AddOperation(Operation.OP_CLEAR, default, default, false); AddOperation(Operation.OP_CLEAR, default, default, false);
// clear after invoking the callback so users can iterate the dictionary
// and take appropriate action on the items before they are wiped.
objects.Clear();
} }
break; break;
@ -231,8 +233,10 @@ public override void OnDeserializeDelta(NetworkReader reader)
public void Clear() public void Clear()
{ {
objects.Clear();
AddOperation(Operation.OP_CLEAR, default, default, true); AddOperation(Operation.OP_CLEAR, default, default, true);
// clear after invoking the callback so users can iterate the dictionary
// and take appropriate action on the items before they are wiped.
objects.Clear();
} }
public bool ContainsKey(TKey key) => objects.ContainsKey(key); public bool ContainsKey(TKey key) => objects.ContainsKey(key);

View File

@ -89,9 +89,19 @@ public void TestAdd()
[Test] [Test]
public void TestClear() public void TestClear()
{ {
// Verifies that the clear method works and that the data is still present for the Callback.
bool called = false;
clientSyncDictionary.Callback = (op, index, item) =>
{
called = true;
Assert.That(op, Is.EqualTo(SyncDictionary<int, string>.Operation.OP_CLEAR));
Assert.That(clientSyncDictionary.Count, Is.EqualTo(3));
};
serverSyncDictionary.Clear(); serverSyncDictionary.Clear();
SerializeDeltaTo(serverSyncDictionary, clientSyncDictionary); SerializeDeltaTo(serverSyncDictionary, clientSyncDictionary);
Assert.That(serverSyncDictionary, Is.EquivalentTo(new SyncDictionary<int, string>())); Assert.That(serverSyncDictionary, Is.EquivalentTo(new SyncDictionary<int, string>()));
Assert.That(called, Is.True);
} }
[Test] [Test]