From 6258bf0c9c35b4b69a383cd820cdabc482494377 Mon Sep 17 00:00:00 2001 From: Nikita Petko Date: Tue, 17 Sep 2024 18:34:03 +0100 Subject: [PATCH] LuaUtility.cs ~ Move Regex for format parts to a GeneratedRegex function to improve performance. ~ Only read the LuaVM template once, as it is read from the resources on every subsequent use. ~ Account for the absence of the LuaVM in results. --- .../lib/utility/Implementation/LuaUtility.cs | 43 ++++++++++++------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/services/grid-bot/lib/utility/Implementation/LuaUtility.cs b/services/grid-bot/lib/utility/Implementation/LuaUtility.cs index 973ce812..a70ce388 100644 --- a/services/grid-bot/lib/utility/Implementation/LuaUtility.cs +++ b/services/grid-bot/lib/utility/Implementation/LuaUtility.cs @@ -14,40 +14,53 @@ /// /// Utility for interacting with grid-server Lua. /// -public class LuaUtility : ILuaUtility +public partial class LuaUtility : ILuaUtility { private static readonly Assembly _assembly = Assembly.GetExecutingAssembly(); private const string _luaVmResource = "Grid.Bot.Lua.LuaVMTemplate.lua"; - private static string FixFormatString(string input) + [GeneratedRegex(@"{{(\d{1,2})}}", RegexOptions.IgnoreCase | RegexOptions.Compiled)] + private static partial Regex FormatPartRegex(); + + + private static readonly string _LuaVM; + + static LuaUtility() { - //language=regex - const string partRegex = @"{{(\d{1,2})}}"; + using var stream = _assembly.GetManifestResourceStream(_luaVmResource); + using var reader = new StreamReader(stream); + _LuaVM = FixFormatString(reader.ReadToEnd()); + } + + private static string FixFormatString(string input) + { input = input.Replace("{", "{{"); input = input.Replace("}", "}}"); - input = Regex.Replace(input, partRegex, (m) => { return $"{{{m.Groups[1]}}}"; }); + input = FormatPartRegex().Replace(input, (m) => { return $"{{{m.Groups[1]}}}"; }); return input; } /// - public string LuaVMTemplate - { - get { - using var stream = _assembly.GetManifestResourceStream(_luaVmResource); - using var reader = new StreamReader(stream); - - return FixFormatString(reader.ReadToEnd()); - } - } + public string LuaVMTemplate => _LuaVM; /// public (string result, ReturnMetadata metadata) ParseResult(IEnumerable result) { + if (result.Count() == 1) + { + // Legacy case, where LuaVM is not enabled. + + var mockMetadata = new ReturnMetadata(); + mockMetadata.Success = true; + + return ((string)Lua.ConvertLua(result.First()), mockMetadata); + } + return ( - (string)Lua.ConvertLua(result.FirstOrDefault()), + (string)Lua.ConvertLua(result.FirstOrDefault()), JsonConvert.DeserializeObject((string)Lua.ConvertLua(result.ElementAtOrDefault(1))) ); }