Element ids: one Classify of the declared type; registration, Plan and Holds walk declared types
IsLeaf, IsObjectType and DictionaryValueType are deleted. Classify(declared) says Leaf, Map (IDictionary<,> or IReadOnlyDictionary<,>), Sequence or Owner; a keyed struct is walked as an owner and is never an element. Plan and Holds take the declared root type and follow declared member types, so a member declared object or a subclass's extra members under a base-typed member are neither minted into nor read. Minted path text is unchanged. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c9c96642e8
commit
1e7b3b25da
4 changed files with 270 additions and 113 deletions
|
|
@ -545,11 +545,14 @@ namespace GameCult.Caching
|
|||
get
|
||||
{
|
||||
if (Variant == null)
|
||||
return CultElementIds.Holds(_document);
|
||||
return CultElementIds.Holds(Descriptor.DocumentType, _document);
|
||||
if (_codec == null)
|
||||
return true;
|
||||
return Variant.Overrides.Any(entry => CultElementIds.Holds(_codec.Deserialize(
|
||||
Descriptor.RichMembers.First(member => member.Slot == entry.Path[0].Slot).MemberType, Descriptor.DocumentType, entry.Value)));
|
||||
return Variant.Overrides.Any(entry =>
|
||||
{
|
||||
var memberType = Descriptor.RichMembers.First(member => member.Slot == entry.Path[0].Slot).MemberType;
|
||||
return CultElementIds.Holds(memberType, _codec.Deserialize(memberType, Descriptor.DocumentType, entry.Value));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2734,7 +2737,7 @@ namespace GameCult.Caching
|
|||
// again, and lands in memory only (variants mint inside Resolve, into their override values).
|
||||
var idPlans = admitted
|
||||
.Where(stored => stored.Variant == null)
|
||||
.Select(stored => (Stored: stored, Plan: CultElementIds.Plan(stored.Document, stored.Key.Value, deterministic: source != null)))
|
||||
.Select(stored => (Stored: stored, Plan: CultElementIds.Plan(stored.Descriptor.DocumentType, stored.Document, stored.Key.Value, deterministic: source != null)))
|
||||
.ToArray();
|
||||
VariantPlan plan;
|
||||
CultCommitOutcome outcome;
|
||||
|
|
@ -3176,7 +3179,7 @@ namespace GameCult.Caching
|
|||
// The override's value is minted like a plain record's members: ids the store never held are filled here, in the
|
||||
// decoded copy, and the delta this hold lands carries them.
|
||||
var bytes = entry.Value;
|
||||
var idPlan = CultElementIds.Plan(value, key + "." + slot.ToString(CultureInfo.InvariantCulture), deterministic: source != null);
|
||||
var idPlan = CultElementIds.Plan(member.MemberType, value, key + "." + slot.ToString(CultureInfo.InvariantCulture), deterministic: source != null);
|
||||
if (idPlan.Count > 0)
|
||||
{
|
||||
idPlan.Apply();
|
||||
|
|
@ -4299,7 +4302,7 @@ namespace GameCult.Caching
|
|||
if (!CultElementIds.CanHoldIds(type))
|
||||
continue;
|
||||
CopiedRecordsDecoded++;
|
||||
if (CultElementIds.Holds(DeserializePayload(type, record.Payload)))
|
||||
if (CultElementIds.Holds(type, DeserializePayload(type, record.Payload)))
|
||||
return true;
|
||||
}
|
||||
catch (Exception e) when (e is not OperationCanceledException)
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ namespace GameCult.Caching
|
|||
public Action<object, string>? SetId;
|
||||
public Func<object, string?>? Derive;
|
||||
public string? DerivedFrom;
|
||||
public (int Slot, Func<object, object?> Get)[] Walk = Array.Empty<(int, Func<object, object?>)>();
|
||||
public (int Slot, Type Type, Func<object, object?> Get)[] Walk = Array.Empty<(int, Type, Func<object, object?>)>();
|
||||
}
|
||||
|
||||
private static readonly ConcurrentDictionary<Type, Shape> Shapes = new();
|
||||
|
|
@ -144,40 +144,35 @@ namespace GameCult.Caching
|
|||
private static void VisitMemberType(Type documentType, Type owner, MemberInfo member, Type memberType, Type[] through, HashSet<Type> seen, Survey survey, Graph graph)
|
||||
{
|
||||
memberType = Nullable.GetUnderlyingType(memberType) ?? memberType;
|
||||
if (IsLeaf(memberType))
|
||||
return;
|
||||
if (DictionaryValueType(memberType) is { } valueType)
|
||||
var (kind, inner) = Classify(memberType);
|
||||
switch (kind)
|
||||
{
|
||||
VisitMemberType(documentType, owner, member, valueType, through.Append(memberType).ToArray(), seen, survey, graph);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ElementTypeOf(memberType) is { } element)
|
||||
{
|
||||
if (IsObjectType(element))
|
||||
{
|
||||
var concretes = ConcreteTypes(element).ToList();
|
||||
graph.Lists.Add((owner, member, element, concretes, through.Append(memberType).ToArray()));
|
||||
case Kind.Leaf:
|
||||
return;
|
||||
case Kind.Map:
|
||||
VisitMemberType(documentType, owner, member, inner, through.Append(memberType).ToArray(), seen, survey, graph);
|
||||
return;
|
||||
case Kind.Sequence when IsElement(inner):
|
||||
var concretes = ConcreteTypes(inner).ToList();
|
||||
graph.Lists.Add((owner, member, inner, concretes, through.Append(memberType).ToArray()));
|
||||
foreach (var concrete in concretes)
|
||||
{
|
||||
if (!survey.Judged.Add(concrete))
|
||||
continue;
|
||||
var problem = IsObjectType(concrete) ? IdProblem(concrete) : UnkeyedElementProblem;
|
||||
var problem = IsElement(concrete) ? IdProblem(concrete) : UnkeyedElementProblem;
|
||||
if (problem != null)
|
||||
survey.Problems.Add($"Cult document {documentType.Name}: list element type {concrete.Name} (in {owner.Name}.{member.Name}) {problem}");
|
||||
}
|
||||
|
||||
VisitObject(documentType, element, seen, survey, graph);
|
||||
}
|
||||
else
|
||||
VisitMemberType(documentType, owner, member, element, through.Append(memberType).ToArray(), seen, survey, graph);
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsObjectType(memberType))
|
||||
{
|
||||
graph.Edges.Add((owner, member, memberType, through));
|
||||
VisitObject(documentType, memberType, seen, survey, graph);
|
||||
VisitObject(documentType, inner, seen, survey, graph);
|
||||
return;
|
||||
case Kind.Sequence:
|
||||
VisitMemberType(documentType, owner, member, inner, through.Append(memberType).ToArray(), seen, survey, graph);
|
||||
return;
|
||||
default:
|
||||
graph.Edges.Add((owner, member, memberType, through));
|
||||
VisitObject(documentType, memberType, seen, survey, graph);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -295,40 +290,37 @@ namespace GameCult.Caching
|
|||
// ---- write: what the stored form holds ----
|
||||
|
||||
// True when some element under root holds a non-empty id: the one fact a store marks its header by. It reads the value
|
||||
// as it is now, refuses nothing and changes nothing, so a writer asks it of exactly what it is about to write.
|
||||
internal static bool Holds(object? root)
|
||||
// as it is now, refuses nothing and changes nothing, so a writer asks it of exactly what it is about to write. The walk
|
||||
// follows declared types, as registration does; a value's own type picks only a union arm.
|
||||
internal static bool Holds(Type declared, object? root)
|
||||
{
|
||||
if (root == null)
|
||||
return false;
|
||||
var type = root.GetType();
|
||||
if (IsLeaf(type))
|
||||
return false;
|
||||
if (root is IDictionary dictionary)
|
||||
var (kind, inner) = Classify(declared);
|
||||
switch (kind)
|
||||
{
|
||||
foreach (DictionaryEntry entry in dictionary)
|
||||
{
|
||||
if (Holds(entry.Value))
|
||||
return true;
|
||||
}
|
||||
case Kind.Leaf:
|
||||
return false;
|
||||
case Kind.Map:
|
||||
return MapEntries(declared)(root).Any(entry => Holds(inner, entry.Value));
|
||||
case Kind.Sequence:
|
||||
var elements = IsElement(inner);
|
||||
if (!elements && Classify(inner).Kind == Kind.Leaf)
|
||||
return false;
|
||||
foreach (var item in (IEnumerable)root)
|
||||
{
|
||||
if (item == null)
|
||||
continue;
|
||||
if (elements && OwnerShape(inner, item).GetId is { } getId && !string.IsNullOrEmpty(getId(item)))
|
||||
return true;
|
||||
if (Holds(inner, item))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
return false;
|
||||
default:
|
||||
return OwnerShape(declared, root).Walk.Any(member => Holds(member.Type, member.Get(root)));
|
||||
}
|
||||
|
||||
if (root is IEnumerable list)
|
||||
{
|
||||
foreach (var item in list)
|
||||
{
|
||||
if (item != null && IsObjectType(item.GetType()) && ShapeOf(item.GetType()).GetId is { } getId &&
|
||||
!string.IsNullOrEmpty(getId(item)))
|
||||
return true;
|
||||
if (Holds(item))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return IsObjectType(type) && ShapeOf(type).Walk.Any(member => Holds(member.Get(root)));
|
||||
}
|
||||
|
||||
// ---- write and load: mint and check ----
|
||||
|
|
@ -337,41 +329,48 @@ namespace GameCult.Caching
|
|||
// that is not 12 lowercase hex characters, a duplicate id in one list, a derived id whose source is null or empty.
|
||||
// rootPath (the record key) seeds deterministic minting and names the record in a refusal. An element object that sits
|
||||
// twice in one list is refused too: planning would give it two ids and it would then be a duplicate on load.
|
||||
internal static IdPlan Plan(object? root, string rootPath, bool deterministic)
|
||||
internal static IdPlan Plan(Type declared, object? root, string rootPath, bool deterministic)
|
||||
{
|
||||
var plan = new IdPlan();
|
||||
Visit(root, rootPath);
|
||||
Visit(declared, root, rootPath);
|
||||
return plan;
|
||||
|
||||
void Visit(object? value, string path)
|
||||
void Visit(Type type, object? value, string path)
|
||||
{
|
||||
if (value == null)
|
||||
return;
|
||||
var type = value.GetType();
|
||||
if (IsLeaf(type))
|
||||
return;
|
||||
if (value is IDictionary dictionary)
|
||||
var (kind, inner) = Classify(type);
|
||||
switch (kind)
|
||||
{
|
||||
foreach (DictionaryEntry entry in dictionary)
|
||||
Visit(entry.Value, path + "{" + Convert.ToString(entry.Key, CultureInfo.InvariantCulture) + "}");
|
||||
}
|
||||
else if (value is IEnumerable list)
|
||||
Elements(list, path);
|
||||
else if (IsObjectType(type))
|
||||
{
|
||||
foreach (var (slot, get) in ShapeOf(type).Walk)
|
||||
Visit(get(value), path + "." + slot.ToString(CultureInfo.InvariantCulture));
|
||||
case Kind.Map:
|
||||
foreach (var entry in MapEntries(type)(value))
|
||||
Visit(inner, entry.Value, path + "{" + Convert.ToString(entry.Key, CultureInfo.InvariantCulture) + "}");
|
||||
break;
|
||||
case Kind.Sequence when IsElement(inner):
|
||||
Elements(inner, (IEnumerable)value, path);
|
||||
break;
|
||||
case Kind.Sequence:
|
||||
if (Classify(inner).Kind == Kind.Leaf)
|
||||
break;
|
||||
var index = 0;
|
||||
foreach (var item in (IEnumerable)value)
|
||||
Visit(inner, item, path + "/" + (index++).ToString(CultureInfo.InvariantCulture));
|
||||
break;
|
||||
case Kind.Owner:
|
||||
foreach (var (slot, memberType, get) in OwnerShape(type, value).Walk)
|
||||
Visit(memberType, get(value), path + "." + slot.ToString(CultureInfo.InvariantCulture));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Elements(IEnumerable list, string path)
|
||||
void Elements(Type element, IEnumerable list, string path)
|
||||
{
|
||||
var items = list.Cast<object?>().ToArray();
|
||||
var taken = new HashSet<string>(StringComparer.Ordinal);
|
||||
var objects = new HashSet<object>(ReferenceComparer.Instance);
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (item == null || !IsObjectType(item.GetType()) || ShapeOf(item.GetType()) is not { GetId: { } getId } shape)
|
||||
if (item == null || OwnerShape(element, item) is not { GetId: { } getId } shape)
|
||||
continue;
|
||||
if (!objects.Add(item))
|
||||
throw new CultElementIdException(
|
||||
|
|
@ -394,7 +393,7 @@ namespace GameCult.Caching
|
|||
if (item == null)
|
||||
continue;
|
||||
var itemPath = path + "/" + index.ToString(CultureInfo.InvariantCulture);
|
||||
if (IsObjectType(item.GetType()) && ShapeOf(item.GetType()) is { SetId: { } , GetId: { } get } itemShape &&
|
||||
if (OwnerShape(element, item) is { SetId: { } , GetId: { } get } itemShape &&
|
||||
string.IsNullOrEmpty(get(item)))
|
||||
{
|
||||
string id;
|
||||
|
|
@ -413,7 +412,7 @@ namespace GameCult.Caching
|
|||
plan.Add(item, itemShape, get(item), id);
|
||||
}
|
||||
|
||||
Visit(item, itemPath);
|
||||
Visit(element, item, itemPath);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -481,6 +480,14 @@ namespace GameCult.Caching
|
|||
|
||||
private static Shape ShapeOf(Type type) => Shapes.GetOrAdd(type, Build);
|
||||
|
||||
// The shape of an owner or element a walk holds under a declared type: a union base writes its arm, so the value's own
|
||||
// type picks the arm; any other declared type is written by its own [Key] layout, whatever a subclass adds.
|
||||
private static Shape OwnerShape(Type declared, object value)
|
||||
{
|
||||
declared = Nullable.GetUnderlyingType(declared) ?? declared;
|
||||
return declared.IsDefined(typeof(UnionAttribute), false) ? ShapeOf(value.GetType()) : ShapeOf(declared);
|
||||
}
|
||||
|
||||
private static Shape Build(Type type)
|
||||
{
|
||||
var shape = new Shape();
|
||||
|
|
@ -498,8 +505,8 @@ namespace GameCult.Caching
|
|||
}
|
||||
|
||||
shape.Walk = KeyedMembers(type)
|
||||
.Where(entry => !IsLeaf(Nullable.GetUnderlyingType(entry.Type) ?? entry.Type))
|
||||
.Select(entry => (Slot: KeyOf(entry.Member)!.Value, Get: entry.Member is FieldInfo fi
|
||||
.Where(entry => Classify(entry.Type).Kind != Kind.Leaf)
|
||||
.Select(entry => (Slot: KeyOf(entry.Member)!.Value, entry.Type, Get: entry.Member is FieldInfo fi
|
||||
? (Func<object, object?>)(o => fi.GetValue(o))
|
||||
: o => ((PropertyInfo)entry.Member).GetValue(o)))
|
||||
.ToArray();
|
||||
|
|
@ -523,18 +530,38 @@ namespace GameCult.Caching
|
|||
|
||||
// ---- type classification ----
|
||||
|
||||
// A value MessagePack writes whole and that cannot hold an element list. Structs are values: never elements, never walked.
|
||||
private static bool IsLeaf(Type type)
|
||||
{
|
||||
if (type.IsPrimitive || type.IsEnum || type == typeof(string) || type.IsValueType)
|
||||
return true;
|
||||
return type.IsArray && IsLeaf(type.GetElementType()!);
|
||||
}
|
||||
private enum Kind { Leaf, Map, Sequence, Owner }
|
||||
|
||||
// An object a store can hold an element list under, or hold as an element: a class MessagePack serializes by key.
|
||||
private static bool IsObjectType(Type type) =>
|
||||
(type.IsClass || type.IsInterface) && type != typeof(string) && type != typeof(object) &&
|
||||
(type.IsDefined(typeof(MessagePackObjectAttribute), true) || type.IsDefined(typeof(UnionAttribute), true));
|
||||
private static readonly ConcurrentDictionary<Type, (Kind Kind, Type Inner)> Classes = new();
|
||||
|
||||
// The one recognition of what MessagePack writes for a declared type: registration, Plan, Holds and the codec's id path
|
||||
// all go through it. Inner is a map's value type, a sequence's element type, or the type itself for an owner.
|
||||
// Leaf a value written whole that holds no element list: primitives, enums, strings, object (untyped on disk),
|
||||
// a struct with no [MessagePackObject] or [Union], and a class with neither.
|
||||
// Map a class or interface implementing IDictionary<,> or IReadOnlyDictionary<,>.
|
||||
// Sequence an array or an IEnumerable<T>.
|
||||
// Owner a class, interface or struct MessagePack serializes by key. A keyed struct is walked as an owner; it is
|
||||
// never an element (IsElement), since a boxed copy cannot carry a minted id.
|
||||
private static (Kind Kind, Type Inner) Classify(Type declared) => Classes.GetOrAdd(declared, static type =>
|
||||
{
|
||||
type = Nullable.GetUnderlyingType(type) ?? type;
|
||||
if (type.IsPrimitive || type.IsEnum || type == typeof(string) || type == typeof(object))
|
||||
return (Kind.Leaf, type);
|
||||
if (type.IsValueType)
|
||||
return IsKeyed(type) ? (Kind.Owner, type) : (Kind.Leaf, type);
|
||||
if (MapTypes(type) is { } map)
|
||||
return (Kind.Map, map.Value);
|
||||
if (ElementTypeOf(type) is { } element)
|
||||
return (Kind.Sequence, element);
|
||||
return IsKeyed(type) ? (Kind.Owner, type) : (Kind.Leaf, type);
|
||||
});
|
||||
|
||||
// A type MessagePack serializes by key: [MessagePackObject] or [Union].
|
||||
private static bool IsKeyed(Type type) =>
|
||||
type.IsDefined(typeof(MessagePackObjectAttribute), true) || type.IsDefined(typeof(UnionAttribute), true);
|
||||
|
||||
// What an object list holds: a keyed class or interface. Never a struct.
|
||||
private static bool IsElement(Type type) => !type.IsValueType && Classify(type).Kind == Kind.Owner;
|
||||
|
||||
private static Type? ElementTypeOf(Type type)
|
||||
{
|
||||
|
|
@ -549,15 +576,34 @@ namespace GameCult.Caching
|
|||
return null;
|
||||
}
|
||||
|
||||
private static Type? DictionaryValueType(Type type)
|
||||
// The key and value types of a map MessagePack writes as a map: IDictionary<,> or IReadOnlyDictionary<,>.
|
||||
private static (Type Key, Type Value)? MapTypes(Type type)
|
||||
{
|
||||
foreach (var candidate in type.GetInterfaces().Append(type))
|
||||
{
|
||||
if (candidate.IsGenericType && candidate.GetGenericTypeDefinition() == typeof(IDictionary<,>))
|
||||
return candidate.GetGenericArguments()[1];
|
||||
if (candidate.IsGenericType &&
|
||||
(candidate.GetGenericTypeDefinition() == typeof(IDictionary<,>) || candidate.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>)))
|
||||
{
|
||||
var arguments = candidate.GetGenericArguments();
|
||||
return (arguments[0], arguments[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static readonly ConcurrentDictionary<Type, Func<object, IEnumerable<(object? Key, object? Value)>>> MapReaders = new();
|
||||
|
||||
// A map's entries read through the generic interface Classify found, so no map shape is recognised twice.
|
||||
private static Func<object, IEnumerable<(object? Key, object? Value)>> MapEntries(Type map) => MapReaders.GetOrAdd(map, static type =>
|
||||
{
|
||||
var (key, value) = MapTypes(type)!.Value;
|
||||
return (Func<object, IEnumerable<(object? Key, object? Value)>>)Delegate.CreateDelegate(
|
||||
typeof(Func<object, IEnumerable<(object? Key, object? Value)>>),
|
||||
typeof(CultElementIds).GetMethod(nameof(ReadMap), BindingFlags.NonPublic | BindingFlags.Static)!.MakeGenericMethod(key, value));
|
||||
});
|
||||
|
||||
private static IEnumerable<(object? Key, object? Value)> ReadMap<TKey, TValue>(object map) =>
|
||||
((IEnumerable<KeyValuePair<TKey, TValue>>)map).Select(entry => ((object?)entry.Key, (object?)entry.Value));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -98,7 +98,7 @@ namespace GameCult.Mesh
|
|||
var descriptor = resolvedRegistry.GetRequired<TDocument>();
|
||||
// Element ids are decided as a cache write decides them, before anything is written: an unset id is minted, a
|
||||
// refused list refuses the write, and the file is marked when it holds an id. A failed write gives the ids back.
|
||||
var ids = CultElementIds.Plan(document, key.Value, deterministic: false);
|
||||
var ids = CultElementIds.Plan(typeof(TDocument), document, key.Value, deterministic: false);
|
||||
ids.Apply();
|
||||
try
|
||||
{
|
||||
|
|
@ -108,7 +108,7 @@ namespace GameCult.Mesh
|
|||
descriptor.ToCatalogEntry(),
|
||||
storedAt,
|
||||
CultDocumentMessagePackSerialization.SerializeUntyped(document, typeof(TDocument)),
|
||||
CultElementIds.Holds(document),
|
||||
CultElementIds.Holds(typeof(TDocument), document),
|
||||
resolvedRegistry);
|
||||
}
|
||||
catch
|
||||
|
|
@ -132,7 +132,7 @@ namespace GameCult.Mesh
|
|||
var payload = ReadSingleFileDocumentPayload(path, key, descriptor.SchemaId);
|
||||
var document = (TDocument)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(TDocument), payload);
|
||||
// A load refuses what a write refuses, and mints the ids a cache load of the same file would mint.
|
||||
CultElementIds.Plan(document, key.Value, deterministic: true).Apply();
|
||||
CultElementIds.Plan(typeof(TDocument), document, key.Value, deterministic: true).Apply();
|
||||
return document;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ namespace GameCult.Caching.Tests
|
|||
|
||||
private static int Assign(object root, string key, bool deterministic)
|
||||
{
|
||||
var plan = CultElementIds.Plan(root, key, deterministic);
|
||||
var plan = CultElementIds.Plan(root.GetType(), root, key, deterministic);
|
||||
plan.Apply();
|
||||
return plan.Count;
|
||||
}
|
||||
|
|
@ -30,7 +30,8 @@ namespace GameCult.Caching.Tests
|
|||
foreach (var holder in new[]
|
||||
{
|
||||
typeof(HList), typeof(HArray), typeof(HDictionary), typeof(HNested), typeof(HListOfLists),
|
||||
typeof(HElementNest), typeof(HUnion), typeof(HNullableInner)
|
||||
typeof(HElementNest), typeof(HUnion), typeof(HNullableInner), typeof(HStruct), typeof(HStructList), typeof(HNullableStruct),
|
||||
typeof(HReadOnlyMap)
|
||||
})
|
||||
RefusesBare(holder);
|
||||
Assert.That(Problems(typeof(HFine)), Is.Empty);
|
||||
|
|
@ -72,28 +73,28 @@ namespace GameCult.Caching.Tests
|
|||
public void HoldsFindsASetIdWhereverAListCanSitAndNothingElse()
|
||||
{
|
||||
const string id = "0123456789ab";
|
||||
Assert.That(CultElementIds.Holds(null), Is.False);
|
||||
Assert.That(CultElementIds.Holds(new HAll
|
||||
Assert.That(CultElementIds.Holds(typeof(HAll), null), Is.False);
|
||||
Assert.That(CultElementIds.Holds(typeof(HAll), new HAll
|
||||
{
|
||||
Dict = { ["k"] = new HHasIds { Items = { new EIded() } } },
|
||||
Grid = { new List<EIded> { new EIded() } },
|
||||
Nest = { new ENest { Sub = { new EIded() } } },
|
||||
}), Is.False, "unset ids hold nothing");
|
||||
Assert.That(CultElementIds.Holds(new HAll { Dict = { ["k"] = new HHasIds { Items = { new EIded { Id = id } } } } }), Is.True, "a dictionary value");
|
||||
Assert.That(CultElementIds.Holds(new HAll { Grid = { new List<EIded> { new EIded { Id = id } } } }), Is.True, "a list of lists");
|
||||
Assert.That(CultElementIds.Holds(new HAll { Nest = { new ENest { Sub = { new EIded { Id = id } } } } }), Is.True, "a list under an unset element");
|
||||
Assert.That(CultElementIds.Holds(new HAll { Nest = { new ENest { Id = id } } }), Is.True, "an element");
|
||||
Assert.That(CultElementIds.Holds(new HAll { Dict = { ["a"] = new HHasIds { Items = { new EIded() } }, ["b"] = new HHasIds { Items = { new EIded { Id = id } } } } }), Is.True, "the second dictionary value");
|
||||
Assert.That(CultElementIds.Holds(new HAll { Grid = { new List<EIded> { new EIded() }, new List<EIded> { new EIded { Id = id } } } }), Is.True, "the second list");
|
||||
Assert.That(CultElementIds.Holds(new HAll { Nest = { new ENest(), new ENest { Sub = { new EIded { Id = id } } } } }), Is.True, "the second item of a list of elements");
|
||||
Assert.That(CultElementIds.Holds(new HAll { Grid = { new List<EIded> { new EIded(), new EIded { Id = id } } } }), Is.True, "the second element of a list");
|
||||
Assert.That(CultElementIds.Holds(typeof(HAll), new HAll { Dict = { ["k"] = new HHasIds { Items = { new EIded { Id = id } } } } }), Is.True, "a dictionary value");
|
||||
Assert.That(CultElementIds.Holds(typeof(HAll), new HAll { Grid = { new List<EIded> { new EIded { Id = id } } } }), Is.True, "a list of lists");
|
||||
Assert.That(CultElementIds.Holds(typeof(HAll), new HAll { Nest = { new ENest { Sub = { new EIded { Id = id } } } } }), Is.True, "a list under an unset element");
|
||||
Assert.That(CultElementIds.Holds(typeof(HAll), new HAll { Nest = { new ENest { Id = id } } }), Is.True, "an element");
|
||||
Assert.That(CultElementIds.Holds(typeof(HAll), new HAll { Dict = { ["a"] = new HHasIds { Items = { new EIded() } }, ["b"] = new HHasIds { Items = { new EIded { Id = id } } } } }), Is.True, "the second dictionary value");
|
||||
Assert.That(CultElementIds.Holds(typeof(HAll), new HAll { Grid = { new List<EIded> { new EIded() }, new List<EIded> { new EIded { Id = id } } } }), Is.True, "the second list");
|
||||
Assert.That(CultElementIds.Holds(typeof(HAll), new HAll { Nest = { new ENest(), new ENest { Sub = { new EIded { Id = id } } } } }), Is.True, "the second item of a list of elements");
|
||||
Assert.That(CultElementIds.Holds(typeof(HAll), new HAll { Grid = { new List<EIded> { new EIded(), new EIded { Id = id } } } }), Is.True, "the second element of a list");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void APlanCountsAndChangesNothingUntilApplied()
|
||||
{
|
||||
var root = new HHasIds { Items = { new EIded(), new EIded() } };
|
||||
var plan = CultElementIds.Plan(root, "r", deterministic: true);
|
||||
var plan = CultElementIds.Plan(typeof(HHasIds), root, "r", deterministic: true);
|
||||
Assert.That(plan.Count, Is.EqualTo(2));
|
||||
Assert.That(root.Items.Select(x => x.Id), Has.All.Empty);
|
||||
plan.Apply();
|
||||
|
|
@ -184,7 +185,7 @@ namespace GameCult.Caching.Tests
|
|||
Assert.That(root.Dict["k"].Items.Select(x => x.Id), Has.All.Empty, "the list before the refused one was not minted into");
|
||||
|
||||
var ok = new HHasIds { Items = { new EIded(), new EIded { Id = "dddddddddddd" } } };
|
||||
var plan = CultElementIds.Plan(ok, "r", deterministic: false);
|
||||
var plan = CultElementIds.Plan(typeof(HHasIds), ok, "r", deterministic: false);
|
||||
plan.Apply();
|
||||
plan.Undo();
|
||||
Assert.That(ok.Items.Select(x => x.Id), Is.EqualTo(new[] { "", "dddddddddddd" }));
|
||||
|
|
@ -375,6 +376,82 @@ namespace GameCult.Caching.Tests
|
|||
Assert.That(CultElementIds.Inspect(typeof(HIdBaseOwner)).IdPath, Is.EquivalentTo(new[] { typeof(HIdBaseOwner), typeof(IdBase), typeof(IdArm), typeof(EIded), typeof(List<EIded>) }));
|
||||
}
|
||||
|
||||
// A keyed struct is a value MessagePack writes by key, and an object list inside one carries element ids like any other.
|
||||
// It is walked as an owner and is never an element: a boxed copy cannot carry a minted id.
|
||||
[Test]
|
||||
public void AKeyedStructIsWalkedAsAnOwnerAndNeverAnElement()
|
||||
{
|
||||
var root = new HStructIded
|
||||
{
|
||||
Hold = new SHoldIded { Items = new List<EIded> { new EIded() } },
|
||||
Many = { new SHoldIded { Items = new List<EIded> { new EIded() } } },
|
||||
};
|
||||
Assert.That(Problems(typeof(HStructIded)), Is.Empty);
|
||||
Assert.That(CultElementIds.Inspect(typeof(HStructIded)).IdPath,
|
||||
Is.EquivalentTo(new[] { typeof(HStructIded), typeof(SHoldIded), typeof(List<SHoldIded>), typeof(List<EIded>), typeof(EIded) }));
|
||||
Assert.That(CultElementIds.Holds(typeof(HStructIded), root), Is.False);
|
||||
Assert.That(Assign(root, "r", deterministic: false), Is.EqualTo(2));
|
||||
Assert.That(root.Hold.Items[0].Id, Is.Not.Empty, "visible through the struct copy");
|
||||
Assert.That(root.Many[0].Items[0].Id, Is.Not.Empty, "visible through the struct in a list");
|
||||
Assert.That(CultElementIds.Holds(typeof(HStructIded), root), Is.True);
|
||||
var one = new HStructIded { Hold = new SHoldIded { Items = new List<EIded> { new EIded { Id = "0123456789ab" } } } };
|
||||
Assert.That(CultElementIds.Holds(typeof(HStructIded), one), Is.True);
|
||||
|
||||
Assert.That(Problems(typeof(HStructValues)), Is.Empty);
|
||||
Assert.That(CultElementIds.Inspect(typeof(HStructValues)).IdPath,
|
||||
Is.EquivalentTo(new[] { typeof(HStructValues), typeof(List<EIded>), typeof(EIded) }), "a list of keyed structs is a value list");
|
||||
var values = new HStructValues { Structs = { new SValue { N = 1 } }, Objects = { new EIded() } };
|
||||
Assert.That(Assign(values, "r", deterministic: false), Is.EqualTo(1));
|
||||
}
|
||||
|
||||
// Every dictionary interface MessagePack writes as a map is walked by one path, and the minted path text is the one a
|
||||
// store loaded before ids already holds, so its deterministic ids do not move.
|
||||
[Test]
|
||||
public void EveryMapInterfaceIsWalkedByTheSamePath()
|
||||
{
|
||||
var element = new Func<HHasIds>(() => new HHasIds { Items = { new EIded() } });
|
||||
var viaInterface = new HReadOnlyIded { Map = new Dictionary<string, HHasIds> { ["k"] = element() } };
|
||||
var viaClass = new HReadOnlyIded { Map = new RoMap(new Dictionary<string, HHasIds> { ["k"] = element() }) };
|
||||
var viaDictionary = new HMapIded { Map = { ["k"] = element() } };
|
||||
Assert.That(Assign(viaInterface, "r", deterministic: true), Is.EqualTo(1));
|
||||
Assert.That(Assign(viaClass, "r", deterministic: true), Is.EqualTo(1), "a class implementing only IReadOnlyDictionary<,>");
|
||||
Assert.That(Assign(viaDictionary, "r", deterministic: true), Is.EqualTo(1));
|
||||
var id = viaDictionary.Map["k"].Items[0].Id;
|
||||
Assert.That(viaInterface.Map["k"].Items[0].Id, Is.EqualTo(id));
|
||||
Assert.That(viaClass.Map["k"].Items[0].Id, Is.EqualTo(id));
|
||||
|
||||
// SHA-256 of "<record key>|<element path>|0": slot 0, the key in braces, slot 0, the index.
|
||||
var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes("r|r.0{k}.0/0|0"));
|
||||
Assert.That(id, Is.EqualTo(Convert.ToHexString(hash, 0, 6).ToLowerInvariant()), "the path text is unchanged");
|
||||
|
||||
var held = new HReadOnlyIded { Map = new RoMap(new Dictionary<string, HHasIds> { ["k"] = new HHasIds { Items = { new EIded { Id = "0123456789ab" } } } }) };
|
||||
Assert.That(CultElementIds.Holds(typeof(HReadOnlyIded), held), Is.True);
|
||||
Assert.That(CultElementIds.Holds(typeof(HReadOnlyIded), viaInterface), Is.True);
|
||||
Assert.That(CultElementIds.Holds(typeof(HMapIded), new HMapIded { Map = { ["k"] = new HHasIds { Items = { new EIded() } } } }), Is.False);
|
||||
}
|
||||
|
||||
// Registration judges the declared shape, so minting and reading follow it: a member declared object is untyped on disk,
|
||||
// and what a subclass adds under a base-typed member is not written, so neither is walked.
|
||||
[Test]
|
||||
public void TheWalkFollowsTheDeclaredShape()
|
||||
{
|
||||
var derived = new HBase { B = new DerC { L = { new EIded(), new EIded { Id = "0123456789ab" } } } };
|
||||
Assert.That(CultElementIds.Plan(typeof(HBase), derived, "r", deterministic: false).Count, Is.Zero);
|
||||
Assert.That(CultElementIds.Holds(typeof(HBase), derived), Is.False);
|
||||
var opaque = new HObject { O = new HHasIds { Items = { new EIded(), new EIded { Id = "0123456789ab" } } } };
|
||||
Assert.That(CultElementIds.Plan(typeof(HObject), opaque, "r", deterministic: false).Count, Is.Zero);
|
||||
Assert.That(CultElementIds.Holds(typeof(HObject), opaque), Is.False);
|
||||
foreach (var type in new[] { typeof(HBase), typeof(HObject) })
|
||||
{
|
||||
Assert.That(Problems(type), Is.Empty, type.Name);
|
||||
Assert.That(CultElementIds.Inspect(type).IdPath, Is.Empty, type.Name);
|
||||
}
|
||||
|
||||
// A union base still writes its arm, so the arm is walked.
|
||||
var arm = new HIdBaseOwner { Root = new IdArm { Items = { new EIded() } } };
|
||||
Assert.That(Assign(arm, "r", deterministic: false), Is.EqualTo(1));
|
||||
}
|
||||
|
||||
// ---- shapes ----
|
||||
[MessagePackObject] public class EBare { [Key(0)] public string X { get; set; } = ""; }
|
||||
[MessagePackObject] public class EIded { [Key(0)] public string X { get; set; } = ""; [Key(1)] [CultElementId] public string Id { get; set; } = ""; }
|
||||
|
|
@ -517,6 +594,37 @@ namespace GameCult.Caching.Tests
|
|||
[Key(2)] public List<ENest> Nest { get; set; } = new();
|
||||
}
|
||||
|
||||
[MessagePackObject] public struct SHold { [Key(0)] public List<EBare> Items; }
|
||||
[MessagePackObject] public struct SHoldIded { [Key(0)] public List<EIded> Items; }
|
||||
[MessagePackObject] public struct SValue { [Key(0)] public int N; }
|
||||
[MessagePackObject] public class HStruct { [Key(0)] public SHold Hold; }
|
||||
[MessagePackObject] public class HStructList { [Key(0)] public List<SHold> Holds { get; set; } = new(); }
|
||||
[MessagePackObject] public class HNullableStruct { [Key(0)] public SHold? Hold; }
|
||||
[MessagePackObject] public class HStructIded { [Key(0)] public SHoldIded Hold; [Key(1)] public List<SHoldIded> Many = new(); }
|
||||
[MessagePackObject] public class HStructValues { [Key(0)] public List<SValue> Structs = new(); [Key(1)] public List<EIded> Objects = new(); }
|
||||
|
||||
[MessagePackObject] public class HReadOnlyMap { [Key(0)] public IReadOnlyDictionary<string, HList> Map { get; set; } = new Dictionary<string, HList>(); }
|
||||
[MessagePackObject] public class HReadOnlyIded { [Key(0)] public IReadOnlyDictionary<string, HHasIds> Map { get; set; } = new Dictionary<string, HHasIds>(); }
|
||||
[MessagePackObject] public class HMapIded { [Key(0)] public Dictionary<string, HHasIds> Map { get; set; } = new(); }
|
||||
public sealed class RoMap : IReadOnlyDictionary<string, HHasIds>
|
||||
{
|
||||
private readonly Dictionary<string, HHasIds> _inner;
|
||||
public RoMap(Dictionary<string, HHasIds> inner) => _inner = inner;
|
||||
public HHasIds this[string key] => _inner[key];
|
||||
public IEnumerable<string> Keys => _inner.Keys;
|
||||
public IEnumerable<HHasIds> Values => _inner.Values;
|
||||
public int Count => _inner.Count;
|
||||
public bool ContainsKey(string key) => _inner.ContainsKey(key);
|
||||
public bool TryGetValue(string key, out HHasIds value) => _inner.TryGetValue(key, out value!);
|
||||
public IEnumerator<KeyValuePair<string, HHasIds>> GetEnumerator() => _inner.GetEnumerator();
|
||||
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
|
||||
}
|
||||
|
||||
[MessagePackObject] public class BaseC { [Key(0)] public int X { get; set; } }
|
||||
[MessagePackObject] public class DerC : BaseC { [Key(1)] public List<EIded> L { get; set; } = new(); }
|
||||
[MessagePackObject] public class HBase { [Key(0)] public BaseC B { get; set; } = new(); }
|
||||
[MessagePackObject] public class HObject { [Key(0)] public object? O { get; set; } }
|
||||
|
||||
[MessagePackObject] public class EDerivedText { [Key(0)] public string? Name { get; set; } [Key(1)] [CultElementId(nameof(Name))] public string Id { get; set; } = ""; }
|
||||
[MessagePackObject] public class HDerivedText { [Key(0)] public List<EDerivedText> Items { get; set; } = new(); }
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue