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
51 changes: 51 additions & 0 deletions source/Handlebars.Test/Collections/FixedSizeDictionaryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,57 @@ public void CanAddAfterClear()
}
}

[Fact]
public void AdjustIndexesCarriesLiveIndexes()
{
var source = new FixedSizeDictionary<object, object, CollisionsComparer>(16, 7, new CollisionsComparer(0));
var destination = new FixedSizeDictionary<object, object, CollisionsComparer>(16, 7, new CollisionsComparer(0));
var sourceIndexes = new EntryIndex<object>[2];
var targetIndexes = new EntryIndex<object>[2];

source.AddOrReplace(new object(), "value", out sourceIndexes[0]);
source.CopyTo(destination);
source.AdjustIndexes(sourceIndexes, destination, targetIndexes);

Assert.True(destination.TryGetValue(targetIndexes[0], out var value));
Assert.Equal("value", value);
}

// https://github.com/Handlebars-Net/Handlebars.Net/issues/707
[Fact]
public void AdjustIndexesKeepsEmptyIndexesEmpty()
{
var source = new FixedSizeDictionary<object, object, CollisionsComparer>(16, 7, new CollisionsComparer(0));
var destination = new FixedSizeDictionary<object, object, CollisionsComparer>(16, 7, new CollisionsComparer(0));
var sourceIndexes = new EntryIndex<object>[2];
var targetIndexes = new EntryIndex<object>[2];

// occupies slot 0, which an empty index would otherwise be restamped to point at
destination.AddOrReplace(new object(), "other key", out _);
source.AdjustIndexes(sourceIndexes, destination, targetIndexes);

Assert.False(targetIndexes[1].IsNotEmpty);
Assert.False(destination.TryGetValue(targetIndexes[1], out _));
}

// https://github.com/Handlebars-Net/Handlebars.Net/issues/707
[Fact]
public void AdjustIndexesDropsStaleIndexes()
{
var source = new FixedSizeDictionary<object, object, CollisionsComparer>(16, 7, new CollisionsComparer(0));
var destination = new FixedSizeDictionary<object, object, CollisionsComparer>(16, 7, new CollisionsComparer(0));
var sourceIndexes = new EntryIndex<object>[2];
var targetIndexes = new EntryIndex<object>[2];

source.AddOrReplace(new object(), "previous use", out sourceIndexes[0]);
source.Reset();
destination.AddOrReplace(new object(), "other key", out _);
source.AdjustIndexes(sourceIndexes, destination, targetIndexes);

Assert.False(targetIndexes[0].IsNotEmpty);
Assert.False(destination.TryGetValue(targetIndexes[0], out _));
}

public void Dispose()
{
FixedSizeDictionary.OptionalClear();
Expand Down
62 changes: 62 additions & 0 deletions source/Handlebars.Test/DataVariableTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using HandlebarsDotNet.PathStructure;
using Xunit;

namespace HandlebarsDotNet.Test
{
// Data variables (`@index`, `@key`, `@first`, ...) are cached per frame as entry indexes into the
// frame's data dictionary. These tests check that an unset data variable never resolves to the
// value stored under a different key. See https://github.com/Handlebars-Net/Handlebars.Net/issues/707
public class DataVariableTests
{
// Must match BindingContext's ContextDataObject: 16 buckets of 7 entries.
private const int BucketsCount = 16;
private const int BucketSize = 7;

[Fact]
public void UnsetDataVariableInChildFrameDoesNotResolveToAnotherDataKey()
{
var key = FindKeyForSlot(0);
var data = new Dictionary<string, object> { [key] = "WRONG" };

var template = Handlebars.Create().Compile("{{#with this}}[{{@index}}|{{@key}}|{{@first}}|{{@last}}]{{/with}}");

Assert.Equal("[|||]", template(new { a = 1 }, data));
}

[Fact]
public void UnsetDataVariableNeverResolvesToAnotherDataKeyAcrossPooledReuse()
{
var handlebars = Handlebars.Create();
var populate = handlebars.Compile("{{#each this}}{{@index}}{{/each}}");
var probe = handlebars.Compile("[{{@index}}]{{#with this}}[{{@index}}]{{/with}}");

// `populate` stores @index at its home slot; put another key there (and at slot 0) for `probe`,
// so a leftover index from an earlier render would point at a live entry.
var data = new Dictionary<string, object>
{
[FindKeyForSlot(SlotOf(ChainSegment.Index.GetHashCode()))] = "WRONG",
[FindKeyForSlot(0)] = "WRONG"
};

// Enough renders for the data dictionaries' byte versions to wrap several times.
for (var i = 0; i < 2000; i++)
{
populate(new[] { 1, 2, 3 });

Check warning on line 46 in source/Handlebars.Test/DataVariableTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array

See more on https://sonarcloud.io/project/issues?id=Handlebars-Net_Handlebars.Net&issues=AaIaHK4J_QlF9L2mPqlH&open=AaIaHK4J_QlF9L2mPqlH&pullRequest=708
Assert.Equal("[][]", probe(new { a = 1 }, data));
}
}

private static string FindKeyForSlot(int slot)
{
for (var i = 0; ; i++)
{
var key = "k" + i;
if (SlotOf(ChainSegment.Create(key).GetHashCode()) == slot) return key;
}
}

private static int SlotOf(int hash) => (hash & (BucketsCount - 1)) * BucketSize + Math.Abs(hash % BucketSize);
}
}
8 changes: 7 additions & 1 deletion source/Handlebars/Collections/FixedSizeDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,13 @@ public void AdjustIndexes(EntryIndex<TKey>[] source, FixedSizeDictionary<TKey, T

for (var i = 0; i < source.Length; i++)
{
target[i] = new EntryIndex<TKey>(source[i].Index, destination._version);
// Only carry over indexes that are live in this dictionary. Restamping an empty or stale
// index with the destination's version would make it point at whatever entry sits in
// that slot, under a different key.
var index = source[i];
target[i] = index.IsNotEmpty && index.Version == _version
? new EntryIndex<TKey>(index.Index, destination._version)
: default;
}
}

Expand Down
6 changes: 5 additions & 1 deletion source/Handlebars/Pools/BindingContext.Pool.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using HandlebarsDotNet.Compiler;
using HandlebarsDotNet.Pools;

Expand Down Expand Up @@ -60,7 +61,10 @@ public bool Return(BindingContext item)

item.BlockParamsObject.OptionalClear();
item.ContextDataObject.OptionalClear();

// Indexes into ContextDataObject from this use must not survive into the next one:
// once the dictionary's byte version wraps they would look current again.
Array.Clear(item.WellKnownVariables, 0, item.WellKnownVariables.Length);

item.Descriptor.Reset();

return true;
Expand Down
Loading