Skip to content

Commit

Permalink
Reduce state machines in RawStatement
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma committed Apr 8, 2021
1 parent ac8608b commit ef8bfae
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 12 deletions.
19 changes: 11 additions & 8 deletions Fluid/Ast/RawStatement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,20 @@ public RawStatement(in TextSpan text)

public ref readonly TextSpan Text => ref _text;

public override async ValueTask<Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext context)
public override ValueTask<Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext context)
{
static async ValueTask<Completion> Awaited(Task task)
{
await task;
return Completion.Normal;
}

context.IncrementSteps();

#if NETSTANDARD2_0
await writer.WriteAsync(_text.ToString());
#else
await writer.WriteAsync(_text.Span.ToArray());
#endif

return Completion.Normal;
var task = writer.WriteAsync(_text.ToString());
return task.IsCompletedSuccessfully
? new ValueTask<Completion>(Completion.Normal)
: Awaited(task);
}
}
}
8 changes: 7 additions & 1 deletion Fluid/ExceptionHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,15 @@ public static void ThrowParseException<T>(string message)
throw new ParseException(message);
}

[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ThrowMaximumStatementsException()
{
throw new InvalidOperationException("The maximum number of statements has been reached. Your script took too long to run.");
}

#if NETSTANDARD2_0
private class DoesNotReturnAttribute : Attribute {}
#endif

}
}
5 changes: 3 additions & 2 deletions Fluid/TemplateContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,10 @@ public TemplateContext(object model) : this()

internal void IncrementSteps()
{
if (Options.MaxSteps != 0 && _steps++ > Options.MaxSteps)
var maxSteps = Options.MaxSteps;
if (maxSteps > 0 && _steps++ > maxSteps)
{
throw new InvalidOperationException("The maximum number of statements has been reached. Your script took too long to run.");
ExceptionHelper.ThrowMaximumStatementsException();
}
}

Expand Down
2 changes: 1 addition & 1 deletion Fluid/TemplateOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class TemplateOptions
/// <summary>
/// Gets or sets the maximum number of steps a script can execute. Leave to 0 for unlimited.
/// </summary>
public int MaxSteps { get; set; } = 0;
public int MaxSteps { get; set; }

/// <summary>
/// Gets or sets the <see cref="CultureInfo"/> instance used to render locale values like dates and numbers.
Expand Down

0 comments on commit ef8bfae

Please sign in to comment.