diff --git a/src/installer/tests/Microsoft.NET.HostModel.Tests/Microsoft.NET.HostModel.Bundle.Tests/BundlerConsistencyTests.cs b/src/installer/tests/Microsoft.NET.HostModel.Tests/Microsoft.NET.HostModel.Bundle.Tests/BundlerConsistencyTests.cs index 6a843806c2f177..e1b13a4414ee44 100644 --- a/src/installer/tests/Microsoft.NET.HostModel.Tests/Microsoft.NET.HostModel.Bundle.Tests/BundlerConsistencyTests.cs +++ b/src/installer/tests/Microsoft.NET.HostModel.Tests/Microsoft.NET.HostModel.Bundle.Tests/BundlerConsistencyTests.cs @@ -347,7 +347,7 @@ public void TestWithAdditionalContentAfterBundleMetadata() using (var file = File.OpenWrite(singleFile)) { file.Position = file.Length; - var blob = Encoding.UTF8.GetBytes("Mock signature at the end of the bundle"); + var blob = "Mock signature at the end of the bundle"u8; file.Write(blob, 0, blob.Length); } diff --git a/src/installer/tests/TestUtils/AppHostExtensions.cs b/src/installer/tests/TestUtils/AppHostExtensions.cs index 50ef2ef22e05aa..97af7d21aa7e02 100644 --- a/src/installer/tests/TestUtils/AppHostExtensions.cs +++ b/src/installer/tests/TestUtils/AppHostExtensions.cs @@ -68,7 +68,7 @@ public static void BindAppHost(string appHostPath) using (var sha256 = SHA256.Create()) { // Replace the hash with the managed DLL name. - var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes("foobar")); + var hash = sha256.ComputeHash("foobar"u8); var hashStr = BitConverter.ToString(hash).Replace("-", "").ToLower(); BinaryUtils.SearchAndReplace(tempPath, Encoding.UTF8.GetBytes(hashStr), Encoding.UTF8.GetBytes(appDll)); } diff --git a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs index b18bb2c15f8393..43af210c122dd5 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs @@ -157,14 +157,10 @@ internal static unsafe SafeSslContextHandle AllocateSslContext(SafeFreeSslCreden } } - byte[]? cipherList = - CipherSuitesPolicyPal.GetOpenSslCipherList(sslAuthenticationOptions.CipherSuitesPolicy, protocols, sslAuthenticationOptions.EncryptionPolicy); - - Debug.Assert(cipherList == null || (cipherList.Length >= 1 && cipherList[cipherList.Length - 1] == 0)); - - byte[]? cipherSuites = - CipherSuitesPolicyPal.GetOpenSslCipherSuites(sslAuthenticationOptions.CipherSuitesPolicy, protocols, sslAuthenticationOptions.EncryptionPolicy); + ReadOnlySpan cipherList = CipherSuitesPolicyPal.GetOpenSslCipherList(sslAuthenticationOptions.CipherSuitesPolicy, protocols, sslAuthenticationOptions.EncryptionPolicy); + Debug.Assert(cipherList.IsEmpty || cipherList[^1] == 0); + byte[]? cipherSuites = CipherSuitesPolicyPal.GetOpenSslCipherSuites(sslAuthenticationOptions.CipherSuitesPolicy, protocols, sslAuthenticationOptions.EncryptionPolicy); Debug.Assert(cipherSuites == null || (cipherSuites.Length >= 1 && cipherSuites[cipherSuites.Length - 1] == 0)); fixed (byte* cipherListStr = cipherList) diff --git a/src/libraries/Common/src/System/Net/Http/aspnetcore/Http2/Hpack/StatusCodes.cs b/src/libraries/Common/src/System/Net/Http/aspnetcore/Http2/Hpack/StatusCodes.cs index c09236f841a715..f4e704a4474a5f 100644 --- a/src/libraries/Common/src/System/Net/Http/aspnetcore/Http2/Hpack/StatusCodes.cs +++ b/src/libraries/Common/src/System/Net/Http/aspnetcore/Http2/Hpack/StatusCodes.cs @@ -8,207 +8,138 @@ namespace System.Net.Http.HPack { internal static partial class StatusCodes { - // This uses C# compiler's ability to refer to static data directly. For more information see https://vcsjones.dev/2019/02/01/csharp-readonly-span-bytes-static - - private static ReadOnlySpan BytesStatus100 => new byte[] { (byte)'1', (byte)'0', (byte)'0' }; - private static ReadOnlySpan BytesStatus101 => new byte[] { (byte)'1', (byte)'0', (byte)'1' }; - private static ReadOnlySpan BytesStatus102 => new byte[] { (byte)'1', (byte)'0', (byte)'2' }; - - private static ReadOnlySpan BytesStatus200 => new byte[] { (byte)'2', (byte)'0', (byte)'0' }; - private static ReadOnlySpan BytesStatus201 => new byte[] { (byte)'2', (byte)'0', (byte)'1' }; - private static ReadOnlySpan BytesStatus202 => new byte[] { (byte)'2', (byte)'0', (byte)'2' }; - private static ReadOnlySpan BytesStatus203 => new byte[] { (byte)'2', (byte)'0', (byte)'3' }; - private static ReadOnlySpan BytesStatus204 => new byte[] { (byte)'2', (byte)'0', (byte)'4' }; - private static ReadOnlySpan BytesStatus205 => new byte[] { (byte)'2', (byte)'0', (byte)'5' }; - private static ReadOnlySpan BytesStatus206 => new byte[] { (byte)'2', (byte)'0', (byte)'6' }; - private static ReadOnlySpan BytesStatus207 => new byte[] { (byte)'2', (byte)'0', (byte)'7' }; - private static ReadOnlySpan BytesStatus208 => new byte[] { (byte)'2', (byte)'0', (byte)'8' }; - private static ReadOnlySpan BytesStatus226 => new byte[] { (byte)'2', (byte)'2', (byte)'6' }; - - private static ReadOnlySpan BytesStatus300 => new byte[] { (byte)'3', (byte)'0', (byte)'0' }; - private static ReadOnlySpan BytesStatus301 => new byte[] { (byte)'3', (byte)'0', (byte)'1' }; - private static ReadOnlySpan BytesStatus302 => new byte[] { (byte)'3', (byte)'0', (byte)'2' }; - private static ReadOnlySpan BytesStatus303 => new byte[] { (byte)'3', (byte)'0', (byte)'3' }; - private static ReadOnlySpan BytesStatus304 => new byte[] { (byte)'3', (byte)'0', (byte)'4' }; - private static ReadOnlySpan BytesStatus305 => new byte[] { (byte)'3', (byte)'0', (byte)'5' }; - private static ReadOnlySpan BytesStatus306 => new byte[] { (byte)'3', (byte)'0', (byte)'6' }; - private static ReadOnlySpan BytesStatus307 => new byte[] { (byte)'3', (byte)'0', (byte)'7' }; - private static ReadOnlySpan BytesStatus308 => new byte[] { (byte)'3', (byte)'0', (byte)'8' }; - - private static ReadOnlySpan BytesStatus400 => new byte[] { (byte)'4', (byte)'0', (byte)'0' }; - private static ReadOnlySpan BytesStatus401 => new byte[] { (byte)'4', (byte)'0', (byte)'1' }; - private static ReadOnlySpan BytesStatus402 => new byte[] { (byte)'4', (byte)'0', (byte)'2' }; - private static ReadOnlySpan BytesStatus403 => new byte[] { (byte)'4', (byte)'0', (byte)'3' }; - private static ReadOnlySpan BytesStatus404 => new byte[] { (byte)'4', (byte)'0', (byte)'4' }; - private static ReadOnlySpan BytesStatus405 => new byte[] { (byte)'4', (byte)'0', (byte)'5' }; - private static ReadOnlySpan BytesStatus406 => new byte[] { (byte)'4', (byte)'0', (byte)'6' }; - private static ReadOnlySpan BytesStatus407 => new byte[] { (byte)'4', (byte)'0', (byte)'7' }; - private static ReadOnlySpan BytesStatus408 => new byte[] { (byte)'4', (byte)'0', (byte)'8' }; - private static ReadOnlySpan BytesStatus409 => new byte[] { (byte)'4', (byte)'0', (byte)'9' }; - private static ReadOnlySpan BytesStatus410 => new byte[] { (byte)'4', (byte)'1', (byte)'0' }; - private static ReadOnlySpan BytesStatus411 => new byte[] { (byte)'4', (byte)'1', (byte)'1' }; - private static ReadOnlySpan BytesStatus412 => new byte[] { (byte)'4', (byte)'1', (byte)'2' }; - private static ReadOnlySpan BytesStatus413 => new byte[] { (byte)'4', (byte)'1', (byte)'3' }; - private static ReadOnlySpan BytesStatus414 => new byte[] { (byte)'4', (byte)'1', (byte)'4' }; - private static ReadOnlySpan BytesStatus415 => new byte[] { (byte)'4', (byte)'1', (byte)'5' }; - private static ReadOnlySpan BytesStatus416 => new byte[] { (byte)'4', (byte)'1', (byte)'6' }; - private static ReadOnlySpan BytesStatus417 => new byte[] { (byte)'4', (byte)'1', (byte)'7' }; - private static ReadOnlySpan BytesStatus418 => new byte[] { (byte)'4', (byte)'1', (byte)'8' }; - private static ReadOnlySpan BytesStatus419 => new byte[] { (byte)'4', (byte)'1', (byte)'9' }; - private static ReadOnlySpan BytesStatus421 => new byte[] { (byte)'4', (byte)'2', (byte)'1' }; - private static ReadOnlySpan BytesStatus422 => new byte[] { (byte)'4', (byte)'2', (byte)'2' }; - private static ReadOnlySpan BytesStatus423 => new byte[] { (byte)'4', (byte)'2', (byte)'3' }; - private static ReadOnlySpan BytesStatus424 => new byte[] { (byte)'4', (byte)'2', (byte)'4' }; - private static ReadOnlySpan BytesStatus426 => new byte[] { (byte)'4', (byte)'2', (byte)'6' }; - private static ReadOnlySpan BytesStatus428 => new byte[] { (byte)'4', (byte)'2', (byte)'8' }; - private static ReadOnlySpan BytesStatus429 => new byte[] { (byte)'4', (byte)'2', (byte)'9' }; - private static ReadOnlySpan BytesStatus431 => new byte[] { (byte)'4', (byte)'3', (byte)'1' }; - private static ReadOnlySpan BytesStatus451 => new byte[] { (byte)'4', (byte)'5', (byte)'1' }; - - private static ReadOnlySpan BytesStatus500 => new byte[] { (byte)'5', (byte)'0', (byte)'0' }; - private static ReadOnlySpan BytesStatus501 => new byte[] { (byte)'5', (byte)'0', (byte)'1' }; - private static ReadOnlySpan BytesStatus502 => new byte[] { (byte)'5', (byte)'0', (byte)'2' }; - private static ReadOnlySpan BytesStatus503 => new byte[] { (byte)'5', (byte)'0', (byte)'3' }; - private static ReadOnlySpan BytesStatus504 => new byte[] { (byte)'5', (byte)'0', (byte)'4' }; - private static ReadOnlySpan BytesStatus505 => new byte[] { (byte)'5', (byte)'0', (byte)'5' }; - private static ReadOnlySpan BytesStatus506 => new byte[] { (byte)'5', (byte)'0', (byte)'6' }; - private static ReadOnlySpan BytesStatus507 => new byte[] { (byte)'5', (byte)'0', (byte)'7' }; - private static ReadOnlySpan BytesStatus508 => new byte[] { (byte)'5', (byte)'0', (byte)'8' }; - private static ReadOnlySpan BytesStatus510 => new byte[] { (byte)'5', (byte)'1', (byte)'0' }; - private static ReadOnlySpan BytesStatus511 => new byte[] { (byte)'5', (byte)'1', (byte)'1' }; - public static ReadOnlySpan ToStatusBytes(int statusCode) { switch (statusCode) { case (int)HttpStatusCode.Continue: - return BytesStatus100; + return "100"u8; case (int)HttpStatusCode.SwitchingProtocols: - return BytesStatus101; + return "101"u8; case (int)HttpStatusCode.Processing: - return BytesStatus102; + return "102"u8; case (int)HttpStatusCode.OK: - return BytesStatus200; + return "200"u8; case (int)HttpStatusCode.Created: - return BytesStatus201; + return "201"u8; case (int)HttpStatusCode.Accepted: - return BytesStatus202; + return "202"u8; case (int)HttpStatusCode.NonAuthoritativeInformation: - return BytesStatus203; + return "203"u8; case (int)HttpStatusCode.NoContent: - return BytesStatus204; + return "204"u8; case (int)HttpStatusCode.ResetContent: - return BytesStatus205; + return "205"u8; case (int)HttpStatusCode.PartialContent: - return BytesStatus206; + return "206"u8; case (int)HttpStatusCode.MultiStatus: - return BytesStatus207; + return "207"u8; case (int)HttpStatusCode.AlreadyReported: - return BytesStatus208; + return "208"u8; case (int)HttpStatusCode.IMUsed: - return BytesStatus226; + return "226"u8; case (int)HttpStatusCode.MultipleChoices: - return BytesStatus300; + return "300"u8; case (int)HttpStatusCode.MovedPermanently: - return BytesStatus301; + return "301"u8; case (int)HttpStatusCode.Found: - return BytesStatus302; + return "302"u8; case (int)HttpStatusCode.SeeOther: - return BytesStatus303; + return "303"u8; case (int)HttpStatusCode.NotModified: - return BytesStatus304; + return "304"u8; case (int)HttpStatusCode.UseProxy: - return BytesStatus305; + return "305"u8; case (int)HttpStatusCode.Unused: - return BytesStatus306; + return "306"u8; case (int)HttpStatusCode.TemporaryRedirect: - return BytesStatus307; + return "307"u8; case (int)HttpStatusCode.PermanentRedirect: - return BytesStatus308; + return "308"u8; case (int)HttpStatusCode.BadRequest: - return BytesStatus400; + return "400"u8; case (int)HttpStatusCode.Unauthorized: - return BytesStatus401; + return "401"u8; case (int)HttpStatusCode.PaymentRequired: - return BytesStatus402; + return "402"u8; case (int)HttpStatusCode.Forbidden: - return BytesStatus403; + return "403"u8; case (int)HttpStatusCode.NotFound: - return BytesStatus404; + return "404"u8; case (int)HttpStatusCode.MethodNotAllowed: - return BytesStatus405; + return "405"u8; case (int)HttpStatusCode.NotAcceptable: - return BytesStatus406; + return "406"u8; case (int)HttpStatusCode.ProxyAuthenticationRequired: - return BytesStatus407; + return "407"u8; case (int)HttpStatusCode.RequestTimeout: - return BytesStatus408; + return "408"u8; case (int)HttpStatusCode.Conflict: - return BytesStatus409; + return "409"u8; case (int)HttpStatusCode.Gone: - return BytesStatus410; + return "410"u8; case (int)HttpStatusCode.LengthRequired: - return BytesStatus411; + return "411"u8; case (int)HttpStatusCode.PreconditionFailed: - return BytesStatus412; + return "412"u8; case (int)HttpStatusCode.RequestEntityTooLarge: - return BytesStatus413; + return "413"u8; case (int)HttpStatusCode.RequestUriTooLong: - return BytesStatus414; + return "414"u8; case (int)HttpStatusCode.UnsupportedMediaType: - return BytesStatus415; + return "415"u8; case (int)HttpStatusCode.RequestedRangeNotSatisfiable: - return BytesStatus416; + return "416"u8; case (int)HttpStatusCode.ExpectationFailed: - return BytesStatus417; + return "417"u8; case (int)418: - return BytesStatus418; + return "418"u8; case (int)419: - return BytesStatus419; + return "419"u8; case (int)HttpStatusCode.MisdirectedRequest: - return BytesStatus421; + return "421"u8; case (int)HttpStatusCode.UnprocessableEntity: - return BytesStatus422; + return "422"u8; case (int)HttpStatusCode.Locked: - return BytesStatus423; + return "423"u8; case (int)HttpStatusCode.FailedDependency: - return BytesStatus424; + return "424"u8; case (int)HttpStatusCode.UpgradeRequired: - return BytesStatus426; + return "426"u8; case (int)HttpStatusCode.PreconditionRequired: - return BytesStatus428; + return "428"u8; case (int)HttpStatusCode.TooManyRequests: - return BytesStatus429; + return "429"u8; case (int)HttpStatusCode.RequestHeaderFieldsTooLarge: - return BytesStatus431; + return "431"u8; case (int)HttpStatusCode.UnavailableForLegalReasons: - return BytesStatus451; + return "451"u8; case (int)HttpStatusCode.InternalServerError: - return BytesStatus500; + return "500"u8; case (int)HttpStatusCode.NotImplemented: - return BytesStatus501; + return "501"u8; case (int)HttpStatusCode.BadGateway: - return BytesStatus502; + return "502"u8; case (int)HttpStatusCode.ServiceUnavailable: - return BytesStatus503; + return "503"u8; case (int)HttpStatusCode.GatewayTimeout: - return BytesStatus504; + return "504"u8; case (int)HttpStatusCode.HttpVersionNotSupported: - return BytesStatus505; + return "505"u8; case (int)HttpStatusCode.VariantAlsoNegotiates: - return BytesStatus506; + return "506"u8; case (int)HttpStatusCode.InsufficientStorage: - return BytesStatus507; + return "507"u8; case (int)HttpStatusCode.LoopDetected: - return BytesStatus508; + return "508"u8; case (int)HttpStatusCode.NotExtended: - return BytesStatus510; + return "510"u8; case (int)HttpStatusCode.NetworkAuthenticationRequired: - return BytesStatus511; + return "511"u8; default: return Encoding.ASCII.GetBytes(statusCode.ToString(CultureInfo.InvariantCulture)); diff --git a/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs b/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs index 104849c23196b2..ed692c4095f14b 100644 --- a/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs +++ b/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs @@ -824,7 +824,7 @@ public virtual async Task Write_DataReadFromDesiredOffset(ReadWriteMode mode) return; } - await WriteAsync(mode, stream, new[] { (byte)'a', (byte)'b', (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'c', (byte)'d' }, 2, 5); + await WriteAsync(mode, stream, "abhellocd"u8, 2, 5); stream.Position = 0; using StreamReader reader = new StreamReader(stream); @@ -1846,7 +1846,7 @@ public virtual async Task Read_Eof_Returns0(ReadWriteMode mode, bool dataAvailab { write = Task.Run(async () => { - await writeable.WriteAsync(Encoding.UTF8.GetBytes("hello")); + await writeable.WriteAsync("hello"u8); await writeable.DisposeAsync(); }); } @@ -1910,7 +1910,7 @@ public virtual async Task Write_DataReadFromDesiredOffset(ReadWriteMode mode) using StreamPair streams = await CreateConnectedStreamsAsync(); (Stream writeable, Stream readable) = GetReadWritePair(streams); - byte[] buffer = new[] { (byte)'\0', (byte)'\0', (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'\0', (byte)'\0' }; + byte[] buffer = "\0\0hello\0\0"u8; const int Offset = 2, Count = 5; Task write = Task.Run(async () => @@ -2192,7 +2192,7 @@ public virtual async Task ZeroByteRead_BlocksUntilDataAvailableOrNops(ReadWriteM Task write = Task.Run(async () => { - await writeable.WriteAsync(Encoding.UTF8.GetBytes("hello")); + await writeable.WriteAsync("hello"u8); if (FlushRequiredToWriteData) { if (FlushGuaranteesAllDataWritten) @@ -2246,7 +2246,7 @@ public virtual async Task ZeroByteRead_BlocksUntilDataAvailableOrNops(ReadWriteM [ActiveIssue("https://github.com/dotnet/runtime/issues/67853", TestPlatforms.tvOS)] public virtual async Task ZeroByteWrite_OtherDataReceivedSuccessfully(ReadWriteMode mode) { - byte[][] buffers = new[] { Array.Empty(), Encoding.UTF8.GetBytes("hello"), Array.Empty(), Encoding.UTF8.GetBytes("world") }; + byte[][] buffers = new[] { Array.Empty(), "hello"u8, Array.Empty(), "world"u8 }; using StreamPair streams = await CreateConnectedStreamsAsync(); foreach ((Stream writeable, Stream readable) in GetReadWritePairs(streams)) @@ -2890,7 +2890,7 @@ public virtual async Task ZeroByteRead_PerformsZeroByteReadOnUnderlyingStreamWhe // (a) produce at least two readable bytes, so we can unblock the reader and read a single byte without clearing its buffer; and // (b) produce no more than 1K of readable bytes, so we can clear the reader buffer below. // If this isn't the case for some Stream(s), we can modify the data or parameterize it per Stream. - byte[] data = Encoding.UTF8.GetBytes("hello world"); + byte[] data = "hello world"u8; using StreamPair innerStreams = ConnectedStreams.CreateBidirectional(); (Stream innerWriteable, Stream innerReadable) = GetReadWritePair(innerStreams); diff --git a/src/libraries/Common/tests/System/Net/Http/Http2LoopbackConnection.cs b/src/libraries/Common/tests/System/Net/Http/Http2LoopbackConnection.cs index 2329475728c67b..8658b4db4b7150 100644 --- a/src/libraries/Common/tests/System/Net/Http/Http2LoopbackConnection.cs +++ b/src/libraries/Common/tests/System/Net/Http/Http2LoopbackConnection.cs @@ -100,7 +100,7 @@ private async Task ReadPrefixAsync() // Since those tests are not set up to handle multiple retries, we instead just send back an invalid response here // so that SocketsHttpHandler will not induce retry. // The contents of what we send don't really matter, as long as it is interpreted by SocketsHttpHandler as an invalid response. - await _connectionStream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/2.0 400 Bad Request\r\n\r\n")); + await _connectionStream.WriteAsync("HTTP/2.0 400 Bad Request\r\n\r\n"u8); _connectionSocket.Shutdown(SocketShutdown.Send); // If WinHTTP doesn't support streaming a request without a length then it will fallback // to HTTP/1.1. Throwing an exception to detect this case in WinHttpHandler tests. diff --git a/src/libraries/Common/tests/System/Net/Http/LoopbackServer.cs b/src/libraries/Common/tests/System/Net/Http/LoopbackServer.cs index 51445abb09c658..61f45aa2b72964 100644 --- a/src/libraries/Common/tests/System/Net/Http/LoopbackServer.cs +++ b/src/libraries/Common/tests/System/Net/Http/LoopbackServer.cs @@ -18,8 +18,8 @@ namespace System.Net.Test.Common { public sealed partial class LoopbackServer : GenericLoopbackServer, IDisposable { - private static readonly byte[] s_newLineBytes = new byte[] { (byte)'\r', (byte)'\n' }; - private static readonly byte[] s_colonSpaceBytes = new byte[] { (byte)':', (byte)' ' }; + private static readonly byte[] s_newLineBytes = "\r\n"u8; + private static readonly byte[] s_colonSpaceBytes = ": "u8; private SocketWrapper _socketWrapper; #if TARGET_BROWSER diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyFileTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyFileTests.cs index afae8f8c7a07a4..d74b661fd7acbb 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyFileTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyFileTests.cs @@ -182,7 +182,7 @@ public static void ReadWriteDsa1024EncryptedPkcs8_PasswordBytes() qE3Db1UI4anCCnyEj/jDA8R6hZTFDjxu6bG0Z66g7I2GBDEYaaB+8x0vtiyu5LXo 6UZ53SX6S+jfIqJoF5YME9zVMoO2kwS/EGvc64+epCGcee1Nx4SGgUcr5HJYz1P4 CU+l4wPQR0rRmYHIJJIvFh5OXk84pV0crsOrekw7tHeNU6DMzw==", - Encoding.UTF8.GetBytes("Password > cipher"), + "Password > cipher"u8, new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyPemTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyPemTests.cs index d27137f9708b21..a6cbe76cd17ef3 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyPemTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyPemTests.cs @@ -287,7 +287,7 @@ public static void ImportFromEncryptedPem_Pkcs8_Encrypted_Byte_Simple() xTL6VO9mx52x6h5WDAQAisMVeMkBoxQUWLANXiw1zSfVbsmB7mDknsRcvD3tcgMs 7YLD7LQMiPAIjDlOP8XP/w== -----END ENCRYPTED PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); + byte[] passwordBytes = "test"u8; dsa.ImportFromEncryptedPem(pem, passwordBytes); DSAParameters dsaParameters = dsa.ExportParameters(true); @@ -319,7 +319,7 @@ public static void ImportFromEncryptedPem_Pkcs8_Encrypted_AmbiguousPem() dVYwfovccu8ktEAwk5XAOo0r+5CCw2lDDw/hbDeO87BToC5Cc5nu3F5LxAUj8Flc v8pi3w== -----END ENCRYPTED PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); + byte[] passwordBytes = "test"u8; ArgumentException ae = AssertExtensions.Throws("input", () => dsa.ImportFromEncryptedPem(pem, passwordBytes)); Assert.Contains(AmbiguousExceptionMarker, ae.Message); @@ -332,7 +332,7 @@ public static void ImportFromEncryptedPem_Pkcs8_Byte_NoPem() using (DSA dsa = DSAFactory.Create()) { string pem = ""; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); + byte[] passwordBytes = "test"u8; ArgumentException ae = AssertExtensions.Throws("input", () => dsa.ImportFromEncryptedPem(pem, passwordBytes)); Assert.Contains(NoPemExceptionMarker, ae.Message); diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSATestData.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSATestData.cs index 93871baa3f222b..6cc72a6e6fa1f9 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSATestData.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSATestData.cs @@ -171,7 +171,7 @@ internal static void GetDSA1024_186_2(out DSAParameters parameters, out byte[] s "41e2345f1f56df2458f426d155b4ba2db6dcd8c8" ).HexToByteArray(); - data = Encoding.ASCII.GetBytes("abc"); + data = "abc"u8; } } } diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.LimitedPrivate.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.LimitedPrivate.cs index ca0f9967c13e40..7dac1255dd3f67 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.LimitedPrivate.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.LimitedPrivate.cs @@ -83,7 +83,7 @@ public void ReadNistP521EncryptedPkcs8_Pbes2_Aes128_LimitedPrivateKey_PasswordBy ReadWriteBase64EncryptedPkcs8( base64, - Encoding.UTF8.GetBytes("qwerty"), + "qwerty"u8, new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA1, diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs index d867f1545a9190..e43e54278a4dee 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs @@ -195,7 +195,7 @@ public void ReadNistP521EncryptedPkcs8_Pbes2_Aes128_Sha384_PasswordBytes() ReadWriteBase64EncryptedPkcs8( base64, - Encoding.UTF8.GetBytes("qwerty"), + "qwerty"u8, new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA1, diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyPemTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyPemTests.cs index 3c367a4557b5a2..f13d108d3b3ce7 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyPemTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyPemTests.cs @@ -342,7 +342,7 @@ public void ImportFromEncryptedPem_Pkcs8_Byte_Simple() /OMt/tWvtMSj17+dJvShsu/NYJXF5fsfpSJbd3e50Y3AisW0Ob7mmF54KBfg6Y+4 aATwwQdUIKVzUZsQctsHPjbriQKKn7GKSyUOikBUNQ+TozojX8/g7JAsl+T9jGM= -----END ENCRYPTED PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); + byte[] passwordBytes = "test"u8; key.ImportFromEncryptedPem(pem, passwordBytes); ECParameters ecParameters = key.ExportParameters(true); ECParameters expected = EccTestData.GetNistP256ReferenceKey(); @@ -370,7 +370,7 @@ public void ImportFromEncryptedPem_AmbiguousPem_Byte() opSAJ/pvHONL5kyAJLeNyG9c/mR2qyrP2L9gL0Z5fB9NyPejKTLi0PXMGQWdDTH8 Qh0fqdrNovgFLubbJFMQN/MwwIAfIuf0Mn0WFYYeQiBJ3kg= -----END ENCRYPTED PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); + byte[] passwordBytes = "test"u8; ArgumentException ae = AssertExtensions.Throws("input", () => key.ImportFromEncryptedPem(pem, passwordBytes)); diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaTests.cs index 187c76ad351a9f..d2b0c1a5ea49f4 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaTests.cs @@ -274,8 +274,6 @@ public static IEnumerable InteroperableSignatureConfigurations() [MemberData(nameof(InteroperableSignatureConfigurations))] public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm) { - byte[] data = Encoding.UTF8.GetBytes("something to repeat and sign"); - // large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses. byte[] dataArray = new byte[33333]; diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyFileTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyFileTests.cs index a9c021ac129424..e354b2231c5f67 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyFileTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyFileTests.cs @@ -781,7 +781,7 @@ public static void ReadPbes2Rc2EncryptedDiminishedDP_PasswordBytes() ReadBase64EncryptedPkcs8( base64, - Encoding.UTF8.GetBytes("rc2"), + "rc2"u8, new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs index 013ec21c8a65ab..c29e4eedfccce3 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs @@ -425,7 +425,7 @@ public static void ImportFromEncryptedPem_Pkcs8Encrypted_Byte_Simple() 5QSEe7EKVF0aHXBYB5SzMGVuxR/BqydDa26jlhVzO3LNvy9FYuqLKUslCrBCmPrt raZNyk8KAsLs+FJq9T2tda0= -----END ENCRYPTED PRIVATE KEY-----"; - rsa.ImportFromEncryptedPem(pem, Encoding.UTF8.GetBytes("test")); + rsa.ImportFromEncryptedPem(pem, "test"u8); RSAParameters rsaParameters = rsa.ExportParameters(true); ImportExport.AssertKeyEquals(TestData.DiminishedDPParameters, rsaParameters); @@ -462,7 +462,7 @@ public static void ImportFromEncryptedPem_Pkcs8Encrypted_AmbiguousPem() N4lD7/hJq7b+yYPhlN3Fvvt8M9MtRg1TLAve67CA2v4TITHB06M/ELe3y42bZuLW CA7ffFk= -----END ENCRYPTED PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); + byte[] passwordBytes = "test"u8; ArgumentException ae = AssertExtensions.Throws("input", () => rsa.ImportFromEncryptedPem(pem, passwordBytes)); Assert.Contains(AmbiguousExceptionMarker, ae.Message); @@ -475,7 +475,7 @@ public static void ImportFromEncryptedPem_Pkcs8Encrypted_Byte_NoPem() using (RSA rsa = RSAFactory.Create()) { string pem = "these aren't the PEMs we're looking for."; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); + byte[] passwordBytes = "test"u8; ArgumentException ae = AssertExtensions.Throws("input", () => rsa.ImportFromEncryptedPem(pem, passwordBytes)); Assert.Contains(NoPemExceptionMarker, ae.Message); @@ -498,7 +498,7 @@ public static void ImportFromEncryptedPem_NoEncryptedPem() acPiMCuFTnRSFYAhozpmsqoLyTREqwIhAMLJlZTGjEB2N+sEazH5ToEczQzKqp7t 9juGNbOPhoEL -----END PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); + byte[] passwordBytes = "test"u8; ArgumentException ae = AssertExtensions.Throws("input", () => rsa.ImportFromEncryptedPem(pem, passwordBytes)); Assert.Contains(NoPemExceptionMarker, ae.Message); diff --git a/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/DynamicTableTest.cs b/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/DynamicTableTest.cs index 9576a9e67b5f95..85ecf2a40b7292 100644 --- a/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/DynamicTableTest.cs +++ b/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/DynamicTableTest.cs @@ -13,8 +13,8 @@ namespace System.Net.Http.Unit.Tests.HPack { public class DynamicTableTest { - private readonly HeaderField _header1 = new HeaderField(staticTableIndex: null, Encoding.ASCII.GetBytes("header-1"), Encoding.ASCII.GetBytes("value1")); - private readonly HeaderField _header2 = new HeaderField(staticTableIndex: null, Encoding.ASCII.GetBytes("header-02"), Encoding.ASCII.GetBytes("value_2")); + private readonly HeaderField _header1 = new HeaderField(staticTableIndex: null, "header-1"u8, "value1"u8); + private readonly HeaderField _header2 = new HeaderField(staticTableIndex: null, "header-02"u8, "value_2"u8); [Fact] public void DynamicTable_IsInitiallyEmpty() diff --git a/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HPackDecoderTest.cs b/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HPackDecoderTest.cs index e5f3c3b698e21d..d0a576d4cbc62f 100644 --- a/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HPackDecoderTest.cs +++ b/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HPackDecoderTest.cs @@ -45,16 +45,14 @@ public class HPackDecoderTests private const string _userAgentString = "user-agent"; private const string _headerNameString = "new-header"; - - private static readonly byte[] _headerNameBytes = Encoding.ASCII.GetBytes(_headerNameString); + private static readonly byte[] _headerNameBytes = "new-header"u8; // n e w - h e a d e r * // 10101000 10111110 00010110 10011100 10100011 10010000 10110110 01111111 private static readonly byte[] _headerNameHuffmanBytes = new byte[] { 0xa8, 0xbe, 0x16, 0x9c, 0xa3, 0x90, 0xb6, 0x7f }; private const string _headerValueString = "value"; - - private static readonly byte[] _headerValueBytes = Encoding.ASCII.GetBytes(_headerValueString); + private static readonly byte[] _headerValueBytes = "value"u8; // v a l u e * // 11101110 00111010 00101101 00101111 diff --git a/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HuffmanDecodingTests.cs b/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HuffmanDecodingTests.cs index 621af899803b48..259f42c5115c32 100644 --- a/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HuffmanDecodingTests.cs +++ b/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HuffmanDecodingTests.cs @@ -93,7 +93,7 @@ public void HuffmanDecoding_InvalidEncoding_Throws() // This input sequence will encode to 17 bits, thus offsetting the next character to encode // by exactly one bit. We use this below to generate a prefix that encodes all of the possible starting // bit offsets for a character, from 0 to 7. - private static readonly byte[] s_offsetByOneBit = new byte[] { (byte)'c', (byte)'l', (byte)'r' }; + private static readonly byte[] s_offsetByOneBit = "clr"u8; public static IEnumerable TestData() { @@ -190,27 +190,27 @@ private static IEnumerable InvalidEncodingData() public static readonly TheoryData _validData = new TheoryData { // Single 5-bit symbol - { new byte[] { 0x07 }, Encoding.ASCII.GetBytes("0") }, + { new byte[] { 0x07 }, "0"u8 }, // Single 6-bit symbol - { new byte[] { 0x57 }, Encoding.ASCII.GetBytes("%") }, + { new byte[] { 0x57 }, "%"u8 }, // Single 7-bit symbol - { new byte[] { 0xb9 }, Encoding.ASCII.GetBytes(":") }, + { new byte[] { 0xb9 }, ":"u8 }, // Single 8-bit symbol - { new byte[] { 0xf8 }, Encoding.ASCII.GetBytes("&") }, + { new byte[] { 0xf8 }, "&"u8 }, // Single 10-bit symbol - { new byte[] { 0xfe, 0x3f }, Encoding.ASCII.GetBytes("!") }, + { new byte[] { 0xfe, 0x3f }, "!"u8 }, // Single 11-bit symbol - { new byte[] { 0xff, 0x7f }, Encoding.ASCII.GetBytes("+") }, + { new byte[] { 0xff, 0x7f }, "+"u8 }, // Single 12-bit symbol - { new byte[] { 0xff, 0xaf }, Encoding.ASCII.GetBytes("#") }, + { new byte[] { 0xff, 0xaf }, "#"u8 }, // Single 13-bit symbol - { new byte[] { 0xff, 0xcf }, Encoding.ASCII.GetBytes("$") }, + { new byte[] { 0xff, 0xcf }, "$"u8 }, // Single 14-bit symbol - { new byte[] { 0xff, 0xf3 }, Encoding.ASCII.GetBytes("^") }, + { new byte[] { 0xff, 0xf3 }, "^"u8 }, // Single 15-bit symbol - { new byte[] { 0xff, 0xf9 }, Encoding.ASCII.GetBytes("<") }, + { new byte[] { 0xff, 0xf9 }, "<"u8 }, // Single 19-bit symbol - { new byte[] { 0xff, 0xfe, 0x1f }, Encoding.ASCII.GetBytes("\\") }, + { new byte[] { 0xff, 0xfe, 0x1f }, "\\"u8 }, // Single 20-bit symbol { new byte[] { 0xff, 0xfe, 0x6f }, new byte[] { 0x80 } }, // Single 21-bit symbol @@ -233,11 +233,11 @@ private static IEnumerable InvalidEncodingData() { new byte[] { 0xff, 0xff, 0xff, 0xf3 }, new byte[] { 0x0a } }, // h e l l o * - { new byte[] { 0b100111_00, 0b101_10100, 0b0_101000_0, 0b0111_1111 }, Encoding.ASCII.GetBytes("hello") }, + { new byte[] { 0b100111_00, 0b101_10100, 0b0_101000_0, 0b0111_1111 }, "hello"u8 }, // Sequences that uncovered errors - { new byte[] { 0xb6, 0xb9, 0xac, 0x1c, 0x85, 0x58, 0xd5, 0x20, 0xa4, 0xb6, 0xc2, 0xad, 0x61, 0x7b, 0x5a, 0x54, 0x25, 0x1f }, Encoding.ASCII.GetBytes("upgrade-insecure-requests") }, - { new byte[] { 0xfe, 0x53 }, Encoding.ASCII.GetBytes("\"t") }, + { new byte[] { 0xb6, 0xb9, 0xac, 0x1c, 0x85, 0x58, 0xd5, 0x20, 0xa4, 0xb6, 0xc2, 0xad, 0x61, 0x7b, 0x5a, 0x54, 0x25, 0x1f }, "upgrade-insecure-requests"u8 }, + { new byte[] { 0xfe, 0x53 }, "\"t"u8 }, { new byte[] { 0xff, 0xff, 0xf6, 0xff, 0xff, 0xfd, 0x68 }, new byte[] { 0xcf, 0xf0, 0x73 } }, { new byte[] { 0xff, 0xff, 0xf9, 0xff, 0xff, 0xfd, 0x86 }, new byte[] { 0xd5, 0xc7, 0x69 } }, }; @@ -344,7 +344,7 @@ public void DecodeCharactersThatSpans5Octets() int decodedLength = Huffman.Decode(new ReadOnlySpan(encoded, 0, encoded.Length), ref decodedBytes); Assert.Equal(expectedLength, decodedLength); - Assert.Equal(new byte[] { (byte)'B', (byte)'\n' }, decodedBytes); + Assert.Equal("B\n"u8, decodedBytes); } [Theory] diff --git a/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http3/QPackDecoderTest.cs b/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http3/QPackDecoderTest.cs index 475fddeab09bdf..531b3df4de2ded 100644 --- a/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http3/QPackDecoderTest.cs +++ b/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http3/QPackDecoderTest.cs @@ -36,9 +36,9 @@ public class QPackDecoderTests private static readonly byte[] _headerNameHuffmanBytes = new byte[] { 0xa8, 0xbe, 0x16, 0x9c, 0xa3, 0x90, 0xb6, 0x7f }; private const string _headerNameString = "new-header"; - private const string _headerValueString = "value"; - private static readonly byte[] _headerValueBytes = Encoding.ASCII.GetBytes(_headerValueString); + private const string _headerValueString = "value"; + private static readonly byte[] _headerValueBytes = "value"u8; // v a l u e * // 11101110 00111010 00101101 00101111 diff --git a/src/libraries/Common/tests/Tests/System/StringTests.cs b/src/libraries/Common/tests/Tests/System/StringTests.cs index 6e863d253a4741..3c29b819506283 100644 --- a/src/libraries/Common/tests/Tests/System/StringTests.cs +++ b/src/libraries/Common/tests/Tests/System/StringTests.cs @@ -7288,7 +7288,7 @@ public static unsafe void Ctor_SByte_NullPointer_ReturnsEmptyString() [Fact] public static void CreateStringFromEncoding_0Length_EmptyStringReturned() // basic test for code coverage; more tests in encodings tests { - byte[] bytes = Encoding.ASCII.GetBytes("hello"); + byte[] bytes = "hello"u8; Assert.Same(string.Empty, new AsciiEncodingWithZeroReturningGetCharCount().GetString(bytes, 0, 0)); } diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHelpers.cs b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHelpers.cs index e25a070946acc5..4069eee62b84f0 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHelpers.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHelpers.cs @@ -54,7 +54,7 @@ private static bool GetIsSystemdService() int parentPid = Interop.libc.GetParentPid(); string ppidString = parentPid.ToString(NumberFormatInfo.InvariantInfo); byte[] comm = File.ReadAllBytes("/proc/" + ppidString + "/comm"); - return comm.AsSpan().SequenceEqual(Encoding.ASCII.GetBytes("systemd\n")); + return comm.AsSpan().SequenceEqual("systemd\n"u8); } catch { diff --git a/src/libraries/System.DirectoryServices.Protocols/tests/DirectoryServicesProtocolsTests.cs b/src/libraries/System.DirectoryServices.Protocols/tests/DirectoryServicesProtocolsTests.cs index 39f7c9b16055b9..0703f130d3b8ed 100644 --- a/src/libraries/System.DirectoryServices.Protocols/tests/DirectoryServicesProtocolsTests.cs +++ b/src/libraries/System.DirectoryServices.Protocols/tests/DirectoryServicesProtocolsTests.cs @@ -479,18 +479,18 @@ private static void RunAsyncSearch(IAsyncResult asyncResult) public static IEnumerable TestCompareRequestTheory_TestData() { yield return new object[] { "input", "input", ResultCode.CompareTrue }; - yield return new object[] { "input", Encoding.UTF8.GetBytes("input"), ResultCode.CompareTrue }; + yield return new object[] { "input", "input"u8, ResultCode.CompareTrue }; yield return new object[] { "input", "false", ResultCode.CompareFalse }; yield return new object[] { "input", new byte[] { 1, 2, 3, 4, 5 }, ResultCode.CompareFalse }; yield return new object[] { "http://example.com/", "http://example.com/", ResultCode.CompareTrue }; yield return new object[] { "http://example.com/", new Uri("http://example.com/"), ResultCode.CompareTrue }; - yield return new object[] { "http://example.com/", Encoding.UTF8.GetBytes("http://example.com/"), ResultCode.CompareTrue }; + yield return new object[] { "http://example.com/", "http://example.com/"u8, ResultCode.CompareTrue }; yield return new object[] { "http://example.com/", "http://false/", ResultCode.CompareFalse }; yield return new object[] { "http://example.com/", new Uri("http://false/"), ResultCode.CompareFalse }; - yield return new object[] { "http://example.com/", Encoding.UTF8.GetBytes("http://false/"), ResultCode.CompareFalse }; + yield return new object[] { "http://example.com/", "http://false/"u8, ResultCode.CompareFalse }; } [ConditionalTheory(nameof(IsLdapConfigurationExist))] diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/ImageConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/ImageConverter.cs index 6b6717382c645e..0223a3bfd6168e 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/ImageConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/ImageConverter.cs @@ -15,9 +15,9 @@ namespace System.Drawing { public class ImageConverter : TypeConverter { - private static ReadOnlySpan PBrush => new byte[] { (byte)'P', (byte)'B', (byte)'r', (byte)'u', (byte)'s', (byte)'h' }; + private static ReadOnlySpan PBrush => "PBrush"u8; - private static ReadOnlySpan BMBytes => new byte[] { (byte)'B', (byte)'M' }; + private static ReadOnlySpan BMBytes => "BM"u8; public override bool CanConvertFrom(ITypeDescriptorContext? context, Type? sourceType) { diff --git a/src/libraries/System.Drawing.Common/tests/ImageTests.cs b/src/libraries/System.Drawing.Common/tests/ImageTests.cs index 00d37e7520df83..0d463795f5d2a1 100644 --- a/src/libraries/System.Drawing.Common/tests/ImageTests.cs +++ b/src/libraries/System.Drawing.Common/tests/ImageTests.cs @@ -248,7 +248,7 @@ public void SetPropertyItem_InvokeMemoryBitmap_Success(int propid) // Change data. PropertyItem item = source.GetPropertyItem(PropertyTagExifUserComment); - item.Value = Encoding.ASCII.GetBytes("Hello World\0"); + item.Value = "Hello World\0"u8; item.Len = item.Value.Length; bitmap.SetPropertyItem(item); @@ -263,7 +263,7 @@ public void SetPropertyItem_InvokeMemoryBitmap_Success(int propid) // New data. item.Id = propid; - item.Value = Encoding.ASCII.GetBytes("New Value\0"); + item.Value = "New Value\0"u8; item.Len = item.Value.Length; bitmap.SetPropertyItem(item); @@ -307,7 +307,7 @@ public void SetPropertyItem_InvokeBitmapJpg_Success(int propid) // Change data. PropertyItem item = bitmap.GetPropertyItem(PropertyTagExifUserComment); - item.Value = Encoding.ASCII.GetBytes("Hello World\0"); + item.Value = "Hello World\0"u8; item.Len = item.Value.Length; bitmap.SetPropertyItem(item); @@ -350,7 +350,7 @@ public void SetPropertyItem_InvokeBitmapJpg_Success(int propid) // New data. item.Id = propid; - item.Value = Encoding.ASCII.GetBytes("New Value\0"); + item.Value = "New Value\0"u8; item.Len = item.Value.Length; bitmap.SetPropertyItem(item); @@ -451,7 +451,7 @@ public void SetPropertyItem_InvokeBitmapBmp_Success(int propid) // Change data. PropertyItem item = source.GetPropertyItem(PropertyTagExifUserComment); - item.Value = Encoding.ASCII.GetBytes("Hello World\0"); + item.Value = "Hello World\0"u8; item.Len = item.Value.Length; bitmap.SetPropertyItem(item); @@ -466,7 +466,7 @@ public void SetPropertyItem_InvokeBitmapBmp_Success(int propid) // New data. item.Id = propid; - item.Value = Encoding.ASCII.GetBytes("New Value\0"); + item.Value = "New Value\0"u8; item.Len = item.Value.Length; bitmap.SetPropertyItem(item); diff --git a/src/libraries/System.IO.Compression.ZipFile/tests/ZipFile.Unix.cs b/src/libraries/System.IO.Compression.ZipFile/tests/ZipFile.Unix.cs index 23f667cdbf31f8..6957d37c579e45 100644 --- a/src/libraries/System.IO.Compression.ZipFile/tests/ZipFile.Unix.cs +++ b/src/libraries/System.IO.Compression.ZipFile/tests/ZipFile.Unix.cs @@ -65,7 +65,7 @@ public void UnixExtractSetsFilePermissionsFromExternalAttributes() { // '7600' tests that S_ISUID, S_ISGID, and S_ISVTX bits don't get extracted to file permissions string[] testPermissions = new[] { "777", "755", "644", "754", "7600" }; - byte[] contents = Encoding.UTF8.GetBytes("contents"); + byte[] contents = "contents"u8; string archivePath = GetTestFilePath(); using (FileStream fileStream = new FileStream(archivePath, FileMode.CreateNew)) diff --git a/src/libraries/System.IO.Compression/tests/ZipArchive/zip_UpdateTests.cs b/src/libraries/System.IO.Compression/tests/ZipArchive/zip_UpdateTests.cs index 637d04500d77a8..99b2d07066e9ec 100644 --- a/src/libraries/System.IO.Compression/tests/ZipArchive/zip_UpdateTests.cs +++ b/src/libraries/System.IO.Compression/tests/ZipArchive/zip_UpdateTests.cs @@ -169,7 +169,7 @@ public static async Task AppendToEntry(bool writeWithSpans) { s.Seek(0, SeekOrigin.End); - byte[] data = Encoding.ASCII.GetBytes("\r\n\r\nThe answer my friend, is blowin' in the wind."); + byte[] data = "\r\n\r\nThe answer my friend, is blowin' in the wind."u8; if (writeWithSpans) { s.Write(data, 0, data.Length); diff --git a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs index 69c2c7208f4074..2d3ab8833ff292 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs @@ -97,11 +97,11 @@ public void WriteToReadOnlyFile() // Operation succeeds when being run by the Unix superuser if (PlatformDetection.IsSuperUser) { - File.WriteAllBytes(path, Encoding.UTF8.GetBytes("text")); - Assert.Equal(Encoding.UTF8.GetBytes("text"), File.ReadAllBytes(path)); + File.WriteAllBytes(path, "text"u8); + Assert.Equal("text"u8, File.ReadAllBytes(path)); } else - Assert.Throws(() => File.WriteAllBytes(path, Encoding.UTF8.GetBytes("text"))); + Assert.Throws(() => File.WriteAllBytes(path, "text"u8)); } finally { diff --git a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs index 3ab0df3700484b..01bb7ce5f3b2b7 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs @@ -108,11 +108,11 @@ public async Task WriteToReadOnlyFileAsync() // Operation succeeds when being run by the Unix superuser if (PlatformDetection.IsSuperUser) { - await File.WriteAllBytesAsync(path, Encoding.UTF8.GetBytes("text")); - Assert.Equal(Encoding.UTF8.GetBytes("text"), await File.ReadAllBytesAsync(path)); + await File.WriteAllBytesAsync(path, "text"u8); + Assert.Equal("text"u8, await File.ReadAllBytesAsync(path)); } else - await Assert.ThrowsAsync(async () => await File.WriteAllBytesAsync(path, Encoding.UTF8.GetBytes("text"))); + await Assert.ThrowsAsync(async () => await File.WriteAllBytesAsync(path, "text"u8)); } finally { diff --git a/src/libraries/System.IO.FileSystem/tests/FileStream/DevicesPipesAndSockets.cs b/src/libraries/System.IO.FileSystem/tests/FileStream/DevicesPipesAndSockets.cs index f5b532e6ce47d7..e44dfceeee2623 100644 --- a/src/libraries/System.IO.FileSystem/tests/FileStream/DevicesPipesAndSockets.cs +++ b/src/libraries/System.IO.FileSystem/tests/FileStream/DevicesPipesAndSockets.cs @@ -21,7 +21,7 @@ public void CharacterDevice_FileStream_Write(string devicePath, FileOptions file { FileStreamOptions options = new() { Options = fileOptions, Access = FileAccess.Write, Share = FileShare.Write }; using FileStream fs = new(devicePath, options); - fs.Write(Encoding.UTF8.GetBytes("foo")); + fs.Write("foo"u8); } [Theory] @@ -30,21 +30,21 @@ public async Task CharacterDevice_FileStream_WriteAsync(string devicePath, FileO { FileStreamOptions options = new() { Options = fileOptions, Access = FileAccess.Write, Share = FileShare.Write }; using FileStream fs = new(devicePath, options); - await fs.WriteAsync(Encoding.UTF8.GetBytes("foo")); + await fs.WriteAsync("foo"u8); } [Theory] [MemberData(nameof(DevicePath_TestData))] public void CharacterDevice_WriteAllBytes(string devicePath) { - File.WriteAllBytes(devicePath, Encoding.UTF8.GetBytes("foo")); + File.WriteAllBytes(devicePath, "foo"u8); } [Theory] [MemberData(nameof(DevicePath_TestData))] public async Task CharacterDevice_WriteAllBytesAsync(string devicePath) { - await File.WriteAllBytesAsync(devicePath, Encoding.UTF8.GetBytes("foo")); + await File.WriteAllBytesAsync(devicePath, "foo"u8); } [Theory] diff --git a/src/libraries/System.IO.FileSystem/tests/FileStream/ctor_str_fm.cs b/src/libraries/System.IO.FileSystem/tests/FileStream/ctor_str_fm.cs index cd3b18da034228..44cafb53a891c8 100644 --- a/src/libraries/System.IO.FileSystem/tests/FileStream/ctor_str_fm.cs +++ b/src/libraries/System.IO.FileSystem/tests/FileStream/ctor_str_fm.cs @@ -218,12 +218,12 @@ public virtual void FileModeAppend(string streamSpecifier) Assert.False(fs.CanRead); Assert.True(fs.CanWrite); - fs.Write(Encoding.ASCII.GetBytes("abcde")); + fs.Write("abcde"u8); Assert.Equal(5, fs.Length); Assert.Equal(5, fs.Position); Assert.Equal(1, fs.Seek(1, SeekOrigin.Begin)); - fs.Write(Encoding.ASCII.GetBytes("xyz")); + fs.Write("xyz"u8); Assert.Equal(4, fs.Position); Assert.Equal(5, fs.Length); } @@ -257,12 +257,12 @@ public virtual void FileModeAppendExisting(string streamSpecifier) Assert.Throws(() => fs.Seek(0, SeekOrigin.Begin)); Assert.Throws(() => fs.ReadByte()); - fs.Write(Encoding.ASCII.GetBytes("abcde")); + fs.Write("abcde"u8); Assert.Equal(position + 5, fs.Position); Assert.Equal(position, fs.Seek(position, SeekOrigin.Begin)); Assert.Equal(position + 1, fs.Seek(1, SeekOrigin.Current)); - fs.Write(Encoding.ASCII.GetBytes("xyz")); + fs.Write("xyz"u8); } Assert.Equal(initialContents + "axyze", File.ReadAllText(fileName)); diff --git a/src/libraries/System.IO.Hashing/tests/Crc32Tests.cs b/src/libraries/System.IO.Hashing/tests/Crc32Tests.cs index 6d2993f1509e47..25cd8ffb628e00 100644 --- a/src/libraries/System.IO.Hashing/tests/Crc32Tests.cs +++ b/src/libraries/System.IO.Hashing/tests/Crc32Tests.cs @@ -51,7 +51,7 @@ public static IEnumerable TestCases "FFFFFFFF"), new TestCase( "Self-test 123456789", - Encoding.ASCII.GetBytes("123456789"), + "123456789"u8, "2639F4CB"), new TestCase( "Self-test residue", @@ -63,7 +63,7 @@ public static IEnumerable TestCases "FFFFFFFF"), new TestCase( "The quick brown fox jumps over the lazy dog", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"), + "The quick brown fox jumps over the lazy dog"u8, "39A34F41"), }; diff --git a/src/libraries/System.IO.Hashing/tests/Crc64Tests.cs b/src/libraries/System.IO.Hashing/tests/Crc64Tests.cs index d647e4b9587989..a4837d1f3b2601 100644 --- a/src/libraries/System.IO.Hashing/tests/Crc64Tests.cs +++ b/src/libraries/System.IO.Hashing/tests/Crc64Tests.cs @@ -59,7 +59,7 @@ public static IEnumerable TestCases "0000000000000000"), new TestCase( "Self-test 123456789", - Encoding.ASCII.GetBytes("123456789"), + "123456789"u8, "6C40DF5F0B497347"), new TestCase( "Self-test residue", @@ -67,7 +67,7 @@ public static IEnumerable TestCases "0000000000000000"), new TestCase( "The quick brown fox jumps over the lazy dog", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"), + "The quick brown fox jumps over the lazy dog"u8, "41E05242FFA9883B"), }; diff --git a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.007.cs b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.007.cs index 9ec9262dd1c5d8..a52b3fd7339df4 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.007.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.007.cs @@ -45,19 +45,19 @@ public static IEnumerable TestCases // Same inputs as the main XxHash32 tests, but with the seed applied. new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8, "21C69E3A"), new TestCase( "The quick brown fox jumps over the lazy dog", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"), + "The quick brown fox jumps over the lazy dog"u8, "558D024f"), new TestCase( "The quick brown fox jumps over the lazy dog.", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog."), + "The quick brown fox jumps over the lazy dog."u8, "E7D2C0A7"), new TestCase( "abc", - Encoding.ASCII.GetBytes("abc"), + "abc"u8, "D46070BB"), new TestCase( "123456", diff --git a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.cs b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.cs index abd77d8c22f97d..8bd602bf886022 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.cs @@ -43,17 +43,17 @@ public static IEnumerable TestCases //https://asecuritysite.com/encryption/xxHash, Example 1 new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8, "E2293B2F"), //https://asecuritysite.com/encryption/xxHash, Example 2 new TestCase( "The quick brown fox jumps over the lazy dog", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"), + "The quick brown fox jumps over the lazy dog"u8, "E85EA4DE"), //https://asecuritysite.com/encryption/xxHash, Example 3 new TestCase( "The quick brown fox jumps over the lazy dog.", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog."), + "The quick brown fox jumps over the lazy dog."u8, "68D039C8"), // Manual exploration to force boundary conditions in code coverage. @@ -62,7 +62,7 @@ public static IEnumerable TestCases // The "in three pieces" test causes this to build up in the accumulator every time. new TestCase( "abc", - Encoding.ASCII.GetBytes("abc"), + "abc"u8, "32D153FF"), // Accumulates every time. new TestCase( diff --git a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.f00d.cs b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.f00d.cs index 4a116bc50354e0..37d4480f2a111c 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.f00d.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.f00d.cs @@ -45,19 +45,19 @@ public static IEnumerable TestCases // Same inputs as the main XxHash32 tests, but with the seed applied. new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8, "E8FF660B"), new TestCase( "The quick brown fox jumps over the lazy dog", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"), + "The quick brown fox jumps over the lazy dog"u8, "C2B00BA1"), new TestCase( "The quick brown fox jumps over the lazy dog.", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog."), + "The quick brown fox jumps over the lazy dog."u8, "11AC3BD7"), new TestCase( "abc", - Encoding.ASCII.GetBytes("abc"), + "abc"u8, "BC85BB95"), new TestCase( "123456", diff --git a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.007.cs b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.007.cs index 836b29230f3e67..5d3086d4075ef5 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.007.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.007.cs @@ -47,19 +47,19 @@ public static IEnumerable TestCases // Same inputs as the main XxHash64 tests, but with the seed applied. new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8, "C86A41E2F34280A0"), new TestCase( "The quick brown fox jumps over the lazy dog", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"), + "The quick brown fox jumps over the lazy dog"u8, "BB05857F11B054EB"), new TestCase( "The quick brown fox jumps over the lazy dog.", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog."), + "The quick brown fox jumps over the lazy dog."u8, "618682461CB28F83"), new TestCase( "abc", - Encoding.ASCII.GetBytes("abc"), + "abc"u8, "6BF4B26E3CA10C20"), new TestCase( "123456", diff --git a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.cs b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.cs index 213e6f91c252cf..37144734b1def9 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.cs @@ -45,17 +45,17 @@ public static IEnumerable TestCases //https://asecuritysite.com/encryption/xxHash, Example 1 new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8, "FBCEA83C8A378BF1"), //https://asecuritysite.com/encryption/xxHash, Example 2 new TestCase( "The quick brown fox jumps over the lazy dog", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"), + "The quick brown fox jumps over the lazy dog"u8, "0B242D361FDA71BC"), //https://asecuritysite.com/encryption/xxHash, Example 3 new TestCase( "The quick brown fox jumps over the lazy dog.", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog."), + "The quick brown fox jumps over the lazy dog."u8, "44AD33705751AD73"), // Manual exploration to force boundary conditions in code coverage. @@ -64,7 +64,7 @@ public static IEnumerable TestCases // The "in three pieces" test causes this to build up in the accumulator every time. new TestCase( "abc", - Encoding.ASCII.GetBytes("abc"), + "abc"u8, "44BC2CF5AD770999"), // Accumulates every time. new TestCase( diff --git a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.f00d.cs b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.f00d.cs index 75fc4f514aca9a..e2019c077e9c8b 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.f00d.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.f00d.cs @@ -47,19 +47,19 @@ public static IEnumerable TestCases // Same inputs as the main XxHash64 tests, but with the seed applied. new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8, "76E6275980CF4E30"), new TestCase( "The quick brown fox jumps over the lazy dog", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"), + "The quick brown fox jumps over the lazy dog"u8, "5CC25b2B8248DF76"), new TestCase( "The quick brown fox jumps over the lazy dog.", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog."), + "The quick brown fox jumps over the lazy dog."u8, "10E8D9E4DA841407"), new TestCase( "abc", - Encoding.ASCII.GetBytes("abc"), + "abc"u8, "AE9DA0E407940A85"), new TestCase( "123456", diff --git a/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs b/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs index adf547a3c452bf..472e1ebc6a1450 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs @@ -43,9 +43,9 @@ public async Task CopyToAsyncStreamWorks() { var messages = new List() { - Encoding.UTF8.GetBytes("Hello World1"), - Encoding.UTF8.GetBytes("Hello World2"), - Encoding.UTF8.GetBytes("Hello World3"), + "Hello World1"u8, + "Hello World2"u8, + "Hello World3"u8, }; var stream = new WriteCheckMemoryStream(); @@ -67,9 +67,9 @@ public async Task CopyToAsyncPipeWriterWorks() { var messages = new List() { - Encoding.UTF8.GetBytes("Hello World1"), - Encoding.UTF8.GetBytes("Hello World2"), - Encoding.UTF8.GetBytes("Hello World3"), + "Hello World1"u8, + "Hello World2"u8, + "Hello World3"u8, }; var targetPipe = new Pipe(s_testOptions); @@ -199,7 +199,7 @@ public async Task CancelingPipeWriterViaCancellationTokenThrowsOperationCancelle // This should make the write call pause var targetPipe = new Pipe(new PipeOptions(pauseWriterThreshold: 1, resumeWriterThreshold: 1)); var cts = new CancellationTokenSource(); - await Pipe.Writer.WriteAsync(Encoding.ASCII.GetBytes("Gello World")); + await Pipe.Writer.WriteAsync("Gello World"u8); Task task = PipeReader.CopyToAsync(targetPipe.Writer, cts.Token); cts.Cancel(); @@ -212,7 +212,7 @@ public async Task CancelingPipeWriterViaPendingFlushThrowsOperationCancelledExce { // This should make the write call pause var targetPipe = new Pipe(new PipeOptions(pauseWriterThreshold: 1, resumeWriterThreshold: 1)); - await Pipe.Writer.WriteAsync(Encoding.ASCII.GetBytes("Gello World")); + await Pipe.Writer.WriteAsync("Gello World"u8); Task task = PipeReader.CopyToAsync(targetPipe.Writer); targetPipe.Writer.CancelPendingFlush(); @@ -290,7 +290,7 @@ public async Task ThrowingFromStreamCallsAdvanceToWithStartOfLastReadResult(int [Fact] public async Task CopyToAsyncStreamCopiesRemainderAfterReadingSome() { - var buffer = Encoding.UTF8.GetBytes("Hello World"); + var buffer = "Hello World"u8; await Pipe.Writer.WriteAsync(buffer); Pipe.Writer.Complete(); @@ -308,7 +308,7 @@ public async Task CopyToAsyncStreamCopiesRemainderAfterReadingSome() [Fact] public async Task CopyToAsyncPipeWriterCopiesRemainderAfterReadingSome() { - var buffer = Encoding.UTF8.GetBytes("Hello World"); + var buffer = "Hello World"u8; await Pipe.Writer.WriteAsync(buffer); Pipe.Writer.Complete(); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeReaderReadAtLeastAsyncTests.cs b/src/libraries/System.IO.Pipelines/tests/PipeReaderReadAtLeastAsyncTests.cs index 64762de5ec8cee..1d564f0ef9a037 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeReaderReadAtLeastAsyncTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeReaderReadAtLeastAsyncTests.cs @@ -31,7 +31,7 @@ protected virtual void SetPipeReaderOptions(MemoryPool? pool = null, int b [Fact] public async Task CanWriteAndReadAtLeast() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; await Pipe.Writer.WriteAsync(bytes); ReadResult result = await PipeReader.ReadAtLeastAsync(11); @@ -46,7 +46,7 @@ public async Task CanWriteAndReadAtLeast() [Fact] public async Task ReadAtLeastShouldNotCompleteIfWriterWroteLessThanMinimum() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; await Pipe.Writer.WriteAsync(bytes.AsMemory(0, 5)); ValueTask task = PipeReader.ReadAtLeastAsync(11); @@ -68,7 +68,7 @@ public async Task ReadAtLeastShouldNotCompleteIfWriterWroteLessThanMinimum() [Fact] public async Task CanAlternateReadAtLeastAndRead() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; await Pipe.Writer.WriteAsync(bytes.AsMemory(0, 5)); ReadResult result = await PipeReader.ReadAtLeastAsync(3); @@ -113,7 +113,7 @@ public async Task ReadAtLeastReturnsIfCompleted() public async Task CanReadAtLeast(int bufferSize, bool bufferedRead) { SetPipeReaderOptions(bufferSize: bufferSize); - await Pipe.Writer.WriteAsync(Encoding.ASCII.GetBytes("Hello Pipelines World")); + await Pipe.Writer.WriteAsync("Hello Pipelines World"u8); if (bufferedRead) { @@ -148,7 +148,7 @@ public Task ReadAtLeastAsyncThrowsIfPassedCanceledCancellationToken() [Fact] public async Task WriteAndCancellingPendingReadBeforeReadAtLeastAsync() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; PipeWriter output = Pipe.Writer; output.Write(bytes); await output.FlushAsync(); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeReaderStreamTests.nonnetstandard.cs b/src/libraries/System.IO.Pipelines/tests/PipeReaderStreamTests.nonnetstandard.cs index 0e8398188c0859..0cf8fd2b1364b3 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeReaderStreamTests.nonnetstandard.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeReaderStreamTests.nonnetstandard.cs @@ -55,7 +55,7 @@ public async Task DisposingPipeReaderStreamCompletesPipeReader(bool dataInPipe) [MemberData(nameof(ReadCalls))] public async Task ReadingFromPipeReaderStreamReadsFromUnderlyingPipeReader(ReadAsyncDelegate readAsync) { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8; var pipe = new Pipe(); await pipe.Writer.WriteAsync(helloBytes); pipe.Writer.Complete(); @@ -73,7 +73,7 @@ public async Task ReadingFromPipeReaderStreamReadsFromUnderlyingPipeReader(ReadA [MemberData(nameof(ReadCalls))] public async Task AsStreamReturnsPipeReaderStream(ReadAsyncDelegate readAsync) { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8; var pipe = new Pipe(); await pipe.Writer.WriteAsync(helloBytes); pipe.Writer.Complete(); @@ -90,7 +90,7 @@ public async Task AsStreamReturnsPipeReaderStream(ReadAsyncDelegate readAsync) [Fact] public async Task ReadingWithSmallerBufferWorks() { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8; var pipe = new Pipe(); await pipe.Writer.WriteAsync(helloBytes); pipe.Writer.Complete(); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs b/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs index 1a325e466a7abf..1ea5bf6ae13f1a 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs @@ -34,7 +34,7 @@ public void Dispose() [Fact] public async Task CanReadAndWrite() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; await _pipe.Writer.WriteAsync(bytes); ReadResult result = await _pipe.Reader.ReadAsync(); @@ -170,7 +170,7 @@ public async Task HelloWorldAcrossTwoBlocks() var blockSize = _pipe.Writer.GetMemory().Length; byte[] paddingBytes = Enumerable.Repeat((byte)'a', blockSize - 5).ToArray(); - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; writeBuffer.Write(paddingBytes); writeBuffer.Write(bytes); @@ -338,7 +338,7 @@ public async Task ReaderShouldNotGetUnflushedBytesWithAppend() await buffer.FlushAsync(); // Write Hello to another pipeline and get the buffer - byte[] bytes = Encoding.ASCII.GetBytes("Hello"); + byte[] bytes = "Hello"u8; var c2 = new Pipe(new PipeOptions(_pool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline)); await c2.Writer.WriteAsync(bytes); @@ -516,7 +516,7 @@ await Assert.ThrowsAsync( public async Task SyncReadThenAsyncRead() { PipeWriter buffer = _pipe.Writer; - buffer.Write(Encoding.ASCII.GetBytes("Hello World")); + buffer.Write("Hello World"u8); await buffer.FlushAsync(); bool gotData = _pipe.Reader.TryRead(out ReadResult result); @@ -601,7 +601,7 @@ public void WhenTryReadReturnsFalseDontNeedToCallAdvance() [Fact] public async Task WritingDataMakesDataReadableViaPipeline() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; await _pipe.Writer.WriteAsync(bytes); ReadResult result = await _pipe.Reader.ReadAsync(); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs b/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs index 4d9fb17b9ea64c..04c5dd4d5ded17 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs @@ -40,7 +40,7 @@ public async Task CopyToAsyncThrowsTaskCanceledExceptionForAlreadyCancelledToken [Fact] public async Task CopyToAsyncWorks() { - var helloBytes = Encoding.UTF8.GetBytes("Hello World"); + var helloBytes = "Hello World"u8; var pipe = new Pipe(); var stream = new MemoryStream(helloBytes); @@ -79,7 +79,7 @@ public async Task CopyToAsyncCalledMultipleTimesWorks() [Fact] public async Task StreamCopyToAsyncWorks() { - var helloBytes = Encoding.UTF8.GetBytes("Hello World"); + var helloBytes = "Hello World"u8; var pipe = new Pipe(); var stream = new MemoryStream(helloBytes); @@ -96,7 +96,7 @@ public async Task StreamCopyToAsyncWorks() [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task CancelingViaCancelPendingFlushThrows() { - var helloBytes = Encoding.UTF8.GetBytes("Hello World"); + var helloBytes = "Hello World"u8; var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: helloBytes.Length - 1, resumeWriterThreshold: 0)); var stream = new MemoryStream(helloBytes); @@ -115,7 +115,7 @@ public async Task CancelingViaCancelPendingFlushThrows() [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task CancelingViaCancellationTokenThrows() { - var helloBytes = Encoding.UTF8.GetBytes("Hello World"); + var helloBytes = "Hello World"u8; var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: helloBytes.Length - 1, resumeWriterThreshold: 0)); var stream = new MemoryStream(helloBytes); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeWriterStreamTests.nonnetstandard.cs b/src/libraries/System.IO.Pipelines/tests/PipeWriterStreamTests.nonnetstandard.cs index 57f6f8ee1e2eef..0e2b782c8b91c8 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeWriterStreamTests.nonnetstandard.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeWriterStreamTests.nonnetstandard.cs @@ -49,7 +49,7 @@ public async Task DisposingPipeWriterStreamCompletesPipeWriter() [MemberData(nameof(WriteCalls))] public async Task WritingToPipeStreamWritesToUnderlyingPipeWriter(WriteAsyncDelegate writeAsync) { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8; var pipe = new Pipe(); var stream = new PipeWriterStream(pipe.Writer, leaveOpen: false); @@ -65,7 +65,7 @@ public async Task WritingToPipeStreamWritesToUnderlyingPipeWriter(WriteAsyncDele [MemberData(nameof(WriteCalls))] public async Task AsStreamReturnsPipeWriterStream(WriteAsyncDelegate writeAsync) { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8; var pipe = new Pipe(); Stream stream = pipe.Writer.AsStream(); @@ -80,7 +80,7 @@ public async Task AsStreamReturnsPipeWriterStream(WriteAsyncDelegate writeAsync) [Fact] public async Task FlushAsyncFlushesBufferedData() { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8; var pipe = new Pipe(); Memory memory = pipe.Writer.GetMemory(); @@ -99,7 +99,6 @@ public async Task FlushAsyncFlushesBufferedData() [Fact] public async Task ReadingFromPipeWriterStreamThrowsNotSupported() { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); var pipe = new Pipe(); Stream stream = pipe.Writer.AsStream(); @@ -122,7 +121,7 @@ public async Task ReadingFromPipeWriterStreamThrowsNotSupported() public async Task CancellingPendingFlushThrowsOperationCancelledException() { var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: 10, resumeWriterThreshold: 0)); - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8; Stream stream = pipe.Writer.AsStream(); ValueTask task = stream.WriteAsync(helloBytes); @@ -139,7 +138,7 @@ public async Task CancellingPendingFlushThrowsOperationCancelledException() public async Task CancellationTokenFlowsToUnderlyingPipeWriter() { var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: 10, resumeWriterThreshold: 0)); - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8; Stream stream = pipe.Writer.AsStream(); var cts = new CancellationTokenSource(); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs b/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs index d7edb408ec3a3a..2b6563adda23ed 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs @@ -185,7 +185,7 @@ public void ThrowsOnAdvanceWithNoMemory() [Fact] public async Task WritesUsingGetSpanWorks() { - var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz"); + var bytes = "abcdefghijklmnopqrstuvwzyz"u8; var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1)); PipeWriter writer = pipe.Writer; @@ -208,7 +208,7 @@ public async Task WritesUsingGetSpanWorks() [Fact] public async Task WritesUsingGetMemoryWorks() { - var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz"); + var bytes = "abcdefghijklmnopqrstuvwzyz"u8; var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1)); PipeWriter writer = pipe.Writer; diff --git a/src/libraries/System.IO.Pipelines/tests/ReadAsyncCancellationTests.cs b/src/libraries/System.IO.Pipelines/tests/ReadAsyncCancellationTests.cs index 8422de30735845..4fef5a1ca593fd 100644 --- a/src/libraries/System.IO.Pipelines/tests/ReadAsyncCancellationTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/ReadAsyncCancellationTests.cs @@ -32,7 +32,7 @@ public async Task AdvanceShouldResetStateIfReadCanceled() [Fact] public async Task CancellingBeforeAdvance() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; PipeWriter output = Pipe.Writer; output.Write(bytes); await output.FlushAsync(); @@ -65,7 +65,7 @@ public async Task CancellingBeforeAdvance() [Fact] public async Task CancellingPendingAfterReadAsync() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; PipeWriter output = Pipe.Writer; output.Write(bytes); @@ -116,7 +116,7 @@ public async Task CancellingPendingReadBeforeReadAsync() Assert.True(result.IsCanceled); Assert.True(buffer.IsEmpty); - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; PipeWriter output = Pipe.Writer; output.Write(bytes); await output.FlushAsync(); @@ -407,7 +407,7 @@ await Assert.ThrowsAsync( [Fact] public async Task WriteAndCancellingPendingReadBeforeReadAsync() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; PipeWriter output = Pipe.Writer; output.Write(bytes); await output.FlushAsync(); diff --git a/src/libraries/System.IO.Pipelines/tests/SchedulerFacts.cs b/src/libraries/System.IO.Pipelines/tests/SchedulerFacts.cs index 000c908639f6c8..1e611a9e79731b 100644 --- a/src/libraries/System.IO.Pipelines/tests/SchedulerFacts.cs +++ b/src/libraries/System.IO.Pipelines/tests/SchedulerFacts.cs @@ -68,7 +68,7 @@ public async Task UseSynchronizationContextFalseIgnoresSyncContextForReaderSched Task reading = doRead(); PipeWriter buffer = pipe.Writer; - buffer.Write(Encoding.UTF8.GetBytes("Hello World")); + buffer.Write("Hello World"u8); // Don't run code on our sync context (we just want to make sure the callbacks) // are scheduled on the sync context @@ -112,7 +112,7 @@ public async Task DefaultReaderSchedulerRunsOnSynchronizationContext() Task reading = doRead(); PipeWriter buffer = pipe.Writer; - buffer.Write(Encoding.UTF8.GetBytes("Hello World")); + buffer.Write("Hello World"u8); // Don't run code on our sync context (we just want to make sure the callbacks) // are scheduled on the sync context @@ -160,7 +160,7 @@ public async Task DefaultReaderSchedulerIgnoresSyncContextIfConfigureAwaitFalse( Task reading = doRead(); PipeWriter buffer = pipe.Writer; - buffer.Write(Encoding.UTF8.GetBytes("Hello World")); + buffer.Write("Hello World"u8); // We don't want to run any code on our fake sync context await buffer.FlushAsync().ConfigureAwait(false); @@ -201,7 +201,7 @@ public async Task DefaultReaderSchedulerRunsOnThreadPool() Task reading = ExecuteOnNonThreadPoolThread(doRead); PipeWriter buffer = pipe.Writer; - buffer.Write(Encoding.UTF8.GetBytes("Hello World")); + buffer.Write("Hello World"u8); await buffer.FlushAsync(); pipe.Writer.Complete(); @@ -480,7 +480,7 @@ public async Task ReadAsyncCallbackRunsOnReaderScheduler() Task reading = ExecuteOnNonThreadPoolThread(doRead); PipeWriter buffer = pipe.Writer; - buffer.Write(Encoding.UTF8.GetBytes("Hello World")); + buffer.Write("Hello World"u8); await buffer.FlushAsync(); await reading; @@ -525,7 +525,7 @@ async Task DoRead() null); #pragma warning restore CS0618 // Type or member is obsolete - buffer.Write(Encoding.UTF8.GetBytes("Hello World")); + buffer.Write("Hello World"u8); await buffer.FlushAsync(); await reading; diff --git a/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs b/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs index d12e4f1ec84704..a3808f755de8cc 100644 --- a/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs @@ -16,7 +16,7 @@ public class SequencePipeReaderTests [Fact] public async Task CanRead() { - var sequence = new ReadOnlySequence(Encoding.ASCII.GetBytes("Hello World")); + var sequence = new ReadOnlySequence("Hello World"u8); var reader = PipeReader.Create(sequence); ReadResult readResult = await reader.ReadAsync(); @@ -33,7 +33,7 @@ public async Task CanRead() [Fact] public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything() { - var sequence = new ReadOnlySequence(Encoding.ASCII.GetBytes("Hello World")); + var sequence = new ReadOnlySequence("Hello World"u8); var reader = PipeReader.Create(sequence); ReadResult readResult = await reader.ReadAsync(); @@ -53,7 +53,7 @@ public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything() [Fact] public async Task TryReadReturnsFalseIfBufferedBytesAndEverythingExamined() { - var sequence = new ReadOnlySequence(Encoding.ASCII.GetBytes("Hello World")); + var sequence = new ReadOnlySequence("Hello World"u8); var reader = PipeReader.Create(sequence); ReadResult readResult = await reader.ReadAsync(); @@ -86,7 +86,7 @@ public async Task ReadAsyncAfterReceivingCompletedReadResultDoesNotThrow() [Fact] public async Task DataCanBeReadMultipleTimes() { - var helloBytes = Encoding.ASCII.GetBytes("Hello World"); + var helloBytes = "Hello World"u8; var sequence = new ReadOnlySequence(helloBytes); PipeReader reader = PipeReader.Create(sequence); diff --git a/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs b/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs index a9cb0d396034b3..9142158078a69d 100644 --- a/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs @@ -17,7 +17,7 @@ public class StreamPipeReaderTests [Fact] public async Task CanRead() { - var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World")); + var stream = new MemoryStream("Hello World"u8); var reader = PipeReader.Create(stream); ReadResult readResult = await reader.ReadAsync(); @@ -34,7 +34,7 @@ public async Task CanRead() [Fact] public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything() { - var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World")); + var stream = new MemoryStream("Hello World"u8); var reader = PipeReader.Create(stream); ReadResult readResult = await reader.ReadAsync(); @@ -54,7 +54,7 @@ public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything() [Fact] public async Task TryReadReturnsFalseIfBufferedBytesAndEverythingExamined() { - var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World")); + var stream = new MemoryStream("Hello World"u8); var reader = PipeReader.Create(stream); ReadResult readResult = await reader.ReadAsync(); @@ -168,7 +168,7 @@ public async Task ReadAsyncAfterReceivingCompletedReadResultDoesNotThrow() [Fact] public async Task BufferingDataPastEndOfStreamCanBeReadAgain() { - var helloBytes = Encoding.ASCII.GetBytes("Hello World"); + var helloBytes = "Hello World"u8; var stream = new ThrowAfterZeroByteReadStream(helloBytes); PipeReader reader = PipeReader.Create(stream); diff --git a/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs b/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs index 4bd99672c49aca..16365a2babd63f 100644 --- a/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs @@ -16,7 +16,7 @@ public class StreamPipeWriterTests [Fact] public void NothingWrittenToStreamUnlessFlushed() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream); @@ -33,7 +33,7 @@ public void NothingWrittenToStreamUnlessFlushed() [Fact] public void DataFlushedOnComplete() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true)); @@ -52,7 +52,7 @@ public void DataFlushedOnComplete() [Fact] public async Task DataFlushedOnCompleteAsync() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true)); @@ -71,7 +71,7 @@ public async Task DataFlushedOnCompleteAsync() [Fact] public void DataNotFlushedOnCompleteWithException() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true)); @@ -88,7 +88,7 @@ public void DataNotFlushedOnCompleteWithException() [Fact] public async Task DataNotFlushedOnCompleteAsyncWithException() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true)); @@ -105,7 +105,7 @@ public async Task DataNotFlushedOnCompleteAsyncWithException() [Fact] public async Task CompleteAsyncDoesNotThrowObjectDisposedException() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true)); @@ -124,7 +124,7 @@ public async Task CompleteAsyncDoesNotThrowObjectDisposedException() [Fact] public async Task DataWrittenOnFlushAsync() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream); @@ -155,7 +155,7 @@ public async Task FlushAsyncWithoutWritingDoesNotFlushAsync() [Fact] public async Task WritesUsingGetSpanWorks() { - var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz"); + var bytes = "abcdefghijklmnopqrstuvwzyz"u8; var stream = new MemoryStream(); var options = new StreamPipeWriterOptions(new HeapBufferPool(), minimumBufferSize: 1); PipeWriter writer = PipeWriter.Create(stream, options); @@ -175,7 +175,7 @@ public async Task WritesUsingGetSpanWorks() [Fact] public async Task WritesUsingGetMemoryWorks() { - var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz"); + var bytes = "abcdefghijklmnopqrstuvwzyz"u8; var stream = new MemoryStream(); var options = new StreamPipeWriterOptions(new HeapBufferPool(), minimumBufferSize: 1); PipeWriter writer = PipeWriter.Create(stream, options); @@ -234,10 +234,10 @@ async Task DoReadsAsync(PipeReader reader, byte[][] reads) var data = new List { - Encoding.ASCII.GetBytes("Hello"), - Encoding.ASCII.GetBytes("World"), - Encoding.ASCII.GetBytes("This"), - Encoding.ASCII.GetBytes("Works"), + "Hello"u8, + "World"u8, + "This"u8, + "Works"u8, }. ToArray(); @@ -438,7 +438,7 @@ public void CompletingWithBufferedBytesStillReturnsMemoryToPool() { using (var pool = new DisposeTrackingBufferPool()) { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; var stream = new MemoryStream(); var options = new StreamPipeWriterOptions(pool); PipeWriter writer = PipeWriter.Create(stream, options); @@ -484,7 +484,6 @@ public void GetMemorySameAsTheMaxPoolSizeUsesThePool() { using (var pool = new DisposeTrackingBufferPool()) { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); var stream = new MemoryStream(); var options = new StreamPipeWriterOptions(pool); PipeWriter writer = PipeWriter.Create(stream, options); @@ -628,7 +627,7 @@ public async Task OperationCancelledExceptionNotSwallowedIfNotThrownFromSpecifie [Fact] public void UnflushedBytesWorks() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8; var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream); diff --git a/src/libraries/System.IO.Pipelines/tests/UnflushedBytesTests.cs b/src/libraries/System.IO.Pipelines/tests/UnflushedBytesTests.cs index 1c2c15e94950b5..ca4fd77de45a9a 100644 --- a/src/libraries/System.IO.Pipelines/tests/UnflushedBytesTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/UnflushedBytesTests.cs @@ -39,7 +39,7 @@ public void NonOverriddenUnflushedBytesThrows() [Fact] public void UnflushedBytesWorks() { - byte[] bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz"); + byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8; Pipe.Writer.Write(bytes); Assert.True(Pipe.Writer.CanGetUnflushedBytes); Assert.Equal(bytes.Length,Pipe.Writer.UnflushedBytes); diff --git a/src/libraries/System.IO.Ports/tests/SerialStream/BeginWrite_Generic.cs b/src/libraries/System.IO.Ports/tests/SerialStream/BeginWrite_Generic.cs index 0ecd3b3ff979ee..160b4f672981ed 100644 --- a/src/libraries/System.IO.Ports/tests/SerialStream/BeginWrite_Generic.cs +++ b/src/libraries/System.IO.Ports/tests/SerialStream/BeginWrite_Generic.cs @@ -286,7 +286,7 @@ private void Verify_Handshake(Handshake handshake) Thread.Sleep(250); } - com1.BaseStream.BeginWrite(new byte[] { (byte)'A' }, 0, 1, null, null); + com1.BaseStream.BeginWrite("A"u8, 0, 1, null, null); Thread.Sleep(250); Assert.Throws( diff --git a/src/libraries/System.IO.Ports/tests/SerialStream/WriteByte_Generic.cs b/src/libraries/System.IO.Ports/tests/SerialStream/WriteByte_Generic.cs index 4e68086e461105..2c91561974887b 100644 --- a/src/libraries/System.IO.Ports/tests/SerialStream/WriteByte_Generic.cs +++ b/src/libraries/System.IO.Ports/tests/SerialStream/WriteByte_Generic.cs @@ -363,7 +363,7 @@ private void Verify_Handshake(Handshake handshake) Thread.Sleep(250); } - com1.BaseStream.BeginWrite(new byte[] { (byte)'A' }, 0, 1, null, null); + com1.BaseStream.BeginWrite("A"u8, 0, 1, null, null); Thread.Sleep(250); Assert.Throws( diff --git a/src/libraries/System.IO/tests/BufferedStream/BufferedStreamTests.cs b/src/libraries/System.IO/tests/BufferedStream/BufferedStreamTests.cs index 8d11c80336711a..49c4ee95369f13 100644 --- a/src/libraries/System.IO/tests/BufferedStream/BufferedStreamTests.cs +++ b/src/libraries/System.IO/tests/BufferedStream/BufferedStreamTests.cs @@ -410,13 +410,13 @@ protected override Stream CreateStream() protected override Stream GetSmallStream() { - byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; + byte[] testData = "HELLO"u8; return new BufferedStream(new MemoryStream(testData)); } protected override Stream GetLargeStream() { - byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; + byte[] testData = "HELLO"u8; List data = new List(); for (int i = 0; i < 1000; i++) { diff --git a/src/libraries/System.IO/tests/StreamReader/StreamReader.CtorTests.cs b/src/libraries/System.IO/tests/StreamReader/StreamReader.CtorTests.cs index c7bf35f44eced1..51a1c7e0e7e904 100644 --- a/src/libraries/System.IO/tests/StreamReader/StreamReader.CtorTests.cs +++ b/src/libraries/System.IO/tests/StreamReader/StreamReader.CtorTests.cs @@ -31,7 +31,7 @@ public static void InputStreamClosed() public static void CreationFromMemoryStreamWithEncodingFalse() { var ms2 = new MemoryStream(); - ms2.Write(new byte[] { 65, 66, 67, 68 }, 0, 4); + ms2.Write("ABCD"u8, 0, 4); ms2.Position = 0; var sr2 = new StreamReader(ms2, false); @@ -43,7 +43,7 @@ public static void CreationFromMemoryStreamWithEncodingFalse() public static void CreationFromMemoryStreamWithEncodingTrue() { var ms2 = new MemoryStream(); - ms2.Write(new byte[] { 65, 66, 67, 68 }, 0, 4); + ms2.Write("ABCD"u8, 0, 4); ms2.Position = 0; var sr2 = new StreamReader(ms2, true); diff --git a/src/libraries/System.IO/tests/StreamReader/StreamReader.StringCtorTests.cs b/src/libraries/System.IO/tests/StreamReader/StreamReader.StringCtorTests.cs index b96ed8532d383c..0fb9a1ed6a944d 100644 --- a/src/libraries/System.IO/tests/StreamReader/StreamReader.StringCtorTests.cs +++ b/src/libraries/System.IO/tests/StreamReader/StreamReader.StringCtorTests.cs @@ -65,7 +65,7 @@ public static void ReadToEnd_detectEncodingFromByteOrderMarks(bool detectEncodin string testfile = Path.GetTempFileName(); try { - File.WriteAllBytes(testfile, new byte[] { 65, 66, 67, 68 }); + File.WriteAllBytes(testfile, "ABCD"u8); using (var sr2 = new StreamReader(testfile, detectEncodingFromByteOrderMarks)) { Assert.Equal("ABCD", sr2.ReadToEnd()); diff --git a/src/libraries/System.IO/tests/StreamReader/StreamReaderTests.cs b/src/libraries/System.IO/tests/StreamReader/StreamReaderTests.cs index 810cbe5380f6cf..1c795fdf418b86 100644 --- a/src/libraries/System.IO/tests/StreamReader/StreamReaderTests.cs +++ b/src/libraries/System.IO/tests/StreamReader/StreamReaderTests.cs @@ -22,14 +22,13 @@ protected virtual Stream CreateStream() protected virtual Stream GetSmallStream() { - byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; + byte[] testData = "HELLO"u8; return new MemoryStream(testData); } protected virtual Stream GetLargeStream() { - byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; - // System.Collections.Generic. + byte[] testData = "HELLO"u8; List data = new List(); for (int i = 0; i < 1000; i++) diff --git a/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs b/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs index 9486ac8270f464..eeec3ef33bcd37 100644 --- a/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs +++ b/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs @@ -19,7 +19,7 @@ public class BinaryDataTests [Fact] public void CanCreateBinaryDataFromBytes() { - byte[] payload = Encoding.UTF8.GetBytes("some data"); + byte[] payload = "some data"u8; BinaryData data = BinaryData.FromBytes(payload); Assert.Equal(payload, data.ToArray()); @@ -83,7 +83,7 @@ public async Task ToStreamRespectsArraySegmentBoundaries() [Fact] public async Task CannotWriteToReadOnlyMemoryStream() { - byte[] buffer = Encoding.UTF8.GetBytes("some data"); + byte[] buffer = "some data"u8; using MemoryStream payload = new MemoryStream(buffer); BinaryData data = BinaryData.FromStream(payload); Stream stream = data.ToStream(); @@ -98,7 +98,7 @@ public async Task CannotWriteToReadOnlyMemoryStream() [Fact] public async Task ToStreamIsMutatedWhenCustomerOwnsBuffer() { - byte[] buffer = Encoding.UTF8.GetBytes("some data"); + byte[] buffer = "some data"u8; BinaryData data = BinaryData.FromBytes(buffer); Stream stream = data.ToStream(); buffer[0] = (byte)'z'; @@ -109,7 +109,7 @@ public async Task ToStreamIsMutatedWhenCustomerOwnsBuffer() [Fact] public async Task ToStreamIsNotMutatedWhenBinaryDataOwnsBuffer() { - byte[] buffer = Encoding.UTF8.GetBytes("some data"); + byte[] buffer = "some data"u8; BinaryData data = BinaryData.FromStream(new MemoryStream(buffer)); Stream stream = data.ToStream(); buffer[0] = (byte)'z'; @@ -120,7 +120,7 @@ public async Task ToStreamIsNotMutatedWhenBinaryDataOwnsBuffer() [Fact] public async Task CanCreateBinaryDataFromStream() { - byte[] buffer = Encoding.UTF8.GetBytes("some data"); + byte[] buffer = "some data"u8; using MemoryStream stream = new MemoryStream(buffer, 0, buffer.Length, true, true); BinaryData data = BinaryData.FromStream(stream); Assert.Equal(buffer, data.ToArray()); @@ -146,7 +146,7 @@ public async Task CanCreateBinaryDataFromStream() [Fact] public async Task CanCreateBinaryDataFromLongStream() { - byte[] buffer = Encoding.UTF8.GetBytes("some data"); + byte[] buffer = "some data"u8; using MemoryStream stream = new OverFlowStream(offset: int.MaxValue - 10000, buffer); BinaryData data = BinaryData.FromStream(stream); Assert.Equal(buffer, data.ToArray()); @@ -177,7 +177,7 @@ public async Task CanCreateBinaryDataFromEmptyStream() Assert.Empty(data.ToArray()); // stream at end - byte[] buffer = Encoding.UTF8.GetBytes("some data"); + byte[] buffer = "some data"u8; stream.Write(buffer, 0, buffer.Length); data = BinaryData.FromStream(stream); Assert.Empty(data.ToArray()); @@ -189,7 +189,7 @@ public async Task CanCreateBinaryDataFromEmptyStream() [Fact] public async Task CanCreateBinaryDataFromStreamUsingBackingBuffer() { - byte[] buffer = Encoding.UTF8.GetBytes("some data"); + byte[] buffer = "some data"u8; using MemoryStream stream = new MemoryStream(); stream.Write(buffer, 0, buffer.Length); stream.Position = 0; @@ -213,7 +213,7 @@ public async Task CanCreateBinaryDataFromStreamUsingBackingBuffer() [Fact] public async Task CanCreateBinaryDataFromNonSeekableStream() { - byte[] buffer = Encoding.UTF8.GetBytes("some data"); + byte[] buffer = "some data"u8; using MemoryStream stream = new NonSeekableStream(buffer); BinaryData data = BinaryData.FromStream(stream); Assert.Equal(buffer, data.ToArray()); @@ -235,7 +235,7 @@ public async Task CanCreateBinaryDataFromNonSeekableStream() [Fact] public async Task CanCreateBinaryDataFromFileStream() { - byte[] buffer = Encoding.UTF8.GetBytes("some data"); + byte[] buffer = "some data"u8; using FileStream stream = new FileStream(Path.GetTempFileName(), FileMode.Open); stream.Write(buffer, 0, buffer.Length); stream.Position = 0; @@ -264,7 +264,7 @@ public async Task CanCreateBinaryDataFromFileStream() public async Task StartPositionOfStreamRespected(int bufferOffset, long streamStart) { var input = "some data"; - ArraySegment buffer = new ArraySegment(Encoding.UTF8.GetBytes("some data"), bufferOffset, input.Length - bufferOffset); + ArraySegment buffer = new ArraySegment("some data"u8, bufferOffset, input.Length - bufferOffset); MemoryStream stream = new MemoryStream(buffer.Array, buffer.Offset, buffer.Count); var payload = new ReadOnlyMemory(buffer.Array, buffer.Offset, buffer.Count).Slice((int)streamStart); @@ -287,7 +287,7 @@ public async Task StartPositionOfStreamRespected(int bufferOffset, long streamSt public async Task StartPositionOfStreamRespectedBackingBuffer(int bufferOffset, long streamStart) { var input = "some data"; - ArraySegment buffer = new ArraySegment(Encoding.UTF8.GetBytes("some data"), bufferOffset, input.Length - bufferOffset); + ArraySegment buffer = new ArraySegment("some data"u8, bufferOffset, input.Length - bufferOffset); MemoryStream stream = new MemoryStream(); stream.Write(buffer.Array, buffer.Offset, buffer.Count); @@ -404,12 +404,12 @@ public void ToObjectThrowsExceptionOnIncompatibleType() [Fact] public void EqualsRespectsReferenceEquality() { - byte[] payload = Encoding.UTF8.GetBytes("some data"); + byte[] payload = "some data"u8; BinaryData a = BinaryData.FromBytes(payload); BinaryData b = BinaryData.FromBytes(payload); Assert.NotEqual(a, b); - BinaryData c = BinaryData.FromBytes(Encoding.UTF8.GetBytes("some data")); + BinaryData c = BinaryData.FromBytes("some data"u8); Assert.NotEqual(a, c); Assert.False(a.Equals("string data")); @@ -418,7 +418,7 @@ public void EqualsRespectsReferenceEquality() [Fact] public void GetHashCodeWorks() { - byte[] payload = Encoding.UTF8.GetBytes("some data"); + byte[] payload = "some data"u8; BinaryData a = BinaryData.FromBytes(payload); BinaryData b = BinaryData.FromBytes(payload); HashSet set = new HashSet @@ -428,7 +428,7 @@ public void GetHashCodeWorks() // hashcodes of a and b should not match since instances are different. Assert.DoesNotContain(b, set); - BinaryData c = BinaryData.FromBytes(Encoding.UTF8.GetBytes("some data")); + BinaryData c = BinaryData.FromBytes("some data"u8); // c should have a different hash code Assert.DoesNotContain(c, set); set.Add(c); @@ -438,7 +438,7 @@ public void GetHashCodeWorks() [Fact] public async Task CanRead() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8; var stream = new BinaryData(buffer).ToStream(); var read = new byte[buffer.Length]; @@ -458,7 +458,7 @@ public async Task CanRead() [Fact] public async Task CanReadPartial() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8; var stream = new BinaryData(buffer).ToStream(); var length = 4; var read = new byte[length]; @@ -479,7 +479,7 @@ public async Task CanReadPartial() [Fact] public void ReadAsyncRespectsCancellation() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8; var stream = new BinaryData(buffer).ToStream(); var read = new byte[buffer.Length]; @@ -498,7 +498,7 @@ public void ReadAsyncRespectsCancellation() [Fact] public async Task CanSeek() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8; var stream = new BinaryData(buffer).ToStream(); stream.Seek(5, SeekOrigin.Begin); @@ -519,7 +519,7 @@ public async Task CanSeek() [Fact] public void ValidatesSeekArguments() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8; var stream = new BinaryData(buffer).ToStream(); Assert.Throws(() => stream.Seek(-1, SeekOrigin.Begin)); @@ -532,7 +532,7 @@ public void ValidatesSeekArguments() [Fact] public async Task ValidatesReadArguments() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8; var stream = new BinaryData(buffer).ToStream(); stream.Seek(3, SeekOrigin.Begin); var read = new byte[buffer.Length - stream.Position]; @@ -549,7 +549,7 @@ public async Task ValidatesReadArguments() [Fact] public void ValidatesPositionValue() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8; var stream = new BinaryData(buffer).ToStream(); Assert.Throws(() => stream.Position = -1); Assert.Throws(() => stream.Position = (long)int.MaxValue + 1); @@ -558,7 +558,7 @@ public void ValidatesPositionValue() [Fact] public void CloseStreamValidation() { - byte[] buffer = Encoding.UTF8.GetBytes("some data"); + byte[] buffer = "some data"u8; Stream stream = new BinaryData(buffer).ToStream(); stream.Dispose(); Assert.Throws(() => stream.Position = -1); diff --git a/src/libraries/System.Memory/tests/Base64/Base64DecoderUnitTests.cs b/src/libraries/System.Memory/tests/Base64/Base64DecoderUnitTests.cs index 7a1112fd206b7c..9e3b73030169b0 100644 --- a/src/libraries/System.Memory/tests/Base64/Base64DecoderUnitTests.cs +++ b/src/libraries/System.Memory/tests/Base64/Base64DecoderUnitTests.cs @@ -337,7 +337,7 @@ public void DecodingInvalidBytes(bool isFinalBlock) for (int j = 0; j < 8; j++) { - Span source = new byte[8] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP" + Span source = "2222PPPP"u8; // valid input Span decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)]; for (int i = 0; i < invalidBytes.Length; i++) @@ -368,7 +368,7 @@ public void DecodingInvalidBytes(bool isFinalBlock) // Input that is not a multiple of 4 is considered invalid, if isFinalBlock = true if (isFinalBlock) { - Span source = new byte[7] { 50, 50, 50, 50, 80, 80, 80 }; // incomplete input - "2222PPP" + Span source = "2222PPP"u8; // incomplete input Span decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)]; Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount)); Assert.Equal(4, consumed); @@ -385,7 +385,7 @@ public void DecodingInvalidBytesPadding(bool isFinalBlock) // Only last 2 bytes can be padding, all other occurrence of padding is invalid for (int j = 0; j < 7; j++) { - Span source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP" + Span source = "2222PPPP"u8; // valid input Span decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)]; source[j] = Base64TestHelper.EncodingPad; Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount, isFinalBlock)); @@ -405,7 +405,7 @@ public void DecodingInvalidBytesPadding(bool isFinalBlock) // Invalid input with valid padding { - Span source = new byte[] { 50, 50, 50, 50, 80, 42, 42, 42 }; + Span source = "2222P***"u8; Span decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)]; source[6] = Base64TestHelper.EncodingPad; source[7] = Base64TestHelper.EncodingPad; // invalid input - "2222P*==" @@ -415,7 +415,7 @@ public void DecodingInvalidBytesPadding(bool isFinalBlock) Assert.Equal(3, decodedByteCount); Assert.True(Base64TestHelper.VerifyDecodingCorrectness(4, 3, source, decodedBytes)); - source = new byte[] { 50, 50, 50, 50, 80, 42, 42, 42 }; + source = "2222P***"u8; decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)]; source[7] = Base64TestHelper.EncodingPad; // invalid input - "2222PP**=" Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8(source, decodedBytes, out consumed, out decodedByteCount, isFinalBlock)); @@ -427,7 +427,7 @@ public void DecodingInvalidBytesPadding(bool isFinalBlock) // The last byte or the last 2 bytes being the padding character is valid, if isFinalBlock = true { - Span source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; + Span source = "2222PPPP"u8; Span decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)]; source[6] = Base64TestHelper.EncodingPad; source[7] = Base64TestHelper.EncodingPad; // valid input - "2222PP==" @@ -441,7 +441,7 @@ public void DecodingInvalidBytesPadding(bool isFinalBlock) Assert.Equal(expectedWritten, decodedByteCount); Assert.True(Base64TestHelper.VerifyDecodingCorrectness(expectedConsumed, expectedWritten, source, decodedBytes)); - source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; + source = "2222PPPP"u8; decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)]; source[7] = Base64TestHelper.EncodingPad; // valid input - "2222PPP=" @@ -535,7 +535,7 @@ public void DecodeInPlaceInvalidBytes() { for (int i = 0; i < invalidBytes.Length; i++) { - Span buffer = new byte[8] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP" + Span buffer = "2222PPPP"u8; // valid input // Don't test padding (byte 61 i.e. '='), which is tested in DecodeInPlaceInvalidBytesPadding if (invalidBytes[i] == Base64TestHelper.EncodingPad) @@ -562,7 +562,7 @@ public void DecodeInPlaceInvalidBytes() // Input that is not a multiple of 4 is considered invalid { - Span buffer = new byte[7] { 50, 50, 50, 50, 80, 80, 80 }; // incomplete input - "2222PPP" + Span buffer = "2222PPP"u8; // incomplete input Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten)); Assert.Equal(0, bytesWritten); } @@ -574,7 +574,7 @@ public void DecodeInPlaceInvalidBytesPadding() // Only last 2 bytes can be padding, all other occurrence of padding is invalid for (int j = 0; j < 7; j++) { - Span buffer = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP" + Span buffer = "2222PPPP"u8; // valid input buffer[j] = Base64TestHelper.EncodingPad; string sourceString = Encoding.ASCII.GetString(buffer.Slice(0, 4).ToArray()); @@ -594,7 +594,7 @@ public void DecodeInPlaceInvalidBytesPadding() // Invalid input with valid padding { - Span buffer = new byte[] { 50, 50, 50, 50, 80, 42, 42, 42 }; + Span buffer = "2222P***"u8; buffer[6] = Base64TestHelper.EncodingPad; buffer[7] = Base64TestHelper.EncodingPad; // invalid input - "2222P*==" string sourceString = Encoding.ASCII.GetString(buffer.Slice(0, 4).ToArray()); @@ -605,7 +605,7 @@ public void DecodeInPlaceInvalidBytesPadding() } { - Span buffer = new byte[] { 50, 50, 50, 50, 80, 42, 42, 42 }; + Span buffer = "2222P***"u8; buffer[7] = Base64TestHelper.EncodingPad; // invalid input - "2222P**=" string sourceString = Encoding.ASCII.GetString(buffer.Slice(0, 4).ToArray()); Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten)); @@ -616,7 +616,7 @@ public void DecodeInPlaceInvalidBytesPadding() // The last byte or the last 2 bytes being the padding character is valid { - Span buffer = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; + Span buffer = "2222PPPP"u8; buffer[6] = Base64TestHelper.EncodingPad; buffer[7] = Base64TestHelper.EncodingPad; // valid input - "2222PP==" string sourceString = Encoding.ASCII.GetString(buffer.ToArray()); @@ -627,7 +627,7 @@ public void DecodeInPlaceInvalidBytesPadding() } { - Span buffer = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; + Span buffer = "2222PPPP"u8; buffer[7] = Base64TestHelper.EncodingPad; // valid input - "2222PPP=" string sourceString = Encoding.ASCII.GetString(buffer.ToArray()); Assert.Equal(OperationStatus.Done, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten)); diff --git a/src/libraries/System.Memory/tests/BuffersExtensions/BuffersExtensionsTests.cs b/src/libraries/System.Memory/tests/BuffersExtensions/BuffersExtensionsTests.cs index fc55fbe29fad49..d3f180d9230d7b 100644 --- a/src/libraries/System.Memory/tests/BuffersExtensions/BuffersExtensionsTests.cs +++ b/src/libraries/System.Memory/tests/BuffersExtensions/BuffersExtensionsTests.cs @@ -13,8 +13,8 @@ public class BuffersExtensionsTests public void WritingToSingleSegmentBuffer() { IBufferWriter bufferWriter = new TestBufferWriterSingleSegment(); - bufferWriter.Write(Encoding.UTF8.GetBytes("Hello")); - bufferWriter.Write(Encoding.UTF8.GetBytes(" World!")); + bufferWriter.Write("Hello"u8); + bufferWriter.Write(" World!"u8); Assert.Equal("Hello World!", bufferWriter.ToString()); } @@ -22,8 +22,8 @@ public void WritingToSingleSegmentBuffer() public void WritingToMultiSegmentBuffer() { var bufferWriter = new TestBufferWriterMultiSegment(); - bufferWriter.Write(Encoding.UTF8.GetBytes("Hello")); - bufferWriter.Write(Encoding.UTF8.GetBytes(" World!")); + bufferWriter.Write("Hello"u8); + bufferWriter.Write(" World!"u8); Assert.Equal(12, bufferWriter.Comitted.Count); Assert.Equal("Hello World!", bufferWriter.ToString()); } diff --git a/src/libraries/System.Memory/tests/EncodingExtensions/EncodingExtensionsTests.cs b/src/libraries/System.Memory/tests/EncodingExtensions/EncodingExtensionsTests.cs index 268b59b909bda3..6c58937760d4dd 100644 --- a/src/libraries/System.Memory/tests/EncodingExtensions/EncodingExtensionsTests.cs +++ b/src/libraries/System.Memory/tests/EncodingExtensions/EncodingExtensionsTests.cs @@ -74,7 +74,7 @@ public static void Convert_Decoder_ReadOnlySpan_IBufferWriter() // First, a small input with no flushing and no leftover data. - ReadOnlySpan inputData = Encoding.UTF8.GetBytes("Hello"); + ReadOnlySpan inputData = "Hello"u8; EncodingExtensions.Convert(decoder, inputData, writer, flush: false, out long charsUsed, out bool completed); Assert.Equal(5, charsUsed); Assert.True(completed); @@ -236,7 +236,7 @@ public static void Convert_Encoder_ReadOnlySequence_IBufferWriter() // Now make sure all of the data was decoded properly. - Assert.Equal(Encoding.UTF8.GetBytes("\u0020\ud7ff\U00100000\ufffd"), writer.WrittenSpan.ToArray()); + Assert.Equal("\u0020\ud7ff\U00100000\ufffd"u8, writer.WrittenSpan.ToArray()); } [Fact] @@ -252,7 +252,7 @@ public static void GetBytes_Encoding_ReadOnlySequence() // First try the single-segment code path. ReadOnlySequence sequence = new ReadOnlySequence("Hello!".ToCharArray()); - Assert.Equal(Encoding.UTF8.GetBytes("Hello!"), EncodingExtensions.GetBytes(Encoding.UTF8, sequence)); + Assert.Equal("Hello!"u8, EncodingExtensions.GetBytes(Encoding.UTF8, sequence)); // Next try the multi-segment code path. // We've intentionally split multi-char subsequences here to test flushing mechanisms. @@ -266,7 +266,7 @@ public static void GetBytes_Encoding_ReadOnlySequence() new char[] { '\udfff' }, // (cont.) new char[] { '\ud800' }); // leftover data (should be replaced) - Assert.Equal(Encoding.UTF8.GetBytes("\u0020\u0061\u0080\U00010000\U0010FFFF\ufffd"), EncodingExtensions.GetBytes(Encoding.UTF8, sequence)); + Assert.Equal("\u0020\u0061\u0080\U00010000\U0010FFFF\ufffd"u8, EncodingExtensions.GetBytes(Encoding.UTF8, sequence)); } [Fact] @@ -278,7 +278,7 @@ public static void GetBytes_Encoding_ReadOnlySequence_IBufferWriter_SingleSegmen long bytesWritten = EncodingExtensions.GetBytes(Encoding.UTF8, sequence, writer); Assert.Equal(5, bytesWritten); - Assert.Equal(Encoding.UTF8.GetBytes("Hello"), writer.WrittenSpan.ToArray()); + Assert.Equal("Hello"u8, writer.WrittenSpan.ToArray()); } [Fact] @@ -320,7 +320,7 @@ public static void GetBytes_Encoding_ReadOnlySequence_Span() ReadOnlySequence sequence = new ReadOnlySequence("Hello!".ToCharArray()); Assert.Equal( - expected: Encoding.UTF8.GetBytes("Hello!"), + expected: "Hello!"u8, actual: destination.Slice(0, EncodingExtensions.GetBytes(Encoding.UTF8, sequence, destination)).ToArray()); // Next try the multi-segment code path. @@ -336,7 +336,7 @@ public static void GetBytes_Encoding_ReadOnlySequence_Span() new char[] { '\ud800' }); // leftover data (should be replaced) Assert.Equal( - expected: Encoding.UTF8.GetBytes("\u0020\u0061\u0080\U00010000\U0010FFFF\ufffd"), + expected: "\u0020\u0061\u0080\U00010000\U0010FFFF\ufffd"u8, actual: destination.Slice(0, EncodingExtensions.GetBytes(Encoding.UTF8, sequence, destination)).ToArray()); } @@ -359,7 +359,7 @@ public static void GetBytes_Encoding_ReadOnlySpan_IBufferWriter() ReadOnlySpan inputData = "Hello"; long bytesWritten = EncodingExtensions.GetBytes(Encoding.UTF8, inputData, writer); Assert.Equal(5, bytesWritten); - Assert.Equal(Encoding.UTF8.GetBytes("Hello"), writer.WrittenSpan.ToArray()); + Assert.Equal("Hello"u8, writer.WrittenSpan.ToArray()); // Then, a large input that goes through the chunked path. // We alternate between 1-char and 2-char sequences so that the input will be split in @@ -399,7 +399,7 @@ public static void GetString_Encoding_ReadOnlySequence() { // First try the single-segment code path. - ReadOnlySequence sequence = new ReadOnlySequence(Encoding.UTF8.GetBytes("Hello!")); + ReadOnlySequence sequence = new ReadOnlySequence("Hello!"u8); Assert.Equal("Hello!", EncodingExtensions.GetString(Encoding.UTF8, sequence)); // Next try the multi-segment code path. @@ -427,7 +427,7 @@ public static void GetString_Encoding_ReadOnlySequence_ParamChecks() [Fact] public static void GetChars_Encoding_ReadOnlySequence_IBufferWriter_SingleSegment() { - ReadOnlySequence sequence = new ReadOnlySequence(Encoding.UTF8.GetBytes("Hello")); + ReadOnlySequence sequence = new ReadOnlySequence("Hello"u8); ArrayBufferWriter writer = new ArrayBufferWriter(); long charsWritten = EncodingExtensions.GetChars(Encoding.UTF8, sequence, writer); @@ -466,7 +466,7 @@ public static void GetChars_Encoding_ReadOnlySequence_Span() // First try the single-segment code path. - ReadOnlySequence sequence = new ReadOnlySequence(Encoding.UTF8.GetBytes("Hello!")); + ReadOnlySequence sequence = new ReadOnlySequence("Hello!"u8); Assert.Equal("Hello!", destination.Slice(0, EncodingExtensions.GetChars(Encoding.UTF8, sequence, destination)).ToString()); // Next try the multi-segment code path. @@ -507,7 +507,7 @@ public static void GetChars_Encoding_ReadOnlySpan_IBufferWriter() // First, a small input that goes through the one-shot code path. - ReadOnlySpan inputData = Encoding.UTF8.GetBytes("Hello"); + ReadOnlySpan inputData = "Hello"u8; long charsWritten = EncodingExtensions.GetChars(Encoding.UTF8, inputData, writer); Assert.Equal(5, charsWritten); Assert.Equal("Hello", writer.WrittenSpan.ToString()); diff --git a/src/libraries/System.Memory/tests/ReadOnlyBuffer/ReadOnlySequenceTests.Common.byte.cs b/src/libraries/System.Memory/tests/ReadOnlyBuffer/ReadOnlySequenceTests.Common.byte.cs index 60e3a6b676db4e..ec93996a40d03f 100644 --- a/src/libraries/System.Memory/tests/ReadOnlyBuffer/ReadOnlySequenceTests.Common.byte.cs +++ b/src/libraries/System.Memory/tests/ReadOnlyBuffer/ReadOnlySequenceTests.Common.byte.cs @@ -44,7 +44,7 @@ public void HelloWorldAcrossTwoBlocks() // [padding..hello] -> [ world ] const int blockSize = 4096; - byte[] items = Encoding.ASCII.GetBytes("Hello World"); + byte[] items = "Hello World"u8; byte[] firstItems = Enumerable.Repeat((byte)'a', blockSize - 5).Concat(items.Take(5)).ToArray(); byte[] secondItems = items.Skip(5).Concat(Enumerable.Repeat((byte)'a', blockSize - (items.Length - 5))).ToArray(); diff --git a/src/libraries/System.Memory/tests/SequenceReader/ReadTo.cs b/src/libraries/System.Memory/tests/SequenceReader/ReadTo.cs index b042eb9d556b8a..964aca941c0313 100644 --- a/src/libraries/System.Memory/tests/SequenceReader/ReadTo.cs +++ b/src/libraries/System.Memory/tests/SequenceReader/ReadTo.cs @@ -173,18 +173,18 @@ public void TryReadToSpan_Sequence(bool advancePastDelimiter) } bytes = SequenceFactory.Create(new byte[][] { - new byte[] { 47, 42, 66, 32, 42, 32, 66, 42, 47 } // /*b * b*/ + "/*B * B*/"u8 }); baseReader = new SequenceReader(bytes); SequenceReader copyReader = baseReader; - Assert.True(copyReader.TryReadTo(out ReadOnlySpan span, new byte[] { 42, 47 }, advancePastDelimiter)); // */ - Assert.True(span.SequenceEqual(new byte[] { 47, 42, 66, 32, 42, 32, 66 })); + Assert.True(copyReader.TryReadTo(out ReadOnlySpan span, "*/"u8, advancePastDelimiter)); // */ + Assert.True(span.SequenceEqual("/*B * B"u8)); copyReader = baseReader; - Assert.True(copyReader.TryReadTo(out ReadOnlySequence sequence, new byte[] { 42, 47 }, advancePastDelimiter)); // */ - Assert.True(sequence.ToArray().AsSpan().SequenceEqual(new byte[] { 47, 42, 66, 32, 42, 32, 66 })); + Assert.True(copyReader.TryReadTo(out ReadOnlySequence sequence, "*/"u8, advancePastDelimiter)); // */ + Assert.True(sequence.ToArray().AsSpan().SequenceEqual("/*B * B"u8)); } [Theory, @@ -258,9 +258,9 @@ public void TryReadTo_SingleDelimiter() [Fact] public void TryReadTo_Span_At_Segments_Boundary() { - Span delimiter = new byte[] { 13, 10 }; // \r\n - BufferSegment segment = new BufferSegment(Text.Encoding.ASCII.GetBytes("Hello\r")); - segment.Append(Text.Encoding.ASCII.GetBytes("\nWorld")); // add next segment + Span delimiter = "\r\n"u8; + BufferSegment segment = new BufferSegment("Hello\r"u8); + segment.Append("\nWorld"u8); // add next segment ReadOnlySequence inputSeq = new ReadOnlySequence(segment, 0, segment, 6); // span only the first segment! SequenceReader sr = new SequenceReader(inputSeq); bool r = sr.TryReadTo(out ReadOnlySpan _, delimiter); diff --git a/src/libraries/System.Memory/tests/SequenceReader/SkipDelimiter.cs b/src/libraries/System.Memory/tests/SequenceReader/SkipDelimiter.cs index 526a5fffe6b0fd..fdd185d611603d 100644 --- a/src/libraries/System.Memory/tests/SequenceReader/SkipDelimiter.cs +++ b/src/libraries/System.Memory/tests/SequenceReader/SkipDelimiter.cs @@ -12,7 +12,7 @@ public class SkipDelimiter [Fact] public void TryReadTo_SkipDelimiter() { - byte[] expected = Encoding.UTF8.GetBytes("This is our ^|understanding^|"); + byte[] expected = "This is our ^|understanding^|"u8; ReadOnlySequence bytes = SequenceFactory.CreateUtf8("This is our ^|understanding^|| you see."); SequenceReader reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out ReadOnlySpan span, (byte)'|', (byte)'^', advancePastDelimiter: true)); @@ -125,12 +125,12 @@ public void TryReadTo_SkipDelimiter() bytes = SequenceFactory.CreateUtf8("abc^|de|"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^|de"), span.ToArray()); + Assert.Equal("abc^|de"u8, span.ToArray()); Assert.True(reader.End); Assert.Equal(8, reader.Consumed); reader.Rewind(reader.Consumed); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^|de"), sequence.ToArray()); + Assert.Equal("abc^|de"u8, sequence.ToArray()); Assert.True(reader.End); Assert.Equal(8, reader.Consumed); @@ -138,12 +138,12 @@ public void TryReadTo_SkipDelimiter() bytes = SequenceFactory.CreateUtf8("^|a|b"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); - Assert.Equal(Encoding.UTF8.GetBytes("^|a"), span.ToArray()); + Assert.Equal("^|a"u8, span.ToArray()); Assert.True(reader.IsNext((byte)'b')); Assert.Equal(4, reader.Consumed); reader.Rewind(reader.Consumed); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); - Assert.Equal(Encoding.UTF8.GetBytes("^|a"), sequence.ToArray()); + Assert.Equal("^|a"u8, sequence.ToArray()); Assert.True(reader.IsNext((byte)'b')); Assert.Equal(4, reader.Consumed); @@ -151,12 +151,12 @@ public void TryReadTo_SkipDelimiter() bytes = SequenceFactory.CreateUtf8("^", "|a|b"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); - Assert.Equal(Encoding.UTF8.GetBytes("^|a"), span.ToArray()); + Assert.Equal("^|a"u8, span.ToArray()); Assert.True(reader.IsNext((byte)'b')); Assert.Equal(4, reader.Consumed); reader.Rewind(reader.Consumed); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); - Assert.Equal(Encoding.UTF8.GetBytes("^|a"), sequence.ToArray()); + Assert.Equal("^|a"u8, sequence.ToArray()); Assert.True(reader.IsNext((byte)'b')); Assert.Equal(4, reader.Consumed); } @@ -167,12 +167,12 @@ public void TryReadTo_SkipDelimiter_Runs() ReadOnlySequence bytes = SequenceFactory.CreateUtf8("abc^^|def"); SequenceReader reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out ReadOnlySpan span, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray()); + Assert.Equal("abc^^"u8, span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(5, reader.Consumed); reader.Rewind(reader.Consumed); Assert.True(reader.TryReadTo(out ReadOnlySequence sequence, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), sequence.ToArray()); + Assert.Equal("abc^^"u8, sequence.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(5, reader.Consumed); @@ -180,12 +180,12 @@ public void TryReadTo_SkipDelimiter_Runs() bytes = SequenceFactory.CreateUtf8("abc^^", "|def"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray()); + Assert.Equal("abc^^"u8, span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(5, reader.Consumed); reader.Rewind(reader.Consumed); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), sequence.ToArray()); + Assert.Equal("abc^^"u8, sequence.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(5, reader.Consumed); @@ -193,24 +193,24 @@ public void TryReadTo_SkipDelimiter_Runs() bytes = SequenceFactory.CreateUtf8("abc^", "^", "|def"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray()); + Assert.Equal("abc^^"u8, span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(5, reader.Consumed); reader.Rewind(reader.Consumed); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), sequence.ToArray()); + Assert.Equal("abc^^"u8, sequence.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(5, reader.Consumed); // Check advance past delimiter reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray()); + Assert.Equal("abc^^"u8, span.ToArray()); Assert.True(reader.IsNext((byte)'d')); Assert.Equal(6, reader.Consumed); reader.Rewind(reader.Consumed); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), sequence.ToArray()); + Assert.Equal("abc^^"u8, sequence.ToArray()); Assert.True(reader.IsNext((byte)'d')); Assert.Equal(6, reader.Consumed); @@ -218,12 +218,12 @@ public void TryReadTo_SkipDelimiter_Runs() bytes = SequenceFactory.CreateUtf8("^^|abc"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("^^"), span.ToArray()); + Assert.Equal("^^"u8, span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(2, reader.Consumed); reader.Rewind(reader.Consumed); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("^^"), sequence.ToArray()); + Assert.Equal("^^"u8, sequence.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(2, reader.Consumed); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs index 68794b69b666e1..6146893db2a134 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs @@ -16,8 +16,8 @@ namespace System.Net.Http { internal sealed class WinHttpRequestStream : Stream { - private static readonly byte[] s_crLfTerminator = new byte[] { 0x0d, 0x0a }; // "\r\n" - private static readonly byte[] s_endChunk = new byte[] { 0x30, 0x0d, 0x0a, 0x0d, 0x0a }; // "0\r\n\r\n" + private static readonly byte[] s_crLfTerminator = "\r\n"u8; + private static readonly byte[] s_endChunk = "0\r\n\r\n"u8; private volatile bool _disposed; private readonly WinHttpRequestState _state; diff --git a/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/BidirectionStreamingTest.cs b/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/BidirectionStreamingTest.cs index 0277ca26e817a2..a412bf2529c254 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/BidirectionStreamingTest.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/BidirectionStreamingTest.cs @@ -30,7 +30,7 @@ public BidirectionStreamingTest(ITestOutputHelper output) : base(output) protected override Version UseVersion => new Version(2, 0); - protected static byte[] DataBytes = Encoding.ASCII.GetBytes("data"); + protected static byte[] DataBytes = "data"u8; protected static Frame MakeDataFrame(int streamId, byte[] data, bool endStream = false) => new DataFrame(data, (endStream ? FrameFlags.EndStream : FrameFlags.None), 0, streamId); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/System.Net.Http.WinHttpHandler.Functional.Tests.csproj b/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/System.Net.Http.WinHttpHandler.Functional.Tests.csproj index f0af02b97b1d11..3abda3522b21f5 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/System.Net.Http.WinHttpHandler.Functional.Tests.csproj +++ b/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/System.Net.Http.WinHttpHandler.Functional.Tests.csproj @@ -3,7 +3,6 @@ $(NetCoreAppCurrent)-windows;net48 true $(DefineConstants);WINHTTPHANDLER_TEST - 10.0 new Version(2, 0); - protected static byte[] DataBytes = Encoding.ASCII.GetBytes("data"); + protected static byte[] DataBytes = "data"u8; protected static readonly IList TrailingHeaders = new HttpHeaderData[] { new HttpHeaderData("MyCoolTrailerHeader", "amazingtrailer"), diff --git a/src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/WinHttpResponseStreamTest.cs b/src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/WinHttpResponseStreamTest.cs index 90900a0517e07a..e7329298e4ee5c 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/WinHttpResponseStreamTest.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/WinHttpResponseStreamTest.cs @@ -331,7 +331,7 @@ public void Read_ReadDataFailsOnCompletionCallback_ThrowsIOException() public void Read_NoOffsetAndNotEndOfData_FillsBuffer() { Stream stream = MakeResponseStream(); - byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + byte[] testData = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"u8; TestServer.ResponseBody = testData; byte[] buffer = new byte[testData.Length]; @@ -348,7 +348,7 @@ public void Read_NoOffsetAndNotEndOfData_FillsBuffer() public void Read_UsingOffsetAndNotEndOfData_FillsBufferFromOffset() { Stream stream = MakeResponseStream(); - byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + byte[] testData = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"u8; TestServer.ResponseBody = testData; byte[] buffer = new byte[testData.Length]; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs index 85b3b94bb27d02..9dc706680c9b2d 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs @@ -75,7 +75,7 @@ internal sealed partial class Http2Connection : HttpConnectionBase // Temporary workaround for request burst handling on connection start. private const int InitialMaxConcurrentStreams = 100; - private static readonly byte[] s_http2ConnectionPreface = Encoding.ASCII.GetBytes("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"); + private static ReadOnlySpan Http2ConnectionPreface => "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"u8; #if DEBUG // In debug builds, start with a very small buffer to induce buffer growing logic. @@ -178,13 +178,13 @@ public async ValueTask SetupAsync() { try { - _outgoingBuffer.EnsureAvailableSpace(s_http2ConnectionPreface.Length + + _outgoingBuffer.EnsureAvailableSpace(Http2ConnectionPreface.Length + FrameHeader.Size + FrameHeader.SettingLength + FrameHeader.Size + FrameHeader.WindowUpdateLength); // Send connection preface - s_http2ConnectionPreface.AsSpan().CopyTo(_outgoingBuffer.AvailableSpan); - _outgoingBuffer.Commit(s_http2ConnectionPreface.Length); + Http2ConnectionPreface.CopyTo(_outgoingBuffer.AvailableSpan); + _outgoingBuffer.Commit(Http2ConnectionPreface.Length); // Send SETTINGS frame. Disable push promise & set initial window size. FrameHeader.WriteTo(_outgoingBuffer.AvailableSpan, 2 * FrameHeader.SettingLength, FrameType.Settings, FrameFlags.None, streamId: 0); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs index 6fc6f59a37033c..60e7a5fa98eeda 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs @@ -27,7 +27,7 @@ private sealed class Http2Stream : IValueTaskSource, IHttpStreamHeadersHandler, 1024; #endif - private static ReadOnlySpan StatusHeaderName => new byte[] { (byte)':', (byte)'s', (byte)'t', (byte)'a', (byte)'t', (byte)'u', (byte)'s' }; + private static ReadOnlySpan StatusHeaderName => ":status"u8; private readonly Http2Connection _connection; private readonly HttpRequestMessage _request; @@ -477,7 +477,7 @@ public void OnWindowUpdate(int amount) private static readonly (HeaderDescriptor descriptor, byte[] value)[] s_hpackStaticHeaderTable = new (HeaderDescriptor, byte[])[LastHPackNormalHeaderId - FirstHPackNormalHeaderId + 1] { (KnownHeaders.AcceptCharset.Descriptor, Array.Empty()), - (KnownHeaders.AcceptEncoding.Descriptor, Encoding.ASCII.GetBytes("gzip, deflate")), + (KnownHeaders.AcceptEncoding.Descriptor, "gzip, deflate"u8), (KnownHeaders.AcceptLanguage.Descriptor, Array.Empty()), (KnownHeaders.AcceptRanges.Descriptor, Array.Empty()), (KnownHeaders.Accept.Descriptor, Array.Empty()), diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3RequestStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3RequestStream.cs index 410f050729d03e..0c3265272617bf 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3RequestStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3RequestStream.cs @@ -869,8 +869,6 @@ private async ValueTask ReadHeadersAsync(long headersLength, CancellationToken c _headerDecoder.Reset(); } - private static ReadOnlySpan StatusHeaderNameBytes => new byte[] { (byte)'s', (byte)'t', (byte)'a', (byte)'t', (byte)'u', (byte)'s' }; - void IHttpStreamHeadersHandler.OnHeader(ReadOnlySpan name, ReadOnlySpan value) { Debug.Assert(name.Length > 0); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs index ee90b645313fd0..611a15349d70d6 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs @@ -34,13 +34,13 @@ internal sealed partial class HttpConnection : HttpConnectionBase /// private const int Expect100ErrorSendThreshold = 1024; - private static readonly byte[] s_contentLength0NewlineAsciiBytes = Encoding.ASCII.GetBytes("Content-Length: 0\r\n"); - private static readonly byte[] s_spaceHttp10NewlineAsciiBytes = Encoding.ASCII.GetBytes(" HTTP/1.0\r\n"); - private static readonly byte[] s_spaceHttp11NewlineAsciiBytes = Encoding.ASCII.GetBytes(" HTTP/1.1\r\n"); + private static readonly byte[] s_contentLength0NewlineAsciiBytes = "Content-Length: 0\r\n"u8; + private static readonly byte[] s_spaceHttp10NewlineAsciiBytes = " HTTP/1.0\r\n"u8; + private static readonly byte[] s_spaceHttp11NewlineAsciiBytes = " HTTP/1.1\r\n"u8; private static readonly byte[] s_httpSchemeAndDelimiter = Encoding.ASCII.GetBytes(Uri.UriSchemeHttp + Uri.SchemeDelimiter); - private static readonly byte[] s_http1DotBytes = Encoding.ASCII.GetBytes("HTTP/1."); - private static readonly ulong s_http10Bytes = BitConverter.ToUInt64(Encoding.ASCII.GetBytes("HTTP/1.0")); - private static readonly ulong s_http11Bytes = BitConverter.ToUInt64(Encoding.ASCII.GetBytes("HTTP/1.1")); + private static readonly byte[] s_http1DotBytes = "HTTP/1."u8; + private static readonly ulong s_http10Bytes = BitConverter.ToUInt64("HTTP/1.0"u8); + private static readonly ulong s_http11Bytes = BitConverter.ToUInt64("HTTP/1.1"u8); private readonly HttpConnectionPool _pool; private readonly Stream _stream; diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/HPackTest.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/HPackTest.cs index c1a4cdb314c3f9..3e42cdec2418af 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/HPackTest.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/HPackTest.cs @@ -68,10 +68,10 @@ public static IEnumerable HeaderEncodingTestData() yield return new object[] { ":path", "/", new byte[] { 0x84 } }; // Indexed name, literal value. - yield return new object[] { "content-type", "text/plain; charset=utf-8", new byte[] { 0x0F, 0x10, 0x19, 0x74, 0x65, 0x78, 0x74, 0x2F, 0x70, 0x6C, 0x61, 0x69, 0x6E, 0x3B, 0x20, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3D, 0x75, 0x74, 0x66, 0x2D, 0x38 } }; + yield return new object[] { "content-type", "text/plain; charset=utf-8", "\u000f\u0010\u0019text/plain; charset=utf-8"u8 }; // Literal name, literal value. - yield return new object[] { LiteralHeaderName, LiteralHeaderValue, new byte[] { 0x00, 0x10, 0x78, 0x2D, 0x6C, 0x69, 0x74, 0x65, 0x72, 0x61, 0x6C, 0x2D, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x0B, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67, 0x20, 0x34, 0x35, 0x36 } }; + yield return new object[] { LiteralHeaderName, LiteralHeaderValue, "\0\u0010x-literal-header\vtesting 456"u8 }; } } } diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.Http2.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.Http2.cs index d22e553f7a29d8..190d349e18481c 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.Http2.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.Http2.cs @@ -2048,7 +2048,7 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async url => } catch (System.OperationCanceledException) { }; Assert.Null(frame); // Make sure we do not get any frames after getting Rst. - await connection.SendResponseBodyAsync(streamId, Encoding.ASCII.GetBytes("final"), isFinal: true); + await connection.SendResponseBodyAsync(streamId, "final"u8, isFinal: true); await connection.WaitForConnectionShutdownAsync(); }); } @@ -2213,7 +2213,7 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async url => } await connection.ReadBodyAsync(); await connection.SendResponseHeadersAsync(streamId, endStream: false, HttpStatusCode.OK); - await connection.SendResponseBodyAsync(streamId, Encoding.ASCII.GetBytes("OK")); + await connection.SendResponseBodyAsync(streamId, "OK"u8); await connection.ShutdownIgnoringErrorsAsync(streamId); }); } @@ -2352,7 +2352,7 @@ private async Task SendAndReceiveRequestEOFAsync(DuplexContent duplexContent, St [Fact] public async Task PostAsyncDuplex_ClientSendsEndStream_Success() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8; using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2412,7 +2412,7 @@ public async Task PostAsyncDuplex_ClientSendsEndStream_Success() [Fact] public async Task PostAsyncDuplex_ServerSendsEndStream_Success() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8; using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2472,7 +2472,7 @@ public async Task PostAsyncDuplex_ServerSendsEndStream_Success() [Fact] public async Task PostAsyncDuplex_RequestContentException_ResetsStream() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8; using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2529,7 +2529,7 @@ public async Task PostAsyncDuplex_RequestContentException_ResetsStream() [Fact] public async Task PostAsyncDuplex_RequestContentExceptionAfterResponseEndReceivedButBeforeConsumed_ResetsStreamAndThrowsOnResponseStreamRead() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8; using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2593,7 +2593,7 @@ public async Task PostAsyncDuplex_RequestContentExceptionAfterResponseEndReceive [Fact] public async Task PostAsyncDuplex_CancelledBeforeResponseHeadersReceived_ResetsStream() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8; using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2649,7 +2649,7 @@ public async Task PostAsyncDuplex_CancelledBeforeResponseHeadersReceived_ResetsS [Fact] public async Task PostAsyncDuplex_ServerResetsStream_Throws() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8; using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2710,7 +2710,7 @@ public async Task PostAsyncDuplex_ServerResetsStream_Throws() [Fact] public async Task PostAsyncDuplex_DisposeResponseBodyBeforeEnd_ResetsStreamAndThrowsOnRequestStreamWriteAndResponseStreamRead() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8; using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2777,7 +2777,7 @@ public async Task PostAsyncDuplex_DisposeResponseBodyBeforeEnd_ResetsStreamAndTh [Fact] public async Task PostAsyncDuplex_DisposeResponseBodyAfterEndReceivedButBeforeConsumed_ResetsStreamAndThrowsOnRequestStreamWriteAndResponseStreamRead() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8; using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2850,7 +2850,7 @@ public async Task PostAsyncDuplex_DisposeResponseBodyAfterEndReceivedButBeforeCo [Fact] public async Task PostAsyncDuplex_FinishRequestBodyAndDisposeResponseBodyAfterEndReceivedButBeforeConsumed_DoesNotResetStream() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8; using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2920,7 +2920,7 @@ public async Task PostAsyncDuplex_ServerCompletesResponseBodyThenResetsStreamWit // We should stop sending the request body, but treat the request as successful and // return the completed response body to the user. - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8; using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2989,7 +2989,7 @@ public async Task PostAsyncNonDuplex_ServerCompletesResponseBodyThenResetsStream // We should stop sending the request body, but treat the request as successful and // return the completed response body to the user. - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8; using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -3248,7 +3248,7 @@ await server.AcceptConnectionAsync(async connection => await sslStream.AuthenticateAsServerAsync(options, CancellationToken.None).ConfigureAwait(false); // Send back HTTP/1.1 response - await sslStream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/1.1 400 Unrecognized request\r\n\r\n"), CancellationToken.None); + await sslStream.WriteAsync("HTTP/1.1 400 Unrecognized request\r\n\r\n"u8, CancellationToken.None); }); Exception e = await Assert.ThrowsAsync(() => requestTask); @@ -3304,7 +3304,7 @@ public async Task Http2GetAsync_TrailigPseudo_Throw() Http2LoopbackConnection connection = await server.EstablishConnectionAsync(); int streamId = await connection.ReadRequestHeaderAsync(); await connection.SendDefaultResponseHeadersAsync(streamId); - await connection.SendResponseDataAsync(streamId, Encoding.ASCII.GetBytes("hello"), endStream: false); + await connection.SendResponseDataAsync(streamId, "hello"u8, endStream: false); await connection.SendResponseHeadersAsync(streamId, endStream : true, isTrailingHeader : true, headers: headers); await Assert.ThrowsAsync(() => sendTask); diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/HttpContentTest.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/HttpContentTest.cs index 4ddd6633a2e97e..f5bb150d779a11 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/HttpContentTest.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/HttpContentTest.cs @@ -366,7 +366,7 @@ public async Task LoadIntoBufferAsync_CallOnMockContentWithNullContentLength_Cop [InlineData(false)] public async Task LoadIntoBufferAsync_CallOnMockContentWithLessLengthThanContentLengthHeader_BufferedStreamLengthMatchesActualLengthNotContentLengthHeaderValue(bool readStreamAsync) { - byte[] data = Encoding.UTF8.GetBytes("16 bytes of data"); + byte[] data = "16 bytes of data"u8; var content = new MockContent(data); content.Headers.ContentLength = 32; // Set the Content-Length header to a value > actual data length. Assert.Equal(32, content.Headers.ContentLength); @@ -964,7 +964,7 @@ public MockContent(byte[] mockData, MockOptions options) if (mockData == null) { - _mockData = Encoding.UTF8.GetBytes("data"); + _mockData = "data"u8; } else { diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs index 1ac9ae91d01e04..83ca26c06b7270 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs @@ -150,7 +150,7 @@ public async Task ReadAsStringAsync_NoSubContent_MatchesExpected(MultipartConten [InlineData(MultipartContentToStringMode.CopyToAsync, true)] public async Task ReadAsStringAsync_OneSubContentWithHeaders_MatchesExpected(MultipartContentToStringMode mode, bool async) { - var subContent = new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent")); + var subContent = new ByteArrayContent("This is a ByteArrayContent"u8); subContent.Headers.Add("someHeaderName", "andSomeHeaderValue"); subContent.Headers.Add("someOtherHeaderName", new[] { "withNotOne", "ButTwoValues" }); subContent.Headers.Add("oneMoreHeader", new[] { "withNotOne", "AndNotTwo", "butThreeValues" }); @@ -177,7 +177,7 @@ public async Task ReadAsStringAsync_OneSubContentWithHeaders_MatchesExpected(Mul public async Task ReadAsStringAsync_TwoSubContents_MatchesExpected(MultipartContentToStringMode mode, bool async) { var mc = new MultipartContent("someSubtype", "theBoundary"); - mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent"))); + mc.Add(new ByteArrayContent("This is a ByteArrayContent"u8)); mc.Add(new StringContent("This is a StringContent")); Assert.Equal( @@ -274,9 +274,9 @@ public async Task ReadAsStreamAsync_Seek_JumpsToSpecifiedPosition(bool nestedCon var mc = new MultipartContent(); if (nestedContent) { - mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent"))); + mc.Add(new ByteArrayContent("This is a ByteArrayContent"u8)); mc.Add(new StringContent("This is a StringContent")); - mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("Another ByteArrayContent :-)"))); + mc.Add(new ByteArrayContent("Another ByteArrayContent :-)"u8)); } var memStream = new MemoryStream(); @@ -399,7 +399,7 @@ public async Task ReadAsStreamAsync_CustomEncodingSelector_SelectorIsCalledWithC stringContent.Headers.Add("StringContent", "foo"); mc.Add(stringContent); - var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("foo")); + var byteArrayContent = new ByteArrayContent("foo"u8); byteArrayContent.Headers.Add("ByteArrayContent", "foo"); mc.Add(byteArrayContent); @@ -445,15 +445,15 @@ public async Task ReadAsStreamAsync_CustomEncodingSelector_CustomEncodingIsUsed( stringContent.Headers.Add("latin1", "\uD83D\uDE00"); mc.Add(stringContent); - var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar2")); + var byteArrayContent = new ByteArrayContent("bar2"u8); byteArrayContent.Headers.Add("utf8", "\uD83D\uDE00"); mc.Add(byteArrayContent); - byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar3")); + byteArrayContent = new ByteArrayContent("bar3"u8); byteArrayContent.Headers.Add("ascii", "\uD83D\uDE00"); mc.Add(byteArrayContent); - byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar4")); + byteArrayContent = new ByteArrayContent("bar4"u8); byteArrayContent.Headers.Add("default", "\uD83D\uDE00"); mc.Add(byteArrayContent); @@ -476,28 +476,28 @@ public async Task ReadAsStreamAsync_CustomEncodingSelector_CustomEncodingIsUsed( } byte[] expected = Concat( - Encoding.Latin1.GetBytes("--fooBoundary\r\n"), - Encoding.Latin1.GetBytes("Content-Type: text/plain; charset=utf-8\r\n"), - Encoding.Latin1.GetBytes("latin1: "), + "--fooBoundary\r\n"u8, + "Content-Type: text/plain; charset=utf-8\r\n"u8, + "latin1: "u8, Encoding.Latin1.GetBytes("\uD83D\uDE00"), - Encoding.Latin1.GetBytes("\r\n\r\n"), - Encoding.Latin1.GetBytes("bar1"), - Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"), - Encoding.Latin1.GetBytes("utf8: "), - Encoding.UTF8.GetBytes("\uD83D\uDE00"), - Encoding.Latin1.GetBytes("\r\n\r\n"), - Encoding.Latin1.GetBytes("bar2"), - Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"), - Encoding.Latin1.GetBytes("ascii: "), + "\r\n\r\n"u8, + "bar1"u8, + "\r\n--fooBoundary\r\n"u8, + "utf8: "u8, + "\uD83D\uDE00"u8, + "\r\n\r\n"u8, + "bar2"u8, + "\r\n--fooBoundary\r\n"u8, + "ascii: "u8, Encoding.ASCII.GetBytes("\uD83D\uDE00"), - Encoding.Latin1.GetBytes("\r\n\r\n"), - Encoding.Latin1.GetBytes("bar3"), - Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"), - Encoding.Latin1.GetBytes("default: "), + "\r\n\r\n"u8, + "bar3"u8, + "\r\n--fooBoundary\r\n"u8, + "default: "u8, Encoding.Latin1.GetBytes("\uD83D\uDE00"), - Encoding.Latin1.GetBytes("\r\n\r\n"), - Encoding.Latin1.GetBytes("bar4"), - Encoding.Latin1.GetBytes("\r\n--fooBoundary--\r\n")); + "\r\n\r\n"u8, + "bar4"u8, + "\r\n--fooBoundary--\r\n"u8); Assert.Equal(expected, ms.ToArray()); diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamConformanceTests.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamConformanceTests.cs index f7f28da5d192a3..95fa61b816ba69 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamConformanceTests.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamConformanceTests.cs @@ -54,9 +54,9 @@ protected override async Task WriteResponseAsync(Stream responseStream, byte[] b // One chunk for the whole response body await responseStream.WriteAsync(Encoding.ASCII.GetBytes($"{bodyData.Length:X}\r\n")); await responseStream.WriteAsync(bodyData); - await responseStream.WriteAsync(Encoding.ASCII.GetBytes("\r\n")); + await responseStream.WriteAsync("\r\n"u8); } - await responseStream.WriteAsync(Encoding.ASCII.GetBytes("0\r\n\r\n")); + await responseStream.WriteAsync("0\r\n\r\n"u8); } } @@ -70,9 +70,9 @@ protected override async Task WriteResponseAsync(Stream responseStream, byte[] b // One chunk per byte of the response body await responseStream.WriteAsync(Encoding.ASCII.GetBytes($"1\r\n")); await responseStream.WriteAsync(bodyData.AsMemory(i, 1)); - await responseStream.WriteAsync(Encoding.ASCII.GetBytes("\r\n")); + await responseStream.WriteAsync("\r\n"u8); } - await responseStream.WriteAsync(Encoding.ASCII.GetBytes("0\r\n\r\n")); + await responseStream.WriteAsync("0\r\n\r\n"u8); } } diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamZeroByteReadTests.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamZeroByteReadTests.cs index 77acc77b344eff..98a8db71a1ef79 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamZeroByteReadTests.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamZeroByteReadTests.cs @@ -48,7 +48,7 @@ protected override async Task WriteAsync(Stream stream, byte[] data) { await stream.WriteAsync(Encoding.ASCII.GetBytes($"{data.Length:X}\r\n")); await stream.WriteAsync(data); - await stream.WriteAsync(Encoding.ASCII.GetBytes("\r\n")); + await stream.WriteAsync("\r\n"u8); } } @@ -62,7 +62,7 @@ protected override async Task WriteAsync(Stream stream, byte[] data) { await stream.WriteAsync(Encoding.ASCII.GetBytes($"1\r\n")); await stream.WriteAsync(data.AsMemory(i, 1)); - await stream.WriteAsync(Encoding.ASCII.GetBytes("\r\n")); + await stream.WriteAsync("\r\n"u8); } } } @@ -136,7 +136,7 @@ public async Task ZeroByteRead_IssuesZeroByteReadOnUnderlyingStream(StreamConfor await sawZeroByteRead.Task.WaitAsync(TimeSpan.FromSeconds(10)); Assert.False(zeroByteReadTask.IsCompleted); - byte[] data = Encoding.UTF8.GetBytes("Hello"); + byte[] data = "Hello"u8; await WriteAsync(server, data); await server.FlushAsync(); diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/SocketsHttpHandlerTest.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/SocketsHttpHandlerTest.cs index e9ad02906d43d8..15b6bff43258d8 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/SocketsHttpHandlerTest.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/SocketsHttpHandlerTest.cs @@ -576,7 +576,7 @@ public abstract class SocketsHttpHandler_TrailingHeaders_Test : HttpClientHandle { public SocketsHttpHandler_TrailingHeaders_Test(ITestOutputHelper output) : base(output) { } - protected static byte[] DataBytes = Encoding.ASCII.GetBytes("data"); + protected static byte[] DataBytes = "data"u8; protected static readonly IList TrailingHeaders = new HttpHeaderData[] { new HttpHeaderData("MyCoolTrailerHeader", "amazingtrailer"), @@ -1222,26 +1222,26 @@ await server.AcceptConnectionAsync(async (LoopbackServer.Connection connection) // Validate writing APIs on clientStream clientStream.WriteByte((byte)'!'); - clientStream.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2); + clientStream.Write("\r\n"u8, 0, 2); Assert.Equal("!", await connection.ReadLineAsync()); - clientStream.Write(new Span(new byte[] { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'\r', (byte)'\n' })); + clientStream.Write("hello\r\n"u8); Assert.Equal("hello", await connection.ReadLineAsync()); - await clientStream.WriteAsync(new byte[] { (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 7); + await clientStream.WriteAsync("world\r\n"u8, 0, 7); Assert.Equal("world", await connection.ReadLineAsync()); - await clientStream.WriteAsync(new Memory(new byte[] { (byte)'a', (byte)'n', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 5)); + await clientStream.WriteAsync(new Memory("and\r\n", 0, 5)); Assert.Equal("and", await connection.ReadLineAsync()); - await Task.Factory.FromAsync(clientStream.BeginWrite, clientStream.EndWrite, new byte[] { (byte)'b', (byte)'e', (byte)'y', (byte)'o', (byte)'n', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 8, null); + await Task.Factory.FromAsync(clientStream.BeginWrite, clientStream.EndWrite, "beyond\r\n"u8, 0, 8, null); Assert.Equal("beyond", await connection.ReadLineAsync()); clientStream.Flush(); await clientStream.FlushAsync(); // Validate reading APIs on clientStream - await connection.Stream.WriteAsync(Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwxyz")); + await connection.Stream.WriteAsync("abcdefghijklmnopqrstuvwxyz"u8); var buffer = new byte[1]; Assert.Equal('a', clientStream.ReadByte()); @@ -2631,8 +2631,8 @@ public async Task ConnectCallback_ConnectionPrefix_Success(bool useSsl) { GenericLoopbackOptions options = new GenericLoopbackOptions() { UseSsl = useSsl }; - byte[] RequestPrefix = Encoding.UTF8.GetBytes("request prefix\r\n"); - byte[] ResponsePrefix = Encoding.UTF8.GetBytes("response prefix\r\n"); + byte[] RequestPrefix = "request prefix\r\n"u8; + byte[] ResponsePrefix = "response prefix\r\n"u8; Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); @@ -3097,8 +3097,8 @@ await LoopbackServerFactory.CreateClientAndServerAsync( [InlineData(false)] public async Task PlaintextStreamFilter_ConnectionPrefix_Success(bool useSsl) { - byte[] RequestPrefix = Encoding.UTF8.GetBytes("request prefix\r\n"); - byte[] ResponsePrefix = Encoding.UTF8.GetBytes("response prefix\r\n"); + byte[] RequestPrefix = "request prefix\r\n"u8; + byte[] ResponsePrefix = "response prefix\r\n"u8; using var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); @@ -3276,7 +3276,7 @@ await LoopbackServerFactory.CreateClientAndServerAsync( context.PlaintextStream.Dispose(); MemoryStream memoryStream = new MemoryStream(); - memoryStream.Write(Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nfoo")); + memoryStream.Write("HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nfoo"u8); memoryStream.Seek(0, SeekOrigin.Begin); DelegateStream newStream = new DelegateStream( diff --git a/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs b/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs index e89d38c204bfdb..2e04d0f206c9bf 100644 --- a/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs +++ b/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs @@ -21,15 +21,15 @@ public static IEnumerable MultipartContent_TestData() stringContent.Headers.Add("latin1", "\uD83D\uDE00"); complexContent.Add(stringContent); - var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar2")); + var byteArrayContent = new ByteArrayContent("bar2"u8); byteArrayContent.Headers.Add("utf8", "\uD83D\uDE00"); complexContent.Add(byteArrayContent); - byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar3")); + byteArrayContent = new ByteArrayContent("bar3"u8); byteArrayContent.Headers.Add("ascii", "\uD83D\uDE00"); complexContent.Add(byteArrayContent); - byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar4")); + byteArrayContent = new ByteArrayContent("bar4"u8); byteArrayContent.Headers.Add("default", "\uD83D\uDE00"); complexContent.Add(byteArrayContent); diff --git a/src/libraries/System.Net.Http/tests/UnitTests/MockContent.cs b/src/libraries/System.Net.Http/tests/UnitTests/MockContent.cs index 84971cbe30f048..917ed1834fd4c5 100644 --- a/src/libraries/System.Net.Http/tests/UnitTests/MockContent.cs +++ b/src/libraries/System.Net.Http/tests/UnitTests/MockContent.cs @@ -72,7 +72,7 @@ public MockContent(byte[] mockData, MockOptions options) if (mockData == null) { - _mockData = Encoding.UTF8.GetBytes("data"); + _mockData = "data"u8; } else { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs index 3a9129933d2be0..a96f250b07c33a 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs @@ -64,7 +64,7 @@ private sealed class Context : TransportContext private HttpListenerContext _context; private bool _isChunked; - private static byte[] s_100continue = Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n"); + private static byte[] s_100continue = "HTTP/1.1 100 Continue\r\n\r\n"u8; internal HttpListenerRequest(HttpListenerContext context) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs index 5aa170f8b74037..ab16dc87b61796 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs @@ -128,7 +128,7 @@ internal async Task WriteWebSocketHandshakeHeadersAsync() } } - private static byte[] s_crlf = new byte[] { 13, 10 }; + private static byte[] s_crlf = "\r\n"u8; private static byte[] GetChunkSizeBytes(int size, bool final) => Encoding.ASCII.GetBytes($"{size:x}\r\n{(final ? "\r\n" : "")}"); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs index 1a04d90b7e81e7..dc54f6cd6bfae0 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs @@ -281,7 +281,7 @@ private void UpdateAfterWrite(uint dataWritten) if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "dataWritten:" + dataWritten + " _leftToWrite:" + _leftToWrite + " _closed:" + _closed); } - private static ReadOnlySpan ChunkTerminator => new byte[] { (byte)'0', (byte)'\r', (byte)'\n', (byte)'\r', (byte)'\n' }; + private static ReadOnlySpan ChunkTerminator => "0\r\n\r\n"u8; private void DisposeCore() { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs index 64514975250536..55d90c45a57210 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs @@ -107,7 +107,7 @@ private static byte[] GetChunkHeader(int size, out int offset) return Header; } - private static readonly byte[] s_CRLFArray = new byte[] { (byte)'\r', (byte)'\n' }; + private static readonly byte[] s_CRLFArray = "\r\n"u8; internal HttpResponseStreamAsyncResult(object asyncObject, object? userState, AsyncCallback? callback, byte[] buffer, int offset, int size, bool chunked, bool sentHeaders, ThreadPoolBoundHandle boundHandle) : base(asyncObject, userState, callback) { diff --git a/src/libraries/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs b/src/libraries/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs index 89d5c2428e06c7..900fea85114181 100644 --- a/src/libraries/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs +++ b/src/libraries/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs @@ -102,7 +102,7 @@ public static IEnumerable BasicAuthenticationHeader_TestData() { yield return new object[] { string.Empty, HttpStatusCode.Unauthorized }; yield return new object[] { null, HttpStatusCode.Unauthorized }; - yield return new object[] { Convert.ToBase64String(Encoding.ASCII.GetBytes("username")), HttpStatusCode.BadRequest }; + yield return new object[] { Convert.ToBase64String("username"u8), HttpStatusCode.BadRequest }; yield return new object[] { "abc", HttpStatusCode.InternalServerError }; } diff --git a/src/libraries/System.Net.HttpListener/tests/HttpListenerContextTests.cs b/src/libraries/System.Net.HttpListener/tests/HttpListenerContextTests.cs index a276a610b400ac..e7e234d612f7a1 100644 --- a/src/libraries/System.Net.HttpListener/tests/HttpListenerContextTests.cs +++ b/src/libraries/System.Net.HttpListener/tests/HttpListenerContextTests.cs @@ -101,7 +101,7 @@ public async Task AcceptWebSocketAsync_ValidWebSocket_SetsUpContextProperties() [ConditionalFact(nameof(IsNotWindows7))] public async Task AcceptWebSocketAsync_AuthorizationInHeaders_ThrowsNotImplementedException() { - Socket.Options.SetRequestHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("user:password"))); + Socket.Options.SetRequestHeader("Authorization", "Basic " + Convert.ToBase64String("user:password"u8)); Factory.GetListener().AuthenticationSchemes = AuthenticationSchemes.Basic; HttpListenerContext context = await GetWebSocketContext(); diff --git a/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.cs b/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.cs index e2d1d826d44999..eab1226fc709ad 100644 --- a/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.cs +++ b/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.cs @@ -13,7 +13,7 @@ public class HttpListenerResponseTestBase : IDisposable { protected HttpListenerFactory Factory { get; } protected Socket Client { get; } - protected static byte[] SimpleMessage { get; } = Encoding.UTF8.GetBytes("Hello"); + protected static byte[] SimpleMessage { get; } = "Hello"u8; public HttpListenerResponseTestBase() { @@ -276,7 +276,7 @@ public async Task CloseResponseEntity_AllContentLengthAlreadySent_DoesNotSendEnt response.OutputStream.Write(SimpleMessage, 0, SimpleMessage.Length); // There is no more space left in the stream - the responseEntity ("a") won't be sent. - response.Close(new byte[] { (byte)'a' }, willBlock); + response.Close("a"u8, willBlock); Assert.Equal(SimpleMessage.Length, response.ContentLength64); string clientResponse = GetClientResponse(111); @@ -296,7 +296,7 @@ public async Task CloseResponseEntity_NotChunkedSentHeaders_SendsEntityWithoutMo response.OutputStream.Write(SimpleMessage, 0, SimpleMessage.Length - 1); // There is space left in the stream - the responseEntity will be sent. - response.Close(new byte[] { (byte)'a' }, willBlock); + response.Close("a"u8, willBlock); Assert.Equal(SimpleMessage.Length, response.ContentLength64); string clientResponse = GetClientResponse(111); @@ -314,7 +314,7 @@ public async Task CloseResponseEntity_ChunkedNotSentHeaders_ModifiesContentLengt { response.SendChunked = true; - response.Close(new byte[] { (byte)'a' }, willBlock); + response.Close("a"u8, willBlock); Assert.Equal(-1, response.ContentLength64); string clientResponse = GetClientResponse(126); @@ -333,7 +333,7 @@ public async Task CloseResponseEntity_ChunkedSentHeaders_DoesNotModifyContentLen response.SendChunked = true; response.OutputStream.Write(SimpleMessage, 0, SimpleMessage.Length); - response.Close(new byte[] { (byte)'a' }, willBlock); + response.Close("a"u8, willBlock); Assert.Equal(-1, response.ContentLength64); string clientResponse = GetClientResponse(136); @@ -372,14 +372,14 @@ public async Task CloseResponseEntity_SendMoreThanContentLength_ThrowsInvalidOpe if (willBlock) { - Assert.Throws(() => response.Close(new byte[] { (byte)'a', (byte)'b' }, willBlock)); + Assert.Throws(() => response.Close("ab"u8, willBlock)); } else { // Since this is non-blocking, an InvalidOperation or ProtocolViolationException may be thrown, // depending on timing. This is because any exceptions are swallowed up by NonBlockingCloseCallback, // but the response could have closed before that. - Assert.ThrowsAny(() => response.Close(new byte[] { (byte)'a', (byte)'b' }, willBlock)); + Assert.ThrowsAny(() => response.Close("ab"u8, willBlock)); } string clientResponse = GetClientResponse(110); @@ -426,7 +426,7 @@ public async Task CloseResponseEntity_SendToClosedConnection_DoesNotThrow(bool w // NonBlockingCloseCallback internally. try { - context.Response.Close(new byte[] { (byte)'a', (byte)'b' }, willBlock); + context.Response.Close("ab", willBlock); } catch (HttpListenerException) { diff --git a/src/libraries/System.Net.HttpListener/tests/HttpResponseStreamTests.cs b/src/libraries/System.Net.HttpListener/tests/HttpResponseStreamTests.cs index 841fae8c293ca2..7ccedb546a153c 100644 --- a/src/libraries/System.Net.HttpListener/tests/HttpResponseStreamTests.cs +++ b/src/libraries/System.Net.HttpListener/tests/HttpResponseStreamTests.cs @@ -62,7 +62,7 @@ public async Task SimpleRequest_WriteAsynchronously_Succeeds(bool sendChunked) outputStream.Close(); } - byte[] extraBytesSentAfterClose = Encoding.UTF8.GetBytes("Should not be sent."); + byte[] extraBytesSentAfterClose = "Should not be sent."u8; await outputStream.WriteAsync(extraBytesSentAfterClose, 0, extraBytesSentAfterClose.Length); } @@ -100,7 +100,7 @@ public async Task SimpleRequest_WriteSynchronouslyNonEmpty_Succeeds(bool sendChu outputStream.Close(); } - byte[] extraBytesSentAfterClose = Encoding.UTF8.GetBytes("Should not be sent."); + byte[] extraBytesSentAfterClose = "Should not be sent."u8; outputStream.Write(extraBytesSentAfterClose, 0, extraBytesSentAfterClose.Length); } @@ -308,7 +308,7 @@ public async Task Write_TooMuch_ThrowsProtocolViolationException() using (HttpListenerResponse response = serverContext.Response) { Stream output = response.OutputStream; - byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string"); + byte[] responseBuffer = "A long string"u8; response.ContentLength64 = responseBuffer.Length - 1; try { @@ -337,7 +337,7 @@ public async Task Write_TooLittleAsynchronouslyAndClose_ThrowsInvalidOperationEx { Stream output = response.OutputStream; - byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string"); + byte[] responseBuffer = "A long string"u8; response.ContentLength64 = responseBuffer.Length + 1; // Throws when there are bytes left to write @@ -363,7 +363,7 @@ public async Task Write_TooLittleSynchronouslyAndClose_ThrowsInvalidOperationExc { Stream output = response.OutputStream; - byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string"); + byte[] responseBuffer = "A long string"u8; response.ContentLength64 = responseBuffer.Length + 1; // Throws when there are bytes left to write diff --git a/src/libraries/System.Net.Mail/src/System/Net/BufferBuilder.cs b/src/libraries/System.Net.Mail/src/System/Net/BufferBuilder.cs index 7c630f65930539..5e47563fdd7821 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/BufferBuilder.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/BufferBuilder.cs @@ -39,6 +39,13 @@ internal void Append(byte[] value) Append(value, 0, value.Length); } + internal void Append(ReadOnlySpan value) + { + EnsureBuffer(value.Length); + value.CopyTo(_buffer.AsSpan(_offset)); + _offset += value.Length; + } + internal void Append(byte[] value, int offset, int count) { EnsureBuffer(count); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailWriter.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailWriter.cs index 914087cee23f87..b0527fe16f8c3f 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailWriter.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailWriter.cs @@ -37,7 +37,7 @@ internal override void WriteHeaders(NameValueCollection headers!!, bool allowUni /// internal override void Close() { - _bufferBuilder.Append(s_crlf); + _bufferBuilder.Append("\r\n"u8); Flush(null); _stream.Close(); } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpCommands.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpCommands.cs index e4b513d54dac17..cb37877b6464a9 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpCommands.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpCommands.cs @@ -666,25 +666,25 @@ internal static void Send(SmtpConnection conn) internal static class SmtpCommands { - internal static readonly byte[] Auth = Encoding.ASCII.GetBytes("AUTH "); - internal static readonly byte[] CRLF = Encoding.ASCII.GetBytes("\r\n"); - internal static readonly byte[] Data = Encoding.ASCII.GetBytes("DATA\r\n"); - internal static readonly byte[] DataStop = Encoding.ASCII.GetBytes("\r\n.\r\n"); - internal static readonly byte[] EHello = Encoding.ASCII.GetBytes("EHLO "); - internal static readonly byte[] Expand = Encoding.ASCII.GetBytes("EXPN "); - internal static readonly byte[] Hello = Encoding.ASCII.GetBytes("HELO "); - internal static readonly byte[] Help = Encoding.ASCII.GetBytes("HELP"); - internal static readonly byte[] Mail = Encoding.ASCII.GetBytes("MAIL FROM:"); - internal static readonly byte[] Noop = Encoding.ASCII.GetBytes("NOOP\r\n"); - internal static readonly byte[] Quit = Encoding.ASCII.GetBytes("QUIT\r\n"); - internal static readonly byte[] Recipient = Encoding.ASCII.GetBytes("RCPT TO:"); - internal static readonly byte[] Reset = Encoding.ASCII.GetBytes("RSET\r\n"); - internal static readonly byte[] Send = Encoding.ASCII.GetBytes("SEND FROM:"); - internal static readonly byte[] SendAndMail = Encoding.ASCII.GetBytes("SAML FROM:"); - internal static readonly byte[] SendOrMail = Encoding.ASCII.GetBytes("SOML FROM:"); - internal static readonly byte[] Turn = Encoding.ASCII.GetBytes("TURN\r\n"); - internal static readonly byte[] Verify = Encoding.ASCII.GetBytes("VRFY "); - internal static readonly byte[] StartTls = Encoding.ASCII.GetBytes("STARTTLS"); + internal static readonly byte[] Auth = "AUTH "u8; + internal static readonly byte[] CRLF = "\r\n"u8; + internal static readonly byte[] Data = "DATA\r\n"u8; + internal static readonly byte[] DataStop = "\r\n.\r\n"u8; + internal static readonly byte[] EHello = "EHLO "u8; + internal static readonly byte[] Expand = "EXPN "u8; + internal static readonly byte[] Hello = "HELO "u8; + internal static readonly byte[] Help = "HELP"u8; + internal static readonly byte[] Mail = "MAIL FROM:"u8; + internal static readonly byte[] Noop = "NOOP\r\n"u8; + internal static readonly byte[] Quit = "QUIT\r\n"u8; + internal static readonly byte[] Recipient = "RCPT TO:"u8; + internal static readonly byte[] Reset = "RSET\r\n"u8; + internal static readonly byte[] Send = "SEND FROM:"u8; + internal static readonly byte[] SendAndMail = "SAML FROM:"u8; + internal static readonly byte[] SendOrMail = "SOML FROM:"u8; + internal static readonly byte[] Turn = "TURN\r\n"u8; + internal static readonly byte[] Verify = "VRFY "u8; + internal static readonly byte[] StartTls = "STARTTLS"u8; } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs index 2998c9ff4226ba..0f1dd3661a2efd 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs @@ -16,7 +16,6 @@ internal abstract class BaseWriter // that are NOT encoded already, which means being less conservative is ok. private const int DefaultLineLength = 76; private static readonly AsyncCallback s_onWrite = OnWrite; - protected static readonly byte[] s_crlf = new byte[] { (byte)'\r', (byte)'\n' }; protected readonly BufferBuilder _bufferBuilder; protected readonly Stream _stream; @@ -50,7 +49,7 @@ internal void WriteHeader(string name!!, string value!!, bool allowUnicode) _bufferBuilder.Append(name); _bufferBuilder.Append(": "); WriteAndFold(value, name.Length + 2, allowUnicode); - _bufferBuilder.Append(s_crlf); + _bufferBuilder.Append("\r\n"u8); } private void WriteAndFold(string value, int charsAlreadyOnLine, bool allowUnicode) @@ -72,7 +71,7 @@ private void WriteAndFold(string value, int charsAlreadyOnLine, bool allowUnicod else if (((index - startOfLine) > (_lineLength - charsAlreadyOnLine)) && lastSpace != startOfLine) { _bufferBuilder.Append(value, startOfLine, lastSpace - startOfLine, allowUnicode); - _bufferBuilder.Append(s_crlf); + _bufferBuilder.Append("\r\n"u8); startOfLine = lastSpace; charsAlreadyOnLine = 0; } @@ -106,7 +105,7 @@ private Stream GetContentStream(MultiAsyncResult? multiResult) CheckBoundary(); - _bufferBuilder.Append(s_crlf); + _bufferBuilder.Append("\r\n"u8); Flush(multiResult); ClosableStream cs = new ClosableStream(new EightBitStream(_stream, _shouldEncodeLeadingDots), _onCloseHandler); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs index 5b1001c6a9ad0f..f9634a04a580ab 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs @@ -40,6 +40,6 @@ private static byte[] CreateHeader(Encoding encoding, bool useBase64Encoding) => Encoding.ASCII.GetBytes("=?" + encoding.HeaderName + "?" + (useBase64Encoding ? "B?" : "Q?")); //The footer that marks the end of a quoted string of some sort - private static readonly byte[] s_footer = new byte[] { (byte)'?', (byte)'=' }; + private static readonly byte[] s_footer = "?="u8; } } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeWriter.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeWriter.cs index 19b444795cdc05..4b6152f17a9e6a 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeWriter.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeWriter.cs @@ -14,8 +14,6 @@ namespace System.Net.Mime /// internal sealed class MimeWriter : BaseWriter { - private static readonly byte[] s_DASHDASH = new byte[] { (byte)'-', (byte)'-' }; - private readonly byte[] _boundaryBytes; private bool _writeBoundary = true; @@ -60,11 +58,9 @@ internal override void Close() private void Close(MultiAsyncResult? multiResult) { - _bufferBuilder.Append(s_crlf); - _bufferBuilder.Append(s_DASHDASH); + _bufferBuilder.Append("\r\n--"u8); _bufferBuilder.Append(_boundaryBytes); - _bufferBuilder.Append(s_DASHDASH); - _bufferBuilder.Append(s_crlf); + _bufferBuilder.Append("--\r\n"u8); Flush(multiResult); } @@ -95,10 +91,9 @@ protected override void CheckBoundary() { if (_writeBoundary) { - _bufferBuilder.Append(s_crlf); - _bufferBuilder.Append(s_DASHDASH); + _bufferBuilder.Append("\r\n--"u8); _bufferBuilder.Append(_boundaryBytes); - _bufferBuilder.Append(s_crlf); + _bufferBuilder.Append("\r\n"u8); _writeBoundary = false; } } diff --git a/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs b/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs index e269cc6eeea77b..69c2ad98249ff4 100644 --- a/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs +++ b/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs @@ -16,8 +16,8 @@ namespace Systen.Net.Mail.Tests { public class LoopbackSmtpServer : IDisposable { - private static readonly ReadOnlyMemory s_messageTerminator = new byte[] { (byte)'\r', (byte)'\n' }; - private static readonly ReadOnlyMemory s_bodyTerminator = new byte[] { (byte)'\r', (byte)'\n', (byte)'.', (byte)'\r', (byte)'\n' }; + private static readonly ReadOnlyMemory s_messageTerminator = "\r\n"u8; + private static readonly ReadOnlyMemory s_bodyTerminator = "\r\n.\r\n"u8; public bool ReceiveMultipleConnections = false; public bool SupportSmtpUTF8 = false; diff --git a/src/libraries/System.Net.Mail/tests/Unit/QuotedPrintableStreamTest.cs b/src/libraries/System.Net.Mail/tests/Unit/QuotedPrintableStreamTest.cs index 0c66e26d9c6fc5..855a15f75b0fbd 100644 --- a/src/libraries/System.Net.Mail/tests/Unit/QuotedPrintableStreamTest.cs +++ b/src/libraries/System.Net.Mail/tests/Unit/QuotedPrintableStreamTest.cs @@ -50,10 +50,10 @@ public void QuotedPrintableStream_EmbededCRAndLFSpltBetweenWrites_EncodeCrlfFlag var outputStream = new MemoryStream(); var testStream = new QuotedPrintableStream(outputStream, false); - byte[] bytesToWrite1 = Encoding.ASCII.GetBytes("Hello \r"); + byte[] bytesToWrite1 = "Hello \r"u8; testStream.Write(bytesToWrite1, 0, bytesToWrite1.Length); - byte[] bytesToWrite2 = Encoding.ASCII.GetBytes("\n World"); + byte[] bytesToWrite2 = "\n World"u8; testStream.Write(bytesToWrite2, 0, bytesToWrite2.Length); testStream.Flush(); diff --git a/src/libraries/System.Net.Ping/tests/FunctionalTests/TestSettings.cs b/src/libraries/System.Net.Ping/tests/FunctionalTests/TestSettings.cs index 8a87d2f0111e67..a6bb9dc2bc0399 100644 --- a/src/libraries/System.Net.Ping/tests/FunctionalTests/TestSettings.cs +++ b/src/libraries/System.Net.Ping/tests/FunctionalTests/TestSettings.cs @@ -18,7 +18,7 @@ internal static class TestSettings // By default, FreeBSD supports buffer only up to 56 bytes public static readonly byte[] PayloadAsBytes = Encoding.UTF8.GetBytes(OperatingSystem.IsFreeBSD() ? TestSettings.PayloadAsString.Substring(0, 55) : TestSettings.PayloadAsString); - public static readonly byte[] PayloadAsBytesShort = Encoding.UTF8.GetBytes("ABCDEF0123456789"); + public static readonly byte[] PayloadAsBytesShort = "ABCDEF0123456789"u8; public static IPAddress[] GetLocalIPAddresses() { diff --git a/src/libraries/System.Net.Quic/tests/FunctionalTests/MsQuicTests.cs b/src/libraries/System.Net.Quic/tests/FunctionalTests/MsQuicTests.cs index 9cd0dad78c32cb..fe2639171a2ce6 100644 --- a/src/libraries/System.Net.Quic/tests/FunctionalTests/MsQuicTests.cs +++ b/src/libraries/System.Net.Quic/tests/FunctionalTests/MsQuicTests.cs @@ -25,7 +25,7 @@ namespace System.Net.Quic.Tests [Collection(nameof(DisableParallelization))] public class MsQuicTests : QuicTestBase { - private static byte[] s_data = Encoding.UTF8.GetBytes("Hello world!"); + private static byte[] s_data = "Hello world!"u8; public MsQuicTests(ITestOutputHelper output) : base(output) { } @@ -551,7 +551,7 @@ public async Task CallDifferentWriteMethodsWorks() { (QuicConnection clientConnection, QuicConnection serverConnection) = await CreateConnectedQuicConnection(); - ReadOnlyMemory helloWorld = Encoding.ASCII.GetBytes("Hello world!"); + ReadOnlyMemory helloWorld = "Hello world!"u8; ReadOnlySequence ros = CreateReadOnlySequenceFromBytes(helloWorld.ToArray()); Assert.False(ros.IsSingleSegment); diff --git a/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicStreamTests.cs b/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicStreamTests.cs index 7c78b34244a4b3..f60e36f36a808c 100644 --- a/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicStreamTests.cs +++ b/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicStreamTests.cs @@ -15,7 +15,7 @@ namespace System.Net.Quic.Tests public abstract class QuicStreamTests : QuicTestBase where T : IQuicImplProviderFactory, new() { - private static byte[] s_data = Encoding.UTF8.GetBytes("Hello world!"); + private static byte[] s_data = "Hello world!"u8; public QuicStreamTests(ITestOutputHelper output) : base(output) { } [Fact] @@ -179,7 +179,7 @@ static async Task MakeStreams(QuicConnection clientConnection, QuicConnection se { byte[] buffer = new byte[64]; QuicStream clientStream = clientConnection.OpenBidirectionalStream(); - ValueTask writeTask = clientStream.WriteAsync(Encoding.UTF8.GetBytes("PING"), endStream: true); + ValueTask writeTask = clientStream.WriteAsync("PING"u8, endStream: true); ValueTask acceptTask = serverConnection.AcceptStreamAsync(); await new Task[] { writeTask.AsTask(), acceptTask.AsTask() }.WhenAllOrAnyFailed(PassingTestTimeoutMilliseconds); QuicStream serverStream = acceptTask.Result; diff --git a/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicTestBase.cs b/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicTestBase.cs index c0b8b4a9caf36c..d254e75c8f3be2 100644 --- a/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicTestBase.cs +++ b/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicTestBase.cs @@ -20,8 +20,8 @@ namespace System.Net.Quic.Tests public abstract class QuicTestBase where T : IQuicImplProviderFactory, new() { - private static readonly byte[] s_ping = Encoding.UTF8.GetBytes("PING"); - private static readonly byte[] s_pong = Encoding.UTF8.GetBytes("PONG"); + private static readonly byte[] s_ping = "PING"u8; + private static readonly byte[] s_pong = "PONG"u8; private static readonly IQuicImplProviderFactory s_factory = new T(); public static QuicImplementationProvider ImplementationProvider { get; } = s_factory.GetProvider(); diff --git a/src/libraries/System.Net.Requests/tests/FtpWebRequestTest.cs b/src/libraries/System.Net.Requests/tests/FtpWebRequestTest.cs index 6cf0d7d7740eeb..dec69dfeff5663 100644 --- a/src/libraries/System.Net.Requests/tests/FtpWebRequestTest.cs +++ b/src/libraries/System.Net.Requests/tests/FtpWebRequestTest.cs @@ -79,7 +79,7 @@ public void GetResponse_ConnectFailure_ThrowsWebException() private const string absoluteUri = "ftp://localhost/"; - private static readonly byte[] helloWorldBytes = Encoding.UTF8.GetBytes("Hello world"); + private static readonly byte[] helloWorldBytes = "Hello world"u8; private static readonly byte[] largeFileBytes = Enumerable.Range(0, 10 * 1024 * 1024).Select((i) => (byte)(i % 256)).ToArray(); [ConditionalTheory(nameof(LocalServerAvailable))] diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs index ef17a3193b06e7..cbc21b7109daef 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs @@ -14,12 +14,6 @@ namespace System.Net.Security { internal sealed class CipherSuitesPolicyPal { - private static readonly byte[] AllowNoEncryptionDefault = - Encoding.ASCII.GetBytes("ALL:eNULL\0"); - - private static readonly byte[] NoEncryptionDefault = - Encoding.ASCII.GetBytes("eNULL\0"); - private byte[] _cipherSuites; private byte[] _tls13CipherSuites; private List _tlsCipherSuites = new List(); @@ -127,7 +121,7 @@ private static bool IsOnlyTls13(SslProtocols protocols) internal static bool WantsTls13(SslProtocols protocols) => protocols == SslProtocols.None || (protocols & SslProtocols.Tls13) != 0; - internal static byte[]? GetOpenSslCipherList( + internal static ReadOnlySpan GetOpenSslCipherList( CipherSuitesPolicy? policy, SslProtocols protocols, EncryptionPolicy encryptionPolicy) @@ -135,7 +129,7 @@ internal static bool WantsTls13(SslProtocols protocols) if (IsOnlyTls13(protocols)) { // older cipher suites will be disabled through protocols - return null; + return default; } if (policy == null) @@ -174,21 +168,21 @@ internal static bool WantsTls13(SslProtocols protocols) return policy.Pal._tls13CipherSuites; } - private static byte[]? CipherListFromEncryptionPolicy(EncryptionPolicy policy) + private static ReadOnlySpan CipherListFromEncryptionPolicy(EncryptionPolicy policy) { switch (policy) { case EncryptionPolicy.RequireEncryption: - return null; + return default; #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete case EncryptionPolicy.AllowNoEncryption: - return AllowNoEncryptionDefault; + return "ALL:eNULL\0"u8; case EncryptionPolicy.NoEncryption: - return NoEncryptionDefault; + return "eNULL\0"u8; #pragma warning restore SYSLIB0040 default: Debug.Fail($"Unknown EncryptionPolicy value ({policy})"); - return null; + return default; } } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs index e92ecaf3edb823..518ddfc76cb135 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs @@ -13,8 +13,6 @@ namespace System.Net.Security internal sealed class SafeChannelBindingHandle : ChannelBinding { private const int CertHashMaxSize = 128; - private static readonly byte[] s_tlsServerEndPointByteArray = Encoding.UTF8.GetBytes("tls-server-end-point:"); - private static readonly byte[] s_tlsUniqueByteArray = Encoding.UTF8.GetBytes("tls-unique:"); private static readonly int s_secChannelBindingSize = Marshal.SizeOf(); private readonly int _cbtPrefixByteArraySize; @@ -32,21 +30,17 @@ internal void SetCertHash(byte[] certHashBytes) SetCertHashLength(length); } - private static byte[] GetPrefixBytes(ChannelBindingKind kind) + internal unsafe SafeChannelBindingHandle(ChannelBindingKind kind) { Debug.Assert(kind == ChannelBindingKind.Endpoint || kind == ChannelBindingKind.Unique); - return kind == ChannelBindingKind.Endpoint - ? s_tlsServerEndPointByteArray - : s_tlsUniqueByteArray; - } + ReadOnlySpan cbtPrefix = kind == ChannelBindingKind.Endpoint ? + "tls-server-end-point:"u8 : + "tls-unique:"u8; - internal SafeChannelBindingHandle(ChannelBindingKind kind) - { - byte[] cbtPrefix = GetPrefixBytes(kind); _cbtPrefixByteArraySize = cbtPrefix.Length; handle = Marshal.AllocHGlobal(s_secChannelBindingSize + _cbtPrefixByteArraySize + CertHashMaxSize); IntPtr cbtPrefixPtr = handle + s_secChannelBindingSize; - Marshal.Copy(cbtPrefix, 0, cbtPrefixPtr, _cbtPrefixByteArraySize); + cbtPrefix.CopyTo(new Span((byte*)cbtPrefixPtr, cbtPrefix.Length)); CertHashPtr = cbtPrefixPtr + _cbtPrefixByteArraySize; Length = CertHashMaxSize; } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs index 6ab268953ad55a..d5190740464f2a 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs @@ -10,9 +10,9 @@ namespace System.Net.Security public readonly struct SslApplicationProtocol : IEquatable { private static readonly Encoding s_utf8 = Encoding.GetEncoding(Encoding.UTF8.CodePage, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); - private static readonly byte[] s_http3Utf8 = new byte[] { 0x68, 0x33 }; // "h3" - private static readonly byte[] s_http2Utf8 = new byte[] { 0x68, 0x32 }; // "h2" - private static readonly byte[] s_http11Utf8 = new byte[] { 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31 }; // "http/1.1" + private static readonly byte[] s_http3Utf8 = "h3"u8; + private static readonly byte[] s_http2Utf8 = "h2"u8; + private static readonly byte[] s_http11Utf8 = "http/1.1"u8; // Refer to IANA on ApplicationProtocols: https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids /// Defines a instance for HTTP 3.0. diff --git a/src/libraries/System.Net.Security/tests/EnterpriseTests/NegotiateStreamLoopbackTest.cs b/src/libraries/System.Net.Security/tests/EnterpriseTests/NegotiateStreamLoopbackTest.cs index bf8272c3f097e7..928cc3f6c111b4 100644 --- a/src/libraries/System.Net.Security/tests/EnterpriseTests/NegotiateStreamLoopbackTest.cs +++ b/src/libraries/System.Net.Security/tests/EnterpriseTests/NegotiateStreamLoopbackTest.cs @@ -23,7 +23,7 @@ private static Task WhenAllOrAnyFailedWithTimeout(params Task[] tasks) => private const string TargetName = "HOST/linuxclient.linux.contoso.com"; private const int PartialBytesToRead = 5; - private static readonly byte[] s_sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message"); + private static readonly byte[] s_sampleMsg = "Sample Test Message"u8; private const int MaxWriteDataSize = 63 * 1024; // NegoState.MaxWriteDataSize private static string s_longString = new string('A', MaxWriteDataSize) + 'Z'; diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamInvalidOperationTest.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamInvalidOperationTest.cs index bbfefa4223d6b2..7ef458aebac304 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamInvalidOperationTest.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamInvalidOperationTest.cs @@ -19,7 +19,7 @@ namespace System.Net.Security.Tests [PlatformSpecific(TestPlatforms.Windows)] // NegotiateStream only supports client-side functionality on Unix public class NegotiateStreamInvalidOperationTest { - private static readonly byte[] s_sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message"); + private static readonly byte[] s_sampleMsg = "Sample Test Message"u8; private const string TargetName = "testTargetName"; [Fact] diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamKerberosTest.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamKerberosTest.cs index 8ca45a58f46381..486ac24d12c2f5 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamKerberosTest.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamKerberosTest.cs @@ -157,7 +157,7 @@ await auth.AuthenticateAsClientAsync( Assert.True(auth.IsSigned); // Send a message to the server. Encode the test data into a byte array. - byte[] message = Encoding.UTF8.GetBytes("Hello from the client."); + byte[] message = "Hello from the client."u8; await auth.WriteAsync(message, 0, message.Length); } } diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs index 043ab1fd09d34c..58320a02c9dfd6 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs @@ -20,7 +20,7 @@ public abstract class NegotiateStreamStreamToStreamTest public static bool IsNtlmInstalled => Capability.IsNtlmInstalled(); private const int PartialBytesToRead = 5; - protected static readonly byte[] s_sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message"); + protected static readonly byte[] s_sampleMsg = "Sample Test Message"u8; private const int MaxWriteDataSize = 63 * 1024; // NegoState.MaxWriteDataSize private static string s_longString = new string('A', MaxWriteDataSize) + 'Z'; diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamAllowRenegotiationTests.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamAllowRenegotiationTests.cs index 7520221e6e9a3e..df5c9ff4b954e6 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamAllowRenegotiationTests.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamAllowRenegotiationTests.cs @@ -55,7 +55,7 @@ public async Task SslStream_AllowRenegotiation_True_Succeeds() Assert.True(ssl.IsEncrypted); // Issue request that triggers renegotiation from server. - byte[] message = Encoding.UTF8.GetBytes("GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"); + byte[] message = "GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"u8; await ssl.WriteAsync(message, 0, message.Length); // Initiate Read operation, that results in starting renegotiation as per server response to the above request. @@ -94,7 +94,7 @@ public async Task SslStream_AllowRenegotiation_False_Throws() Assert.True(ssl.IsEncrypted); // Issue request that triggers regotiation from server. - byte[] message = Encoding.UTF8.GetBytes("GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"); + byte[] message = "GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"u8; await ssl.WriteAsync(message, 0, message.Length); // Initiate Read operation, that results in starting renegotiation as per server response to the above request. diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamNetworkStreamTest.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamNetworkStreamTest.cs index 7264e322d44718..22f1e20576ec0d 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamNetworkStreamTest.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamNetworkStreamTest.cs @@ -164,7 +164,7 @@ public async Task SslStream_NetworkStream_Renegotiation_Succeeds(bool useSync) Assert.True(ssl.IsEncrypted); // Issue request that triggers regotiation from server. - byte[] message = Encoding.UTF8.GetBytes("GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"); + byte[] message = "GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"u8; if (useSync) { ssl.Write(message, 0, message.Length); diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamStreamToStreamTest.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamStreamToStreamTest.cs index 083c3cde51d608..93e911f0d94008 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamStreamToStreamTest.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamStreamToStreamTest.cs @@ -20,8 +20,6 @@ namespace System.Net.Security.Tests public abstract class SslStreamStreamToStreamTest { - private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message"); - protected static async Task WithServerCertificate(X509Certificate serverCertificate, Func func) { X509Certificate certificate = serverCertificate ?? Configuration.Certificates.GetServerCertificate(); diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/TestHelper.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/TestHelper.cs index 0a5c14df841122..e0a0972a46b7d7 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/TestHelper.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/TestHelper.cs @@ -43,8 +43,8 @@ public static class TestHelper private static readonly X509BasicConstraintsExtension s_eeConstraints = new X509BasicConstraintsExtension(false, false, 0, false); - public static readonly byte[] s_ping = Encoding.UTF8.GetBytes("PING"); - public static readonly byte[] s_pong = Encoding.UTF8.GetBytes("PONG"); + public static readonly byte[] s_ping = "PING"u8; + public static readonly byte[] s_pong = "PONG"u8; public static bool AllowAnyServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { diff --git a/src/libraries/System.Net.Security/tests/UnitTests/SslApplicationProtocolTests.cs b/src/libraries/System.Net.Security/tests/UnitTests/SslApplicationProtocolTests.cs index fe016e6c631efe..b12fbbe0113cab 100644 --- a/src/libraries/System.Net.Security/tests/UnitTests/SslApplicationProtocolTests.cs +++ b/src/libraries/System.Net.Security/tests/UnitTests/SslApplicationProtocolTests.cs @@ -13,18 +13,16 @@ public class SslApplicationProtocolTests [Fact] public void Constants_Values_AreCorrect() { - Assert.Equal(new SslApplicationProtocol(new byte[] { 0x68, 0x33 }), SslApplicationProtocol.Http3); - Assert.Equal(new SslApplicationProtocol(new byte[] { 0x68, 0x32 }), SslApplicationProtocol.Http2); - Assert.Equal(new SslApplicationProtocol(new byte[] { 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31 }), SslApplicationProtocol.Http11); + Assert.Equal(new SslApplicationProtocol("h3"u8), SslApplicationProtocol.Http3); + Assert.Equal(new SslApplicationProtocol("h2"u8), SslApplicationProtocol.Http2); + Assert.Equal(new SslApplicationProtocol("http/1.1"u8), SslApplicationProtocol.Http11); } [Fact] public void Constructor_Overloads_Succeeds() { - const string hello = "hello"; - byte[] expected = Encoding.UTF8.GetBytes(hello); - SslApplicationProtocol byteProtocol = new SslApplicationProtocol(expected); - SslApplicationProtocol stringProtocol = new SslApplicationProtocol(hello); + SslApplicationProtocol byteProtocol = new SslApplicationProtocol("hello"u8); + SslApplicationProtocol stringProtocol = new SslApplicationProtocol("hello"); Assert.Equal(byteProtocol, stringProtocol); SslApplicationProtocol defaultProtocol = default; @@ -42,7 +40,7 @@ public void Constructor_Overloads_Succeeds() [Fact] public void Constructor_ByteArray_Copies() { - byte[] expected = Encoding.UTF8.GetBytes("hello"); + byte[] expected = "hello"u8; SslApplicationProtocol byteProtocol = new SslApplicationProtocol(expected); ArraySegment arraySegment; @@ -95,7 +93,7 @@ public static IEnumerable Protocol_Equality_TestData() public static IEnumerable Protocol_InEquality_TestData() { yield return new object[] { new SslApplicationProtocol("hello"), new SslApplicationProtocol("world") }; - yield return new object[] { new SslApplicationProtocol(new byte[] { 0x42 }), new SslApplicationProtocol(new byte[] { 0x52, 0x62 }) }; + yield return new object[] { new SslApplicationProtocol(new byte[] { 0x42 }), new SslApplicationProtocol("Rb"u8) }; yield return new object[] { null, new SslApplicationProtocol(new byte[] { 0x42 }) }; yield return new object[] { new SslApplicationProtocol(new byte[] { 0x42 }), null }; } diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/NetworkStreamTest.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/NetworkStreamTest.cs index 52022c5da82164..42972a020a1b3c 100644 --- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/NetworkStreamTest.cs +++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/NetworkStreamTest.cs @@ -106,11 +106,11 @@ public async Task Ctor_Socket_CanReadAndWrite_DoesntOwn() // Verify Read and Write on both streams byte[] buffer = new byte[1]; - await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1); + await serverStream.WriteAsync("a"u8, 0, 1); Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1)); Assert.Equal('a', (char)buffer[0]); - await clientStream.WriteAsync(new byte[] { (byte)'b' }, 0, 1); + await clientStream.WriteAsync("b"u8, 0, 1); Assert.Equal(1, await serverStream.ReadAsync(buffer, 0, 1)); Assert.Equal('b', (char)buffer[0]); } @@ -147,11 +147,11 @@ public async Task Ctor_SocketFileAccessBool_CanReadAndWrite_DoesntOwn(FileAccess // Verify Read and Write on both streams byte[] buffer = new byte[1]; - await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1); + await serverStream.WriteAsync("a"u8, 0, 1); Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1)); Assert.Equal('a', (char)buffer[0]); - await clientStream.WriteAsync(new byte[] { (byte)'b' }, 0, 1); + await clientStream.WriteAsync("b"u8, 0, 1); Assert.Equal(1, await serverStream.ReadAsync(buffer, 0, 1)); Assert.Equal('b', (char)buffer[0]); } @@ -190,11 +190,11 @@ public async Task Ctor_SocketBool_CanReadAndWrite(bool ownsSocket) // Verify Read and Write on both streams byte[] buffer = new byte[1]; - await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1); + await serverStream.WriteAsync("a"u8, 0, 1); Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1)); Assert.Equal('a', (char)buffer[0]); - await clientStream.WriteAsync(new byte[] { (byte)'b' }, 0, 1); + await clientStream.WriteAsync("b"u8, 0, 1); Assert.Equal(1, await serverStream.ReadAsync(buffer, 0, 1)); Assert.Equal('b', (char)buffer[0]); } @@ -242,7 +242,7 @@ public async Task Ctor_SocketFileAccess_CanReadAndWrite() // Verify Read and Write on both streams byte[] buffer = new byte[1]; - await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1); + await serverStream.WriteAsync("a"u8, 0, 1); Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1)); Assert.Equal('a', (char)buffer[0]); diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/TcpClientTest.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/TcpClientTest.cs index 6f02308d73f4d9..11f98ae0c2a5c9 100644 --- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/TcpClientTest.cs +++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/TcpClientTest.cs @@ -190,7 +190,7 @@ public async Task ConnectAsync_DnsEndPoint_Success(int mode) using (NetworkStream s = client.GetStream()) { - byte[] getRequest = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\n\r\n"); + byte[] getRequest = "GET / HTTP/1.1\r\n\r\n"u8; await s.WriteAsync(getRequest, 0, getRequest.Length); Assert.NotEqual(-1, s.ReadByte()); // just verify we successfully get any data back } @@ -240,7 +240,7 @@ public void Connect_DnsEndPoint_Success(int mode) using (NetworkStream s = client.GetStream()) { - byte[] getRequest = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\n\r\n"); + byte[] getRequest = "GET / HTTP/1.1\r\n\r\n"u8; s.Write(getRequest, 0, getRequest.Length); Assert.NotEqual(-1, s.ReadByte()); // just verify we successfully get any data back } diff --git a/src/libraries/System.Net.WebSockets/tests/WebSocketCreateTest.cs b/src/libraries/System.Net.WebSockets/tests/WebSocketCreateTest.cs index f9fd4e3c564e57..744830928d0cfb 100644 --- a/src/libraries/System.Net.WebSockets/tests/WebSocketCreateTest.cs +++ b/src/libraries/System.Net.WebSockets/tests/WebSocketCreateTest.cs @@ -77,7 +77,7 @@ public async Task WebSocketProtocol_CreateFromConnectedStream_CanSendReceiveData public async Task ReceiveAsync_UTF8SplitAcrossMultipleBuffers_ValidDataReceived() { // 1 character - 2 bytes - byte[] payload = Encoding.UTF8.GetBytes("\u00E6"); + byte[] payload = "\u00E6"u8; var frame = new byte[payload.Length + 2]; frame[0] = 0x81; // FIN = true, Opcode = Text frame[1] = (byte)payload.Length; @@ -294,7 +294,7 @@ public async Task WebSocketProtocol_CreateFromConnectedStream_CloseAsyncAfterClo Assert.Equal(WebSocketState.Open, socket.State); // Ask server to send us a close - await socket.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes(".close")), WebSocketMessageType.Text, true, default); + await socket.SendAsync(new ArraySegment(".close"u8), WebSocketMessageType.Text, true, default); // Verify received server-initiated close message. WebSocketReceiveResult recvResult = await socket.ReceiveAsync(new ArraySegment(new byte[256]), default); diff --git a/src/libraries/System.Net.WebSockets/tests/WebSocketDeflateTests.cs b/src/libraries/System.Net.WebSockets/tests/WebSocketDeflateTests.cs index 03ae5981c9b898..da63c4115a8011 100644 --- a/src/libraries/System.Net.WebSockets/tests/WebSocketDeflateTests.cs +++ b/src/libraries/System.Net.WebSockets/tests/WebSocketDeflateTests.cs @@ -77,11 +77,11 @@ public async Task SendHelloWithContextTakeover() DangerousDeflateOptions = new WebSocketDeflateOptions() }); - await websocket.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken); + await websocket.SendAsync("Hello"u8, WebSocketMessageType.Text, true, CancellationToken); Assert.Equal("C107F248CDC9C90700", Convert.ToHexString(stream.NextAvailableBytes)); stream.Clear(); - await websocket.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken); + await websocket.SendAsync("Hello"u8, WebSocketMessageType.Text, true, CancellationToken); // Because context takeover is set by default if we try to send // the same message it should result in fewer bytes. @@ -98,7 +98,7 @@ public async Task SendHelloWithDisableCompression() DangerousDeflateOptions = new WebSocketDeflateOptions() }); - byte[] bytes = Encoding.UTF8.GetBytes("Hello"); + byte[] bytes = "Hello"u8; WebSocketMessageFlags flags = WebSocketMessageFlags.DisableCompression | WebSocketMessageFlags.EndOfMessage; await websocket.SendAsync(bytes, WebSocketMessageType.Text, flags, CancellationToken); @@ -116,7 +116,7 @@ public async Task SendHelloWithEmptyFrame() DangerousDeflateOptions = new WebSocketDeflateOptions() }); - byte[] bytes = Encoding.UTF8.GetBytes("Hello"); + byte[] bytes = "Hello"u8; await websocket.SendAsync(Memory.Empty, WebSocketMessageType.Text, endOfMessage: false, CancellationToken); await websocket.SendAsync(bytes, WebSocketMessageType.Text, endOfMessage: true, CancellationToken); @@ -181,7 +181,7 @@ public async Task SendHelloWithoutContextTakeover() for (var i = 0; i < 100; ++i) { - await websocket.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken); + await websocket.SendAsync("Hello"u8, WebSocketMessageType.Text, true, CancellationToken); // Without context takeover the message should look the same every time Assert.Equal("C107F248CDC9C90700", Convert.ToHexString(stream.NextAvailableBytes)); diff --git a/src/libraries/System.Private.CoreLib/gen/EventSourceGenerator.Emitter.cs b/src/libraries/System.Private.CoreLib/gen/EventSourceGenerator.Emitter.cs index 2dcedb1b435ce8..07051fc47be666 100644 --- a/src/libraries/System.Private.CoreLib/gen/EventSourceGenerator.Emitter.cs +++ b/src/libraries/System.Private.CoreLib/gen/EventSourceGenerator.Emitter.cs @@ -62,37 +62,16 @@ private static void GenerateConstructor(EventSourceClass ec, StringBuilder sb) private static void GenerateProviderMetadata(string sourceName, StringBuilder sb) { - sb.Append(@" - private protected override ReadOnlySpan ProviderMetadata => new byte[] { "); - - byte[] metadataBytes = MetadataForString(sourceName); - foreach (byte b in metadataBytes) + if (sourceName != null && sourceName.IndexOf('\0') >= 0) { - sb.Append($"0x{b:x}, "); + throw new ArgumentOutOfRangeException(nameof(sourceName)); } - sb.AppendLine(@"};"); - } - - // From System.Private.CoreLib - private static byte[] MetadataForString(string name) - { - CheckName(name); - int metadataSize = Encoding.UTF8.GetByteCount(name) + 3; - byte[]? metadata = new byte[metadataSize]; + int metadataSize = Encoding.UTF8.GetByteCount(sourceName) + 3; ushort totalSize = checked((ushort)(metadataSize)); - metadata[0] = unchecked((byte)totalSize); - metadata[1] = unchecked((byte)(totalSize >> 8)); - Encoding.UTF8.GetBytes(name, 0, name.Length, metadata, 2); - return metadata; - } - private static void CheckName(string? name) - { - if (name != null && 0 <= name.IndexOf('\0')) - { - throw new ArgumentOutOfRangeException(nameof(name)); - } + sb.Append($@" + private protected override ReadOnlySpan ProviderMetadata => ""\u{(byte)totalSize:X4}\u{(byte)(totalSize >> 8):X4}{sourceName}\0""u8;"); } } } diff --git a/src/libraries/System.Private.CoreLib/gen/EventSourceGenerator.cs b/src/libraries/System.Private.CoreLib/gen/EventSourceGenerator.cs index cebe3a5d32c504..7d2f3f43c7b4da 100644 --- a/src/libraries/System.Private.CoreLib/gen/EventSourceGenerator.cs +++ b/src/libraries/System.Private.CoreLib/gen/EventSourceGenerator.cs @@ -29,7 +29,7 @@ public partial class EventSourceGenerator : IIncrementalGenerator // { // private RuntimeEventSource() : base(new Guid(0x49592c0f,0x5a05,0x516d,0xaa,0x4b,0xa6,0x4e,0x02,0x02,0x6c,0x89), "System.Runtime") { } // - // private protected override ReadOnlySpan ProviderMetadata => new byte[] { 0x11, 0x0, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x2e, 0x52, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x0, }; + // private protected override ReadOnlySpan ProviderMetadata => "\u0011\0System.Runtime\0"u8; // } // } diff --git a/src/libraries/System.Private.CoreLib/gen/System.Private.CoreLib.Generators.csproj b/src/libraries/System.Private.CoreLib/gen/System.Private.CoreLib.Generators.csproj index b3274719f5a15a..ccffe3fd399fcf 100644 --- a/src/libraries/System.Private.CoreLib/gen/System.Private.CoreLib.Generators.csproj +++ b/src/libraries/System.Private.CoreLib/gen/System.Private.CoreLib.Generators.csproj @@ -1,7 +1,6 @@ netstandard2.0 - 10.0 enable false $(NoWarn);CS3001 diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs index d6de2307fb363d..249cc8f589f3a2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs @@ -31,11 +31,11 @@ private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } // UTF-8 is fastpath, so that's how these are stored // Compare methods adapt to Unicode. - private static readonly byte[] s_encodingAttr = new byte[] { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g' }; - private static readonly byte[] s_encodingUTF8 = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8' }; - private static readonly byte[] s_encodingUnicode = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6' }; - private static readonly byte[] s_encodingUnicodeLE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'l', (byte)'e' }; - private static readonly byte[] s_encodingUnicodeBE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'b', (byte)'e' }; + private static readonly byte[] s_encodingAttr = "encoding"u8; + private static readonly byte[] s_encodingUTF8 = "utf-8"u8; + private static readonly byte[] s_encodingUnicode = "utf-16"u8; + private static readonly byte[] s_encodingUnicodeLE = "utf-16le"u8; + private static readonly byte[] s_encodingUnicodeBE = "utf-16be"u8; private SupportedEncoding _encodingCode; private Encoding? _encoding; diff --git a/src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/NamespaceHandlingTests.cs b/src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/NamespaceHandlingTests.cs index a1cfd7ec90b657..bb3d25770d47e0 100644 --- a/src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/NamespaceHandlingTests.cs +++ b/src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/NamespaceHandlingTests.cs @@ -758,7 +758,7 @@ public void NS_Handling_22(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; - byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; + byte[] buffer = "abc"u8; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { @@ -780,7 +780,7 @@ public void NS_Handling_23(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; - byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; + byte[] buffer = "abc"u8; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { @@ -803,7 +803,6 @@ public void NS_Handling_24(XmlWriterUtils utils, NamespaceHandling nsHandling) XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlWriter w = CreateMemWriter(utils, wSettings); - byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; w.WriteStartElement("A"); w.WriteAttributeString("xmlns", "p", null, "ns1"); diff --git a/src/libraries/System.Private.Xml/tests/XmlNodeReader/System.Xml.XmlNodeReader.Tests/XmlNodeReaderReadTests.cs b/src/libraries/System.Private.Xml/tests/XmlNodeReader/System.Xml.XmlNodeReader.Tests/XmlNodeReaderReadTests.cs index c6907131729632..3cc9b1fa6f0674 100644 --- a/src/libraries/System.Private.Xml/tests/XmlNodeReader/System.Xml.XmlNodeReader.Tests/XmlNodeReaderReadTests.cs +++ b/src/libraries/System.Private.Xml/tests/XmlNodeReader/System.Xml.XmlNodeReader.Tests/XmlNodeReaderReadTests.cs @@ -153,7 +153,7 @@ public void NodeReaderReadContentAsBase64WithEmptyXml() [Fact] public void NodeReaderReadContentAsBase64WithSimpleXml() { - byte[] byteData = Encoding.ASCII.GetBytes("hello world"); + byte[] byteData = "hello world"u8; string xml = $""; //hello world encoded XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml); Assert.True(nodeReader.Read()); @@ -179,7 +179,7 @@ public void NodeReaderReadContentAsBinHexWithEmptyXml() [Fact] public void NodeReaderReadContentAsBinHexWithSimpleXml() { - byte[] byteData = Encoding.ASCII.GetBytes("hello world"); + byte[] byteData = "hello world"u8; string xml = $""; XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml); Assert.True(nodeReader.Read()); @@ -205,7 +205,7 @@ public void NodeReaderReadElementContentAsBase64WithEmptyXml() [Fact] public void NodeReaderReadElementContentAsBase64WithSimpleXml() { - byte[] byteData = Encoding.ASCII.GetBytes("hello world"); + byte[] byteData = "hello world"u8; string xml = $"{Convert.ToBase64String(byteData)}"; //hello world encoded XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml); Assert.True(nodeReader.Read()); @@ -229,7 +229,7 @@ public void NodeReaderReadElementContentAsBinHexWithEmptyXml() [Fact] public void NodeReaderReadElementContentAsBinHexWithSimpleXml() { - byte[] byteData = Encoding.ASCII.GetBytes("hello world"); + byte[] byteData = "hello world"u8; string xml = $"{BitConverter.ToString(byteData).Replace("-", "")}"; XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml); Assert.True(nodeReader.Read()); diff --git a/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverAddRemoveTests.cs b/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverAddRemoveTests.cs index 1ca6c15354dc30..49699bb056cd07 100644 --- a/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverAddRemoveTests.cs +++ b/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverAddRemoveTests.cs @@ -40,7 +40,7 @@ public void XmlResolverAddWithValidData() { var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10); - byte[] data = Encoding.ASCII.GetBytes("hello world"); + byte[] data = "hello world"u8; MemoryStream stream = new MemoryStream(data); xmlResolver.Add(new Uri("-//Sample//URI//For Testing", UriKind.RelativeOrAbsolute), stream); Stream result = xmlResolver.GetEntity(new Uri("-//Sample//URI//For Testing", UriKind.RelativeOrAbsolute), @@ -70,7 +70,7 @@ public void XmlResolverRemoveWithInvalidData() public void XmlResolverRemoveWithValidData() { var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10); - byte[] data = Encoding.ASCII.GetBytes("hello world"); + byte[] data = "hello world"u8; MemoryStream stream = new MemoryStream(data); xmlResolver.Add(new Uri("-//W3C//DTD XHTML 1.0 Transitional//EN", UriKind.RelativeOrAbsolute), stream); xmlResolver.Remove(new Uri("-//W3C//DTD XHTML 1.0 Transitional//EN", UriKind.RelativeOrAbsolute)); diff --git a/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverGetEntity.cs b/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverGetEntity.cs index 061d666ac60767..dee512900895b1 100644 --- a/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverGetEntity.cs +++ b/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverGetEntity.cs @@ -108,7 +108,7 @@ public void XmlResolverGetEntityAsyncWithInvalidData() [Fact] public void XmlResolverGetEntityAsyncWithValidUserSuppliedData() { - byte[] inpData = Encoding.ASCII.GetBytes("hello world"); + byte[] inpData = "hello world"u8; var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10); xmlResolver.Add(new Uri("-//W3C//DTD FAKE 1.0 Not Real//EN", UriKind.RelativeOrAbsolute), inpData); Task output = xmlResolver.GetEntityAsync(new Uri("-//W3C//DTD FAKE 1.0 Not Real//EN", diff --git a/src/libraries/System.Reflection.Metadata/tests/Metadata/BlobTests.cs b/src/libraries/System.Reflection.Metadata/tests/Metadata/BlobTests.cs index cefd6e109d4e3b..423e300e680c98 100644 --- a/src/libraries/System.Reflection.Metadata/tests/Metadata/BlobTests.cs +++ b/src/libraries/System.Reflection.Metadata/tests/Metadata/BlobTests.cs @@ -981,31 +981,31 @@ public void WriteUTF8_Substring() writer.Clear(); writer.WriteUTF8("abc", 0, 1, allowUnpairedSurrogates: true, prependSize: false); - AssertEx.Equal(new[] { (byte)'a' }, writer.ToArray()); + AssertEx.Equal("a"u8, writer.ToArray()); writer.Clear(); writer.WriteUTF8("abc", 0, 2, allowUnpairedSurrogates: true, prependSize: false); - AssertEx.Equal(new[] { (byte)'a', (byte)'b' }, writer.ToArray()); + AssertEx.Equal("ab"u8, writer.ToArray()); writer.Clear(); writer.WriteUTF8("abc", 0, 3, allowUnpairedSurrogates: true, prependSize: false); - AssertEx.Equal(new[] { (byte)'a', (byte)'b', (byte)'c' }, writer.ToArray()); + AssertEx.Equal("abc"u8, writer.ToArray()); writer.Clear(); writer.WriteUTF8("abc", 1, 0, allowUnpairedSurrogates: true, prependSize: false); - AssertEx.Equal(new byte[0], writer.ToArray()); + AssertEx.Equal(""u8, writer.ToArray()); writer.Clear(); writer.WriteUTF8("abc", 1, 1, allowUnpairedSurrogates: true, prependSize: false); - AssertEx.Equal(new[] { (byte)'b' }, writer.ToArray()); + AssertEx.Equal("b"u8, writer.ToArray()); writer.Clear(); writer.WriteUTF8("abc", 1, 2, allowUnpairedSurrogates: true, prependSize: false); - AssertEx.Equal(new[] { (byte)'b', (byte)'c' }, writer.ToArray()); + AssertEx.Equal("bc"u8, writer.ToArray()); writer.Clear(); writer.WriteUTF8("abc", 2, 1, allowUnpairedSurrogates: true, prependSize: false); - AssertEx.Equal(new[] { (byte)'c' }, writer.ToArray()); + AssertEx.Equal("c"u8, writer.ToArray()); writer.Clear(); } diff --git a/src/libraries/System.Reflection.Metadata/tests/Metadata/MetadataReaderTests.cs b/src/libraries/System.Reflection.Metadata/tests/Metadata/MetadataReaderTests.cs index f02b3e292b413a..c7a7b0da5fa96c 100644 --- a/src/libraries/System.Reflection.Metadata/tests/Metadata/MetadataReaderTests.cs +++ b/src/libraries/System.Reflection.Metadata/tests/Metadata/MetadataReaderTests.cs @@ -126,7 +126,7 @@ public unsafe void InvalidFindMscorlibAssemblyRefNoProjection() PEHeaders headers = new PEHeaders(new MemoryStream(peImage)); //find index for mscorlib - int mscorlibIndex = IndexOf(peImage, Encoding.ASCII.GetBytes("mscorlib"), headers.MetadataStartOffset); + int mscorlibIndex = IndexOf(peImage, "mscorlib"u8, headers.MetadataStartOffset); Assert.NotEqual(-1, mscorlibIndex); //mutate mscorlib peImage[mscorlibIndex + headers.MetadataStartOffset] = 0xFF; @@ -145,7 +145,7 @@ public unsafe void InvalidStreamHeaderLengths() // mutate CLR to reach MetadataKind.WindowsMetadata // find CLR - int clrIndex = IndexOf(peImage, Encoding.ASCII.GetBytes("CLR"), headers.MetadataStartOffset); + int clrIndex = IndexOf(peImage, "CLR"u8, headers.MetadataStartOffset); Assert.NotEqual(-1, clrIndex); //find 5, This is the streamcount and is the last thing that should be read befor the test. int fiveIndex = IndexOf(peImage, new byte[] {5}, headers.MetadataStartOffset + clrIndex); @@ -435,7 +435,7 @@ public void GetString_WinRTPrefixed_Projected() winrtDef.Attributes); var strReader = reader.GetBlobReader(winrtDef.Name); - Assert.Equal(Encoding.UTF8.GetBytes("Class1"), strReader.ReadBytes("Class1".Length)); + Assert.Equal("Class1"u8, strReader.ReadBytes("Class1".Length)); Assert.Equal(0, strReader.RemainingBytes); // .class /*02000003*/ private auto ansi import windowsruntime sealed beforefieldinit Lib.'Class1' @@ -449,7 +449,7 @@ public void GetString_WinRTPrefixed_Projected() clrDef.Attributes); strReader = reader.GetBlobReader(clrDef.Name); - Assert.Equal(Encoding.UTF8.GetBytes("Class1"), strReader.ReadBytes("Class1".Length)); + Assert.Equal("Class1"u8, strReader.ReadBytes("Class1".Length)); Assert.Equal(0, strReader.RemainingBytes); } @@ -469,7 +469,7 @@ public void GetString_WinRTPrefixed_NotProjected() winrtDef.Attributes); var strReader = reader.GetBlobReader(winrtDef.Name); - Assert.Equal(Encoding.UTF8.GetBytes("Class1"), strReader.ReadBytes("Class1".Length)); + Assert.Equal("Class1"u8, strReader.ReadBytes("Class1".Length)); Assert.Equal(0, strReader.RemainingBytes); // .class /*02000003*/ public auto ansi windowsruntime sealed beforefieldinit Lib.Class1 @@ -483,7 +483,7 @@ public void GetString_WinRTPrefixed_NotProjected() clrDef.Attributes); strReader = reader.GetBlobReader(clrDef.Name); - Assert.Equal(Encoding.UTF8.GetBytes("Class1"), strReader.ReadBytes("Class1".Length)); + Assert.Equal("Class1"u8, strReader.ReadBytes("Class1".Length)); Assert.Equal(0, strReader.RemainingBytes); } @@ -497,14 +497,14 @@ public void GetString_DotTerminated() Assert.Equal("System.Runtime.CompilerServices", reader.GetString(typeRef.Namespace)); var strReader = reader.GetBlobReader(typeRef.Namespace); - Assert.Equal(Encoding.UTF8.GetBytes("System.Runtime.CompilerServices"), strReader.ReadBytes("System.Runtime.CompilerServices".Length)); + Assert.Equal("System.Runtime.CompilerServices"u8, strReader.ReadBytes("System.Runtime.CompilerServices".Length)); Assert.Equal(0, strReader.RemainingBytes); var dotTerminated = typeRef.Namespace.WithDotTermination(); Assert.Equal("System", reader.GetString(dotTerminated)); strReader = reader.GetBlobReader(dotTerminated); - Assert.Equal(Encoding.UTF8.GetBytes("System"), strReader.ReadBytes("System".Length)); + Assert.Equal("System"u8, strReader.ReadBytes("System".Length)); Assert.Equal(0, strReader.RemainingBytes); } diff --git a/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs b/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs index 20f68af2878708..f82d6c4ff43fa7 100644 --- a/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs +++ b/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs @@ -31,7 +31,7 @@ public void ReadNullPaddedUTF8RemovesNullPadding() [Fact] public void ReadNullPaddedUTF8WorksWithNoNullPadding() { - var headerBytes = Encoding.UTF8.GetBytes(".abcdefg"); + var headerBytes = ".abcdefg"u8; var stream = new MemoryStream(headerBytes); stream.Position = 0; diff --git a/src/libraries/System.Reflection.Metadata/tests/Utilities/BlobReaderTests.cs b/src/libraries/System.Reflection.Metadata/tests/Utilities/BlobReaderTests.cs index 096846d0ce49e8..f7c87f4a20e538 100644 --- a/src/libraries/System.Reflection.Metadata/tests/Utilities/BlobReaderTests.cs +++ b/src/libraries/System.Reflection.Metadata/tests/Utilities/BlobReaderTests.cs @@ -389,7 +389,7 @@ public unsafe void ReadFromMemoryBlock() Assert.Equal("", block.PeekUtf8NullTerminated(4, null, stringDecoder, out bytesRead)); Assert.Equal(0, bytesRead); - byte[] helloPrefix = Encoding.UTF8.GetBytes("Hello"); + byte[] helloPrefix = "Hello"u8; Assert.Equal("Hello\u0001", block.PeekUtf8NullTerminated(1, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(2, bytesRead); diff --git a/src/libraries/System.Reflection.Metadata/tests/Utilities/MemoryBlockTests.cs b/src/libraries/System.Reflection.Metadata/tests/Utilities/MemoryBlockTests.cs index 2fd01ef55a10da..3d454f563b35a8 100644 --- a/src/libraries/System.Reflection.Metadata/tests/Utilities/MemoryBlockTests.cs +++ b/src/libraries/System.Reflection.Metadata/tests/Utilities/MemoryBlockTests.cs @@ -20,20 +20,20 @@ public unsafe void Utf8NullTerminatedStringStartsWithAsciiPrefix() Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, "")); } - fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("Hello World!\0"))) + fixed (byte* heapPtr = (heap = "Hello World!\0"u8)) { Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix("Hello ".Length, "World")); Assert.False(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix("Hello ".Length, "World?")); } - fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("x\0"))) + fixed (byte* heapPtr = (heap = "x\0"u8)) { Assert.False(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, "xyz")); Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, "x")); } // bad metadata (#String heap is not nul-terminated): - fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("abcx"))) + fixed (byte* heapPtr = (heap = "abcx"u8)) { Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(3, "x")); Assert.False(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(3, "xyz")); @@ -56,7 +56,7 @@ public unsafe void DefaultDecodingFallbackMatchesBcl() Assert.Equal(s, Encoding.UTF8.GetString(buffer)); Assert.Equal(buffer.Length, bytesRead); - s = new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, Encoding.UTF8.GetBytes("Hello"), decoder, out bytesRead); + s = new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, "Hello"u8, decoder, out bytesRead); Assert.Equal("Hello\uFFFD", s); Assert.Equal(s, "Hello" + Encoding.UTF8.GetString(buffer)); Assert.Equal(buffer.Length, bytesRead); @@ -131,14 +131,14 @@ public unsafe void DecoderIsUsedCorrectly() } ); - fixed (byte* fixedPtr = (buffer = Encoding.UTF8.GetBytes("Test"))) + fixed (byte* fixedPtr = (buffer = "Test"u8)) { ptr = fixedPtr; Assert.Equal("Intercepted", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, null, decoder, out bytesRead)); Assert.Equal(buffer.Length, bytesRead); prefixed = true; - Assert.Equal("Intercepted", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, Encoding.UTF8.GetBytes("Prefix"), decoder, out bytesRead)); + Assert.Equal("Intercepted", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, "Prefix"u8, decoder, out bytesRead)); Assert.Equal(buffer.Length, bytesRead); } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Utf8Constants.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Utf8Constants.cs index 5617958b5f8162..b18432725d60d3 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Utf8Constants.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Utf8Constants.cs @@ -5,60 +5,60 @@ namespace System.Reflection.TypeLoading { internal static class Utf8Constants { - public static ReadOnlySpan System => new byte[] { 83, 121, 115, 116, 101, 109 }; - public static ReadOnlySpan SystemReflection => new byte[] { 83, 121, 115, 116, 101, 109, 46, 82, 101, 102, 108, 101, 99, 116, 105, 111, 110 }; - public static ReadOnlySpan SystemCollectionsGeneric => new byte[] { 83, 121, 115, 116, 101, 109, 46, 67, 111, 108, 108, 101, 99, 116, 105, 111, 110, 115, 46, 71, 101, 110, 101, 114, 105, 99 }; - public static ReadOnlySpan SystemRuntimeInteropServices => new byte[] { 83, 121, 115, 116, 101, 109, 46, 82, 117, 110, 116, 105, 109, 101, 46, 73, 110, 116, 101, 114, 111, 112, 83, 101, 114, 118, 105, 99, 101, 115 }; - public static ReadOnlySpan SystemRuntimeCompilerServices => new byte[] { 83, 121, 115, 116, 101, 109, 46, 82, 117, 110, 116, 105, 109, 101, 46, 67, 111, 109, 112, 105, 108, 101, 114, 83, 101, 114, 118, 105, 99, 101, 115 }; + public static ReadOnlySpan System => "System"u8; + public static ReadOnlySpan SystemReflection => "System.Reflection"u8; + public static ReadOnlySpan SystemCollectionsGeneric => "System.Collections.Generic"u8; + public static ReadOnlySpan SystemRuntimeInteropServices => "System.Runtime.InteropServices"u8; + public static ReadOnlySpan SystemRuntimeCompilerServices => "System.Runtime.CompilerServices"u8; - public static ReadOnlySpan Array => new byte[] { 65, 114, 114, 97, 121 }; - public static ReadOnlySpan Boolean => new byte[] { 66, 111, 111, 108, 101, 97, 110 }; - public static ReadOnlySpan Byte => new byte[] { 66, 121, 116, 101 }; - public static ReadOnlySpan Char => new byte[] { 67, 104, 97, 114 }; - public static ReadOnlySpan Double => new byte[] { 68, 111, 117, 98, 108, 101 }; - public static ReadOnlySpan Enum => new byte[] { 69, 110, 117, 109 }; - public static ReadOnlySpan Int16 => new byte[] { 73, 110, 116, 49, 54 }; - public static ReadOnlySpan Int32 => new byte[] { 73, 110, 116, 51, 50 }; - public static ReadOnlySpan Int64 => new byte[] { 73, 110, 116, 54, 52 }; - public static ReadOnlySpan IntPtr => new byte[] { 73, 110, 116, 80, 116, 114 }; - public static ReadOnlySpan Object => new byte[] { 79, 98, 106, 101, 99, 116 }; - public static ReadOnlySpan NullableT => new byte[] { 78, 117, 108, 108, 97, 98, 108, 101, 96, 49 }; - public static ReadOnlySpan SByte => new byte[] { 83, 66, 121, 116, 101 }; - public static ReadOnlySpan Single => new byte[] { 83, 105, 110, 103, 108, 101 }; - public static ReadOnlySpan String => new byte[] { 83, 116, 114, 105, 110, 103 }; - public static ReadOnlySpan TypedReference => new byte[] { 84, 121, 112, 101, 100, 82, 101, 102, 101, 114, 101, 110, 99, 101 }; - public static ReadOnlySpan UInt16 => new byte[] { 85, 73, 110, 116, 49, 54 }; - public static ReadOnlySpan UInt32 => new byte[] { 85, 73, 110, 116, 51, 50 }; - public static ReadOnlySpan UInt64 => new byte[] { 85, 73, 110, 116, 54, 52 }; - public static ReadOnlySpan UIntPtr => new byte[] { 85, 73, 110, 116, 80, 116, 114 }; - public static ReadOnlySpan ValueType => new byte[] { 86, 97, 108, 117, 101, 84, 121, 112, 101 }; - public static ReadOnlySpan Void => new byte[] { 86, 111, 105, 100 }; - public static ReadOnlySpan MulticastDelegate => new byte[] { 77, 117, 108, 116, 105, 99, 97, 115, 116, 68, 101, 108, 101, 103, 97, 116, 101 }; - public static ReadOnlySpan IEnumerableT => new byte[] { 73, 69, 110, 117, 109, 101, 114, 97, 98, 108, 101, 96, 49 }; - public static ReadOnlySpan ICollectionT => new byte[] { 73, 67, 111, 108, 108, 101, 99, 116, 105, 111, 110, 96, 49 }; - public static ReadOnlySpan IListT => new byte[] { 73, 76, 105, 115, 116, 96, 49 }; - public static ReadOnlySpan IReadOnlyListT => new byte[] { 73, 82, 101, 97, 100, 79, 110, 108, 121, 76, 105, 115, 116, 96, 49 }; - public static ReadOnlySpan Type => new byte[] { 84, 121, 112, 101 }; - public static ReadOnlySpan DBNull => new byte[] { 68, 66, 78, 117, 108, 108 }; - public static ReadOnlySpan Decimal => new byte[] { 68, 101, 99, 105, 109, 97, 108 }; - public static ReadOnlySpan DateTime => new byte[] { 68, 97, 116, 101, 84, 105, 109, 101 }; - public static ReadOnlySpan ComImportAttribute => new byte[] { 67, 111, 109, 73, 109, 112, 111, 114, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan DllImportAttribute => new byte[] { 68, 108, 108, 73, 109, 112, 111, 114, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan CallingConvention => new byte[] { 67, 97, 108, 108, 105, 110, 103, 67, 111, 110, 118, 101, 110, 116, 105, 111, 110 }; - public static ReadOnlySpan CharSet => new byte[] { 67, 104, 97, 114, 83, 101, 116 }; - public static ReadOnlySpan MarshalAsAttribute => new byte[] { 77, 97, 114, 115, 104, 97, 108, 65, 115, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan UnmanagedType => new byte[] { 85, 110, 109, 97, 110, 97, 103, 101, 100, 84, 121, 112, 101 }; - public static ReadOnlySpan VarEnum => new byte[] { 86, 97, 114, 69, 110, 117, 109 }; - public static ReadOnlySpan InAttribute => new byte[] { 73, 110, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan OutAttriubute => new byte[] { 79, 117, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan OptionalAttribute => new byte[] { 79, 112, 116, 105, 111, 110, 97, 108, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan PreserveSigAttribute => new byte[] { 80, 114, 101, 115, 101, 114, 118, 101, 83, 105, 103, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan FieldOffsetAttribute => new byte[] { 70, 105, 101, 108, 100, 79, 102, 102, 115, 101, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan IsByRefLikeAttribute => new byte[] { 73, 115, 66, 121, 82, 101, 102, 76, 105, 107, 101, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan DecimalConstantAttribute => new byte[] { 68, 101, 99, 105, 109, 97, 108, 67, 111, 110, 115, 116, 97, 110, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan CustomConstantAttribute => new byte[] { 67, 117, 115, 116, 111, 109, 67, 111, 110, 115, 116, 97, 110, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan GuidAttribute => new byte[] { 71, 117, 105, 100, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan DefaultMemberAttribute => new byte[] { 68, 101, 102, 97, 117, 108, 116, 77, 101, 109, 98, 101, 114, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; - public static ReadOnlySpan DateTimeConstantAttribute => new byte[] { 68, 97, 116, 101, 84, 105, 109, 101, 67, 111, 110, 115, 116, 97, 110, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 }; + public static ReadOnlySpan Array => "Array"u8; + public static ReadOnlySpan Boolean => "Boolean"u8; + public static ReadOnlySpan Byte => "Byte"u8; + public static ReadOnlySpan Char => "Char"u8; + public static ReadOnlySpan Double => "Double"u8; + public static ReadOnlySpan Enum => "Enum"u8; + public static ReadOnlySpan Int16 => "Int16"u8; + public static ReadOnlySpan Int32 => "Int32"u8; + public static ReadOnlySpan Int64 => "Int64"u8; + public static ReadOnlySpan IntPtr => "IntPtr"u8; + public static ReadOnlySpan Object => "Object"u8; + public static ReadOnlySpan NullableT => "Nullable`1"u8; + public static ReadOnlySpan SByte => "SByte"u8; + public static ReadOnlySpan Single => "Single"u8; + public static ReadOnlySpan String => "String"u8; + public static ReadOnlySpan TypedReference => "TypedReference"u8; + public static ReadOnlySpan UInt16 => "UInt16"u8; + public static ReadOnlySpan UInt32 => "UInt32"u8; + public static ReadOnlySpan UInt64 => "UInt64"u8; + public static ReadOnlySpan UIntPtr => "UIntPtr"u8; + public static ReadOnlySpan ValueType => "ValueType"u8; + public static ReadOnlySpan Void => "Void"u8; + public static ReadOnlySpan MulticastDelegate => "MulticastDelegate"u8; + public static ReadOnlySpan IEnumerableT => "IEnumerable`1"u8; + public static ReadOnlySpan ICollectionT => "ICollection`1"u8; + public static ReadOnlySpan IListT => "IList`1"u8; + public static ReadOnlySpan IReadOnlyListT => "IReadOnlyList`1"u8; + public static ReadOnlySpan Type => "Type"u8; + public static ReadOnlySpan DBNull => "DBNull"u8; + public static ReadOnlySpan Decimal => "Decimal"u8; + public static ReadOnlySpan DateTime => "DateTime"u8; + public static ReadOnlySpan ComImportAttribute => "ComImportAttribute"u8; + public static ReadOnlySpan DllImportAttribute => "DllImportAttribute"u8; + public static ReadOnlySpan CallingConvention => "CallingConvention"u8; + public static ReadOnlySpan CharSet => "CharSet"u8; + public static ReadOnlySpan MarshalAsAttribute => "MarshalAsAttribute"u8; + public static ReadOnlySpan UnmanagedType => "UnmanagedType"u8; + public static ReadOnlySpan VarEnum => "VarEnum"u8; + public static ReadOnlySpan InAttribute => "InAttribute"u8; + public static ReadOnlySpan OutAttriubute => "OutAttribute"u8; + public static ReadOnlySpan OptionalAttribute => "OptionalAttribute"u8; + public static ReadOnlySpan PreserveSigAttribute => "PreserveSigAttribute"u8; + public static ReadOnlySpan FieldOffsetAttribute => "FieldOffsetAttribute"u8; + public static ReadOnlySpan IsByRefLikeAttribute => "IsByRefLikeAttribute"u8; + public static ReadOnlySpan DecimalConstantAttribute => "DecimalConstantAttribute"u8; + public static ReadOnlySpan CustomConstantAttribute => "CustomConstantAttribute"u8; + public static ReadOnlySpan GuidAttribute => "GuidAttribute"u8; + public static ReadOnlySpan DefaultMemberAttribute => "DefaultMemberAttribute"u8; + public static ReadOnlySpan DateTimeConstantAttribute => "DateTimeConstantAttribute"u8; } } diff --git a/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToBase64CharArray.cs b/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToBase64CharArray.cs index d888e140c4af0c..0a11c579ebacde 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToBase64CharArray.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToBase64CharArray.cs @@ -21,7 +21,7 @@ public static void ValidOffsetIn() public static void ShortInputArray() { // Regression test for bug where a short input array caused an exception to be thrown - byte[] inputBuffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; + byte[] inputBuffer = "abc"u8; char[] ouputBuffer = new char[4]; Convert.ToBase64CharArray(inputBuffer, 0, 3, ouputBuffer, 0); Convert.ToBase64CharArray(inputBuffer, 0, 2, ouputBuffer, 0); diff --git a/src/libraries/System.Runtime.Extensions/tests/System/Net/WebUtility.cs b/src/libraries/System.Runtime.Extensions/tests/System/Net/WebUtility.cs index 5a9bbab770e8a2..dfa89a8b3c9766 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/Net/WebUtility.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/Net/WebUtility.cs @@ -437,7 +437,7 @@ public static void UrlEncodeToBytes_NoEncodingNeeded_ReturnsNewClonedArray() // prevent problems where the input array is changed if // the output one is modified. - byte[] input = Encoding.UTF8.GetBytes("Dont.Need.Encoding"); + byte[] input = "Dont.Need.Encoding"u8; byte[] output = WebUtility.UrlEncodeToBytes(input, 0, input.Length); Assert.NotSame(input, output); } @@ -445,7 +445,7 @@ public static void UrlEncodeToBytes_NoEncodingNeeded_ReturnsNewClonedArray() [Fact] public static void UrlDecodeToBytes_NoDecodingNeeded_ReturnsNewClonedArray() { - byte[] input = Encoding.UTF8.GetBytes("Dont.Need.Decoding"); + byte[] input = "Dont.Need.Decoding"u8; byte[] output = WebUtility.UrlDecodeToBytes(input, 0, input.Length); Assert.NotSame(input, output); } diff --git a/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/SampleTypes.cs b/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/SampleTypes.cs index 81d2acff15d42c..0d226aebf8dad8 100644 --- a/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/SampleTypes.cs +++ b/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/SampleTypes.cs @@ -4147,7 +4147,7 @@ public class DCWithReadOnlyField public class IReadWriteXmlWriteBinHex_EqualityDefined : IXmlSerializable { - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8; public System.Xml.Schema.XmlSchema GetSchema() { @@ -4176,7 +4176,7 @@ public virtual void ReadXml(System.Xml.XmlReader reader) public virtual void WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8; writer.WriteBinHex(bits, 0, bits.Length); } @@ -4202,7 +4202,7 @@ public override int GetHashCode() internal class PrivateIXmlSerializables : IXmlSerializable { - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8; public System.Xml.Schema.XmlSchema GetSchema() { @@ -4231,7 +4231,7 @@ public virtual void ReadXml(System.Xml.XmlReader reader) public virtual void WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8; writer.WriteBinHex(bits, 0, bits.Length); } } @@ -4241,7 +4241,7 @@ public class PrivateDefaultCtorIXmlSerializables : IXmlSerializable private PrivateDefaultCtorIXmlSerializables() { } public PrivateDefaultCtorIXmlSerializables(bool init) { } - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8; public System.Xml.Schema.XmlSchema GetSchema() { @@ -4270,7 +4270,7 @@ public virtual void ReadXml(System.Xml.XmlReader reader) public virtual void WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8; writer.WriteBinHex(bits, 0, bits.Length); } } @@ -4278,7 +4278,7 @@ public virtual void WriteXml(System.Xml.XmlWriter writer) [XmlSchemaProvider("MySchema")] public class PublicIXmlSerializablesWithPublicSchemaProvider : IXmlSerializable { - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8; public System.Xml.Schema.XmlSchema GetSchema() { @@ -4312,7 +4312,7 @@ public virtual void ReadXml(System.Xml.XmlReader reader) public virtual void WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8; writer.WriteBinHex(bits, 0, bits.Length); } } @@ -4320,7 +4320,7 @@ public virtual void WriteXml(System.Xml.XmlWriter writer) [XmlSchemaProvider("MySchema")] public class PublicExplicitIXmlSerializablesWithPublicSchemaProvider : IXmlSerializable { - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8; System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() { @@ -4354,7 +4354,7 @@ void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8; writer.WriteBinHex(bits, 0, bits.Length); } } @@ -4362,7 +4362,7 @@ void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) [XmlSchemaProvider("MySchema")] public class PublicIXmlSerializablesWithPrivateSchemaProvider : IXmlSerializable { - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8; public System.Xml.Schema.XmlSchema GetSchema() { @@ -4396,7 +4396,7 @@ public virtual void ReadXml(System.Xml.XmlReader reader) public virtual void WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8; writer.WriteBinHex(bits, 0, bits.Length); } } diff --git a/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs b/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs index 80d4eac5790bff..66d38d71b00ed3 100644 --- a/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs +++ b/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs @@ -21,7 +21,7 @@ public class CoseTestHelpers internal const int KnownHeaderIV = 5; internal const int KnownHeaderPartialIV = 6; internal const int KnownHeaderCounterSignature = 7; - internal static readonly byte[] s_sampleContent = Encoding.UTF8.GetBytes("This is the content."); + internal static readonly byte[] s_sampleContent = "This is the content."u8; internal const string ContentTypeDummyValue = "application/cose; cose-type=\"cose-sign1\""; internal const string NullCborHex = "F6"; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampRequestTests.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampRequestTests.cs index 850232f8fe22cf..53662bea6c013a 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampRequestTests.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampRequestTests.cs @@ -16,7 +16,7 @@ public static class TimestampRequestTests public static void BuildExpectedRequest_FromData(bool viaSpan) { Rfc3161TimestampRequest request = Rfc3161TimestampRequest.CreateFromData( - System.Text.Encoding.ASCII.GetBytes("Hello, world!!"), + "Hello, world!!"u8, HashAlgorithmName.SHA256, requestSignerCertificates: true); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampTokenTestData.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampTokenTestData.cs index dba1da30509667..39a7d468cb6206 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampTokenTestData.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampTokenTestData.cs @@ -100,7 +100,7 @@ internal static TimestampTokenTestData GetTestData(string testDataName) "D50DF295F1DB078C84EECBCB30F1018E939B1FEA8615B31F39F87F02EF816EFF" + "FE80A39C0857ECA510882DD2D66D49B743F0E7FF8DBEE4650449"); - data.MessageContent = Encoding.ASCII.GetBytes("This is a test.\n"); + data.MessageContent = "This is a test.\n"u8; data.TokenInfoBytes = data.FullTokenBytes.Slice(64, 412); data.PolicyId = "1.2.3.4.1"; @@ -283,7 +283,7 @@ internal static TimestampTokenTestData GetTestData(string testDataName) "FD6B6AB4F89DC6750F14EC2E0134BA61B4D0B2C1FB2F60F622379249CE6381AF" + "667900B17A7BB6AE"); - data.MessageContent = Encoding.ASCII.GetBytes("Hello, world!"); + data.MessageContent = "Hello, world!"u8; data.EmbeddedSigningCertificate = data.FullTokenBytes.Slice(1659, 1359); @@ -422,7 +422,7 @@ internal static TimestampTokenTestData GetTestData(string testDataName) "76252A2F4605B97BD3C299D1CD79929273BB86E7DF9E113C92802380ED6D4041" + "9DA4C01214D4FA24"); - data.MessageContent = Encoding.UTF8.GetBytes("My TST signer attributes are sorted incorrectly."); + data.MessageContent = "My TST signer attributes are sorted incorrectly."u8; data.EmbeddedSigningCertificate = data.FullTokenBytes.Slice(188, 1670); diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs b/src/libraries/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs index b4a4487a1ce5fe..c265a6a72dda41 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs @@ -347,7 +347,7 @@ public static void TestKey_RSA384_ValidatesSignature() 0x11, 0xE0, 0x6E, 0xD2, 0x22, 0x75, 0xE7, 0x7C, }; - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); + byte[] helloBytes = "Hello"u8; using (var cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes)) using (RSA rsa = cert.GetRSAPublicKey()) @@ -360,7 +360,7 @@ public static void TestKey_RSA384_ValidatesSignature() public static void TestKey_ECDsabrainpool_PublicKey(byte[] curveData, byte[] notUsed) { _ = notUsed; - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); + byte[] helloBytes = "Hello"u8; try { @@ -386,7 +386,7 @@ public static void TestKey_ECDsabrainpool_PublicKey(byte[] curveData, byte[] not [Fact] public static void TestECDsaPublicKey() { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); + byte[] helloBytes = "Hello"u8; using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) @@ -439,7 +439,7 @@ public static void TestECDsaPublicKey_ValidatesSignature() 0x08, 0xC5, 0xAA, 0xA6, 0xE5, 0xFD, 0xD0, 0x96, }; - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); + byte[] helloBytes = "Hello"u8; using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) @@ -476,7 +476,7 @@ public static void TestECDHPublicKey_DeriveSecret() [Theory, MemberData(nameof(BrainpoolCurves))] public static void TestECDsaPublicKey_BrainpoolP160r1_ValidatesSignature(byte[] curveData, byte[] existingSignature) { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); + byte[] helloBytes = "Hello"u8; try { diff --git a/src/libraries/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs b/src/libraries/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs index 5e11d908899341..806ef6b0b115ee 100644 --- a/src/libraries/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs +++ b/src/libraries/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs @@ -611,7 +611,7 @@ public void EncryptKey_RSA_RSANull() [Fact] public void EncryptKey_RSA_UseOAEP() { - byte[] data = Encoding.ASCII.GetBytes("12345678"); + byte[] data = "12345678"u8; using (RSA rsa = RSA.Create()) { byte[] encryptedData = EncryptedXml.EncryptKey(data, rsa, true); @@ -852,7 +852,7 @@ public void EncryptKey_TripleDES() { using (TripleDES tripleDES = TripleDES.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678"); + byte[] key = "123456781234567812345678"u8; byte[] encryptedKey = EncryptedXml.EncryptKey(key, tripleDES); @@ -866,7 +866,7 @@ public void EncryptKey_AES() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678"); + byte[] key = "123456781234567812345678"u8; byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes); @@ -880,7 +880,7 @@ public void EncryptKey_AES8Bytes() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("12345678"); + byte[] key = "12345678"u8; byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes); @@ -894,7 +894,7 @@ public void EncryptKey_AESNotDivisibleBy8() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("1234567"); + byte[] key = "1234567"u8; Assert.Throws(() => EncryptedXml.EncryptKey(key, aes)); } @@ -905,7 +905,7 @@ public void DecryptKey_TripleDESWrongKeySize() { using (TripleDES tripleDES = TripleDES.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123"); + byte[] key = "123"u8; Assert.Throws(() => EncryptedXml.DecryptKey(key, tripleDES)); } @@ -916,7 +916,7 @@ public void DecryptKey_TripleDESCorruptedKey() { using (TripleDES tripleDES = TripleDES.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678"); + byte[] key = "123456781234567812345678"u8; byte[] encryptedKey = EncryptedXml.EncryptKey(key, tripleDES); encryptedKey[0] ^= 0xFF; @@ -930,7 +930,7 @@ public void DecryptKey_AESWrongKeySize() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123"); + byte[] key = "123"u8; Assert.Throws(() => EncryptedXml.DecryptKey(key, aes)); } @@ -941,7 +941,7 @@ public void DecryptKey_AESCorruptedKey() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678"); + byte[] key = "123456781234567812345678"u8; byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes); encryptedKey[0] ^= 0xFF; @@ -955,7 +955,7 @@ public void DecryptKey_AESCorruptedKey8Bytes() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("12345678"); + byte[] key = "12345678"u8; byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes); encryptedKey[0] ^= 0xFF; diff --git a/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs b/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs index a7b051beb2f132..7a020fd93d8c9d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs +++ b/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs @@ -1448,7 +1448,7 @@ static void hmacMustBeMultipleOfEightBits(int bits) "; SignedXml sign = GetSignedXml(string.Format(xml, bits)); // only multiple of 8 bits are supported - sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("secret"))); + sign.CheckSignature(new HMACSHA1("secret"u8)); } for (int i = 1; i < 160; i++) @@ -1484,10 +1484,10 @@ public void VerifyHMAC_ZeroLength() "; SignedXml sign = GetSignedXml(xml); - CheckErratum(sign, new HMACSHA1(Encoding.ASCII.GetBytes("no clue")), "1"); - CheckErratum(sign, new HMACSHA1(Encoding.ASCII.GetBytes("")), "2"); - CheckErratum(sign, new HMACSHA1(Encoding.ASCII.GetBytes("oops")), "3"); - CheckErratum(sign, new HMACSHA1(Encoding.ASCII.GetBytes("secret")), "4"); + CheckErratum(sign, new HMACSHA1("no clue"u8), "1"); + CheckErratum(sign, new HMACSHA1(""u8), "2"); + CheckErratum(sign, new HMACSHA1("oops"u8), "3"); + CheckErratum(sign, new HMACSHA1("secret"u8), "4"); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")] @@ -1497,7 +1497,7 @@ public void VerifyHMAC_SmallerThanMinimumLength() // 72 is a multiple of 8 but smaller than the minimum of 80 bits string xml = @"72nz4GS0NbH2SrWlD/4fX313CoTzc=2dimB+P5Aw5Ksome other text"; SignedXml sign = GetSignedXml(xml); - CheckErratum(sign, new HMACSHA1(Encoding.ASCII.GetBytes("secret")), "72"); + CheckErratum(sign, new HMACSHA1("secret"u8), "72"); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")] @@ -1507,7 +1507,7 @@ public void VerifyHMAC_MinimumLength() // 80 bits is the minimum (and the half-size of HMACSHA1) string xml = @"80nz4GS0NbH2SrWlD/4fX313CoTzc=jVQPtLj61zNYjw==some other text"; SignedXml sign = GetSignedXml(xml); - Assert.True(sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("secret")))); + Assert.True(sign.CheckSignature(new HMACSHA1("secret"u8))); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")] @@ -1517,7 +1517,7 @@ public void VerifyHMAC_SmallerHalfLength() // 80bits is smaller than the half-size of HMACSHA256 string xml = @"80nz4GS0NbH2SrWlD/4fX313CoTzc=vPtw7zKVV/JwQg==some other text"; SignedXml sign = GetSignedXml(xml); - CheckErratum(sign, new HMACSHA256(Encoding.ASCII.GetBytes("secret")), "80"); + CheckErratum(sign, new HMACSHA256("secret"u8), "80"); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")] @@ -1527,7 +1527,7 @@ public void VerifyHMAC_HalfLength() // 128 is the half-size of HMACSHA256 string xml = @"128nz4GS0NbH2SrWlD/4fX313CoTzc=aegpvkAwOL8gN/CjSnW6qw==some other text"; SignedXml sign = GetSignedXml(xml); - Assert.True(sign.CheckSignature(new HMACSHA256(Encoding.ASCII.GetBytes("secret")))); + Assert.True(sign.CheckSignature(new HMACSHA256("secret"u8))); } [Fact] @@ -1535,7 +1535,7 @@ public void VerifyHMAC_FullLength() { string xml = @"7/XTsHaBSOnJ/jXD5v0zL6VKYsk=a0goL9esBUKPqtFYgpp2KST4huk=some text"; SignedXml sign = GetSignedXml(xml); - Assert.True(sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("secret")))); + Assert.True(sign.CheckSignature(new HMACSHA1("secret"u8))); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")] @@ -1560,7 +1560,7 @@ public void VerifyHMAC_HMACOutputLength_Signature_Mismatch() "; SignedXml sign = GetSignedXml(xml); - Assert.Throws(() => sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("no clue")))); + Assert.Throws(() => sign.CheckSignature(new HMACSHA1("no clue"u8))); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")] @@ -1585,7 +1585,7 @@ public void VerifyHMAC_HMACOutputLength_Invalid() "; SignedXml sign = GetSignedXml(xml); - Assert.Throws(() => sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("no clue")))); + Assert.Throws(() => sign.CheckSignature(new HMACSHA1("no clue"u8))); } [Fact] diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Export.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Export.cs index 5bb45c5dab5a5c..951cecafaa7b60 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Export.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Export.cs @@ -116,10 +116,6 @@ internal bool TryExportPkcs8KeyBlob( out _); } - // The Windows APIs for OID strings are ASCII-only - private static readonly byte[] s_pkcs12TripleDesOidBytes = - System.Text.Encoding.ASCII.GetBytes("1.2.840.113549.1.12.1.3\0"); - internal static unsafe bool ExportPkcs8KeyBlob( bool allocate, SafeNCryptKeyHandle keyHandle, @@ -131,7 +127,8 @@ internal static unsafe bool ExportPkcs8KeyBlob( { using (SafeUnicodeStringHandle stringHandle = new SafeUnicodeStringHandle(password)) { - fixed (byte* oidPtr = s_pkcs12TripleDesOidBytes) + ReadOnlySpan pkcs12TripleDesOidBytes = "1.2.840.113549.1.12.1.3\0"u8; // the Windows APIs for OID strings are ASCII-only + fixed (byte* oidPtr = pkcs12TripleDesOidBytes) { Interop.NCrypt.NCryptBuffer* buffers = stackalloc Interop.NCrypt.NCryptBuffer[3]; @@ -156,7 +153,7 @@ internal static unsafe bool ExportPkcs8KeyBlob( buffers[1] = new Interop.NCrypt.NCryptBuffer { BufferType = Interop.NCrypt.BufferType.PkcsAlgOid, - cbBuffer = s_pkcs12TripleDesOidBytes.Length, + cbBuffer = pkcs12TripleDesOidBytes.Length, pvBuffer = (IntPtr)oidPtr, }; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKeyLite.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKeyLite.cs index efa152cc562c72..409654e052081c 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKeyLite.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKeyLite.cs @@ -280,10 +280,6 @@ internal static bool TryExportPkcs8KeyBlob( out _); } - // The Windows APIs for OID strings are ASCII-only - private static readonly byte[] s_pkcs12TripleDesOidBytes = - System.Text.Encoding.ASCII.GetBytes("1.2.840.113549.1.12.1.3\0"); - internal static unsafe bool ExportPkcs8KeyBlob( bool allocate, SafeNCryptKeyHandle keyHandle, @@ -295,7 +291,8 @@ internal static unsafe bool ExportPkcs8KeyBlob( { using (SafeUnicodeStringHandle stringHandle = new SafeUnicodeStringHandle(password)) { - fixed (byte* oidPtr = s_pkcs12TripleDesOidBytes) + ReadOnlySpan pkcs12TripleDesOidBytes = "1.2.840.113549.1.12.1.3\0"u8; // the Windows APIs for OID strings are ASCII-only + fixed (byte* oidPtr = pkcs12TripleDesOidBytes) { Interop.NCrypt.NCryptBuffer* buffers = stackalloc Interop.NCrypt.NCryptBuffer[3]; @@ -320,7 +317,7 @@ internal static unsafe bool ExportPkcs8KeyBlob( buffers[1] = new Interop.NCrypt.NCryptBuffer { BufferType = Interop.NCrypt.BufferType.PkcsAlgOid, - cbBuffer = s_pkcs12TripleDesOidBytes.Length, + cbBuffer = pkcs12TripleDesOidBytes.Length, pvBuffer = (IntPtr)oidPtr, }; diff --git a/src/libraries/System.Security.Cryptography/tests/Base64TransformsTests.cs b/src/libraries/System.Security.Cryptography/tests/Base64TransformsTests.cs index 72ee58f6031f28..b1e36b3942db4d 100644 --- a/src/libraries/System.Security.Cryptography/tests/Base64TransformsTests.cs +++ b/src/libraries/System.Security.Cryptography/tests/Base64TransformsTests.cs @@ -56,7 +56,7 @@ public static IEnumerable TestData_Oversize() [Fact] public void InvalidInput_ToBase64Transform() { - byte[] data_3bytes = Text.Encoding.ASCII.GetBytes("aaa"); + byte[] data_3bytes = "aaa"u8; ICryptoTransform transform = new ToBase64Transform(); AssertExtensions.Throws("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0)); @@ -77,7 +77,7 @@ public void InvalidInput_ToBase64Transform() [Fact] public void InvalidInput_FromBase64Transform() { - byte[] data_4bytes = Text.Encoding.ASCII.GetBytes("aaaa"); + byte[] data_4bytes = "aaaa"u8; ICryptoTransform transform = new FromBase64Transform(); AssertExtensions.Throws("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0)); diff --git a/src/libraries/System.Security.Cryptography/tests/CryptoStream.cs b/src/libraries/System.Security.Cryptography/tests/CryptoStream.cs index 68e210472d4544..6e877fbf5a027c 100644 --- a/src/libraries/System.Security.Cryptography/tests/CryptoStream.cs +++ b/src/libraries/System.Security.Cryptography/tests/CryptoStream.cs @@ -304,7 +304,7 @@ public static void PaddedAes_PartialRead_Success() var memoryStream = new MemoryStream(); using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write, leaveOpen: true)) { - cryptoStream.Write(Encoding.ASCII.GetBytes("Sample string that's bigger than cryptoAlg.BlockSize")); + cryptoStream.Write("Sample string that's bigger than cryptoAlg.BlockSize"u8); cryptoStream.FlushFinalBlock(); } diff --git a/src/libraries/System.Security.Cryptography/tests/Rfc2898OneShotTests.cs b/src/libraries/System.Security.Cryptography/tests/Rfc2898OneShotTests.cs index cd92dc99b57eaa..5aba32f95db922 100644 --- a/src/libraries/System.Security.Cryptography/tests/Rfc2898OneShotTests.cs +++ b/src/libraries/System.Security.Cryptography/tests/Rfc2898OneShotTests.cs @@ -289,7 +289,7 @@ public static void Pbkdf2_Rfc6070_HighIterations() string password = "password"; int iterations = 16777216; byte[] expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984".HexToByteArray(); - byte[] salt = Encoding.UTF8.GetBytes("salt"); + byte[] salt = "salt"u8; byte[] actual = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA1, expected.Length); Assert.Equal(expected, actual); } diff --git a/src/libraries/System.Security.Cryptography/tests/TripleDesTests.cs b/src/libraries/System.Security.Cryptography/tests/TripleDesTests.cs index 64b9c402a5da85..91eb1da032920e 100644 --- a/src/libraries/System.Security.Cryptography/tests/TripleDesTests.cs +++ b/src/libraries/System.Security.Cryptography/tests/TripleDesTests.cs @@ -63,7 +63,7 @@ public static void TripleDesCannotSetWeakKey() [Fact] public static void TripleDesCreate() { - byte[] inputBytes = Encoding.ASCII.GetBytes("This is a secret message and is a sentence that is longer than a block, it ensures that multi-block functions work."); + byte[] inputBytes = "This is a secret message and is a sentence that is longer than a block, it ensures that multi-block functions work."u8; TripleDES tripleDes = TripleDES.Create(); byte[] encryptedBytes; diff --git a/src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs b/src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs index 3dc2f53edb0923..953b4cc37795ed 100644 --- a/src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs +++ b/src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs @@ -30,7 +30,7 @@ public static void TestEncoderReplacementFallback() // Test when the fallback will not occur encodedBytes = new byte[asciiEncoding.GetByteCount(s_asciiInputStringWinNoFallback)]; numberOfEncodedBytes = asciiEncoding.GetBytes(s_asciiInputStringWinNoFallback, 0, s_asciiInputStringWinNoFallback.Length, encodedBytes, 0); - Assert.Equal(encodedBytes, new byte[] { (byte)'a', (byte)'b', (byte)'c' }); + Assert.Equal("abc"u8, encodedBytes); decodedString = asciiEncoding.GetString(encodedBytes); Assert.Equal(decodedString, s_asciiInputStringWinNoFallback); } diff --git a/src/libraries/System.Text.Encodings.Web/tests/TextEncoderTests.cs b/src/libraries/System.Text.Encodings.Web/tests/TextEncoderTests.cs index cb26b483e7ce3e..39c2d7ab2f6ce1 100644 --- a/src/libraries/System.Text.Encodings.Web/tests/TextEncoderTests.cs +++ b/src/libraries/System.Text.Encodings.Web/tests/TextEncoderTests.cs @@ -150,7 +150,7 @@ public void EncodeUtf8_MixedInputWhichRequiresEncodingOrReplacement() Assert.Equal(OperationStatus.Done, encoder.EncodeUtf8(aggregateInputBytesSoFar.ToArray(), destination, out bytesConsumed, out bytesWritten, isFinalBlock: true)); Assert.Equal(aggregateInputBytesSoFar.Count, bytesConsumed); Assert.Equal(expectedOutputBytesSoFar.Count + "[FFFD]".Length, bytesWritten); - Assert.Equal(expectedOutputBytesSoFar.Concat(Encoding.UTF8.GetBytes("[FFFD]")).ToArray(), new Span(destination, 0, expectedOutputBytesSoFar.Count + "[FFFD]".Length).ToArray()); + Assert.Equal(expectedOutputBytesSoFar.Concat("[FFFD]"u8).ToArray(), new Span(destination, 0, expectedOutputBytesSoFar.Count + "[FFFD]".Length).ToArray()); } // Consume the remainder of this entry and make sure it escaped properly (if needed). @@ -222,7 +222,7 @@ public void FindFirstCharToEncodeUtf8_WellFormedData_AllCharsAllowed() { // Arrange - byte[] inputBytes = Encoding.UTF8.GetBytes("\U00000040\U00000400\U00004000\U00040000"); // code units of different lengths + byte[] inputBytes = "\U00000040\U00000400\U00004000\U00040000"u8; // code units of different lengths var encoder = new ConfigurableScalarTextEncoder(_ => true /* allow everything */); // Act @@ -239,7 +239,7 @@ public void FindFirstCharToEncodeUtf8_WellFormedData_SomeCharsDisallowed() { // Arrange - byte[] inputBytes = Encoding.UTF8.GetBytes("\U00000040\U00000400\U00004000\U00040000"); // code units of different lengths + byte[] inputBytes = "\U00000040\U00000400\U00004000\U00040000"u8; // code units of different lengths var encoder = new ConfigurableScalarTextEncoder(codePoint => codePoint != 0x4000 /* disallow U+4000, allow all else */); // Act diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/JsonConstants.cs b/src/libraries/System.Text.Json/src/System/Text/Json/JsonConstants.cs index bed577622f5faa..93ff7cea77f9a0 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/JsonConstants.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/JsonConstants.cs @@ -33,13 +33,13 @@ internal static partial class JsonConstants public const byte StartingByteOfNonStandardSeparator = 0xE2; public static ReadOnlySpan Utf8Bom => new byte[] { 0xEF, 0xBB, 0xBF }; - public static ReadOnlySpan TrueValue => new byte[] { (byte)'t', (byte)'r', (byte)'u', (byte)'e' }; - public static ReadOnlySpan FalseValue => new byte[] { (byte)'f', (byte)'a', (byte)'l', (byte)'s', (byte)'e' }; - public static ReadOnlySpan NullValue => new byte[] { (byte)'n', (byte)'u', (byte)'l', (byte)'l' }; + public static ReadOnlySpan TrueValue => "true"u8; + public static ReadOnlySpan FalseValue => "false"u8; + public static ReadOnlySpan NullValue => "null"u8; - public static ReadOnlySpan NaNValue => new byte[] { (byte)'N', (byte)'a', (byte)'N' }; - public static ReadOnlySpan PositiveInfinityValue => new byte[] { (byte)'I', (byte)'n', (byte)'f', (byte)'i', (byte)'n', (byte)'i', (byte)'t', (byte)'y' }; - public static ReadOnlySpan NegativeInfinityValue => new byte[] { (byte)'-', (byte)'I', (byte)'n', (byte)'f', (byte)'i', (byte)'n', (byte)'i', (byte)'t', (byte)'y' }; + public static ReadOnlySpan NaNValue => "NaN"u8; + public static ReadOnlySpan PositiveInfinityValue => "Infinity"u8; + public static ReadOnlySpan NegativeInfinityValue => "-Infinity"u8; // Used to search for the end of a number public static ReadOnlySpan Delimiters => new byte[] { ListSeparator, CloseBrace, CloseBracket, Space, LineFeed, CarriageReturn, Tab, Slash }; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs index b262cddd2a1e08..28d83345a74b26 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs @@ -10,14 +10,9 @@ namespace System.Text.Json { public static partial class JsonSerializer { - internal static readonly byte[] s_idPropertyName - = new byte[] { (byte)'$', (byte)'i', (byte)'d' }; - - internal static readonly byte[] s_refPropertyName - = new byte[] { (byte)'$', (byte)'r', (byte)'e', (byte)'f' }; - - internal static readonly byte[] s_valuesPropertyName - = new byte[] { (byte)'$', (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', (byte)'s' }; + internal static readonly byte[] s_idPropertyName = "$id"u8; + internal static readonly byte[] s_refPropertyName = "$ref"u8; + internal static readonly byte[] s_valuesPropertyName = "$values"u8; internal static bool TryReadMetadata(JsonConverter converter, ref Utf8JsonReader reader, ref ReadStack state) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs index 3cac73e64cd36a..58377bbdf41a9f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs @@ -10,7 +10,7 @@ namespace System.Text.Json public sealed partial class Utf8JsonWriter { private static readonly char[] s_singleLineCommentDelimiter = new char[2] { '*', '/' }; - private static ReadOnlySpan SingleLineCommentDelimiterUtf8 => new byte[2] { (byte)'*', (byte)'/' }; + private static ReadOnlySpan SingleLineCommentDelimiterUtf8 => "*/"u8; /// /// Writes the string text value (as a JSON comment). diff --git a/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.Stream.cs b/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.Stream.cs index cb99feac24acf3..87936328d5ab50 100644 --- a/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.Stream.cs +++ b/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.Stream.cs @@ -148,7 +148,7 @@ async Task RunTestAsync() await Assert.ThrowsAsync(async () => await StreamingSerializer.DeserializeWrapper(stream, options)); } - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("{}"))) + using (MemoryStream stream = new MemoryStream("{}"u8)) { JsonSerializerOptions options = new JsonSerializerOptions { diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonElementWriteTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonElementWriteTests.cs index 2898ab9d862c28..8e8de286f5fe9f 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonElementWriteTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonElementWriteTests.cs @@ -78,7 +78,7 @@ public void WritePropertyOutsideObject(bool skipValidation) }; const string CharLabel = "char"; - byte[] byteUtf8 = Encoding.UTF8.GetBytes("byte"); + byte[] byteUtf8 = "byte"u8; using var writer = new Utf8JsonWriter(buffer, options); if (skipValidation) diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/ParseTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/ParseTests.cs index 5c6022f503f112..0c46c491cd07b9 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/ParseTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/ParseTests.cs @@ -138,7 +138,7 @@ public static void NullLiteral() Assert.Null(JsonSerializer.Deserialize("null")); Assert.Null(JsonNode.Parse("null")); - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null"))) + using (MemoryStream stream = new MemoryStream("null"u8)) { Assert.Null(JsonNode.Parse(stream)); } diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonReaderStateAndOptionsTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonReaderStateAndOptionsTests.cs index 182691e52f33f3..f835cb7b9dfebc 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonReaderStateAndOptionsTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonReaderStateAndOptionsTests.cs @@ -103,7 +103,7 @@ public static void DefaultJsonReaderOptions() [Fact] public static void ZeroMaxDepthDefaultsTo64() { - byte[] dataUtf8 = Encoding.UTF8.GetBytes("{}"); + byte[] dataUtf8 = "{}"u8; ReadOnlyMemory dataMemory = dataUtf8; var firstSegment = new BufferSegment(dataMemory.Slice(0, 1)); @@ -134,7 +134,7 @@ public static void ZeroMaxDepthDefaultsTo64() [Fact] public static void MaxDepthIsHonored() { - byte[] dataUtf8 = Encoding.UTF8.GetBytes("{}"); + byte[] dataUtf8 = "{}"u8; ReadOnlyMemory dataMemory = dataUtf8; var firstSegment = new BufferSegment(dataMemory.Slice(0, 1)); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonTestHelper.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonTestHelper.cs index 3feeb33dd8be0f..e069f232bf8806 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonTestHelper.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonTestHelper.cs @@ -448,19 +448,19 @@ public static byte[] ReaderLoop(int inpuDataLength, out int length, ref Utf8Json // Special casing Null so that it matches what JSON.NET does break; case JsonTokenType.StartObject: - Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)'{' })); + Assert.True(json.ValueSpan.SequenceEqual("{"u8)); Assert.True(json.ValueSequence.IsEmpty); break; case JsonTokenType.EndObject: - Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)'}' })); + Assert.True(json.ValueSpan.SequenceEqual("}"u8)); Assert.True(json.ValueSequence.IsEmpty); break; case JsonTokenType.StartArray: - Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)'[' })); + Assert.True(json.ValueSpan.SequenceEqual("["u8)); Assert.True(json.ValueSequence.IsEmpty); break; case JsonTokenType.EndArray: - Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)']' })); + Assert.True(json.ValueSpan.SequenceEqual("]"u8)); Assert.True(json.ValueSequence.IsEmpty); break; default: @@ -496,18 +496,18 @@ public static object ReaderLoop(ref Utf8JsonReader json) case JsonTokenType.Null: break; case JsonTokenType.StartObject: - Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'{' })); + Assert.True(valueSpan.SequenceEqual("{"u8)); root = ReaderDictionaryLoop(ref json); break; case JsonTokenType.StartArray: - Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'[' })); + Assert.True(valueSpan.SequenceEqual("["u8)); root = ReaderListLoop(ref json); break; case JsonTokenType.EndObject: - Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'}' })); + Assert.True(valueSpan.SequenceEqual("}"u8)); break; case JsonTokenType.EndArray: - Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)']' })); + Assert.True(valueSpan.SequenceEqual("]"u8)); break; case JsonTokenType.None: case JsonTokenType.Comment: @@ -581,7 +581,7 @@ public static Dictionary ReaderDictionaryLoop(ref Utf8JsonReader } break; case JsonTokenType.StartObject: - Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'{' })); + Assert.True(valueSpan.SequenceEqual("{"u8)); value = ReaderDictionaryLoop(ref json); if (dictionary.TryGetValue(key, out _)) { @@ -593,7 +593,7 @@ public static Dictionary ReaderDictionaryLoop(ref Utf8JsonReader } break; case JsonTokenType.StartArray: - Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'[' })); + Assert.True(valueSpan.SequenceEqual("["u8)); value = ReaderListLoop(ref json); if (dictionary.TryGetValue(key, out _)) { @@ -605,7 +605,7 @@ public static Dictionary ReaderDictionaryLoop(ref Utf8JsonReader } break; case JsonTokenType.EndObject: - Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'}' })); + Assert.True(valueSpan.SequenceEqual("}"u8)); return dictionary; case JsonTokenType.None: case JsonTokenType.Comment: @@ -646,17 +646,17 @@ public static List ReaderListLoop(ref Utf8JsonReader json) arrayList.Add(value); break; case JsonTokenType.StartObject: - Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'{' })); + Assert.True(valueSpan.SequenceEqual("{"u8)); value = ReaderDictionaryLoop(ref json); arrayList.Add(value); break; case JsonTokenType.StartArray: - Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'[' })); + Assert.True(valueSpan.SequenceEqual("["u8)); value = ReaderListLoop(ref json); arrayList.Add(value); break; case JsonTokenType.EndArray: - Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)']' })); + Assert.True(valueSpan.SequenceEqual("]"u8)); return arrayList; case JsonTokenType.None: case JsonTokenType.Comment: diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/NewtonsoftTests/CustomObjectConverterTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/NewtonsoftTests/CustomObjectConverterTests.cs index 3531efddf16d3c..c7a75a95c55522 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/NewtonsoftTests/CustomObjectConverterTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/NewtonsoftTests/CustomObjectConverterTests.cs @@ -138,7 +138,7 @@ public void DeserializeByteArrayClass() Assert.Null(byteArrayClass.NullByteArray); } - private static readonly byte[] s_testData = Encoding.UTF8.GetBytes("This is some test data!!!"); + private static readonly byte[] s_testData = "This is some test data!!!"u8; [Fact] public void AssertShouldSerializeTest() diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Array.ReadTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Array.ReadTests.cs index 913c9196a08684..115e91c909db01 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Array.ReadTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Array.ReadTests.cs @@ -154,7 +154,7 @@ public static void ReadArrayWithInterleavedComments() var options = new JsonSerializerOptions(); options.ReadCommentHandling = JsonCommentHandling.Skip; - int[][] i = JsonSerializer.Deserialize(Encoding.UTF8.GetBytes("[[1,2] // Inline [\n,[3, /* Multi\n]] Line*/4]]"), options); + int[][] i = JsonSerializer.Deserialize("[[1,2] // Inline [\n,[3, /* Multi\n]] Line*/4]]"u8, options); Assert.Equal(1, i[0][0]); Assert.Equal(2, i[0][1]); Assert.Equal(3, i[1][0]); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Null.ReadTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Null.ReadTests.cs index 0f32389207a504..a2a714b5ae84f3 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Null.ReadTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Null.ReadTests.cs @@ -188,7 +188,7 @@ public static void ParseNullStringToStructShouldThrowJsonException() [Fact] public static async Task ParseNullStringShouldThrowJsonExceptionAsync() { - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("null"))) + using (var stream = new MemoryStream("null"u8)) { await Assert.ThrowsAsync(async () => await JsonSerializer.DeserializeAsync(stream)); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/ReadValueTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/ReadValueTests.cs index e7eb6f5b314a4d..c2a45ad6f5a86c 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/ReadValueTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/ReadValueTests.cs @@ -61,7 +61,7 @@ public static void SerializerOptionsStillApply() [Fact] public static void ReaderOptionsWinMaxDepth() { - byte[] utf8 = Encoding.UTF8.GetBytes("[[]]"); + byte[] utf8 = "[[]]"u8; var readerOptions = new JsonReaderOptions { @@ -114,7 +114,7 @@ public static void ReaderOptionsWinMaxDepth() [Fact] public static void ReaderOptionsWinTrailingCommas() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, 3,]"); + byte[] utf8 = "[1, 2, 3,]"u8; var serializerOptions = new JsonSerializerOptions { @@ -151,7 +151,7 @@ public static void ReaderOptionsWinTrailingCommas() [Fact] public static void ReaderOptionsWinComments() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, /* some comment */ 3]"); + byte[] utf8 = "[1, 2, /* some comment */ 3]"u8; var serializerOptions = new JsonSerializerOptions { @@ -175,7 +175,7 @@ public static void ReaderOptionsWinComments() ReadAndVerify(utf8, serializerOptions: null, readerOptions, utf8.Length); ReadAndVerify(utf8, serializerOptions, readerOptions, utf8.Length); - byte[] utf8_CommentsAfter = Encoding.UTF8.GetBytes("[1, 2, 3]/* some comment */"); + byte[] utf8_CommentsAfter = "[1, 2, 3]/* some comment */"u8; ReadAndVerify(utf8_CommentsAfter, serializerOptions, readerOptions: default, expectedLength: "[1, 2, 3]".Length); ReadAndVerify(utf8_CommentsAfter, serializerOptions, readerOptions, expectedLength: "[1, 2, 3]".Length); @@ -193,7 +193,7 @@ static void ReadAndVerify(byte[] utf8, JsonSerializerOptions serializerOptions, [Fact] public static void OnInvalidReaderIsRestored() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, 3}"); + byte[] utf8 = "[1, 2, 3}"u8; var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default); reader.Read(); @@ -292,7 +292,7 @@ public static void ReadObjectMultiSegment(bool isFinalBlock) public static void NotEnoughData(bool isFinalBlock) { { - byte[] utf8 = Encoding.UTF8.GetBytes("\"start of string"); + byte[] utf8 = "\"start of string"u8; var reader = new Utf8JsonReader(utf8, isFinalBlock, state: default); Assert.Equal(0, reader.BytesConsumed); @@ -310,7 +310,7 @@ public static void NotEnoughData(bool isFinalBlock) } { - byte[] utf8 = Encoding.UTF8.GetBytes("{"); + byte[] utf8 = "{"u8; var reader = new Utf8JsonReader(utf8, isFinalBlock, state: default); reader.Read(); @@ -333,7 +333,7 @@ public static void NotEnoughData(bool isFinalBlock) [Fact] public static void EndObjectOrArrayIsInvalid() { - byte[] utf8 = Encoding.UTF8.GetBytes("[{}]"); + byte[] utf8 = "[{}]"u8; var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default); reader.Read(); @@ -575,7 +575,7 @@ public static void ReadClasses() [Fact] public static void ReadPartial() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, 3]"); + byte[] utf8 = "[1, 2, 3]"u8; var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default); reader.Read(); int[] array = JsonSerializer.Deserialize(ref reader); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/SpanTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/SpanTests.cs index c01ce57372c1f0..a12035655bb8fd 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/SpanTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/SpanTests.cs @@ -60,7 +60,7 @@ public static void ReadGenericApi() [Fact] public static void ParseUntyped() { - byte[] bytes = Encoding.UTF8.GetBytes("42"); + byte[] bytes = "42"u8; object obj = JsonSerializer.Deserialize(bytes, typeof(object)); Assert.IsType(obj); JsonElement element = (JsonElement)obj; diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs index 5112265009e8bb..1a324586b7bb08 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs @@ -69,7 +69,7 @@ public async Task ReadPrimitivesAsync() [Fact] public async Task ReadPrimitivesWithTrailingTriviaAsync() { - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(" 1\t// Comment\r\n/* Multi\r\nLine */"))) + using (MemoryStream stream = new MemoryStream(" 1\t// Comment\r\n/* Multi\r\nLine */"u8)) { JsonSerializerOptions options = new JsonSerializerOptions { @@ -85,7 +85,7 @@ public async Task ReadPrimitivesWithTrailingTriviaAsync() [Fact] public async Task ReadReferenceTypeCollectionPassingNullValueAsync() { - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null"))) + using (MemoryStream stream = new MemoryStream("null"u8)) { IList referenceTypeCollection = await Serializer.DeserializeWrapper>(stream); Assert.Null(referenceTypeCollection); @@ -95,7 +95,7 @@ public async Task ReadReferenceTypeCollectionPassingNullValueAsync() [Fact] public async Task ReadValueTypeCollectionPassingNullValueAsync() { - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null"))) + using (MemoryStream stream = new MemoryStream("null"u8)) { IList valueTypeCollection = await Serializer.DeserializeWrapper>(stream); Assert.Null(valueTypeCollection); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Value.WriteTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Value.WriteTests.cs index 4f1121a2e8195c..f05cc5294b3283 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Value.WriteTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Value.WriteTests.cs @@ -48,7 +48,7 @@ public static void WritePrimitives() { Span json = JsonSerializer.SerializeToUtf8Bytes(1); - Assert.Equal(Encoding.UTF8.GetBytes("1"), json.ToArray()); + Assert.Equal("1"u8, json.ToArray()); } { diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/WriteValueTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/WriteValueTests.cs index 66b89f1c151f80..e6bd6fe2e37a00 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/WriteValueTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/WriteValueTests.cs @@ -67,7 +67,7 @@ public async static void NullValueWithValueTypeThrows() [Fact] public async static void NullValueWithNullableSuccess() { - byte[] nullUtf8Literal = Encoding.UTF8.GetBytes("null"); + byte[] nullUtf8Literal = "null"u8; var stream = new MemoryStream(); Utf8JsonWriter writer = new Utf8JsonWriter(stream); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.MultiSegment.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.MultiSegment.cs index d4cbb837f2e059..2379fc7bd07fde 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.MultiSegment.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.MultiSegment.cs @@ -15,7 +15,7 @@ public static partial class Utf8JsonReaderTests [Fact] public static void InitialStateMultiSegment() { - byte[] utf8 = Encoding.UTF8.GetBytes("1"); + byte[] utf8 = "1"u8; ReadOnlySequence sequence = JsonTestHelper.GetSequence(utf8, 1); var json = new Utf8JsonReader(sequence, isFinalBlock: true, state: default); @@ -393,7 +393,7 @@ private static void InvalidReadStringHelper(ref Utf8JsonReader jsonReader, int e [Fact] public static void InitialStateSimpleCtorMultiSegment() { - byte[] utf8 = Encoding.UTF8.GetBytes("1"); + byte[] utf8 = "1"u8; ReadOnlySequence sequence = JsonTestHelper.GetSequence(utf8, 1); var json = new Utf8JsonReader(sequence); @@ -417,7 +417,7 @@ public static void InitialStateSimpleCtorMultiSegment() [Fact] public static void StateRecoveryMultiSegment() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1]"); + byte[] utf8 = "[1]"u8; ReadOnlySequence sequence = JsonTestHelper.GetSequence(utf8, 1); var json = new Utf8JsonReader(sequence, isFinalBlock: false, state: default); @@ -444,7 +444,7 @@ public static void StateRecoveryMultiSegment() Assert.NotEqual(default, json.Position); Assert.True(json.HasValueSequence); Assert.True(json.ValueSpan.SequenceEqual(default)); - Assert.True(json.ValueSequence.ToArray().AsSpan().SequenceEqual(new byte[] { (byte)'1' })); + Assert.True(json.ValueSequence.ToArray().AsSpan().SequenceEqual("1"u8)); Assert.Equal(64, json.CurrentState.Options.MaxDepth); Assert.False(json.CurrentState.Options.AllowTrailingCommas); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.ValueTextEquals.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.ValueTextEquals.cs index 69df6ce26211eb..7c143d6189d2c9 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.ValueTextEquals.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.ValueTextEquals.cs @@ -13,10 +13,10 @@ public static partial class Utf8JsonReaderTests [Fact] public static void TestTextEqualsBasic() { - byte[] connectionId = Encoding.UTF8.GetBytes("connectionId"); - byte[] availableTransports = Encoding.UTF8.GetBytes("availableTransports"); - byte[] value123 = Encoding.UTF8.GetBytes("123"); - byte[] embeddedQuotes = Encoding.UTF8.GetBytes("My name is \"Ahson\""); + byte[] connectionId = "connectionId"u8; + byte[] availableTransports = "availableTransports"u8; + byte[] value123 = "123"u8; + byte[] embeddedQuotes = "My name is \"Ahson\""u8; bool foundId = false; bool foundTransports = false; bool foundValue = false; @@ -370,7 +370,7 @@ public static void TestTextEqualsTooSmallToMatch(string jsonString) { if (json.TokenType == JsonTokenType.String) { - if (json.ValueTextEquals(new byte[] { (byte)'a' }) || + if (json.ValueTextEquals("a"u8) || json.ValueTextEquals(new char[] { 'a' }) || json.ValueTextEquals("a")) { @@ -390,7 +390,7 @@ public static void TestTextEqualsTooSmallToMatch(string jsonString) { if (json.TokenType == JsonTokenType.String) { - if (json.ValueTextEquals(new byte[] { (byte)'a' }) || + if (json.ValueTextEquals("a"u8) || json.ValueTextEquals(new char[] { 'a' }) || json.ValueTextEquals("a")) { @@ -550,7 +550,7 @@ public static void TextEqualsEscapedCharAtTheLastSegment() public static void TestTextEqualsMismatchMultiSegment() { string jsonString = "\"Hi, \\\"Ahson\\\"!\""; - byte[] lookup = Encoding.UTF8.GetBytes("Hello, \"Ahson\""); + byte[] lookup = "Hello, \"Ahson\""u8; byte[] utf8Data = Encoding.UTF8.GetBytes(jsonString); bool found = false; diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.cs index 274fbdf978e365..63e6283ed6502c 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.cs @@ -110,7 +110,7 @@ private static void TestGetMethodsOnDefault() [Fact] public static void InitialState() { - var json = new Utf8JsonReader(Encoding.UTF8.GetBytes("1"), isFinalBlock: true, state: default); + var json = new Utf8JsonReader("1"u8, isFinalBlock: true, state: default); Assert.Equal(0, json.BytesConsumed); Assert.Equal(0, json.TokenStartIndex); @@ -133,7 +133,7 @@ public static void InitialState() [Fact] public static void InitialStateSimpleCtor() { - var json = new Utf8JsonReader(Encoding.UTF8.GetBytes("1")); + var json = new Utf8JsonReader("1"u8); Assert.Equal(0, json.BytesConsumed); Assert.Equal(0, json.TokenStartIndex); @@ -156,7 +156,7 @@ public static void InitialStateSimpleCtor() [Fact] public static void StateRecovery() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1]"); + byte[] utf8 = "[1]"u8; var json = new Utf8JsonReader(utf8, isFinalBlock: false, state: default); Assert.Equal(0, json.BytesConsumed); @@ -182,7 +182,7 @@ public static void StateRecovery() Assert.Equal(JsonTokenType.Number, json.TokenType); Assert.Equal(default, json.Position); Assert.False(json.HasValueSequence); - Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)'1' })); + Assert.True(json.ValueSpan.SequenceEqual("1"u8)); Assert.True(json.ValueSequence.IsEmpty); Assert.Equal(64, json.CurrentState.Options.MaxDepth); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.WriteRaw.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.WriteRaw.cs index eb59af3510cb9c..f763a898520f6b 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.WriteRaw.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.WriteRaw.cs @@ -13,7 +13,7 @@ public partial class Utf8JsonWriterTests private const string TestGuidAsStr = "eb97fadd-3ebf-4781-8722-f4773989160e"; private readonly static Guid s_guid = Guid.Parse(TestGuidAsStr); - private static byte[] s_oneAsJson = new byte[] { (byte)'1' }; + private static byte[] s_oneAsJson = "1"u8; [Theory] [MemberData(nameof(GetRootLevelPrimitives))] @@ -57,13 +57,13 @@ public static IEnumerable GetRootLevelPrimitives() Action validate; validate = (data) => Assert.Equal(123456789, JsonSerializer.Deserialize(data)); - yield return new object[] { Encoding.UTF8.GetBytes("123456789"), validate }; + yield return new object[] { "123456789"u8, validate }; validate = (data) => Assert.Equal(1234.56789, JsonSerializer.Deserialize(data)); - yield return new object[] { Encoding.UTF8.GetBytes("1234.56789"), validate }; + yield return new object[] { "1234.56789"u8, validate }; validate = (data) => Assert.Equal(1234.56789, JsonSerializer.Deserialize(data)); - yield return new object[] { Encoding.UTF8.GetBytes(" 1234.56789 "), validate }; + yield return new object[] { " 1234.56789 "u8, validate }; validate = (data) => Assert.Equal(@"Hello", JsonSerializer.Deserialize(data)); yield return new object[] { Encoding.UTF8.GetBytes(@"""Hello"""), validate }; @@ -110,7 +110,7 @@ public static IEnumerable GetArrays() }; yield return new object[] { json, validate }; - json = Encoding.UTF8.GetBytes("[ 1, 1,1,1,1 ] "); + json = "[ 1, 1,1,1,1 ] "u8; validate = (data) => { foreach (int val in JsonSerializer.Deserialize(data)) @@ -266,7 +266,7 @@ void RunTest(bool skipInputValidation) { writer.WriteRawValue(@"{}", skipInputValidation); writer.Flush(); - Assert.True(ms.ToArray().SequenceEqual(new byte[] { (byte)'{', (byte)'{', (byte)'}' })); + Assert.True(ms.ToArray().SequenceEqual("{{}"u8)); } else { diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs index 4ce5bc05542fc0..2c3c41c1763476 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs @@ -1416,7 +1416,7 @@ public void GrowBeyondBufferSize(bool formatted, bool skipValidation) var output = new FixedSizedBufferWriter(InitialGrowthSize); var options = new JsonWriterOptions { Indented = formatted, SkipValidation = skipValidation }; - byte[] utf8String = Encoding.UTF8.GetBytes("this is a string long enough to overflow the buffer and cause an exception to be thrown."); + byte[] utf8String = "this is a string long enough to overflow the buffer and cause an exception to be thrown."u8; using var jsonUtf8 = new Utf8JsonWriter(output, options); @@ -1436,7 +1436,7 @@ private static async Task WriteLargeToStreamHelper(Stream stream, JsonWriterOpti await using var jsonUtf8 = new Utf8JsonWriter(stream, options); - byte[] utf8String = Encoding.UTF8.GetBytes("some string 1234"); + byte[] utf8String = "some string 1234"u8; jsonUtf8.WriteStartArray(); for (int i = 0; i < 10_000; i++) @@ -2316,14 +2316,14 @@ public void InvalidJsonMismatch(bool formatted, bool skipValidation) jsonUtf8.WritePropertyName("test name"); jsonUtf8.WritePropertyName(JsonEncodedText.Encode("test name")); jsonUtf8.WritePropertyName("test name".AsSpan()); - jsonUtf8.WritePropertyName(Encoding.UTF8.GetBytes("test name")); + jsonUtf8.WritePropertyName("test name"u8); } else { Assert.Throws(() => jsonUtf8.WritePropertyName("test name")); Assert.Throws(() => jsonUtf8.WritePropertyName(JsonEncodedText.Encode("test name"))); Assert.Throws(() => jsonUtf8.WritePropertyName("test name".AsSpan())); - Assert.Throws(() => jsonUtf8.WritePropertyName(Encoding.UTF8.GetBytes("test name"))); + Assert.Throws(() => jsonUtf8.WritePropertyName("test name"u8)); } } @@ -2833,7 +2833,7 @@ public void WriteSeparateProperties(bool formatted, bool skipValidation) using var jsonUtf8 = new Utf8JsonWriter(output, options); jsonUtf8.WriteStartObject(); - jsonUtf8.WritePropertyName(Encoding.UTF8.GetBytes("foo1")); + jsonUtf8.WritePropertyName("foo1"u8); jsonUtf8.WriteStringValue("bar1"); jsonUtf8.WritePropertyName("foo2"); jsonUtf8.WriteStringValue("bar2"); @@ -2895,9 +2895,9 @@ public void WritingTooDeepProperty(bool formatted, bool skipValidation) jsonUtf8.WriteStartObject(); for (int i = 0; i < 999; i++) { - jsonUtf8.WriteStartObject(Encoding.UTF8.GetBytes("name")); + jsonUtf8.WriteStartObject("name"u8); } - Assert.Throws(() => jsonUtf8.WriteStartArray(Encoding.UTF8.GetBytes("name"))); + Assert.Throws(() => jsonUtf8.WriteStartArray("name"u8)); } using (var jsonUtf8 = new Utf8JsonWriter(output, options)) @@ -3107,7 +3107,7 @@ public void WritingTooLargeBase64Bytes(bool formatted, bool skipValidation) using (var jsonUtf8 = new Utf8JsonWriter(output, options)) { jsonUtf8.WriteStartObject(); - Assert.Throws(() => jsonUtf8.WriteBase64String(Encoding.UTF8.GetBytes("foo"), value)); + Assert.Throws(() => jsonUtf8.WriteBase64String("foo"u8, value)); } using (var jsonUtf8 = new Utf8JsonWriter(output, options)) @@ -3169,7 +3169,7 @@ public void WritingLargestPossibleBase64Bytes(bool formatted, bool skipValidatio using (var jsonUtf8 = new Utf8JsonWriter(output, options)) { jsonUtf8.WriteStartObject(); - jsonUtf8.WriteBase64String(Encoding.UTF8.GetBytes("foo"), value); + jsonUtf8.WriteBase64String("foo"u8, value); jsonUtf8.WriteEndObject(); } @@ -3231,7 +3231,7 @@ public void Writing3MBBase64Bytes(bool formatted, bool skipValidation) using (var jsonUtf8 = new Utf8JsonWriter(output, options)) { jsonUtf8.WriteStartObject(); - jsonUtf8.WriteBase64String(Encoding.UTF8.GetBytes("foo"), value); + jsonUtf8.WriteBase64String("foo"u8, value); jsonUtf8.WriteEndObject(); } JsonTestHelper.AssertContents(expectedJson, output); @@ -3290,8 +3290,8 @@ public void WriteHelloWorld(bool formatted, bool skipValidation) JsonEncodedText encodedPropertyName = JsonEncodedText.Encode(propertyName); JsonEncodedText encodedValue = JsonEncodedText.Encode(value); - byte[] utf8PropertyName = Encoding.UTF8.GetBytes("message"); - byte[] utf8Value = Encoding.UTF8.GetBytes("Hello, World!"); + byte[] utf8PropertyName = "message"u8; + byte[] utf8Value = "Hello, World!"u8; var options = new JsonWriterOptions { Indented = formatted, SkipValidation = skipValidation }; @@ -4971,7 +4971,7 @@ public void WriteStartEndWithPropertyNameArray(bool formatted, bool skipValidati jsonUtf8.WriteStartArray("property name".AsSpan()); break; case 2: - jsonUtf8.WriteStartArray(Encoding.UTF8.GetBytes("property name")); + jsonUtf8.WriteStartArray("property name"u8); break; } @@ -5060,7 +5060,7 @@ public void WriteStartEndWithPropertyNameObject(bool formatted, bool skipValidat jsonUtf8.WriteStartObject("property name".AsSpan()); break; case 2: - jsonUtf8.WriteStartObject(Encoding.UTF8.GetBytes("property name")); + jsonUtf8.WriteStartObject("property name"u8); break; } @@ -5149,7 +5149,7 @@ public void WriteArrayWithProperty(bool formatted, bool skipValidation) jsonUtf8.WriteStartArray("message".AsSpan()); break; case 2: - jsonUtf8.WriteStartArray(Encoding.UTF8.GetBytes("message")); + jsonUtf8.WriteStartArray("message"u8); break; } @@ -5337,7 +5337,7 @@ public void WriteIntegerValue(bool formatted, bool skipValidation, int value) jsonUtf8.WriteNumber("message".AsSpan(), value); break; case 2: - jsonUtf8.WriteNumber(Encoding.UTF8.GetBytes("message"), value); + jsonUtf8.WriteNumber("message"u8, value); break; case 3: jsonUtf8.WritePropertyName("message"); @@ -5383,7 +5383,7 @@ public void WriteFloatValue(bool formatted, bool skipValidation, float value) jsonUtf8.WriteNumber("message".AsSpan(), value); break; case 2: - jsonUtf8.WriteNumber(Encoding.UTF8.GetBytes("message"), value); + jsonUtf8.WriteNumber("message"u8, value); break; case 3: jsonUtf8.WritePropertyName("message"); @@ -5429,7 +5429,7 @@ public void WriteDoubleValue(bool formatted, bool skipValidation, double value) jsonUtf8.WriteNumber("message".AsSpan(), value); break; case 2: - jsonUtf8.WriteNumber(Encoding.UTF8.GetBytes("message"), value); + jsonUtf8.WriteNumber("message"u8, value); break; case 3: jsonUtf8.WritePropertyName("message"); @@ -6913,7 +6913,7 @@ public static void WriteString_NullPropertyName_Guid() public static void WriteString_NullPropertyName_ReadOnlySpan_Byte() { WriteNullPropertyName_Simple( - Encoding.UTF8.GetBytes("utf8"), + "utf8"u8, "\"utf8\"", (writer, name, value) => writer.WriteString(name, value), (writer, name, value) => writer.WriteString(name, value), @@ -7017,7 +7017,7 @@ public static void WriteStringValue_ReadOnlySpanCharProperty_NullString() [Fact] public static void WriteStringValue_ReadOnlySpanBytesProperty_NullString() { - byte[] propertyName = Encoding.UTF8.GetBytes("propUtf8"); + byte[] propertyName = "propUtf8"u8; WriteNullValue_InObject( "\"propUtf8\":\"\"", diff --git a/src/tasks/WasmBuildTasks/GenerateWasmBundle.cs b/src/tasks/WasmBuildTasks/GenerateWasmBundle.cs index c4fc6a7849fc7e..b162d3282fd5d8 100644 --- a/src/tasks/WasmBuildTasks/GenerateWasmBundle.cs +++ b/src/tasks/WasmBuildTasks/GenerateWasmBundle.cs @@ -61,7 +61,7 @@ public override bool Execute() using (var file = File.Open(OutputFileName!, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { var lengthBytes = new byte[4]; - var magicBytes = Encoding.ASCII.GetBytes("talb"); + var magicBytes = "talb"u8; BinaryPrimitives.WriteInt32LittleEndian(lengthBytes, data.json_bytes.Length); file.Write(magicBytes); file.Write(lengthBytes); diff --git a/src/tests/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9.cs b/src/tests/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9.cs index 04c223596e6d85..f6aa0dc1059d0f 100644 --- a/src/tests/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9.cs +++ b/src/tests/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9.cs @@ -68,7 +68,7 @@ static void loadThreeData(Stream stream) { // find three sequence int matchIndex = 0; - var toFind = new[] { (byte)'>', (byte)'T', (byte)'H', (byte)'R', (byte)'E', (byte)'E' }; + byte[] toFind = ">THREE"u8; var buffer = new byte[BLOCK_SIZE]; do { @@ -78,7 +78,7 @@ static void loadThreeData(Stream stream) // Skip to end of line matchIndex = 0; - toFind = new[] { (byte)'\n' }; + toFind = "\n"u8; threeStart = find(buffer, toFind, threeStart, ref matchIndex); while (threeStart == -1) { @@ -99,7 +99,7 @@ static void loadThreeData(Stream stream) // find next seq or end of input matchIndex = 0; - toFind = new[] { (byte)'>' }; + toFind = ">"u8; threeEnd = find(buffer, toFind, threeStart, ref matchIndex); while (threeEnd == -1) { diff --git a/src/tests/JIT/Regression/JitBlue/GitHub_13568/GitHub_13568.cs b/src/tests/JIT/Regression/JitBlue/GitHub_13568/GitHub_13568.cs index b64cee7b40f1ca..1ede7bc9c64645 100644 --- a/src/tests/JIT/Regression/JitBlue/GitHub_13568/GitHub_13568.cs +++ b/src/tests/JIT/Regression/JitBlue/GitHub_13568/GitHub_13568.cs @@ -10,7 +10,7 @@ namespace VectorWiden { class Program { - private static byte[] _asciiBytes = Encoding.ASCII.GetBytes("text/plain,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7"); + private static byte[] _asciiBytes = "text/plain,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7"u8; private static string _asciiString = new string('\0', _asciiBytes.Length); private static string compareString = "text/plain,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7"; diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035.cs b/src/tests/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035.cs index 791037a8670882..9d67724778a5d7 100644 --- a/src/tests/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035.cs +++ b/src/tests/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035.cs @@ -11,7 +11,7 @@ class Program { static int Main(string[] args) { - byte[] inputBytes = Encoding.UTF8.GetBytes("https://github.com/dotnet/runtime"); + byte[] inputBytes = "https://github.com/dotnet/runtime"u8; Console.WriteLine(UrlEncoder.Default.FindFirstCharacterToEncodeUtf8(inputBytes)); return 100; } diff --git a/src/tests/tracing/eventpipe/common/IpcUtils.cs b/src/tests/tracing/eventpipe/common/IpcUtils.cs index 0640e7e898c31a..ab4f832bd0c6bd 100644 --- a/src/tests/tracing/eventpipe/common/IpcUtils.cs +++ b/src/tests/tracing/eventpipe/common/IpcUtils.cs @@ -191,7 +191,7 @@ public IpcHeader(byte commandSet, byte commandId) // Helper expression to quickly get V1 magic string for comparison // should be 14 bytes long - public static byte[] DotnetIpcV1 => Encoding.ASCII.GetBytes("DOTNET_IPC_V1" + '\0'); + public static byte[] DotnetIpcV1 => "DOTNET_IPC_V1\0"u8; public byte[] Serialize() { diff --git a/src/tests/tracing/eventpipe/common/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcAdvertise.cs b/src/tests/tracing/eventpipe/common/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcAdvertise.cs index 861c6245d27659..c0d8726f6f930f 100644 --- a/src/tests/tracing/eventpipe/common/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcAdvertise.cs +++ b/src/tests/tracing/eventpipe/common/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcAdvertise.cs @@ -25,7 +25,7 @@ namespace Microsoft.Diagnostics.NETCore.Client internal sealed class IpcAdvertise { - private static byte[] Magic_V1 => Encoding.ASCII.GetBytes("ADVR_V1" + '\0'); + private static byte[] Magic_V1 => "ADVR_V1\0"u8; private static readonly int IpcAdvertiseV1SizeInBytes = Magic_V1.Length + 16 + 8 + 2; // 34 bytes private IpcAdvertise(byte[] magic, Guid cookie, UInt64 pid, UInt16 future) diff --git a/src/tests/tracing/eventpipe/common/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcHeader.cs b/src/tests/tracing/eventpipe/common/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcHeader.cs index 95e025a2e3cdc6..eb32399febd941 100644 --- a/src/tests/tracing/eventpipe/common/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcHeader.cs +++ b/src/tests/tracing/eventpipe/common/Microsoft.Diagnostics.NETCore.Client/DiagnosticsIpc/IpcHeader.cs @@ -33,7 +33,7 @@ public IpcHeader(DiagnosticsServerCommandSet commandSet, byte commandId) // Helper expression to quickly get V1 magic string for comparison // should be 14 bytes long - public static byte[] DotnetIpcV1 => Encoding.ASCII.GetBytes("DOTNET_IPC_V1" + '\0'); + public static byte[] DotnetIpcV1 => "DOTNET_IPC_V1\0"u8; public byte[] Serialize() { diff --git a/src/tests/tracing/eventpipe/common/Reverse.cs b/src/tests/tracing/eventpipe/common/Reverse.cs index b301cf59598f10..9610835791dfd4 100644 --- a/src/tests/tracing/eventpipe/common/Reverse.cs +++ b/src/tests/tracing/eventpipe/common/Reverse.cs @@ -27,7 +27,7 @@ namespace Tracing.Tests.Common public class IpcAdvertise { public static int Size_V1 => 34; - public static byte[] Magic_V1 => System.Text.Encoding.ASCII.GetBytes("ADVR_V1" + '\0'); + public static byte[] Magic_V1 => "ADVR_V1\0"u8; public static int MagicSize_V1 => 8; public byte[] Magic = Magic_V1;