diff --git a/src/Discord.Net.Commands/Map/CommandMap.cs b/src/Discord.Net.Commands/Map/CommandMap.cs index 5cf667903..98ff297b0 100644 --- a/src/Discord.Net.Commands/Map/CommandMap.cs +++ b/src/Discord.Net.Commands/Map/CommandMap.cs @@ -6,6 +6,8 @@ namespace Discord.Commands { internal class CommandMap { + static readonly char[] _whitespaceChars = new char[] { ' ', '\r', '\n' }; + private readonly ConcurrentDictionary _nodes; public CommandMap() @@ -16,15 +18,16 @@ namespace Discord.Commands public void AddCommand(Command command) { string text = command.Text; - int nextSpace = text.IndexOf(' '); + int nextSpace = NextWhitespace(text); string name; + if (nextSpace == -1) + name = command.Text; + else + name = command.Text.Substring(0, nextSpace); + lock (this) { - if (nextSpace == -1) - name = command.Text; - else - name = command.Text.Substring(0, nextSpace); var nextNode = _nodes.GetOrAdd(name, x => new CommandMapNode(x)); nextNode.AddCommand(nextSpace == -1 ? "" : text, nextSpace + 1, command); } @@ -32,16 +35,16 @@ namespace Discord.Commands public void RemoveCommand(Command command) { string text = command.Text; - int nextSpace = text.IndexOf(' '); + int nextSpace = NextWhitespace(text); string name; + if (nextSpace == -1) + name = command.Text; + else + name = command.Text.Substring(0, nextSpace); + lock (this) { - if (nextSpace == -1) - name = command.Text; - else - name = command.Text.Substring(0, nextSpace); - CommandMapNode nextNode; if (_nodes.TryGetValue(name, out nextNode)) { @@ -54,16 +57,16 @@ namespace Discord.Commands public IEnumerable GetCommands(string text) { - int nextSpace = text.IndexOf(' '); + int nextSpace = NextWhitespace(text); string name; + if (nextSpace == -1) + name = text; + else + name = text.Substring(0, nextSpace); + lock (this) { - if (nextSpace == -1) - name = text; - else - name = text.Substring(0, nextSpace); - CommandMapNode nextNode; if (_nodes.TryGetValue(name, out nextNode)) return nextNode.GetCommands(text, nextSpace + 1); @@ -71,5 +74,17 @@ namespace Discord.Commands return Enumerable.Empty(); } } + + private static int NextWhitespace(string text) + { + int lowest = int.MaxValue; + for (int i = 0; i < _whitespaceChars.Length; i++) + { + int index = text.IndexOf(_whitespaceChars[i]); + if (index != -1 && index < lowest) + lowest = index; + } + return (lowest != int.MaxValue) ? lowest : -1; + } } }