Skip to content

Commit 5433b53

Browse files
committed
add SyncedConfig2 and SyncedEntryFieldAttribute
1 parent 3165cca commit 5433b53

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

CSync/Lib/SyncedConfig2.cs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
using System;
2+
using System.Linq;
3+
using System.Reflection;
4+
using System.Threading;
5+
using CSync.Extensions;
6+
using HarmonyLib;
7+
using JetBrains.Annotations;
8+
9+
namespace CSync.Lib;
10+
11+
/// <summary>
12+
/// Wrapper class allowing the config class (type parameter) to be synchronized.<br></br>
13+
/// Stores the mod's unique identifier and handles registering and sending of named messages.
14+
/// </summary>
15+
[PublicAPI]
16+
public class SyncedConfig2<T> : ISyncedConfig where T : SyncedConfig2<T>
17+
{
18+
public ISyncedEntryContainer EntryContainer { get; } = new SyncedEntryContainer();
19+
private int _entryContainerPopulated = 0;
20+
21+
public SyncedConfig2(string guid)
22+
{
23+
GUID = guid;
24+
}
25+
26+
/// <summary>
27+
/// The mod name or abbreviation. After being given to the constructor, it cannot be changed.
28+
/// </summary>
29+
public string GUID { get; }
30+
31+
private static Lazy<FieldInfo[]> SyncedEntryFields = new(
32+
() => AccessTools.GetDeclaredFields(typeof(T))
33+
.Where(field => field.GetCustomAttribute<SyncedEntryFieldAttribute>() is not null)
34+
.Where(field => typeof(SyncedEntryBase).IsAssignableFrom(field.FieldType))
35+
.ToArray()
36+
);
37+
38+
internal void PopulateEntryContainer()
39+
{
40+
if (Interlocked.Exchange(ref _entryContainerPopulated, 1) != 0) return;
41+
foreach (var fieldInfo in SyncedEntryFields.Value)
42+
{
43+
var entryBase = (SyncedEntryBase)fieldInfo.GetValue(this);
44+
EntryContainer.Add(entryBase.BoxedEntry.ToSyncedEntryIdentifier(), entryBase);
45+
}
46+
}
47+
48+
public event EventHandler? InitialSyncCompleted;
49+
internal void OnInitialSyncCompleted(object sender, EventArgs e) => InitialSyncCompleted?.Invoke(sender, e);
50+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
using System;
2+
3+
namespace CSync.Lib;
4+
5+
[AttributeUsage(AttributeTargets.Field)]
6+
public class SyncedEntryFieldAttribute : Attribute;

0 commit comments

Comments
 (0)