| | | 1 | | //======================================================================= |
| | | 2 | | // MemoryPackRecordSerializer.cs |
| | | 3 | | //======================================================================= |
| | | 4 | | // MIT License, Copyright (c) 2024-present David Oravsky (mrdav30) |
| | | 5 | | // See LICENSE file in the project root for full license information. |
| | | 6 | | //======================================================================= |
| | | 7 | | |
| | | 8 | | #if !CHRONICLER_DISABLE_MEMORYPACK |
| | | 9 | | |
| | | 10 | | using System; |
| | | 11 | | using System.Collections.Generic; |
| | | 12 | | using System.Diagnostics.CodeAnalysis; |
| | | 13 | | using MemoryPack; |
| | | 14 | | |
| | | 15 | | namespace Chronicler.Serialization; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Saves recorded state as MemoryPack bytes and restores it into host-created objects. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <remarks>Each call made without a session context creates one with an empty link registry.</remarks> |
| | | 21 | | public static class MemoryPackRecordSerializer |
| | | 22 | | { |
| | 1 | 23 | | private static readonly byte[] EmptyRecordBytes = MemoryPackSerializer.Serialize(new MemoryPackRecordEnvelope()); |
| | | 24 | | |
| | | 25 | | /// <inheritdoc cref="Serialize(IRecordable, ChronicleContext)"/> |
| | | 26 | | public static byte[] Serialize(IRecordable target) |
| | 7 | 27 | | => Serialize(target, context: null); |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Saves the state declared by a recordable instance. |
| | | 31 | | /// </summary> |
| | | 32 | | /// <param name="target">The source whose schema runs in <see cref="SerializationMode.Saving"/> mode.</param> |
| | | 33 | | /// <param name="context">The session that supplies stable link IDs. Null creates a fresh context.</param> |
| | | 34 | | /// <returns>The recorded payload in a new byte array owned by the caller.</returns> |
| | | 35 | | /// <exception cref="ArgumentNullException"><paramref name="target"/> is null.</exception> |
| | | 36 | | /// <exception cref="InvalidOperationException">A non-null recorded link has no stable ID.</exception> |
| | | 37 | | public static byte[] Serialize(IRecordable target, ChronicleContext? context) |
| | | 38 | | { |
| | 78 | 39 | | if (target == null) |
| | 1 | 40 | | throw new ArgumentNullException(nameof(target)); |
| | | 41 | | |
| | 77 | 42 | | context ??= new ChronicleContext(); |
| | | 43 | | |
| | 77 | 44 | | var chronicler = new MemoryPackRecordWriter(context); |
| | 77 | 45 | | target.RecordData(chronicler); |
| | 75 | 46 | | return chronicler.ToArray(); |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | /// <inheritdoc cref="Populate(IRecordable, byte[], ChronicleContext)"/> |
| | | 50 | | public static void Populate(IRecordable target, byte[] data) |
| | 8 | 51 | | => Populate(target, data, context: null); |
| | | 52 | | |
| | | 53 | | /// <inheritdoc cref="Populate(IRecordable, ReadOnlySpan{byte}, ChronicleContext)" |
| | | 54 | | /// path="/*[not(self::exception[@cref='T:System.ArgumentNullException'])]"/> |
| | | 55 | | /// <exception cref="ArgumentNullException"><paramref name="target"/> or <paramref name="data"/> is null.</exception |
| | | 56 | | public static void Populate(IRecordable target, byte[] data, ChronicleContext? context) |
| | | 57 | | { |
| | 91 | 58 | | if (data == null) |
| | 1 | 59 | | throw new ArgumentNullException(nameof(data)); |
| | | 60 | | |
| | 90 | 61 | | Populate(target, data.AsSpan(), context); |
| | 50 | 62 | | } |
| | | 63 | | |
| | | 64 | | /// <inheritdoc cref="Populate(IRecordable, ReadOnlySpan{byte}, ChronicleContext)"/> |
| | | 65 | | public static void Populate(IRecordable target, ReadOnlySpan<byte> data) |
| | 2 | 66 | | => Populate(target, data, context: null); |
| | | 67 | | |
| | | 68 | | /// <summary> |
| | | 69 | | /// Applies a MemoryPack record to an existing instance. |
| | | 70 | | /// </summary> |
| | | 71 | | /// <param name="target">The object to mutate. Initialize owned class instances needed by present deep records.</par |
| | | 72 | | /// <param name="data">The nonempty payload to read. The serializer leaves the caller's buffer intact and retains no |
| | | 73 | | /// <param name="context">The destination session for link resolution. Null creates a fresh context.</param> |
| | | 74 | | /// <remarks> |
| | | 75 | | /// Runs the target schema, then calls <see cref="ChronicleContext.ResolveDeferredLinks"/>. |
| | | 76 | | /// A failure can leave earlier assignments applied. A supplied context retains pending callbacks. |
| | | 77 | | /// </remarks> |
| | | 78 | | /// <exception cref="ArgumentNullException"><paramref name="target"/> is null.</exception> |
| | | 79 | | /// <exception cref="ArgumentException"><paramref name="data"/> is empty.</exception> |
| | | 80 | | /// <exception cref="MemoryPackSerializationException">The MemoryPack decoder rejects the payload or a recorded valu |
| | | 81 | | /// <exception cref="InvalidOperationException">A present deep class lacks an initialized target, or link resolution |
| | | 82 | | public static void Populate(IRecordable target, ReadOnlySpan<byte> data, ChronicleContext? context) |
| | | 83 | | { |
| | 92 | 84 | | if (target == null) |
| | 1 | 85 | | throw new ArgumentNullException(nameof(target)); |
| | 91 | 86 | | if (data.IsEmpty) |
| | 1 | 87 | | throw new ArgumentException("Serialized bytes must not be empty.", nameof(data)); |
| | | 88 | | |
| | 90 | 89 | | context ??= new ChronicleContext(); |
| | | 90 | | |
| | 90 | 91 | | var chronicler = new MemoryPackRecordReader(data, context); |
| | 90 | 92 | | target.RecordData(chronicler); |
| | 53 | 93 | | context.ResolveDeferredLinks(); |
| | 51 | 94 | | } |
| | | 95 | | |
| | | 96 | | private sealed class MemoryPackRecordWriter : IChronicler |
| | | 97 | | { |
| | 188 | 98 | | private readonly OrderedStringMap<byte[]?> _entries = new(8, StringComparer.Ordinal); |
| | | 99 | | |
| | 188 | 100 | | public MemoryPackRecordWriter(ChronicleContext context) |
| | | 101 | | { |
| | 188 | 102 | | Context = context; |
| | 188 | 103 | | } |
| | | 104 | | |
| | | 105 | | public ChronicleContext Context { get; } |
| | | 106 | | |
| | 21 | 107 | | public SerializationMode Mode => SerializationMode.Saving; |
| | | 108 | | |
| | | 109 | | public void LookValue<T>(ref T value, string name, T? defaultValue = default) |
| | | 110 | | { |
| | 354 | 111 | | if (value is null || EqualityComparer<T>.Default.Equals(value, defaultValue!)) |
| | 105 | 112 | | return; |
| | | 113 | | |
| | 249 | 114 | | _entries[name] = MemoryPackSerializer.Serialize(value); |
| | 249 | 115 | | } |
| | | 116 | | |
| | | 117 | | public void LookDeep<T>(ref T value, string name) where T : class, IRecordable |
| | | 118 | | { |
| | 12 | 119 | | if (value == null) |
| | | 120 | | { |
| | 1 | 121 | | _entries[name] = null; |
| | 1 | 122 | | return; |
| | | 123 | | } |
| | | 124 | | |
| | 11 | 125 | | var nested = new MemoryPackRecordWriter(Context); |
| | 11 | 126 | | value.RecordData(nested); |
| | 11 | 127 | | _entries[name] = nested.ToArray(); |
| | 11 | 128 | | } |
| | | 129 | | |
| | | 130 | | public void LookDeepStruct<T>(ref T value, string name) where T : struct, IRecordable |
| | | 131 | | { |
| | 95 | 132 | | var nested = new MemoryPackRecordWriter(Context); |
| | 95 | 133 | | value.RecordData(nested); |
| | 95 | 134 | | _entries[name] = nested.ToArray(); |
| | 95 | 135 | | } |
| | | 136 | | |
| | | 137 | | public void LookNullableDeep<T>(ref T? value, string name) where T : struct, IRecordable |
| | | 138 | | { |
| | 7 | 139 | | if (!value.HasValue) |
| | 2 | 140 | | return; |
| | | 141 | | |
| | 5 | 142 | | T nestedValue = value.Value; |
| | 5 | 143 | | var nested = new MemoryPackRecordWriter(Context); |
| | 5 | 144 | | nestedValue.RecordData(nested); |
| | 5 | 145 | | _entries[name] = nested.ToArray(); |
| | 5 | 146 | | } |
| | | 147 | | |
| | | 148 | | public void LookLink<T>( |
| | | 149 | | ref T value, |
| | | 150 | | string name, |
| | | 151 | | string? slot = null, |
| | | 152 | | RecordLinkResolveMode resolveMode = RecordLinkResolveMode.Immediate, |
| | | 153 | | Action<T>? assignLoadedValue = null) |
| | | 154 | | { |
| | 15 | 155 | | string? id = null; |
| | 15 | 156 | | if (value is not null |
| | 15 | 157 | | && !Context.Links.TryGetReferenceId(value, out id, slot)) |
| | | 158 | | { |
| | 2 | 159 | | throw new InvalidOperationException( |
| | 2 | 160 | | $"Unable to save link '{name}' of type {typeof(T).Name} because no stable id could be produced{Forma |
| | | 161 | | } |
| | | 162 | | |
| | 13 | 163 | | _entries[name] = MemoryPackSerializer.Serialize(id); |
| | 13 | 164 | | } |
| | | 165 | | |
| | | 166 | | public byte[] ToArray() |
| | | 167 | | { |
| | 186 | 168 | | return MemoryPackSerializer.Serialize(MemoryPackRecordEnvelope.FromEntries(_entries)); |
| | | 169 | | } |
| | | 170 | | } |
| | | 171 | | |
| | | 172 | | private sealed class MemoryPackRecordReader : IChronicler |
| | | 173 | | { |
| | | 174 | | private readonly OrderedStringMap<byte[]?> _entries; |
| | | 175 | | |
| | 216 | 176 | | public MemoryPackRecordReader(ReadOnlySpan<byte> data, ChronicleContext context) |
| | | 177 | | { |
| | 216 | 178 | | MemoryPackRecordEnvelope? envelope = MemoryPackRecordEnvelope.Deserialize(data); |
| | 216 | 179 | | _entries = envelope == null |
| | 216 | 180 | | ? new OrderedStringMap<byte[]?>(8, StringComparer.Ordinal) |
| | 216 | 181 | | : envelope.ToEntryMap(); |
| | 216 | 182 | | Context = context; |
| | 216 | 183 | | } |
| | | 184 | | |
| | | 185 | | public ChronicleContext Context { get; } |
| | | 186 | | |
| | 28 | 187 | | public SerializationMode Mode => SerializationMode.Loading; |
| | | 188 | | |
| | | 189 | | public void LookValue<T>(ref T value, string name, T? defaultValue = default) |
| | | 190 | | { |
| | 371 | 191 | | if (!_entries.TryGetValue(name, out byte[]? entry) |
| | 371 | 192 | | || entry == null) |
| | | 193 | | { |
| | 153 | 194 | | value = defaultValue!; |
| | 153 | 195 | | return; |
| | | 196 | | } |
| | | 197 | | |
| | 218 | 198 | | T? loadedValue = MemoryPackSerializer.Deserialize<T>(entry); |
| | 218 | 199 | | if (loadedValue is null) |
| | | 200 | | { |
| | 1 | 201 | | value = defaultValue!; |
| | 1 | 202 | | return; |
| | | 203 | | } |
| | | 204 | | |
| | 217 | 205 | | value = loadedValue; |
| | 217 | 206 | | } |
| | | 207 | | |
| | | 208 | | public void LookDeep<T>(ref T value, string name) where T : class, IRecordable |
| | | 209 | | { |
| | 11 | 210 | | if (!_entries.TryGetValue(name, out byte[]? entry) |
| | 11 | 211 | | || entry == null) |
| | 2 | 212 | | return; |
| | | 213 | | |
| | 9 | 214 | | if (value == null) |
| | 1 | 215 | | throw new InvalidOperationException( |
| | 1 | 216 | | $"Unable to load '{name}' because {typeof(T).Name} must already be instantiated for a deep chronicle |
| | | 217 | | |
| | 8 | 218 | | var nested = new MemoryPackRecordReader(entry, Context); |
| | 8 | 219 | | value.RecordData(nested); |
| | 8 | 220 | | } |
| | | 221 | | |
| | | 222 | | public void LookDeepStruct<T>(ref T value, string name) where T : struct, IRecordable |
| | | 223 | | { |
| | 109 | 224 | | if (!_entries.TryGetValue(name, out byte[]? entry) |
| | 109 | 225 | | || entry == null) |
| | | 226 | | { |
| | 11 | 227 | | value = CreateDefaultDeepStruct<T>(); |
| | 10 | 228 | | return; |
| | | 229 | | } |
| | | 230 | | |
| | 98 | 231 | | value = new(); |
| | 98 | 232 | | var nested = new MemoryPackRecordReader(entry, Context); |
| | 98 | 233 | | value.RecordData(nested); |
| | 92 | 234 | | } |
| | | 235 | | |
| | | 236 | | public void LookNullableDeep<T>(ref T? value, string name) where T : struct, IRecordable |
| | | 237 | | { |
| | 13 | 238 | | if (!_entries.TryGetValue(name, out byte[]? entry) |
| | 13 | 239 | | || entry == null) |
| | | 240 | | { |
| | 4 | 241 | | value = null; |
| | 4 | 242 | | return; |
| | | 243 | | } |
| | | 244 | | |
| | 9 | 245 | | T nestedValue = new(); |
| | 9 | 246 | | var nested = new MemoryPackRecordReader(entry, Context); |
| | 9 | 247 | | nestedValue.RecordData(nested); |
| | 3 | 248 | | value = nestedValue; |
| | 3 | 249 | | } |
| | | 250 | | |
| | | 251 | | public void LookLink<T>( |
| | | 252 | | ref T value, |
| | | 253 | | string name, |
| | | 254 | | string? slot = null, |
| | | 255 | | RecordLinkResolveMode resolveMode = RecordLinkResolveMode.Immediate, |
| | | 256 | | Action<T>? assignLoadedValue = null) |
| | | 257 | | { |
| | 15 | 258 | | if (!TryReadLinkId(name, out string? id)) |
| | | 259 | | { |
| | 6 | 260 | | value = default!; |
| | 6 | 261 | | assignLoadedValue?.Invoke(value); |
| | 6 | 262 | | return; |
| | | 263 | | } |
| | | 264 | | |
| | 9 | 265 | | if (resolveMode == RecordLinkResolveMode.Deferred) |
| | | 266 | | { |
| | 5 | 267 | | LoadDeferredLink(ref value, name, id, slot, assignLoadedValue); |
| | 4 | 268 | | return; |
| | | 269 | | } |
| | | 270 | | |
| | 4 | 271 | | LoadImmediateLink(ref value, name, id, slot, assignLoadedValue); |
| | 3 | 272 | | } |
| | | 273 | | |
| | | 274 | | private bool TryReadLinkId(string name, [NotNullWhen(true)] out string? id) |
| | | 275 | | { |
| | 15 | 276 | | if (!_entries.TryGetValue(name, out byte[]? entry) |
| | 15 | 277 | | || entry == null) |
| | | 278 | | { |
| | 3 | 279 | | id = null; |
| | 3 | 280 | | return false; |
| | | 281 | | } |
| | | 282 | | |
| | 12 | 283 | | id = MemoryPackSerializer.Deserialize<string>(entry); |
| | 12 | 284 | | return id != null; |
| | | 285 | | } |
| | | 286 | | |
| | | 287 | | private void LoadDeferredLink<T>( |
| | | 288 | | ref T value, |
| | | 289 | | string name, |
| | | 290 | | string id, |
| | | 291 | | string? slot, |
| | | 292 | | Action<T>? assignLoadedValue) |
| | | 293 | | { |
| | 5 | 294 | | if (assignLoadedValue == null) |
| | 1 | 295 | | throw new InvalidOperationException( |
| | 1 | 296 | | $"Deferred link '{name}' of type {typeof(T).Name} requires an assignment callback."); |
| | | 297 | | |
| | 4 | 298 | | if (Context.Links.TryResolve(id, out T? deferredValue, slot)) |
| | | 299 | | { |
| | 1 | 300 | | value = deferredValue!; |
| | 1 | 301 | | assignLoadedValue(deferredValue!); |
| | 1 | 302 | | return; |
| | | 303 | | } |
| | | 304 | | |
| | 3 | 305 | | Context.QueueDeferredLink(name, id, slot, assignLoadedValue); |
| | 3 | 306 | | value = default!; |
| | 3 | 307 | | } |
| | | 308 | | |
| | | 309 | | private void LoadImmediateLink<T>( |
| | | 310 | | ref T value, |
| | | 311 | | string name, |
| | | 312 | | string id, |
| | | 313 | | string? slot, |
| | | 314 | | Action<T>? assignLoadedValue) |
| | | 315 | | { |
| | 4 | 316 | | if (!Context.Links.TryResolve(id, out T? resolvedValue, slot)) |
| | 1 | 317 | | throw new InvalidOperationException( |
| | 1 | 318 | | $"Unable to load link '{name}' of type {typeof(T).Name} with id '{id}'{FormatSlot(slot)}."); |
| | | 319 | | |
| | 3 | 320 | | value = resolvedValue!; |
| | 3 | 321 | | assignLoadedValue?.Invoke(resolvedValue!); |
| | 3 | 322 | | } |
| | | 323 | | |
| | | 324 | | private T CreateDefaultDeepStruct<T>() where T : struct, IRecordable |
| | | 325 | | { |
| | 11 | 326 | | T defaultValue = new(); |
| | 11 | 327 | | var nested = new MemoryPackRecordReader(EmptyRecordBytes, Context); |
| | 11 | 328 | | defaultValue.RecordData(nested); |
| | 10 | 329 | | return defaultValue; |
| | | 330 | | } |
| | | 331 | | } |
| | | 332 | | |
| | | 333 | | private static string FormatSlot(string? slot) |
| | | 334 | | { |
| | 3 | 335 | | return string.IsNullOrEmpty(slot) |
| | 3 | 336 | | ? string.Empty |
| | 3 | 337 | | : $" in slot '{slot}'"; |
| | | 338 | | } |
| | | 339 | | } |
| | | 340 | | |
| | | 341 | | #endif |