From ba04246a16c66c532598df3f072f7e7ccba7d5ac Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Fri, 13 Jan 2017 01:07:13 +1300 Subject: [PATCH] -Improved SplitFullyQualifiedTypeName allocations --- .../Utilities/ReflectionUtils.cs | 4 +- Src/Newtonsoft.Json/Utilities/StringUtils.cs | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs index 6c1057bd..03a445df 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -866,8 +866,8 @@ namespace Newtonsoft.Json.Utilities if (assemblyDelimiterIndex != null) { - typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.GetValueOrDefault()).Trim(); - assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.GetValueOrDefault() + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.GetValueOrDefault() - 1).Trim(); + typeName = fullyQualifiedTypeName.Trim(0, assemblyDelimiterIndex.GetValueOrDefault()); + assemblyName = fullyQualifiedTypeName.Trim(assemblyDelimiterIndex.GetValueOrDefault() + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.GetValueOrDefault() - 1); } else { diff --git a/Src/Newtonsoft.Json/Utilities/StringUtils.cs b/Src/Newtonsoft.Json/Utilities/StringUtils.cs index cd3877a4..aaf6c2d8 100644 --- a/Src/Newtonsoft.Json/Utilities/StringUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/StringUtils.cs @@ -285,5 +285,43 @@ namespace Newtonsoft.Json.Utilities { return (source.Length > 0 && source[source.Length - 1] == value); } + + public static string Trim(this string s, int start, int length) + { + // References: https://referencesource.microsoft.com/#mscorlib/system/string.cs,2691 + // https://referencesource.microsoft.com/#mscorlib/system/string.cs,1226 + if (s == null) + { + throw new ArgumentNullException(); + } + if (start < 0) + { + throw new ArgumentOutOfRangeException(nameof(start)); + } + if (length < 0) + { + throw new ArgumentOutOfRangeException(nameof(length)); + } + int end = start + length - 1; + if (end >= s.Length) + { + throw new ArgumentOutOfRangeException(nameof(length)); + } + for (; start < end; start++) + { + if (!char.IsWhiteSpace(s[start])) + { + break; + } + } + for (; end >= start; end--) + { + if (!char.IsWhiteSpace(s[end])) + { + break; + } + } + return s.Substring(start, end - start + 1); + } } } \ No newline at end of file