Skip to content

Commit 6b8ec46

Browse files
committed
Use target-typed new.
1 parent 7bfef49 commit 6b8ec46

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+182
-182
lines changed

src/MySqlConnector.Logging.Serilog/SerilogLoggerProvider.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public void Log(MySqlConnectorLogLevel level, string message, object[] args = nu
4747
_ => throw new ArgumentOutOfRangeException(nameof(level), level, "Invalid value for 'level'."),
4848
};
4949

50-
static readonly Regex tokenReplacer = new Regex(@"((\w+)?\s?(?:=|:)?\s?'?)\{(?:\d+)(\:\w+)?\}('?)", RegexOptions.Compiled);
50+
static readonly Regex tokenReplacer = new(@"((\w+)?\s?(?:=|:)?\s?'?)\{(?:\d+)(\:\w+)?\}('?)", RegexOptions.Compiled);
5151

5252
readonly ILogger m_logger;
5353
readonly string m_name;

src/MySqlConnector/Core/CommandExecutor.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public static async Task<MySqlDataReader> ExecuteReaderAsync(IReadOnlyList<IMySq
3131
{
3232
if (command2.CommandType == CommandType.StoredProcedure)
3333
{
34-
cachedProcedures ??= new Dictionary<string, CachedProcedure?>();
34+
cachedProcedures ??= new();
3535
var commandText = command2.CommandText!;
3636
if (!cachedProcedures.ContainsKey(commandText))
3737
{

src/MySqlConnector/Core/ConnectionPool.cs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ public async ValueTask<ServerSession> GetSessionAsync(MySqlConnection connection
9090
else
9191
{
9292
// pooled session is ready to be used; return it
93-
session.OwningConnection = new WeakReference<MySqlConnection>(connection);
93+
session.OwningConnection = new(connection);
9494
int leasedSessionsCountPooled;
9595
lock (m_leasedSessions)
9696
{
@@ -104,12 +104,12 @@ public async ValueTask<ServerSession> GetSessionAsync(MySqlConnection connection
104104
}
105105

106106
// create a new session
107-
session = new ServerSession(this, m_generation, Interlocked.Increment(ref m_lastSessionId));
107+
session = new(this, m_generation, Interlocked.Increment(ref m_lastSessionId));
108108
if (Log.IsInfoEnabled())
109109
Log.Info("Pool{0} no pooled session available; created new Session{1}", m_logArguments[0], session.Id);
110110
await session.ConnectAsync(ConnectionSettings, startTickCount, m_loadBalancer, ioBehavior, cancellationToken).ConfigureAwait(false);
111111
AdjustHostConnectionCount(session, 1);
112-
session.OwningConnection = new WeakReference<MySqlConnection>(connection);
112+
session.OwningConnection = new(connection);
113113
int leasedSessionsCountNew;
114114
lock (m_leasedSessions)
115115
{
@@ -376,7 +376,7 @@ private async Task CreateMinimumPooledSessions(IOBehavior ioBehavior, Cancellati
376376
// check if pool has already been created for this exact connection string
377377
if (s_pools.TryGetValue(connectionString, out var pool))
378378
{
379-
s_mruCache = new ConnectionStringPool(connectionString, pool);
379+
s_mruCache = new(connectionString, pool);
380380
return pool;
381381
}
382382

@@ -385,7 +385,7 @@ private async Task CreateMinimumPooledSessions(IOBehavior ioBehavior, Cancellati
385385
if (!connectionStringBuilder.Pooling)
386386
{
387387
s_pools.GetOrAdd(connectionString, default(ConnectionPool));
388-
s_mruCache = new ConnectionStringPool(connectionString, null);
388+
s_mruCache = new(connectionString, null);
389389
return null;
390390
}
391391

@@ -396,7 +396,7 @@ private async Task CreateMinimumPooledSessions(IOBehavior ioBehavior, Cancellati
396396
// try to set the pool for the connection string to the canonical pool; if someone else
397397
// beats us to it, just use the existing value
398398
pool = s_pools.GetOrAdd(connectionString, pool)!;
399-
s_mruCache = new ConnectionStringPool(connectionString, pool);
399+
s_mruCache = new(connectionString, pool);
400400
return pool;
401401
}
402402

@@ -407,7 +407,7 @@ private async Task CreateMinimumPooledSessions(IOBehavior ioBehavior, Cancellati
407407

408408
if (pool == newPool)
409409
{
410-
s_mruCache = new ConnectionStringPool(connectionString, pool);
410+
s_mruCache = new(connectionString, pool);
411411
pool.StartReaperTask();
412412

413413
// if we won the race to create the new pool, also store it under the original connection string
@@ -445,13 +445,13 @@ private ConnectionPool(ConnectionSettings cs)
445445
ConnectionSettings = cs;
446446
SslProtocols = cs.TlsVersions;
447447
m_generation = 0;
448-
m_cleanSemaphore = new SemaphoreSlim(1);
449-
m_sessionSemaphore = new SemaphoreSlim(cs.MaximumPoolSize);
450-
m_sessions = new LinkedList<ServerSession>();
451-
m_leasedSessions = new Dictionary<string, ServerSession>();
448+
m_cleanSemaphore = new(1);
449+
m_sessionSemaphore = new(cs.MaximumPoolSize);
450+
m_sessions = new();
451+
m_leasedSessions = new();
452452
if (cs.ConnectionProtocol == MySqlConnectionProtocol.Sockets && cs.LoadBalance == MySqlLoadBalance.LeastConnections)
453453
{
454-
m_hostSessions = new Dictionary<string, int>();
454+
m_hostSessions = new();
455455
foreach (var hostName in cs.HostNames!)
456456
m_hostSessions[hostName] = 0;
457457
}

src/MySqlConnector/Core/ILoadBalancer.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,14 @@ public IEnumerable<string> LoadBalance(IReadOnlyList<string> hosts)
4646
return shuffled;
4747
}
4848

49-
private RandomLoadBalancer() => m_random = new Random();
49+
private RandomLoadBalancer() => m_random = new();
5050

5151
readonly Random m_random;
5252
}
5353

5454
internal sealed class RoundRobinLoadBalancer : ILoadBalancer
5555
{
56-
public RoundRobinLoadBalancer() => m_lock = new object();
56+
public RoundRobinLoadBalancer() => m_lock = new();
5757

5858
public IEnumerable<string> LoadBalance(IReadOnlyList<string> hosts)
5959
{

src/MySqlConnector/Core/ParsedStatement.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,12 @@ internal sealed class ParsedStatement
1818
/// The names of the parameters (if known) of the parameters in the prepared statement. There
1919
/// is one entry in this list for each parameter, which will be <c>null</c> if the name is unknown.
2020
/// </summary>
21-
public List<string?> ParameterNames { get; } = new List<string?>();
21+
public List<string?> ParameterNames { get; } = new();
2222

2323
/// <summary>
2424
/// The indexes of the parameters in the prepared statement. There is one entry in this list for
2525
/// each parameter; it will be <c>-1</c> if the parameter is named.
2626
/// </summary>
27-
public List<int> ParameterIndexes { get; }= new List<int>();
27+
public List<int> ParameterIndexes { get; }= new();
2828
}
2929
}

src/MySqlConnector/Core/ResultSet.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ public async Task ReadResultSetHeaderAsync(IOBehavior ioBehavior)
8888
int byteCount;
8989
while ((byteCount = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
9090
{
91-
payload = new PayloadData(new ArraySegment<byte>(buffer, 0, byteCount));
91+
payload = new(new ArraySegment<byte>(buffer, 0, byteCount));
9292
await Session.SendReplyAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false);
9393
}
9494
}
@@ -110,7 +110,7 @@ public async Task ReadResultSetHeaderAsync(IOBehavior ioBehavior)
110110
catch (Exception ex)
111111
{
112112
// store the exception, to be thrown after reading the response packet from the server
113-
ReadResultSetHeaderException = new MySqlException("Error during LOAD DATA LOCAL INFILE", ex);
113+
ReadResultSetHeaderException = new("Error during LOAD DATA LOCAL INFILE", ex);
114114
}
115115

116116
await Session.SendReplyAsync(EmptyPayload.Instance, ioBehavior, CancellationToken.None).ConfigureAwait(false);
@@ -219,7 +219,7 @@ public async Task<bool> ReadAsync(IOBehavior ioBehavior, CancellationToken cance
219219
var row = await ScanRowAsync(ioBehavior, null, cancellationToken).ConfigureAwait(false);
220220
if (row is null)
221221
return null;
222-
m_readBuffer ??= new Queue<Row>();
222+
m_readBuffer ??= new();
223223
m_readBuffer.Enqueue(row);
224224
return row;
225225
}

src/MySqlConnector/Core/SchemaProvider.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ internal sealed class SchemaProvider
1212
public SchemaProvider(MySqlConnection connection)
1313
{
1414
m_connection = connection;
15-
m_schemaCollections = new Dictionary<string, Action<DataTable>>
15+
m_schemaCollections = new()
1616
{
1717
{ "DataSourceInformation", FillDataSourceInformation},
1818
{ "MetaDataCollections", FillMetadataCollections },

src/MySqlConnector/Core/ServerSession.cs

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@ public ServerSession()
3737

3838
public ServerSession(ConnectionPool? pool, int poolGeneration, int id)
3939
{
40-
m_lock = new object();
41-
m_payloadCache = new ArraySegmentHolder<byte>();
40+
m_lock = new();
41+
m_payloadCache = new();
4242
Id = (pool?.Id ?? 0) + "." + id;
4343
ServerVersion = ServerVersion.Empty;
4444
CreatedTicks = unchecked((uint) Environment.TickCount);
@@ -224,7 +224,7 @@ public async Task PrepareAsync(IMySqlCommand command, IOBehavior ioBehavior, Can
224224
preparedStatements.Add(new(response.StatementId, statement, columns, parameters));
225225
}
226226

227-
m_preparedStatements ??= new Dictionary<string, PreparedStatements>();
227+
m_preparedStatements ??= new();
228228
m_preparedStatements.Add(commandText, new(preparedStatements, parsedStatements));
229229
}
230230

@@ -399,7 +399,7 @@ public async Task ConnectAsync(ConnectionSettings cs, int startTickCount, ILoadB
399399
throw new NotSupportedException("Authentication method '{0}' is not supported.".FormatInvariant(initialHandshake.AuthPluginName));
400400
}
401401

402-
ServerVersion = new ServerVersion(initialHandshake.ServerVersion);
402+
ServerVersion = new(initialHandshake.ServerVersion);
403403
ConnectionId = initialHandshake.ConnectionId;
404404
AuthPluginData = initialHandshake.AuthPluginData;
405405
m_useCompression = cs.UseCompression && (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.Compress) != 0;
@@ -561,7 +561,7 @@ private async Task<PayloadData> SwitchAuthenticationAsync(ConnectionSettings cs,
561561
case "mysql_native_password":
562562
AuthPluginData = switchRequest.Data;
563563
var hashedPassword = AuthenticationUtility.CreateAuthenticationResponse(AuthPluginData, cs.Password);
564-
payload = new PayloadData(hashedPassword);
564+
payload = new(hashedPassword);
565565
await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);
566566
return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
567567

@@ -574,13 +574,13 @@ private async Task<PayloadData> SwitchAuthenticationAsync(ConnectionSettings cs,
574574
// send the password as a NULL-terminated UTF-8 string
575575
var passwordBytes = Encoding.UTF8.GetBytes(cs.Password);
576576
Array.Resize(ref passwordBytes, passwordBytes.Length + 1);
577-
payload = new PayloadData(passwordBytes);
577+
payload = new(passwordBytes);
578578
await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);
579579
return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
580580

581581
case "caching_sha2_password":
582582
var scrambleBytes = AuthenticationUtility.CreateScrambleResponse(Utility.TrimZeroByte(switchRequest.Data.AsSpan()), cs.Password);
583-
payload = new PayloadData(scrambleBytes);
583+
payload = new(scrambleBytes);
584584
await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);
585585
payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
586586

@@ -620,7 +620,7 @@ private async Task<PayloadData> SwitchAuthenticationAsync(ConnectionSettings cs,
620620
case "client_ed25519":
621621
if (!AuthenticationPlugins.TryGetPlugin(switchRequest.Name, out var ed25519Plugin))
622622
throw new NotSupportedException("You must install the MySqlConnector.Authentication.Ed25519 package and call Ed25519AuthenticationPlugin.Install to use client_ed25519 authentication.");
623-
payload = new PayloadData(ed25519Plugin.CreateResponse(cs.Password, switchRequest.Data));
623+
payload = new(ed25519Plugin.CreateResponse(cs.Password, switchRequest.Data));
624624
await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);
625625
return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
626626

@@ -891,7 +891,7 @@ private async Task<bool> OpenTcpSocketAsync(ConnectionSettings cs, ILoadBalancer
891891
TcpClient? tcpClient = null;
892892
try
893893
{
894-
tcpClient = new TcpClient(ipAddress.AddressFamily);
894+
tcpClient = new(ipAddress.AddressFamily);
895895

896896
using (cancellationToken.Register(() => tcpClient.Client?.Dispose()))
897897
{
@@ -1084,7 +1084,7 @@ private async Task InitSslAsync(ProtocolCapabilities serverCapabilities, Connect
10841084
throw new MySqlException("No certificates were found in the certificate store");
10851085
}
10861086

1087-
clientCertificates = new X509CertificateCollection(store.Certificates);
1087+
clientCertificates = new(store.Certificates);
10881088
}
10891089
else
10901090
{
@@ -1097,7 +1097,7 @@ private async Task InitSslAsync(ProtocolCapabilities serverCapabilities, Connect
10971097
throw new MySqlException("Certificate with Thumbprint {0} not found".FormatInvariant(cs.CertificateThumbprint));
10981098
}
10991099

1100-
clientCertificates = new X509CertificateCollection(foundCertificates);
1100+
clientCertificates = new(foundCertificates);
11011101
}
11021102
}
11031103
catch (CryptographicException ex)
@@ -1168,7 +1168,7 @@ private async Task InitSslAsync(ProtocolCapabilities serverCapabilities, Connect
11681168
#endif
11691169

11701170
m_clientCertificate = certificate;
1171-
clientCertificates = new X509CertificateCollection { certificate };
1171+
clientCertificates = new() { certificate };
11721172
}
11731173

11741174
catch (CryptographicException ex)
@@ -1195,7 +1195,7 @@ private async Task InitSslAsync(ProtocolCapabilities serverCapabilities, Connect
11951195
"CertificateFile should be in PKCS #12 (.pfx) format and contain both a Certificate and Private Key");
11961196
}
11971197
m_clientCertificate = certificate;
1198-
clientCertificates = new X509CertificateCollection { certificate };
1198+
clientCertificates = new() { certificate };
11991199
}
12001200
catch (CryptographicException ex)
12011201
{
@@ -1210,13 +1210,13 @@ private async Task InitSslAsync(ProtocolCapabilities serverCapabilities, Connect
12101210
X509Chain? caCertificateChain = null;
12111211
if (cs.CACertificateFile is not null)
12121212
{
1213-
X509Chain? certificateChain = new X509Chain
1213+
X509Chain? certificateChain = new()
12141214
{
12151215
ChainPolicy =
1216-
{
1217-
RevocationMode = X509RevocationMode.NoCheck,
1218-
VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority
1219-
}
1216+
{
1217+
RevocationMode = X509RevocationMode.NoCheck,
1218+
VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority
1219+
}
12201220
};
12211221

12221222
try

src/MySqlConnector/Core/ServerVersion.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public ServerVersion(ReadOnlySpan<byte> versionString)
4343
{
4444
totalBytesRead += bytesConsumed;
4545
if (totalBytesRead == mariaDbIndex)
46-
MariaDbVersion = new Version(major, minor, build);
46+
MariaDbVersion = new(major, minor, build);
4747
}
4848
}
4949
}
@@ -55,7 +55,7 @@ public ServerVersion(ReadOnlySpan<byte> versionString)
5555
public Version Version { get; }
5656
public Version? MariaDbVersion { get; }
5757

58-
public static ServerVersion Empty { get; } = new ServerVersion();
58+
public static ServerVersion Empty { get; } = new();
5959

6060
private ServerVersion()
6161
{

src/MySqlConnector/Core/ServerVersions.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,18 @@ namespace MySqlConnector.Core
55
internal static class ServerVersions
66
{
77
// https://dev.mysql.com/doc/relnotes/mysql/5.5/en/news-5-5-3.html
8-
public static readonly Version SupportsUtf8Mb4 = new Version(5, 5, 3);
8+
public static readonly Version SupportsUtf8Mb4 = new(5, 5, 3);
99

1010
// https://dev.mysql.com/doc/refman/5.7/en/mysql-reset-connection.html
11-
public static readonly Version SupportsResetConnection = new Version(5, 7, 3);
11+
public static readonly Version SupportsResetConnection = new(5, 7, 3);
1212

1313
// https://mariadb.com/kb/en/library/com_reset_connection/
14-
public static readonly Version MariaDbSupportsResetConnection = new Version(10, 2, 4);
14+
public static readonly Version MariaDbSupportsResetConnection = new(10, 2, 4);
1515

1616
// http://dev.mysql.com/doc/refman/5.5/en/parameters-table.html
17-
public static readonly Version SupportsProcedureCache = new Version(5, 5, 3);
17+
public static readonly Version SupportsProcedureCache = new(5, 5, 3);
1818

1919
// https://ocelot.ca/blog/blog/2017/08/22/no-more-mysql-proc-in-mysql-8-0/
20-
public static readonly Version RemovesMySqlProcTable = new Version(8, 0, 0);
20+
public static readonly Version RemovesMySqlProcTable = new(8, 0, 0);
2121
}
2222
}

0 commit comments

Comments
 (0)