From 888a1a3fbd389c03b6123808e1167b52a7be71fb Mon Sep 17 00:00:00 2001 From: Todd Menier Date: Mon, 25 Jul 2016 10:36:03 -0500 Subject: [PATCH] replace usage of string.Split(char[], int), not supported in full PCL profile (#119) --- Test/Flurl.Test.Shared/CommonExtensionsTests.cs | 9 +++++++++ src/Flurl.Shared/Url.cs | 6 +++--- src/Flurl.Shared/Util/CommonExtensions.cs | 14 ++++++++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/Test/Flurl.Test.Shared/CommonExtensionsTests.cs b/Test/Flurl.Test.Shared/CommonExtensionsTests.cs index 4150c26..d836e62 100644 --- a/Test/Flurl.Test.Shared/CommonExtensionsTests.cs +++ b/Test/Flurl.Test.Shared/CommonExtensionsTests.cs @@ -101,5 +101,14 @@ namespace Flurl.Test }; Assert.Throws(() => kv.ToKeyValuePairs().ToList());// need to force it to iterate for the exception to be thrown } + +// todo: why can't netcore test app find SplitOnFirstOccurence? (making it public doesn't help) +#if !NETCOREAPP1_0 + [Test] + public void SplitOnFirstOccurence_works() { + var result = "hello/how/are/you".SplitOnFirstOccurence('/'); + Assert.AreEqual(new[] { "hello", "how/are/you" }, result); + } +#endif } } diff --git a/src/Flurl.Shared/Url.cs b/src/Flurl.Shared/Url.cs index 20c8363..9c00ccc 100644 --- a/src/Flurl.Shared/Url.cs +++ b/src/Flurl.Shared/Url.cs @@ -42,9 +42,9 @@ namespace Flurl if (baseUrl == null) throw new ArgumentNullException(nameof(baseUrl)); - var parts = baseUrl.Split(new[] { '#' }, 2); + var parts = baseUrl.SplitOnFirstOccurence('#'); Fragment = (parts.Length == 2) ? parts[1] : ""; - parts = parts[0].Split(new[] { '?' }, 2); + parts = parts[0].SplitOnFirstOccurence('?'); Query = (parts.Length == 2) ? parts[1] : ""; Path = parts[0]; } @@ -62,7 +62,7 @@ namespace Flurl result.AddRange( from p in query.Split('&') - let pair = p.Split(new[] { '=' }, 2) + let pair = p.SplitOnFirstOccurence('=') let name = pair[0] let value = (pair.Length == 1) ? "" : pair[1] select new QueryParameter(name, value, true)); diff --git a/src/Flurl.Shared/Util/CommonExtensions.cs b/src/Flurl.Shared/Util/CommonExtensions.cs index ab8c78a..a73c953 100644 --- a/src/Flurl.Shared/Util/CommonExtensions.cs +++ b/src/Flurl.Shared/Util/CommonExtensions.cs @@ -48,6 +48,20 @@ namespace Flurl.Util return obj.ToString(); } + /// + /// Needed because full PCL profile doesn't support Split(char[], int) (#119) + /// + internal static string[] SplitOnFirstOccurence(this string s, char separator) { + if (string.IsNullOrEmpty(s)) + return new[] { s }; + + var i = s.IndexOf(separator); + if (i == -1) + return new[] { s }; + + return new[] { s.Substring(0, i), s.Substring(i + 1) }; + } + private static IEnumerable> StringToKV(string s) { return Url.ParseQueryParams(s).Select(p => new KeyValuePair(p.Name, p.Value)); }