Skip to content

Commit

Permalink
Cleanup and optimise
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeyzimarev committed Jun 12, 2024
1 parent d12b00a commit c591ea0
Show file tree
Hide file tree
Showing 73 changed files with 547 additions and 403 deletions.
2 changes: 1 addition & 1 deletion src/RestSharp.Serializers.CsvHelper/CsvHelperSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public CsvHelperSerializer() : this(new CsvConfiguration(CultureInfo.InvariantCu
}

foreach (var record in csvReader.GetRecords(itemType)) {
method.Invoke(result, new[] { record });
method.Invoke(result, [record]);
}

return result;
Expand Down
8 changes: 4 additions & 4 deletions src/RestSharp.Serializers.NewtonsoftJson/JsonNetSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class JsonNetSerializer : IRestSerializer, ISerializer, IDeserializer {
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};

[ThreadStatic] static WriterBuffer? writerBuffer;
[ThreadStatic] static WriterBuffer? _writerBuffer;

readonly JsonSerializer _serializer;

Expand All @@ -52,11 +52,11 @@ public class JsonNetSerializer : IRestSerializer, ISerializer, IDeserializer {
public string? Serialize(object? obj) {
if (obj == null) return null;

using var writerBuffer = JsonNetSerializer.writerBuffer ??= new WriterBuffer(_serializer);
using var buffer = _writerBuffer ??= new WriterBuffer(_serializer);

_serializer.Serialize(writerBuffer.GetJsonTextWriter(), obj, obj.GetType());
_serializer.Serialize(buffer.GetJsonTextWriter(), obj, obj.GetType());

return writerBuffer.GetStringWriter().ToString();
return buffer.GetStringWriter().ToString();
}

public string? Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);
Expand Down
2 changes: 2 additions & 0 deletions src/RestSharp.Serializers.Xml/SerializeAsAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

using System.Globalization;
using RestSharp.Extensions;
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
// ReSharper disable MemberCanBePrivate.Global

// ReSharper disable once CheckNamespace
namespace RestSharp.Serializers;
Expand Down
10 changes: 4 additions & 6 deletions src/RestSharp.Serializers.Xml/XmlDeserializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using System.Xml;
using System.Xml.Linq;
using RestSharp.Extensions;
// ReSharper disable VirtualMemberNeverOverridden.Global

namespace RestSharp.Serializers.Xml;

Expand All @@ -37,7 +38,7 @@ public class XmlDeserializer : IXmlDeserializer, IWithRootElement, IWithDateForm
if (string.IsNullOrEmpty(response.Content))
return default;

var doc = XDocument.Parse(response.Content);
var doc = XDocument.Parse(response.Content!);
var root = doc.Root;
var rootElement = response.RootElement ?? RootElement;

Expand Down Expand Up @@ -161,8 +162,7 @@ protected virtual object Map(object x, XElement? root) {
var asType = type.AsType();

if (asType == typeof(bool)) {
var toConvert = value.ToString()!
.ToLower(Culture);
var toConvert = value.ToString()!.ToLower(Culture);

prop.SetValue(x, XmlConvert.ToBoolean(toConvert), null);
}
Expand Down Expand Up @@ -227,9 +227,7 @@ protected virtual object Map(object x, XElement? root) {
else if (asType == typeof(Guid)) {
var raw = value.ToString();

value = string.IsNullOrEmpty(raw)
? Guid.Empty
: new Guid(value.ToString()!);
value = string.IsNullOrEmpty(raw) ? Guid.Empty : new Guid(value.ToString()!);

prop.SetValue(x, value, null);
}
Expand Down
1 change: 1 addition & 0 deletions src/RestSharp.Serializers.Xml/XmlSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public XmlSerializer() { }
/// Specify the namespaced to be used when serializing
/// </summary>
/// <param name="namespace">XML namespace</param>
[PublicAPI]
public XmlSerializer(string @namespace) => Namespace = @namespace;

/// <summary>
Expand Down
30 changes: 16 additions & 14 deletions src/RestSharp/AsyncHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ static class AsyncHelpers {
/// Executes a task synchronously on the calling thread by installing a temporary synchronization context that queues continuations
/// </summary>
/// <param name="task">Callback for asynchronous task to run</param>
public static void RunSync(Func<Task> task) {
static void RunSync(Func<Task> task) {
var currentContext = SynchronizationContext.Current;
var customContext = new CustomSynchronizationContext(task);

Expand Down Expand Up @@ -80,19 +80,6 @@ public override void Post(SendOrPostCallback function, object? state) {
/// Enqueues the function to be executed and executes all resulting continuations until it is completely done
/// </summary>
public void Run() {
async void PostCallback(object? _) {
try {
await _task().ConfigureAwait(false);
}
catch (Exception exception) {
_caughtException = ExceptionDispatchInfo.Capture(exception);
throw;
}
finally {
Post(_ => _done = true, null);
}
}

Post(PostCallback, null);

while (!_done) {
Expand All @@ -107,6 +94,21 @@ async void PostCallback(object? _) {
_workItemsWaiting.WaitOne();
}
}

return;

async void PostCallback(object? _) {
try {
await _task().ConfigureAwait(false);
}
catch (Exception exception) {
_caughtException = ExceptionDispatchInfo.Capture(exception);
throw;
}
finally {
Post(_ => _done = true, null);
}
}
}

/// <summary>
Expand Down
4 changes: 3 additions & 1 deletion src/RestSharp/Authenticators/OAuth/OAuth1Authenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@
using RestSharp.Authenticators.OAuth;
using RestSharp.Extensions;
using System.Web;
// ReSharper disable PropertyCanBeMadeInitOnly.Global

// ReSharper disable NotResolvedInText
// ReSharper disable CheckNamespace

namespace RestSharp.Authenticators;

/// <seealso href="http://tools.ietf.org/html/rfc5849">RFC: The OAuth 1.0 Protocol</seealso>
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global
public class OAuth1Authenticator : IAuthenticator {
public virtual string? Realm { get; set; }
public virtual OAuthParameterHandling ParameterHandling { get; set; }
Expand Down Expand Up @@ -246,7 +248,7 @@ internal static void AddOAuthData(
var url = client.BuildUri(request).ToString();
var queryStringStart = url.IndexOf('?');

if (queryStringStart != -1) url = url.Substring(0, queryStringStart);
if (queryStringStart != -1) url = url[..queryStringStart];

var method = request.Method.ToString().ToUpperInvariant();
var parameters = new WebPairCollection();
Expand Down
4 changes: 2 additions & 2 deletions src/RestSharp/Authenticators/OAuth/OAuthTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ static class OAuthTools {
/// <summary>
/// The set of characters that are unreserved in RFC 2396 but are NOT unreserved in RFC 3986.
/// </summary>
static readonly string[] UriRfc3986CharsToEscape = { "!", "*", "'", "(", ")" };
static readonly string[] UriRfc3986CharsToEscape = ["!", "*", "'", "(", ")"];

static readonly string[] UriRfc3968EscapedHex = { "%21", "%2A", "%27", "%28", "%29" };
static readonly string[] UriRfc3968EscapedHex = ["%21", "%2A", "%27", "%28", "%29"];

static OAuthTools() {
var bytes = new byte[4];
Expand Down
16 changes: 8 additions & 8 deletions src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,14 @@ WebPairCollection GenerateAuthParameters(string timestamp, string nonce)

WebPairCollection GenerateXAuthParameters(string timestamp, string nonce)
=> [
new("x_auth_username", Ensure.NotNull(ClientUsername, nameof(ClientUsername))),
new("x_auth_password", Ensure.NotNull(ClientPassword, nameof(ClientPassword))),
new("x_auth_mode", "client_auth"),
new("oauth_consumer_key", Ensure.NotNull(ConsumerKey, nameof(ConsumerKey)), true),
new("oauth_signature_method", SignatureMethod.ToRequestValue()),
new("oauth_timestamp", timestamp),
new("oauth_nonce", nonce),
new("oauth_version", Version ?? "1.0")
new WebPair("x_auth_username", Ensure.NotNull(ClientUsername, nameof(ClientUsername))),
new WebPair("x_auth_password", Ensure.NotNull(ClientPassword, nameof(ClientPassword))),
new WebPair("x_auth_mode", "client_auth"),
new WebPair("oauth_consumer_key", Ensure.NotNull(ConsumerKey, nameof(ConsumerKey)), true),
new WebPair("oauth_signature_method", SignatureMethod.ToRequestValue()),
new WebPair("oauth_timestamp", timestamp),
new WebPair("oauth_nonce", nonce),
new WebPair("oauth_version", Version ?? "1.0")
];

internal class OAuthParameters {
Expand Down
2 changes: 1 addition & 1 deletion src/RestSharp/Authenticators/OAuth/WebPairCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
namespace RestSharp.Authenticators.OAuth;

class WebPairCollection : IList<WebPair> {
readonly List<WebPair> _parameters = new();
readonly List<WebPair> _parameters = [];

public IEnumerator<WebPair> GetEnumerator() => _parameters.GetEnumerator();

Expand Down
2 changes: 1 addition & 1 deletion src/RestSharp/BuildUriExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ string EncodeParameter(Parameter parameter)
}

static void DoBuildUriValidations(IRestClient client, RestRequest request) {
if (client.Options.BaseUrl == null && !request.Resource.ToLowerInvariant().StartsWith("http"))
if (client.Options.BaseUrl == null && !request.Resource.StartsWith("http", StringComparison.InvariantCultureIgnoreCase))
throw new ArgumentOutOfRangeException(
nameof(request),
"Request resource doesn't contain a valid scheme for an empty base URL of the client"
Expand Down
10 changes: 3 additions & 7 deletions src/RestSharp/ContentType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public class ContentType : IEquatable<ContentType> {

public override string ToString() => Value;

public static implicit operator ContentType(string? contentType) => contentType == null ? Undefined : new(contentType);
public static implicit operator ContentType(string? contentType) => contentType == null ? Undefined : new ContentType(contentType);

public static implicit operator string(ContentType contentType) => contentType.Value;

Expand All @@ -59,13 +59,9 @@ public class ContentType : IEquatable<ContentType> {
{ DataFormat.Binary, Binary }
};

public static readonly string[] JsonAccept = {
Json, "text/json", "text/x-json", "text/javascript"
};
public static readonly string[] JsonAccept = [Json, "text/json", "text/x-json", "text/javascript"];

public static readonly string[] XmlAccept = {
Xml, "text/xml"
};
public static readonly string[] XmlAccept = [Xml, "text/xml"];

readonly string _value;

Expand Down
2 changes: 1 addition & 1 deletion src/RestSharp/Ensure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ public static string NotEmptyString(object? value, [InvokerParameterName] string
var s = value as string ?? value?.ToString();
return string.IsNullOrWhiteSpace(s) ? throw new ArgumentNullException(name) : s!;
}
}
}
1 change: 0 additions & 1 deletion src/RestSharp/Enum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Net;

namespace RestSharp;

Expand Down
4 changes: 2 additions & 2 deletions src/RestSharp/Extensions/GenerateImmutableAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
namespace RestSharp.Extensions;

[AttributeUsage(AttributeTargets.Class)]
class GenerateImmutableAttribute : Attribute { }
class GenerateImmutableAttribute : Attribute;

[AttributeUsage(AttributeTargets.Property)]
class Exclude : Attribute { }
class Exclude : Attribute;
95 changes: 79 additions & 16 deletions src/RestSharp/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,21 @@

namespace RestSharp.Extensions;

static class StringExtensions {
static readonly Regex IsUpperCaseRegex = new(@"^[A-Z]+$");
// ReSharper disable once PartialTypeWithSinglePart
static partial class StringExtensions {
static readonly Regex IsUpperCaseRegex = IsUpperCase();

static readonly Regex AddUnderscoresRegex1 = new(@"[-\s]");
static readonly Regex AddUnderscoresRegex2 = new(@"([a-z\d])([A-Z])");
static readonly Regex AddUnderscoresRegex3 = new(@"([A-Z]+)([A-Z][a-z])");
static readonly Regex AddUnderscoresRegex1 = AddUnderscores1();
static readonly Regex AddUnderscoresRegex2 = AddUnderscores2();
static readonly Regex AddUnderscoresRegex3 = AddUnderscores3();

static readonly Regex AddDashesRegex1 = new(@"[\s]");
static readonly Regex AddDashesRegex2 = new(@"([a-z\d])([A-Z])");
static readonly Regex AddDashesRegex3 = new(@"([A-Z]+)([A-Z][a-z])");
static readonly Regex AddDashesRegex1 = AddDashes1();
static readonly Regex AddDashesRegex2 = AddDashes2();
static readonly Regex AddDashesRegex3 = AddDashes3();

static readonly Regex AddSpacesRegex1 = new(@"[-\s]");
static readonly Regex AddSpacesRegex2 = new(@"([a-z\d])([A-Z])");
static readonly Regex AddSpacesRegex3 = new(@"([A-Z]+)([A-Z][a-z])");
static readonly Regex AddSpacesRegex1 = AddSpaces1();
static readonly Regex AddSpacesRegex2 = AddSpaces2();
static readonly Regex AddSpacesRegex3 = AddSpaces3();

internal static string UrlDecode(this string input) => HttpUtility.UrlDecode(input);

Expand Down Expand Up @@ -67,7 +68,7 @@ internal static string UrlEncode(this string input) {
return sb.ToString();
}

internal static string? UrlEncode(this string input, Encoding encoding) {
internal static string? UrlEncode(this string? input, Encoding encoding) {
var encoded = HttpUtility.UrlEncode(input, encoding);
return encoded?.Replace("+", "%20");
}
Expand All @@ -91,7 +92,7 @@ internal static string ToPascalCase(this string text, bool removeUnderscores, Cu
.JoinToString(joinString);

string CaseWord(string word) {
var restOfWord = word.Substring(1);
var restOfWord = word[1..];
var firstChar = char.ToUpper(word[0], culture);

if (restOfWord.IsUpperCase()) restOfWord = restOfWord.ToLower(culture);
Expand Down Expand Up @@ -151,8 +152,7 @@ internal static IEnumerable<string> GetNameVariants(this string name, CultureInf

internal static string JoinToString(this IEnumerable<string> strings, string separator) => string.Join(separator, strings);

static string MakeInitialLowerCase(this string word, CultureInfo culture)
=> string.Concat(word.Substring(0, 1).ToLower(culture), word.Substring(1));
static string MakeInitialLowerCase(this string word, CultureInfo culture) => string.Concat(word[..1].ToLower(culture), word[1..]);

static string AddUnderscores(this string pascalCasedWord)
=> AddUnderscoresRegex1.Replace(
Expand Down Expand Up @@ -184,4 +184,67 @@ static string AddSpaces(this string pascalCasedWord)
),
" "
);
}

const string RIsUpperCase = "^[A-Z]+$";
const string RAddUnderscore1 = @"[-\s]";
const string RAddUnderscore2 = @"([a-z\d])([A-Z])";
const string RAddUnderscore3 = "([A-Z]+)([A-Z][a-z])";
const string RAddDashes1 = @"[\s]";
const string RAddDashes2 = @"([a-z\d])([A-Z])";
const string RAddDashes3 = "([A-Z]+)([A-Z][a-z])";
const string RAddSpaces1 = @"[-\s]";
const string RAddSpaces2 = @"([a-z\d])([A-Z])";
const string RAddSpaces3 = "([A-Z]+)([A-Z][a-z])";

#if NET7_0_OR_GREATER
[GeneratedRegex(RIsUpperCase)]
private static partial Regex IsUpperCase();

[GeneratedRegex(RAddUnderscore1)]
private static partial Regex AddUnderscores1();

[GeneratedRegex(RAddUnderscore2)]
private static partial Regex AddUnderscores2();

[GeneratedRegex(RAddUnderscore3)]
private static partial Regex AddUnderscores3();

[GeneratedRegex(RAddDashes1)]
private static partial Regex AddDashes1();

[GeneratedRegex(RAddDashes2)]
private static partial Regex AddDashes2();

[GeneratedRegex(RAddDashes3)]
private static partial Regex AddDashes3();

[GeneratedRegex(RAddSpaces1)]
private static partial Regex AddSpaces1();

[GeneratedRegex(RAddSpaces2)]
private static partial Regex AddSpaces2();

[GeneratedRegex(RAddSpaces3)]
private static partial Regex AddSpaces3();
#else
static Regex IsUpperCase() => new(RIsUpperCase);

static Regex AddUnderscores1() => new(RAddUnderscore1);

static Regex AddUnderscores2() => new(RAddUnderscore2);

static Regex AddUnderscores3() => new(RAddUnderscore3);

static Regex AddDashes1() => new(RAddDashes1);

static Regex AddDashes2() => new(RAddDashes2);

static Regex AddDashes3() => new(RAddDashes3);

static Regex AddSpaces1() => new(RAddSpaces1);

static Regex AddSpaces2() => new(RAddSpaces1);

static Regex AddSpaces3() => new(RAddSpaces1);
#endif
}
Loading

0 comments on commit c591ea0

Please sign in to comment.