Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix enum array contains #426

Merged
merged 3 commits into from
Apr 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 28 additions & 2 deletions src/Scriban.Tests/TestFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,32 @@ public void TestSortNoError()
{
TestParser.AssertTemplate("true", "{{ [1,2] || array.sort }}");
}

[Test]
public void TestContains()
{
var mixed = new object[] { "hi", 1, TestEnum.First };
Assert.True(ArrayFunctions.Contains(mixed, "hi"));
Assert.True(ArrayFunctions.Contains(mixed, 1));
Assert.True(ArrayFunctions.Contains(mixed, TestEnum.First));
Assert.True(ArrayFunctions.Contains(mixed, "First"));
Assert.True(ArrayFunctions.Contains(mixed, 100));
TestParser.AssertTemplate("true", "{{ value | array.contains 'First' }}", model: new ObjectModel { Value = mixed });
TestParser.AssertTemplate("true", "{{ value | array.contains 100 }}", model: new ObjectModel { Value = mixed });
TestParser.AssertTemplate("false", "{{ value | array.contains 'Second' }}", model: new ObjectModel { Value = mixed });
TestParser.AssertTemplate("false", "{{ value | array.contains 101 }}", model: new ObjectModel { Value = mixed });
TestParser.AssertTemplate("false", "{{ value | array.contains 'Third' }}", model: new ObjectModel { Value = mixed });
}
class ObjectModel
{
public object[] Value { get; set; }
}

enum TestEnum : int
{
First = 100,
Second = 101
}
}

public class Strings
Expand Down Expand Up @@ -68,7 +94,7 @@ public record IndexOfTestCase(
public void TestIndexOf(IndexOfTestCase testCase)
{
testCase = testCase ?? throw new ArgumentNullException(nameof(testCase));
var args = new []
var args = new[]
{
(Name: "text", Value: MakeString(testCase.Text)),
(Name: "search", Value: MakeString(testCase.Search)),
Expand Down Expand Up @@ -124,7 +150,7 @@ public void TestReplaceFirst(string source, string match, string replace, bool f
true, // fromEnd
"Hello, world. Goodbye, buddy.", // expected
},
// notghing to replace
// nothing to replace
new object [] {
"Hello, world. Goodbye, world.", // source
"xxxx", // match
Expand Down
26 changes: 21 additions & 5 deletions src/Scriban/Functions/ArrayFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using Scriban.Parsing;
using Scriban.Runtime;
Expand Down Expand Up @@ -46,7 +47,7 @@ public static IEnumerable Add(IEnumerable list, object value)
return new ScriptRange { value };
}

return list is IList ? (IEnumerable)new ScriptArray(list) {value} : new ScriptRange(list) {value};
return list is IList ? (IEnumerable)new ScriptArray(list) { value } : new ScriptRange(list) { value };
}


Expand Down Expand Up @@ -149,7 +150,7 @@ public static object Cycle(TemplateContext context, SourceSpan span, IList list,
cycleValue = 0;
}

var cycleIndex = (int) cycleValue;
var cycleIndex = (int)cycleValue;
cycleIndex = list.Count == 0 ? 0 : cycleIndex % list.Count;
object result = null;
if (list.Count > 0)
Expand Down Expand Up @@ -226,7 +227,7 @@ static IEnumerable FilterInternal(TemplateContext context, ScriptNode callerCont
var itemToTransform = context.ToObject(span, item, destType);
arg[0] = itemToTransform;
var itemTransformed = ScriptFunctionCall.Call(context, callerContext, function, arg);
if (context.ToBool(span,itemTransformed))
if (context.ToBool(span, itemTransformed))
yield return itemToTransform;
}
}
Expand Down Expand Up @@ -596,7 +597,7 @@ public static IEnumerable Sort(TemplateContext context, SourceSpan span, object
var enumerable = list as IEnumerable;
if (enumerable == null)
{
return new ScriptArray(1) {list};
return new ScriptArray(1) { list };
}

var realList = enumerable.Cast<object>().ToList();
Expand Down Expand Up @@ -668,10 +669,25 @@ public static IEnumerable Uniq(IEnumerable list)
public static bool Contains(IEnumerable list, object item)
{
foreach (var element in list)
{
if (element == item || (element != null && element.Equals(item))) return true;
if (element is Enum e && CompareEnum(e, item)) return true;
}

return false;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool CompareEnum(Enum e, object item)
{
try
{
if (item is string s) return Enum.Parse(e.GetType(), s)?.Equals(e) ?? false;
return Enum.ToObject(e.GetType(), item)?.Equals(e) ?? false;
}
catch { return false; }
}

/// <summary>
/// Delegate type for function used to process a list
/// </summary>
Expand Down Expand Up @@ -722,7 +738,7 @@ public override bool Equals(object obj)
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((CycleKey) obj);
return Equals((CycleKey)obj);
}

public override int GetHashCode()
Expand Down