Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ Every `Deserialize` and `Serialize` overload takes an optional `KVSerializerOpti
* `FileLoader` - Provider for files referenced by KV1 `#include` and `#base` directives. See [Includes](#includes).
* `StringTable` - String table used by the KV1 binary format. See [Binary](#binary).
* `SkipHeader` - Whether to omit the KV3 header comment when serializing and to not expect one when deserializing.
* `KeyComparer` - Comparer that keys of deserialized KV3 objects are looked up with, for example `StringComparer.OrdinalIgnoreCase`. KV1 objects keep their keys in a list and always compare them exactly.

```csharp
var options = new KVSerializerOptions
Expand Down
35 changes: 35 additions & 0 deletions ValveKeyValue/ValveKeyValue.Test/KVObjectApiTestCase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,21 @@ public void DefaultConstructorCreatesEmptyCollection()
}
}

[Test]
public void ConstructorWithKeyComparerLooksUpKeysWithIt()
{
var obj = new KVObject(StringComparer.OrdinalIgnoreCase);
obj.Add("StartDisabled", true);

using (Assert.EnterMultipleScope())
{
Assert.That(obj.ContainsKey("startdisabled"), Is.True);
Assert.That((bool)obj["STARTDISABLED"], Is.True);
Assert.That(obj.TryAdd("startdisabled", false), Is.False);
Assert.That(obj.Keys.Single(), Is.EqualTo("StartDisabled"));
}
}

#endregion

#region KVObject null
Expand Down Expand Up @@ -702,6 +717,26 @@ public void KV3DeserializationContainsKeyWorks()
}
}

[Test]
public void KV3DeserializationLooksUpKeysWithKeyComparer()
{
var options = new KVSerializerOptions
{
SkipHeader = true,
KeyComparer = StringComparer.OrdinalIgnoreCase,
};

using var stream = new MemoryStream("{ Outer = { StartDisabled = true } }"u8.ToArray());
var data = KVSerializer.Create(KVSerializationFormat.KeyValues3Text).Deserialize(stream, options).Root;

using (Assert.EnterMultipleScope())
{
Assert.That(data.ContainsKey("outer"), Is.True);
Assert.That((bool)data["OUTER"]["startdisabled"], Is.True);
Assert.That(data["outer"].Keys.Single(), Is.EqualTo("StartDisabled"));
}
}

[Test]
public void KV3DeserializationChildrenIterable()
{
Expand Down
3 changes: 3 additions & 0 deletions ValveKeyValue/ValveKeyValue.Test/Test Data/apisurface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ public class ValveKeyValue.KVObject : IConvertible, System.Collections.Generic.I
public .ctor(long value);
public .ctor(short value);
public .ctor(string value);
public .ctor(System.Collections.Generic.IEqualityComparer`1[[string]] keyComparer);
public .ctor(uint value);
public .ctor(ulong value);
public .ctor(ushort value);
Expand Down Expand Up @@ -307,6 +308,7 @@ public sealed class ValveKeyValue.KVSerializerOptions
public bool get_EnableValveNullByteBugBehavior();
public ValveKeyValue.IIncludedFileLoader get_FileLoader();
public bool get_HasEscapeSequences();
public System.Collections.Generic.IEqualityComparer`1[[string]] get_KeyComparer();
public bool get_SkipHeader();
public ValveKeyValue.StringTable get_StringTable();
public int GetHashCode();
Expand All @@ -315,6 +317,7 @@ public sealed class ValveKeyValue.KVSerializerOptions
public void set_EnableValveNullByteBugBehavior(bool value);
public void set_FileLoader(ValveKeyValue.IIncludedFileLoader value);
public void set_HasEscapeSequences(bool value);
public void set_KeyComparer(System.Collections.Generic.IEqualityComparer`1[[string]] value);
public void set_SkipHeader(bool value);
public void set_StringTable(ValveKeyValue.StringTable value);
public string ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ namespace ValveKeyValue.Deserialization
class KVObjectBuilder : IParsingVisitationListener
{
readonly bool useDictionary;
readonly IEqualityComparer<string>? keyComparer;
readonly List<KVObjectBuilder> associatedBuilders = new();

public KVObjectBuilder(bool useDictionaryForCollections = false)
public KVObjectBuilder(bool useDictionaryForCollections = false, IEqualityComparer<string>? keyComparer = null)
{
useDictionary = useDictionaryForCollections;
this.keyComparer = keyComparer;
}

public KeyValuePair<string, KVObject> GetObject()
Expand Down Expand Up @@ -200,7 +202,7 @@ static KeyValuePair<string, KVObject> MakeResult(KVPartialState state, KVObject?
}

KVObject result = useDictionary
? KVObject.Collection(state.Items)
? KVObject.Collection(state.Items, keyComparer)
: new KVObject(KVValueType.Collection, state.DetachItems());

if (state.Flag != KVFlag.None)
Expand Down
16 changes: 14 additions & 2 deletions ValveKeyValue/ValveKeyValue/KVObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,18 @@ public KVObject()
_ref = new Dictionary<string, KVObject>();
}

/// <summary>
/// Initializes a new instance of the <see cref="KVObject"/> class as an empty dictionary-backed collection
/// whose keys are compared with the given comparer.
/// </summary>
/// <param name="keyComparer">The comparer keys are looked up with.</param>
public KVObject(IEqualityComparer<string> keyComparer)
{
ArgumentNullException.ThrowIfNull(keyComparer);
ValueType = KVValueType.Collection;
_ref = new Dictionary<string, KVObject>(keyComparer);
}

/// <summary>
/// Initializes a new instance of the <see cref="KVObject"/> class with a string value.
/// </summary>
Expand Down Expand Up @@ -463,9 +475,9 @@ public static KVObject Collection(IEnumerable<KeyValuePair<string, KVObject>> ch
}

// Enumerates the list directly rather than through IEnumerable, which would box its enumerator.
internal static KVObject Collection(List<KeyValuePair<string, KVObject>> children)
internal static KVObject Collection(List<KeyValuePair<string, KVObject>> children, IEqualityComparer<string>? keyComparer = null)
{
var dict = new Dictionary<string, KVObject>(children.Count);
var dict = new Dictionary<string, KVObject>(children.Count, keyComparer);
foreach (var (key, value) in children)
{
dict[key] = value;
Expand Down
7 changes: 4 additions & 3 deletions ValveKeyValue/ValveKeyValue/KVSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,10 @@ public KVDocument Deserialize(Stream stream, KVSerializerOptions? options = null
{
ArgumentNullException.ThrowIfNull(stream);

var builder = new KVObjectBuilder(useDictionaryForCollections: format == KVSerializationFormat.KeyValues3Text);
options ??= KVSerializerOptions.DefaultOptions;
var builder = new KVObjectBuilder(useDictionaryForCollections: format == KVSerializationFormat.KeyValues3Text, options.KeyComparer);

using var reader = MakeReader(stream, builder, options ?? KVSerializerOptions.DefaultOptions);
using var reader = MakeReader(stream, builder, options);

var header = reader.ReadHeader();
var result = builder.GetObject();
Expand Down Expand Up @@ -138,7 +139,7 @@ public void Serialize(Stream stream, KVDocument data, KVSerializerOptions? optio

var resolvedOptions = options ?? KVSerializerOptions.DefaultOptions;
var spans = new List<KvSourceSpan>();
var builder = new KVObjectBuilder(useDictionaryForCollections: format == KVSerializationFormat.KeyValues3Text);
var builder = new KVObjectBuilder(useDictionaryForCollections: format == KVSerializationFormat.KeyValues3Text, resolvedOptions.KeyComparer);

using var stringReader = new StringReader(text);
using var reader = MakeSourceMapReader(stringReader, builder, resolvedOptions, spans);
Expand Down
6 changes: 6 additions & 0 deletions ValveKeyValue/ValveKeyValue/KVSerializerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ public sealed class KVSerializerOptions
/// </summary>
public StringTable? StringTable { get; set; }

/// <summary>
/// Gets or sets the comparer that keys of deserialized dictionary-backed collections are looked up with.
/// KV3 text is the format that deserializes into dictionary-backed collections.
/// </summary>
public IEqualityComparer<string>? KeyComparer { get; set; }

/// <summary>
/// Gets the default options (used when none are specified).
/// </summary>
Expand Down
Loading