Use u8 in more places (#69995)
authorStephen Toub <stoub@microsoft.com>
Tue, 7 Jun 2022 17:42:23 +0000 (13:42 -0400)
committerGitHub <noreply@github.com>
Tue, 7 Jun 2022 17:42:23 +0000 (13:42 -0400)
* Use u8 in more places

Primarily replacing Encoding.UTF8/ASCII.GetBytes("literal") with "literal"u8.ToArray()

* Address PR feedback (and fix some vars)

138 files changed:
src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs
src/libraries/Common/tests/System/Net/Http/Http2LoopbackConnection.cs
src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyFileTests.cs
src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyPemTests.cs
src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSATestData.cs
src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.LimitedPrivate.cs
src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs
src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyPemTests.cs
src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaTests.cs
src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyFileTests.cs
src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs
src/libraries/Common/tests/Tests/System/StringTests.cs
src/libraries/System.Diagnostics.Process/tests/RemotelyInvokable.cs
src/libraries/System.DirectoryServices.Protocols/tests/DirectoryServicesProtocolsTests.cs
src/libraries/System.Drawing.Common/tests/ImageTests.cs
src/libraries/System.Formats.Asn1/tests/Reader/ReadGeneralizedTime.cs
src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs
src/libraries/System.IO.Compression.ZipFile/tests/ZipFile.Unix.cs
src/libraries/System.IO.Compression/tests/ZipArchive/zip_UpdateTests.cs
src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs
src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs
src/libraries/System.IO.FileSystem/tests/FileStream/DevicesPipesAndSockets.cs
src/libraries/System.IO.FileSystem/tests/FileStream/ctor_str_fm.cs
src/libraries/System.IO.Hashing/tests/Crc32Tests.cs
src/libraries/System.IO.Hashing/tests/Crc64Tests.cs
src/libraries/System.IO.Hashing/tests/XxHash32Tests.007.cs
src/libraries/System.IO.Hashing/tests/XxHash32Tests.cs
src/libraries/System.IO.Hashing/tests/XxHash32Tests.f00d.cs
src/libraries/System.IO.Hashing/tests/XxHash64Tests.007.cs
src/libraries/System.IO.Hashing/tests/XxHash64Tests.cs
src/libraries/System.IO.Hashing/tests/XxHash64Tests.f00d.cs
src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs
src/libraries/System.IO.Pipelines/tests/PipeReaderReadAtLeastAsyncTests.cs
src/libraries/System.IO.Pipelines/tests/PipeReaderStreamTests.nonnetstandard.cs
src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs
src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs
src/libraries/System.IO.Pipelines/tests/PipeWriterStreamTests.nonnetstandard.cs
src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs
src/libraries/System.IO.Pipelines/tests/ReadAsyncCancellationTests.cs
src/libraries/System.IO.Pipelines/tests/SchedulerFacts.cs
src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs
src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs
src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs
src/libraries/System.IO.Pipelines/tests/UnflushedBytesTests.cs
src/libraries/System.Memory.Data/tests/BinaryDataTests.cs
src/libraries/System.Memory/tests/Base64/Base64DecoderUnitTests.cs
src/libraries/System.Memory/tests/BuffersExtensions/BuffersExtensionsTests.cs
src/libraries/System.Memory/tests/EncodingExtensions/EncodingExtensionsTests.cs
src/libraries/System.Memory/tests/ReadOnlyBuffer/ReadOnlySequenceTests.Common.byte.cs
src/libraries/System.Memory/tests/SequenceReader/ReadTo.cs
src/libraries/System.Memory/tests/SequenceReader/SkipDelimiter.cs
src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs
src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/BidirectionStreamingTest.cs
src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/System.Net.Http.WinHttpHandler.Functional.Tests.csproj
src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/TrailingHeadersTest.cs
src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/WinHttpResponseStreamTest.cs
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs
src/libraries/System.Net.Http/tests/FunctionalTests/HPackTest.cs
src/libraries/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.Http2.cs
src/libraries/System.Net.Http/tests/FunctionalTests/HttpContentTest.cs
src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs
src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamConformanceTests.cs
src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamZeroByteReadTests.cs
src/libraries/System.Net.Http/tests/FunctionalTests/SocketsHttpHandlerTest.cs
src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs
src/libraries/System.Net.Http/tests/UnitTests/MockContent.cs
src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs
src/libraries/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs
src/libraries/System.Net.HttpListener/tests/HttpListenerContextTests.cs
src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.cs
src/libraries/System.Net.HttpListener/tests/HttpResponseStreamTests.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs
src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs
src/libraries/System.Net.Mail/tests/Unit/QuotedPrintableStreamTest.cs
src/libraries/System.Net.Ping/tests/FunctionalTests/TestSettings.cs
src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicApi.cs
src/libraries/System.Net.Quic/tests/FunctionalTests/MsQuicTests.cs
src/libraries/System.Net.Quic/tests/FunctionalTests/QuicStreamTests.cs
src/libraries/System.Net.Quic/tests/FunctionalTests/QuicTestBase.cs
src/libraries/System.Net.Requests/tests/FtpWebRequestTest.cs
src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs
src/libraries/System.Net.Security/tests/EnterpriseTests/NegotiateStreamLoopbackTest.cs
src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamInvalidOperationTest.cs
src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamKerberosTest.cs
src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs
src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamAllowRenegotiationTests.cs
src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamNetworkStreamTest.cs
src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamStreamToStreamTest.cs
src/libraries/System.Net.Security/tests/FunctionalTests/TestHelper.cs
src/libraries/System.Net.Security/tests/UnitTests/SslApplicationProtocolTests.cs
src/libraries/System.Net.Sockets/tests/FunctionalTests/TcpClientTest.cs
src/libraries/System.Net.WebSockets/tests/WebSocketCreateTest.cs
src/libraries/System.Net.WebSockets/tests/WebSocketDeflateTests.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs
src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/NamespaceHandlingTests.cs
src/libraries/System.Private.Xml/tests/XmlNodeReader/System.Xml.XmlNodeReader.Tests/XmlNodeReaderReadTests.cs
src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverAddRemoveTests.cs
src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverGetEntity.cs
src/libraries/System.Reflection.Metadata/tests/Metadata/MetadataReaderTests.cs
src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs
src/libraries/System.Reflection.Metadata/tests/Utilities/BlobReaderTests.cs
src/libraries/System.Reflection.Metadata/tests/Utilities/MemoryBlockTests.cs
src/libraries/System.Runtime.Extensions/tests/System/Convert.ToBase64CharArray.cs
src/libraries/System.Runtime.Extensions/tests/System/Net/WebUtility.cs
src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/SampleTypes.cs
src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs
src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampRequestTests.cs
src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampTokenTestData.cs
src/libraries/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs
src/libraries/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs
src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.Pem.iOS.cs
src/libraries/System.Security.Cryptography/tests/Base64TransformsTests.cs
src/libraries/System.Security.Cryptography/tests/CryptoStream.cs
src/libraries/System.Security.Cryptography/tests/Rfc2898OneShotTests.cs
src/libraries/System.Security.Cryptography/tests/TripleDesTests.cs
src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs
src/libraries/System.Text.Encodings.Web/tests/TextEncoderTests.cs
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs
src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.Stream.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonElementWriteTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/ParseTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonReaderStateAndOptionsTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/NewtonsoftTests/CustomObjectConverterTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Array.ReadTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Null.ReadTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/ReadValueTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/SpanTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Value.WriteTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/WriteValueTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.MultiSegment.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.ValueTextEquals.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.WriteRaw.cs
src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs

index f12aa87..1086ffe 100644 (file)
@@ -1855,7 +1855,7 @@ namespace System.IO.Tests
             {
                 write = Task.Run(async () =>
                 {
-                    await writeable.WriteAsync(Encoding.UTF8.GetBytes("hello"));
+                    await writeable.WriteAsync("hello"u8.ToArray());
                     await writeable.DisposeAsync();
                 });
             }
@@ -2206,7 +2206,7 @@ namespace System.IO.Tests
 
                         Task write = Task.Run(async () =>
                         {
-                            await writeable.WriteAsync(Encoding.UTF8.GetBytes("hello"));
+                            await writeable.WriteAsync("hello"u8.ToArray());
                             if (FlushRequiredToWriteData)
                             {
                                 if (FlushGuaranteesAllDataWritten)
@@ -2261,7 +2261,7 @@ namespace System.IO.Tests
         [SkipOnPlatform(TestPlatforms.LinuxBionic, "SElinux blocks UNIX sockets")]
         public virtual async Task ZeroByteWrite_OtherDataReceivedSuccessfully(ReadWriteMode mode)
         {
-            byte[][] buffers = new[] { Array.Empty<byte>(), Encoding.UTF8.GetBytes("hello"), Array.Empty<byte>(), Encoding.UTF8.GetBytes("world") };
+            byte[][] buffers = new[] { Array.Empty<byte>(), "hello"u8.ToArray(), Array.Empty<byte>(), "world"u8.ToArray() };
 
             using StreamPair streams = await CreateConnectedStreamsAsync();
             foreach ((Stream writeable, Stream readable) in GetReadWritePairs(streams))
@@ -2915,7 +2915,7 @@ namespace System.IO.Tests
             // (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.ToArray();
 
             using StreamPair innerStreams = ConnectedStreams.CreateBidirectional();
             (Stream innerWriteable, Stream innerReadable) = GetReadWritePair(innerStreams);
index 2329475..fbba51f 100644 (file)
@@ -100,7 +100,7 @@ namespace System.Net.Test.Common
                 // 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.ToArray());
                 _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. 
index afae8f8..980a8a9 100644 (file)
@@ -182,7 +182,7 @@ QT4YuclwLvQmTewyjLtDGiDF/mC+4kpyBePeO9kfkRUDHiwSNk/efN4ug1xQgwhu
 qE3Db1UI4anCCnyEj/jDA8R6hZTFDjxu6bG0Z66g7I2GBDEYaaB+8x0vtiyu5LXo
 6UZ53SX6S+jfIqJoF5YME9zVMoO2kwS/EGvc64+epCGcee1Nx4SGgUcr5HJYz1P4
 CU+l4wPQR0rRmYHIJJIvFh5OXk84pV0crsOrekw7tHeNU6DMzw==",
-                Encoding.UTF8.GetBytes("Password > cipher"),
+                "Password > cipher"u8.ToArray(),
                 new PbeParameters(
                     PbeEncryptionAlgorithm.Aes192Cbc,
                     HashAlgorithmName.SHA256,
index d27137f..a00c34b 100644 (file)
@@ -287,7 +287,7 @@ ho0YNYGUDSgOs6RxBpw1rJUCnAlHNU09peCjEP+aZSrhsxlejN/GpVS4e0JTmMeo
 xTL6VO9mx52x6h5WDAQAisMVeMkBoxQUWLANXiw1zSfVbsmB7mDknsRcvD3tcgMs
 7YLD7LQMiPAIjDlOP8XP/w==
 -----END ENCRYPTED PRIVATE KEY-----";
-                byte[] passwordBytes = Encoding.UTF8.GetBytes("test");
+                byte[] passwordBytes = "test"u8.ToArray();
                 dsa.ImportFromEncryptedPem(pem, passwordBytes);
                 DSAParameters dsaParameters = dsa.ExportParameters(true);
 
@@ -319,9 +319,8 @@ MGHbpaaShD6iJfoGMRX0frr0mMCtuOOZkkjBF9pSpkhaH0TDSq1PrVLxcM0/S4Vs
 dVYwfovccu8ktEAwk5XAOo0r+5CCw2lDDw/hbDeO87BToC5Cc5nu3F5LxAUj8Flc
 v8pi3w==
 -----END ENCRYPTED PRIVATE KEY-----";
-                byte[] passwordBytes = Encoding.UTF8.GetBytes("test");
                 ArgumentException ae = AssertExtensions.Throws<ArgumentException>("input", () =>
-                    dsa.ImportFromEncryptedPem(pem, passwordBytes));
+                    dsa.ImportFromEncryptedPem(pem, "test"u8));
                 Assert.Contains(AmbiguousExceptionMarker, ae.Message);
             }
         }
@@ -332,9 +331,8 @@ v8pi3w==
             using (DSA dsa = DSAFactory.Create())
             {
                 string pem = "";
-                byte[] passwordBytes = Encoding.UTF8.GetBytes("test");
                 ArgumentException ae = AssertExtensions.Throws<ArgumentException>("input", () =>
-                    dsa.ImportFromEncryptedPem(pem, passwordBytes));
+                    dsa.ImportFromEncryptedPem(pem, "test"u8));
                 Assert.Contains(NoPemExceptionMarker, ae.Message);
             }
         }
index 93871ba..7d6bfe3 100644 (file)
@@ -171,7 +171,7 @@ namespace System.Security.Cryptography.Dsa.Tests
                 "41e2345f1f56df2458f426d155b4ba2db6dcd8c8"
                 ).HexToByteArray();
 
-            data = Encoding.ASCII.GetBytes("abc");
+            data = "abc"u8.ToArray();
         }
     }
 }
index ca0f996..ac74a49 100644 (file)
@@ -83,7 +83,7 @@ PFzVQfJ396S+yx4IIC4=";
 
             ReadWriteBase64EncryptedPkcs8(
                 base64,
-                Encoding.UTF8.GetBytes("qwerty"),
+                "qwerty"u8.ToArray(),
                 new PbeParameters(
                     PbeEncryptionAlgorithm.Aes256Cbc,
                     HashAlgorithmName.SHA1,
index d867f15..492c9d4 100644 (file)
@@ -195,7 +195,7 @@ qtlbnispri1a/EghiaPQ0po=";
 
             ReadWriteBase64EncryptedPkcs8(
                 base64,
-                Encoding.UTF8.GetBytes("qwerty"),
+                "qwerty"u8.ToArray(),
                 new PbeParameters(
                     PbeEncryptionAlgorithm.Aes256Cbc,
                     HashAlgorithmName.SHA1,
index 3c367a4..52458f1 100644 (file)
@@ -342,8 +342,7 @@ iE/+pIb/4quf+Y524bXUKTGYXzdSUE8Dp1qdZFcwDiCYCTtpL+065fGhmf1KZS2c
 /OMt/tWvtMSj17+dJvShsu/NYJXF5fsfpSJbd3e50Y3AisW0Ob7mmF54KBfg6Y+4
 aATwwQdUIKVzUZsQctsHPjbriQKKn7GKSyUOikBUNQ+TozojX8/g7JAsl+T9jGM=
 -----END ENCRYPTED PRIVATE KEY-----";
-                byte[] passwordBytes = Encoding.UTF8.GetBytes("test");
-                key.ImportFromEncryptedPem(pem, passwordBytes);
+                key.ImportFromEncryptedPem(pem, "test"u8);
                 ECParameters ecParameters = key.ExportParameters(true);
                 ECParameters expected = EccTestData.GetNistP256ReferenceKey();
                 EccTestBase.AssertEqual(expected, ecParameters);
@@ -370,10 +369,9 @@ Evt9yfvEjiP/6yITq59drw1Kcgp6buOCVCY7LZ06aD6WpogiqGDYMuzfvqg5hNFp
 opSAJ/pvHONL5kyAJLeNyG9c/mR2qyrP2L9gL0Z5fB9NyPejKTLi0PXMGQWdDTH8
 Qh0fqdrNovgFLubbJFMQN/MwwIAfIuf0Mn0WFYYeQiBJ3kg=
 -----END ENCRYPTED PRIVATE KEY-----";
-                byte[] passwordBytes = Encoding.UTF8.GetBytes("test");
 
                 ArgumentException ae = AssertExtensions.Throws<ArgumentException>("input", () =>
-                    key.ImportFromEncryptedPem(pem, passwordBytes));
+                    key.ImportFromEncryptedPem(pem, "test"u8));
 
                 Assert.Contains(AmbiguousExceptionMarker, ae.Message);
             }
index 187c76a..d2b0c1a 100644 (file)
@@ -274,8 +274,6 @@ namespace System.Security.Cryptography.EcDsa.Tests
         [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];
 
index a9c021a..daa175d 100644 (file)
@@ -781,7 +781,7 @@ RdMKfFP3he4C+CFyGGslffbxCaJhKebeuOil5xxlvP8aBPVNDtQfSS1HXHd1/Ikq
 
             ReadBase64EncryptedPkcs8(
                 base64,
-                Encoding.UTF8.GetBytes("rc2"),
+                "rc2"u8.ToArray(),
                 new PbeParameters(
                     PbeEncryptionAlgorithm.Aes192Cbc,
                     HashAlgorithmName.SHA256,
index 013ec21..27438e9 100644 (file)
@@ -425,7 +425,7 @@ E+nr7hyinl51raM1RSHojJB22oOW+GwV7GgWYIjUgIEMDOhN10FcGNfTeC65PCXx
 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,9 +462,8 @@ AWvBUt33Sozc+dF0l7NGLAWL2tqkkpyDQuKn6UgYz/vxkFeQAVfSuaJVR+fUlHg0
 N4lD7/hJq7b+yYPhlN3Fvvt8M9MtRg1TLAve67CA2v4TITHB06M/ELe3y42bZuLW
 CA7ffFk=
 -----END ENCRYPTED PRIVATE KEY-----";
-                byte[] passwordBytes = Encoding.UTF8.GetBytes("test");
                 ArgumentException ae = AssertExtensions.Throws<ArgumentException>("input", () =>
-                    rsa.ImportFromEncryptedPem(pem, passwordBytes));
+                    rsa.ImportFromEncryptedPem(pem, "test"u8));
                 Assert.Contains(AmbiguousExceptionMarker, ae.Message);
             }
         }
@@ -475,9 +474,8 @@ CA7ffFk=
             using (RSA rsa = RSAFactory.Create())
             {
                 string pem = "these aren't the PEMs we're looking for.";
-                byte[] passwordBytes = Encoding.UTF8.GetBytes("test");
                 ArgumentException ae = AssertExtensions.Throws<ArgumentException>("input", () =>
-                    rsa.ImportFromEncryptedPem(pem, passwordBytes));
+                    rsa.ImportFromEncryptedPem(pem, "test"u8));
                 Assert.Contains(NoPemExceptionMarker, ae.Message);
             }
         }
@@ -498,9 +496,8 @@ Ya8CHwiO/cUU9RIt8A2B84gf2ZfuV2nPMaSuZpTPFC/K5UsCIQCsJMzx1JuilQAN
 acPiMCuFTnRSFYAhozpmsqoLyTREqwIhAMLJlZTGjEB2N+sEazH5ToEczQzKqp7t
 9juGNbOPhoEL
 -----END PRIVATE KEY-----";
-                byte[] passwordBytes = Encoding.UTF8.GetBytes("test");
                 ArgumentException ae = AssertExtensions.Throws<ArgumentException>("input", () =>
-                    rsa.ImportFromEncryptedPem(pem, passwordBytes));
+                    rsa.ImportFromEncryptedPem(pem, "test"u8));
                 Assert.Contains(NoPemExceptionMarker, ae.Message);
             }
         }
index a162e9d..7d2558a 100644 (file)
@@ -7418,8 +7418,7 @@ namespace System.Tests
         [Fact]
         public static void CreateStringFromEncoding_0Length_EmptyStringReturned() // basic test for code coverage; more tests in encodings tests
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("hello");
-            Assert.Same(string.Empty, new AsciiEncodingWithZeroReturningGetCharCount().GetString(bytes, 0, 0));
+            Assert.Same(string.Empty, new AsciiEncodingWithZeroReturningGetCharCount().GetString("hello"u8.ToArray(), 0, 0));
         }
 
         private sealed class AsciiEncodingWithZeroReturningGetCharCount : ASCIIEncoding
index 7d7fa66..a61596b 100644 (file)
@@ -99,7 +99,7 @@ namespace System.Diagnostics.Tests
         public static int WriteSlowlyByByte()
         {
             var stdout = Console.OpenStandardOutput();
-            var bytes = new byte[] { 97, 0 }; //Encoding.Unicode.GetBytes("a");
+            var bytes = new byte[] { 97, 0 }; // Encoding.Unicode.GetBytes("a");
 
             for (int i = 0; i != bytes.Length; ++i)
             {
index 39f7c9b..229b611 100644 (file)
@@ -479,18 +479,18 @@ namespace System.DirectoryServices.Protocols.Tests
         public static IEnumerable<object[]> 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.ToArray(), 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.ToArray(), 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.ToArray(), ResultCode.CompareFalse };
         }
 
         [ConditionalTheory(nameof(IsLdapConfigurationExist))]
index cfd315a..e1b8512 100644 (file)
@@ -238,7 +238,7 @@ namespace System.Drawing.Tests
 
             // Change data.
             PropertyItem item = source.GetPropertyItem(PropertyTagExifUserComment);
-            item.Value = Encoding.ASCII.GetBytes("Hello World\0");
+            item.Value = "Hello World\0"u8.ToArray();
             item.Len = item.Value.Length;
 
             bitmap.SetPropertyItem(item);
@@ -253,7 +253,7 @@ namespace System.Drawing.Tests
 
             // New data.
             item.Id = propid;
-            item.Value = Encoding.ASCII.GetBytes("New Value\0");
+            item.Value = "New Value\0"u8.ToArray();
             item.Len = item.Value.Length;
 
             bitmap.SetPropertyItem(item);
@@ -296,7 +296,7 @@ namespace System.Drawing.Tests
 
             // Change data.
             PropertyItem item = bitmap.GetPropertyItem(PropertyTagExifUserComment);
-            item.Value = Encoding.ASCII.GetBytes("Hello World\0");
+            item.Value = "Hello World\0"u8.ToArray();
             item.Len = item.Value.Length;
 
             bitmap.SetPropertyItem(item);
@@ -339,7 +339,7 @@ namespace System.Drawing.Tests
 
             // New data.
             item.Id = propid;
-            item.Value = Encoding.ASCII.GetBytes("New Value\0");
+            item.Value = "New Value\0"u8.ToArray();
             item.Len = item.Value.Length;
 
             bitmap.SetPropertyItem(item);
@@ -439,7 +439,7 @@ namespace System.Drawing.Tests
 
             // Change data.
             PropertyItem item = source.GetPropertyItem(PropertyTagExifUserComment);
-            item.Value = Encoding.ASCII.GetBytes("Hello World\0");
+            item.Value = "Hello World\0"u8.ToArray();
             item.Len = item.Value.Length;
 
             bitmap.SetPropertyItem(item);
@@ -454,7 +454,7 @@ namespace System.Drawing.Tests
 
             // New data.
             item.Id = propid;
-            item.Value = Encoding.ASCII.GetBytes("New Value\0");
+            item.Value = "New Value\0"u8.ToArray();
             item.Len = item.Value.Length;
 
             bitmap.SetPropertyItem(item);
index 6583a7d..cdd3437 100644 (file)
@@ -229,7 +229,7 @@ namespace System.Formats.Asn1.Tests.Reader
         [Fact]
         public static void ExcessivelyPreciseFraction()
         {
-            byte[] inputData = Text.Encoding.ASCII.GetBytes("\u0018\u002A2017092118.012345678901234567890123456789Z");
+            byte[] inputData = "\u0018\u002A2017092118.012345678901234567890123456789Z"u8.ToArray();
 
             AsnReader berReader = new AsnReader(inputData, AsnEncodingRules.BER);
             DateTimeOffset value = berReader.ReadGeneralizedTime();
@@ -244,7 +244,7 @@ namespace System.Formats.Asn1.Tests.Reader
         [Fact]
         public static void ExcessivelyPreciseFraction_OneTenthPlusEpsilon()
         {
-            byte[] inputData = Text.Encoding.ASCII.GetBytes("\u0018\u002A20170921180044.10000000000000000000000001Z");
+            byte[] inputData = "\u0018\u002A20170921180044.10000000000000000000000001Z"u8.ToArray();
 
             AsnReader derReader = new AsnReader(inputData, AsnEncodingRules.DER);
             DateTimeOffset value = derReader.ReadGeneralizedTime();
@@ -287,7 +287,7 @@ namespace System.Formats.Asn1.Tests.Reader
         [Fact]
         public static void ExcessivelyPreciseFraction_OneTenthPlusEpsilonAndZero()
         {
-            byte[] inputData = Text.Encoding.ASCII.GetBytes("\u0018\u002A20170921180044.10000000000000000000000010Z");
+            byte[] inputData = "\u0018\u002A20170921180044.10000000000000000000000010Z"u8.ToArray();
 
             AsnReader berReader = new AsnReader(inputData, AsnEncodingRules.BER);
             DateTimeOffset value = berReader.ReadGeneralizedTime();
@@ -305,7 +305,7 @@ namespace System.Formats.Asn1.Tests.Reader
         [Fact]
         public static void ExcessivelyPreciseNonFraction()
         {
-            byte[] inputData = Text.Encoding.ASCII.GetBytes("\u0018\u002A2017092118.012345678901234567890123Q56789Z");
+            byte[] inputData = "\u0018\u002A2017092118.012345678901234567890123Q56789Z"u8.ToArray();
             AsnReader berReader = new AsnReader(inputData, AsnEncodingRules.BER);
 
             Assert.Throws<AsnContentException>(() => berReader.ReadGeneralizedTime());
index c82566a..0995447 100644 (file)
@@ -12,11 +12,11 @@ namespace System.Formats.Tar
     // Writes header attributes of a tar archive entry.
     internal partial struct TarHeader
     {
-        private static ReadOnlySpan<byte> PaxMagicBytes => new byte[] { 0x75, 0x73, 0x74, 0x61, 0x72, 0x0 }; // "ustar\0"
-        private static ReadOnlySpan<byte> PaxVersionBytes => new byte[] { TarHelpers.ZeroChar, TarHelpers.ZeroChar }; // "00"
+        private static ReadOnlySpan<byte> PaxMagicBytes => "ustar\0"u8;
+        private static ReadOnlySpan<byte> PaxVersionBytes => "00"u8;
 
-        private static ReadOnlySpan<byte> GnuMagicBytes => new byte[] { 0x75, 0x73, 0x74, 0x61, 0x72, TarHelpers.SpaceChar }; // "ustar "
-        private static ReadOnlySpan<byte> GnuVersionBytes => new byte[] { TarHelpers.SpaceChar, 0x0 }; // " \0"
+        private static ReadOnlySpan<byte> GnuMagicBytes => "ustar "u8;
+        private static ReadOnlySpan<byte> GnuVersionBytes => " \0"u8;
 
         // Extended Attribute entries have a special format in the Name field:
         // "{dirName}/PaxHeaders.{processId}/{fileName}{trailingSeparator}"
index e13fec3..91b6b4b 100644 (file)
@@ -61,7 +61,6 @@ namespace System.IO.Compression.Tests
         {
             // '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");
 
             string archivePath = GetTestFilePath();
             using (FileStream fileStream = new FileStream(archivePath, FileMode.CreateNew))
@@ -72,7 +71,7 @@ namespace System.IO.Compression.Tests
                     ZipArchiveEntry entry = archive.CreateEntry(permission + ".txt");
                     entry.ExternalAttributes = Convert.ToInt32(permission, 8) << 16;
                     using Stream stream = entry.Open();
-                    stream.Write(contents);
+                    stream.Write("contents"u8);
                     stream.Flush();
                 }
             }
index 637d045..93adafa 100644 (file)
@@ -169,14 +169,14 @@ namespace System.IO.Compression.Tests
                 {
                     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.ToArray();
                     if (writeWithSpans)
                     {
-                        s.Write(data, 0, data.Length);
+                        s.Write(new ReadOnlySpan<byte>(data));
                     }
                     else
                     {
-                        s.Write(new ReadOnlySpan<byte>(data));
+                        s.Write(data, 0, data.Length);
                     }
                 }
 
index 69c2c72..bcb3de4 100644 (file)
@@ -97,11 +97,11 @@ namespace System.IO.Tests
                 // 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.ToArray());
+                    Assert.Equal("text"u8.ToArray(), File.ReadAllBytes(path));
                 }
                 else
-                    Assert.Throws<UnauthorizedAccessException>(() => File.WriteAllBytes(path, Encoding.UTF8.GetBytes("text")));
+                    Assert.Throws<UnauthorizedAccessException>(() => File.WriteAllBytes(path, "text"u8.ToArray()));
             }
             finally
             {
index 3ab0df3..2c6df24 100644 (file)
@@ -108,11 +108,11 @@ namespace System.IO.Tests
                 // 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.ToArray());
+                    Assert.Equal("text"u8.ToArray(), await File.ReadAllBytesAsync(path));
                 }
                 else
-                    await Assert.ThrowsAsync<UnauthorizedAccessException>(async () => await File.WriteAllBytesAsync(path, Encoding.UTF8.GetBytes("text")));
+                    await Assert.ThrowsAsync<UnauthorizedAccessException>(async () => await File.WriteAllBytesAsync(path, "text"u8.ToArray()));
             }
             finally
             {
index 04d04aa..86a4901 100644 (file)
@@ -21,7 +21,7 @@ namespace System.IO.Tests
         {
             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 @@ namespace System.IO.Tests
         {
             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.ToArray());
         }
 
         [Theory]
         [MemberData(nameof(DevicePath_TestData))]
         public void CharacterDevice_WriteAllBytes(string devicePath)
         {
-            File.WriteAllBytes(devicePath, Encoding.UTF8.GetBytes("foo"));
+            File.WriteAllBytes(devicePath, "foo"u8.ToArray());
         }
 
         [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.ToArray());
         }
 
         [Theory]
index cd3b18d..44cafb5 100644 (file)
@@ -218,12 +218,12 @@ namespace System.IO.Tests
                 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 @@ namespace System.IO.Tests
                 Assert.Throws<IOException>(() => fs.Seek(0, SeekOrigin.Begin));
                 Assert.Throws<NotSupportedException>(() => 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));
index 6d2993f..0761450 100644 (file)
@@ -51,7 +51,7 @@ namespace System.IO.Hashing.Tests
                     "FFFFFFFF"),
                 new TestCase(
                     "Self-test 123456789",
-                    Encoding.ASCII.GetBytes("123456789"),
+                    "123456789"u8.ToArray(),
                     "2639F4CB"),
                 new TestCase(
                     "Self-test residue",
@@ -63,7 +63,7 @@ namespace System.IO.Hashing.Tests
                     "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.ToArray(),
                     "39A34F41"),
             };
 
index d647e4b..52971f0 100644 (file)
@@ -59,7 +59,7 @@ namespace System.IO.Hashing.Tests
                     "0000000000000000"),
                 new TestCase(
                     "Self-test 123456789",
-                    Encoding.ASCII.GetBytes("123456789"),
+                    "123456789"u8.ToArray(),
                     "6C40DF5F0B497347"),
                 new TestCase(
                     "Self-test residue",
@@ -67,7 +67,7 @@ namespace System.IO.Hashing.Tests
                     "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.ToArray(),
                     "41E05242FFA9883B"),
             };
 
index 9ec9262..db17893 100644 (file)
@@ -45,19 +45,19 @@ namespace System.IO.Hashing.Tests
                 // 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.ToArray(),
                     "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.ToArray(),
                     "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.ToArray(),
                     "E7D2C0A7"),
                 new TestCase(
                     "abc",
-                    Encoding.ASCII.GetBytes("abc"),
+                    "abc"u8.ToArray(),
                     "D46070BB"),
                 new TestCase(
                     "123456",
index abd77d8..9c6bad4 100644 (file)
@@ -43,17 +43,17 @@ namespace System.IO.Hashing.Tests
                 //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.ToArray(),
                     "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.ToArray(),
                     "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.ToArray(),
                     "68D039C8"),
 
                 // Manual exploration to force boundary conditions in code coverage.
@@ -62,7 +62,7 @@ namespace System.IO.Hashing.Tests
                 // The "in three pieces" test causes this to build up in the accumulator every time.
                 new TestCase(
                     "abc",
-                    Encoding.ASCII.GetBytes("abc"),
+                    "abc"u8.ToArray(),
                     "32D153FF"),
                 // Accumulates every time.
                 new TestCase(
index 4a116bc..edf94fb 100644 (file)
@@ -45,19 +45,19 @@ namespace System.IO.Hashing.Tests
                 // 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.ToArray(),
                     "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.ToArray(),
                     "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.ToArray(),
                     "11AC3BD7"),
                 new TestCase(
                     "abc",
-                    Encoding.ASCII.GetBytes("abc"),
+                    "abc"u8.ToArray(),
                     "BC85BB95"),
                 new TestCase(
                     "123456",
index 836b292..6c902b8 100644 (file)
@@ -47,19 +47,19 @@ namespace System.IO.Hashing.Tests
                 // 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.ToArray(),
                     "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.ToArray(),
                     "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.ToArray(),
                     "618682461CB28F83"),
                 new TestCase(
                     "abc",
-                    Encoding.ASCII.GetBytes("abc"),
+                    "abc"u8.ToArray(),
                     "6BF4B26E3CA10C20"),
                 new TestCase(
                     "123456",
index 213e6f9..10485ba 100644 (file)
@@ -45,17 +45,17 @@ namespace System.IO.Hashing.Tests
                 //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.ToArray(),
                     "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.ToArray(),
                     "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.ToArray(),
                     "44AD33705751AD73"),
 
                 // Manual exploration to force boundary conditions in code coverage.
@@ -64,7 +64,7 @@ namespace System.IO.Hashing.Tests
                 // The "in three pieces" test causes this to build up in the accumulator every time.
                 new TestCase(
                     "abc",
-                    Encoding.ASCII.GetBytes("abc"),
+                    "abc"u8.ToArray(),
                     "44BC2CF5AD770999"),
                 // Accumulates every time.
                 new TestCase(
index 75fc4f5..283f192 100644 (file)
@@ -47,19 +47,19 @@ namespace System.IO.Hashing.Tests
                 // 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.ToArray(),
                     "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.ToArray(),
                     "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.ToArray(),
                     "10E8D9E4DA841407"),
                 new TestCase(
                     "abc",
-                    Encoding.ASCII.GetBytes("abc"),
+                    "abc"u8.ToArray(),
                     "AE9DA0E407940A85"),
                 new TestCase(
                     "123456",
index adf547a..f6e87e2 100644 (file)
@@ -43,9 +43,9 @@ namespace System.IO.Pipelines.Tests
         {
             var messages = new List<byte[]>()
             {
-                Encoding.UTF8.GetBytes("Hello World1"),
-                Encoding.UTF8.GetBytes("Hello World2"),
-                Encoding.UTF8.GetBytes("Hello World3"),
+                "Hello World1"u8.ToArray(),
+                "Hello World2"u8.ToArray(),
+                "Hello World3"u8.ToArray(),
             };
 
             var stream = new WriteCheckMemoryStream();
@@ -67,9 +67,9 @@ namespace System.IO.Pipelines.Tests
         {
             var messages = new List<byte[]>()
             {
-                Encoding.UTF8.GetBytes("Hello World1"),
-                Encoding.UTF8.GetBytes("Hello World2"),
-                Encoding.UTF8.GetBytes("Hello World3"),
+                "Hello World1"u8.ToArray(),
+                "Hello World2"u8.ToArray(),
+                "Hello World3"u8.ToArray(),
             };
 
             var targetPipe = new Pipe(s_testOptions);
@@ -199,7 +199,7 @@ namespace System.IO.Pipelines.Tests
             // 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.ToArray());
             Task task = PipeReader.CopyToAsync(targetPipe.Writer, cts.Token);
 
             cts.Cancel();
@@ -212,7 +212,7 @@ namespace System.IO.Pipelines.Tests
         {
             // 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.ToArray());
             Task task = PipeReader.CopyToAsync(targetPipe.Writer);
 
             targetPipe.Writer.CancelPendingFlush();
@@ -290,7 +290,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task CopyToAsyncStreamCopiesRemainderAfterReadingSome()
         {
-            var buffer = Encoding.UTF8.GetBytes("Hello World");
+            byte[] buffer = "Hello World"u8.ToArray();
             await Pipe.Writer.WriteAsync(buffer);
             Pipe.Writer.Complete();
 
@@ -308,7 +308,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task CopyToAsyncPipeWriterCopiesRemainderAfterReadingSome()
         {
-            var buffer = Encoding.UTF8.GetBytes("Hello World");
+            byte[] buffer = "Hello World"u8.ToArray();
             await Pipe.Writer.WriteAsync(buffer);
             Pipe.Writer.Complete();
 
index 64762de..9a76f91 100644 (file)
@@ -31,7 +31,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task CanWriteAndReadAtLeast()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
 
             await Pipe.Writer.WriteAsync(bytes);
             ReadResult result = await PipeReader.ReadAtLeastAsync(11);
@@ -46,7 +46,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task ReadAtLeastShouldNotCompleteIfWriterWroteLessThanMinimum()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
 
             await Pipe.Writer.WriteAsync(bytes.AsMemory(0, 5));
             ValueTask<ReadResult> task = PipeReader.ReadAtLeastAsync(11);
@@ -68,7 +68,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task CanAlternateReadAtLeastAndRead()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
 
             await Pipe.Writer.WriteAsync(bytes.AsMemory(0, 5));
             ReadResult result = await PipeReader.ReadAtLeastAsync(3);
@@ -113,7 +113,7 @@ namespace System.IO.Pipelines.Tests
         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.ToArray());
 
             if (bufferedRead)
             {
@@ -148,7 +148,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task WriteAndCancellingPendingReadBeforeReadAtLeastAsync()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             PipeWriter output = Pipe.Writer;
             output.Write(bytes);
             await output.FlushAsync();
index 0e83981..803c101 100644 (file)
@@ -55,7 +55,7 @@ namespace System.IO.Pipelines.Tests
         [MemberData(nameof(ReadCalls))]
         public async Task ReadingFromPipeReaderStreamReadsFromUnderlyingPipeReader(ReadAsyncDelegate readAsync)
         {
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
             var pipe = new Pipe();
             await pipe.Writer.WriteAsync(helloBytes);
             pipe.Writer.Complete();
@@ -73,7 +73,7 @@ namespace System.IO.Pipelines.Tests
         [MemberData(nameof(ReadCalls))]
         public async Task AsStreamReturnsPipeReaderStream(ReadAsyncDelegate readAsync)
         {
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
             var pipe = new Pipe();
             await pipe.Writer.WriteAsync(helloBytes);
             pipe.Writer.Complete();
@@ -90,7 +90,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task ReadingWithSmallerBufferWorks()
         {
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
             var pipe = new Pipe();
             await pipe.Writer.WriteAsync(helloBytes);
             pipe.Writer.Complete();
index 1a325e4..c5cd74d 100644 (file)
@@ -34,7 +34,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task CanReadAndWrite()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
 
             await _pipe.Writer.WriteAsync(bytes);
             ReadResult result = await _pipe.Reader.ReadAsync();
@@ -170,7 +170,7 @@ namespace System.IO.Pipelines.Tests
             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.ToArray();
 
             writeBuffer.Write(paddingBytes);
             writeBuffer.Write(bytes);
@@ -338,7 +338,7 @@ namespace System.IO.Pipelines.Tests
             await buffer.FlushAsync();
 
             // Write Hello to another pipeline and get the buffer
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello");
+            byte[] bytes = "Hello"u8.ToArray();
 
             var c2 = new Pipe(new PipeOptions(_pool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline));
             await c2.Writer.WriteAsync(bytes);
@@ -516,7 +516,7 @@ namespace System.IO.Pipelines.Tests
         public async Task SyncReadThenAsyncRead()
         {
             PipeWriter buffer = _pipe.Writer;
-            buffer.Write(Encoding.ASCII.GetBytes("Hello World"));
+            buffer.Write("Hello World"u8.ToArray());
             await buffer.FlushAsync();
 
             bool gotData = _pipe.Reader.TryRead(out ReadResult result);
@@ -601,7 +601,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task WritingDataMakesDataReadableViaPipeline()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
 
             await _pipe.Writer.WriteAsync(bytes);
             ReadResult result = await _pipe.Reader.ReadAsync();
index 4d9fb17..9977b6d 100644 (file)
@@ -40,7 +40,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task CopyToAsyncWorks()
         {
-            var helloBytes = Encoding.UTF8.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
 
             var pipe = new Pipe();
             var stream = new MemoryStream(helloBytes);
@@ -79,7 +79,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task StreamCopyToAsyncWorks()
         {
-            var helloBytes = Encoding.UTF8.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
 
             var pipe = new Pipe();
             var stream = new MemoryStream(helloBytes);
@@ -96,7 +96,7 @@ namespace System.IO.Pipelines.Tests
         [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
         public async Task CancelingViaCancelPendingFlushThrows()
         {
-            var helloBytes = Encoding.UTF8.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
 
             var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: helloBytes.Length - 1, resumeWriterThreshold: 0));
             var stream = new MemoryStream(helloBytes);
@@ -115,7 +115,7 @@ namespace System.IO.Pipelines.Tests
         [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
         public async Task CancelingViaCancellationTokenThrows()
         {
-            var helloBytes = Encoding.UTF8.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
 
             var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: helloBytes.Length - 1, resumeWriterThreshold: 0));
             var stream = new MemoryStream(helloBytes);
index 57f6f8e..c7df565 100644 (file)
@@ -49,7 +49,7 @@ namespace System.IO.Pipelines.Tests
         [MemberData(nameof(WriteCalls))]
         public async Task WritingToPipeStreamWritesToUnderlyingPipeWriter(WriteAsyncDelegate writeAsync)
         {
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
             var pipe = new Pipe();
             var stream = new PipeWriterStream(pipe.Writer, leaveOpen: false);
 
@@ -65,7 +65,7 @@ namespace System.IO.Pipelines.Tests
         [MemberData(nameof(WriteCalls))]
         public async Task AsStreamReturnsPipeWriterStream(WriteAsyncDelegate writeAsync)
         {
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
             var pipe = new Pipe();
             Stream stream = pipe.Writer.AsStream();
 
@@ -80,7 +80,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task FlushAsyncFlushesBufferedData()
         {
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
             var pipe = new Pipe();
 
             Memory<byte> memory = pipe.Writer.GetMemory();
@@ -99,7 +99,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task ReadingFromPipeWriterStreamThrowsNotSupported()
         {
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
             var pipe = new Pipe();
 
             Stream stream = pipe.Writer.AsStream();
@@ -122,7 +122,7 @@ namespace System.IO.Pipelines.Tests
         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.ToArray();
 
             Stream stream = pipe.Writer.AsStream();
             ValueTask task = stream.WriteAsync(helloBytes);
@@ -139,7 +139,7 @@ namespace System.IO.Pipelines.Tests
         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.ToArray();
 
             Stream stream = pipe.Writer.AsStream();
             var cts = new CancellationTokenSource();
index d7edb40..5dbbeee 100644 (file)
@@ -185,7 +185,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task WritesUsingGetSpanWorks()
         {
-            var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
+            byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray();
             var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1));
             PipeWriter writer = pipe.Writer;
 
@@ -208,7 +208,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task WritesUsingGetMemoryWorks()
         {
-            var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
+            byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray();
             var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1));
             PipeWriter writer = pipe.Writer;
 
index 8422de3..fb17873 100644 (file)
@@ -32,7 +32,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task CancellingBeforeAdvance()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             PipeWriter output = Pipe.Writer;
             output.Write(bytes);
             await output.FlushAsync();
@@ -65,7 +65,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task CancellingPendingAfterReadAsync()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             PipeWriter output = Pipe.Writer;
             output.Write(bytes);
 
@@ -116,7 +116,7 @@ namespace System.IO.Pipelines.Tests
             Assert.True(result.IsCanceled);
             Assert.True(buffer.IsEmpty);
 
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             PipeWriter output = Pipe.Writer;
             output.Write(bytes);
             await output.FlushAsync();
@@ -407,7 +407,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task WriteAndCancellingPendingReadBeforeReadAsync()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             PipeWriter output = Pipe.Writer;
             output.Write(bytes);
             await output.FlushAsync();
index 000c908..ba55833 100644 (file)
@@ -68,7 +68,7 @@ namespace System.IO.Pipelines.Tests
                 Task reading = doRead();
 
                 PipeWriter buffer = pipe.Writer;
-                buffer.Write(Encoding.UTF8.GetBytes("Hello World"));
+                buffer.Write("Hello World"u8.ToArray());
 
                 // 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 @@ namespace System.IO.Pipelines.Tests
                 Task reading = doRead();
 
                 PipeWriter buffer = pipe.Writer;
-                buffer.Write(Encoding.UTF8.GetBytes("Hello World"));
+                buffer.Write("Hello World"u8.ToArray());
 
                 // 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 @@ namespace System.IO.Pipelines.Tests
                 Task reading = doRead();
 
                 PipeWriter buffer = pipe.Writer;
-                buffer.Write(Encoding.UTF8.GetBytes("Hello World"));
+                buffer.Write("Hello World"u8.ToArray());
 
                 // We don't want to run any code on our fake sync context
                 await buffer.FlushAsync().ConfigureAwait(false);
@@ -201,7 +201,7 @@ namespace System.IO.Pipelines.Tests
             Task reading = ExecuteOnNonThreadPoolThread(doRead);
 
             PipeWriter buffer = pipe.Writer;
-            buffer.Write(Encoding.UTF8.GetBytes("Hello World"));
+            buffer.Write("Hello World"u8.ToArray());
             await buffer.FlushAsync();
 
             pipe.Writer.Complete();
@@ -480,7 +480,7 @@ namespace System.IO.Pipelines.Tests
                     Task reading = ExecuteOnNonThreadPoolThread(doRead);
 
                     PipeWriter buffer = pipe.Writer;
-                    buffer.Write(Encoding.UTF8.GetBytes("Hello World"));
+                    buffer.Write("Hello World"u8.ToArray());
                     await buffer.FlushAsync();
 
                     await reading;
@@ -525,7 +525,7 @@ namespace System.IO.Pipelines.Tests
             null);
 #pragma warning restore CS0618 // Type or member is obsolete
 
-            buffer.Write(Encoding.UTF8.GetBytes("Hello World"));
+            buffer.Write("Hello World"u8.ToArray());
             await buffer.FlushAsync();
 
             await reading;
index d12e4f1..3c76c15 100644 (file)
@@ -16,7 +16,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task CanRead()
         {
-            var sequence = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("Hello World"));
+            var sequence = new ReadOnlySequence<byte>("Hello World"u8.ToArray());
             var reader = PipeReader.Create(sequence);
 
             ReadResult readResult = await reader.ReadAsync();
@@ -33,7 +33,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything()
         {
-            var sequence = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("Hello World"));
+            var sequence = new ReadOnlySequence<byte>("Hello World"u8.ToArray());
             var reader = PipeReader.Create(sequence);
 
             ReadResult readResult = await reader.ReadAsync();
@@ -53,7 +53,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task TryReadReturnsFalseIfBufferedBytesAndEverythingExamined()
         {
-            var sequence = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("Hello World"));
+            var sequence = new ReadOnlySequence<byte>("Hello World"u8.ToArray());
             var reader = PipeReader.Create(sequence);
 
             ReadResult readResult = await reader.ReadAsync();
@@ -86,7 +86,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task DataCanBeReadMultipleTimes()
         {
-            var helloBytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
             var sequence = new ReadOnlySequence<byte>(helloBytes);
             PipeReader reader = PipeReader.Create(sequence);
 
index b86151a..a59af1d 100644 (file)
@@ -17,7 +17,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task CanRead()
         {
-            var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World"));
+            var stream = new MemoryStream("Hello World"u8.ToArray());
             var reader = PipeReader.Create(stream);
 
             ReadResult readResult = await reader.ReadAsync();
@@ -34,7 +34,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything()
         {
-            var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World"));
+            var stream = new MemoryStream("Hello World"u8.ToArray());
             var reader = PipeReader.Create(stream);
 
             ReadResult readResult = await reader.ReadAsync();
@@ -54,7 +54,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task TryReadReturnsFalseIfBufferedBytesAndEverythingExamined()
         {
-            var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World"));
+            var stream = new MemoryStream("Hello World"u8.ToArray());
             var reader = PipeReader.Create(stream);
 
             ReadResult readResult = await reader.ReadAsync();
@@ -168,7 +168,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task BufferingDataPastEndOfStreamCanBeReadAgain()
         {
-            var helloBytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] helloBytes = "Hello World"u8.ToArray();
             var stream = new ThrowAfterZeroByteReadStream(helloBytes);
             PipeReader reader = PipeReader.Create(stream);
 
index 4bd9967..6b158f8 100644 (file)
@@ -16,7 +16,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public void NothingWrittenToStreamUnlessFlushed()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             var stream = new MemoryStream();
             PipeWriter writer = PipeWriter.Create(stream);
 
@@ -33,7 +33,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public void DataFlushedOnComplete()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             var stream = new MemoryStream();
             PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true));
 
@@ -52,7 +52,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task DataFlushedOnCompleteAsync()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             var stream = new MemoryStream();
             PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true));
 
@@ -71,7 +71,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public void DataNotFlushedOnCompleteWithException()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             var stream = new MemoryStream();
             PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true));
 
@@ -88,7 +88,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task DataNotFlushedOnCompleteAsyncWithException()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             var stream = new MemoryStream();
             PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true));
 
@@ -105,7 +105,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task CompleteAsyncDoesNotThrowObjectDisposedException()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             var stream = new MemoryStream();
             PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true));
 
@@ -124,7 +124,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task DataWrittenOnFlushAsync()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             var stream = new MemoryStream();
             PipeWriter writer = PipeWriter.Create(stream);
 
@@ -155,7 +155,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task WritesUsingGetSpanWorks()
         {
-            var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
+            byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray();
             var stream = new MemoryStream();
             var options = new StreamPipeWriterOptions(new HeapBufferPool(), minimumBufferSize: 1);
             PipeWriter writer = PipeWriter.Create(stream, options);
@@ -175,7 +175,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public async Task WritesUsingGetMemoryWorks()
         {
-            var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
+            byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray();
             var stream = new MemoryStream();
             var options = new StreamPipeWriterOptions(new HeapBufferPool(), minimumBufferSize: 1);
             PipeWriter writer = PipeWriter.Create(stream, options);
@@ -234,10 +234,10 @@ namespace System.IO.Pipelines.Tests
 
             var data = new List<byte[]>
             {
-                Encoding.ASCII.GetBytes("Hello"),
-                Encoding.ASCII.GetBytes("World"),
-                Encoding.ASCII.GetBytes("This"),
-                Encoding.ASCII.GetBytes("Works"),
+                "Hello"u8.ToArray(),
+                "World"u8.ToArray(),
+                "This"u8.ToArray(),
+                "Works"u8.ToArray(),
             }.
             ToArray();
 
@@ -438,7 +438,7 @@ namespace System.IO.Pipelines.Tests
         {
             using (var pool = new DisposeTrackingBufferPool())
             {
-                byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+                byte[] bytes = "Hello World"u8.ToArray();
                 var stream = new MemoryStream();
                 var options = new StreamPipeWriterOptions(pool);
                 PipeWriter writer = PipeWriter.Create(stream, options);
@@ -484,7 +484,7 @@ namespace System.IO.Pipelines.Tests
         {
             using (var pool = new DisposeTrackingBufferPool())
             {
-                byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+                byte[] bytes = "Hello World"u8.ToArray();
                 var stream = new MemoryStream();
                 var options = new StreamPipeWriterOptions(pool);
                 PipeWriter writer = PipeWriter.Create(stream, options);
@@ -628,7 +628,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public void UnflushedBytesWorks()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+            byte[] bytes = "Hello World"u8.ToArray();
             var stream = new MemoryStream();
             PipeWriter writer = PipeWriter.Create(stream);
 
index 1c2c15e..d9a4e7c 100644 (file)
@@ -39,7 +39,7 @@ namespace System.IO.Pipelines.Tests
         [Fact]
         public void UnflushedBytesWorks()
         {
-            byte[] bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
+            byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray();
             Pipe.Writer.Write(bytes);
             Assert.True(Pipe.Writer.CanGetUnflushedBytes);
             Assert.Equal(bytes.Length,Pipe.Writer.UnflushedBytes);
index be62653..3ec8164 100644 (file)
@@ -20,7 +20,7 @@ namespace System.Tests
         [Fact]
         public void CanCreateBinaryDataFromBytes()
         {
-            byte[] payload = Encoding.UTF8.GetBytes("some data");
+            byte[] payload = "some data"u8.ToArray();
             BinaryData data = BinaryData.FromBytes(payload);
             Assert.Equal(payload, data.ToArray());
 
@@ -84,7 +84,7 @@ namespace System.Tests
         [Fact]
         public async Task CannotWriteToReadOnlyMemoryStream()
         {
-            byte[] buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             using MemoryStream payload = new MemoryStream(buffer);
             BinaryData data = BinaryData.FromStream(payload);
             Stream stream = data.ToStream();
@@ -99,7 +99,7 @@ namespace System.Tests
         [Fact]
         public async Task ToStreamIsMutatedWhenCustomerOwnsBuffer()
         {
-            byte[] buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             BinaryData data = BinaryData.FromBytes(buffer);
             Stream stream = data.ToStream();
             buffer[0] = (byte)'z';
@@ -110,7 +110,7 @@ namespace System.Tests
         [Fact]
         public async Task ToStreamIsNotMutatedWhenBinaryDataOwnsBuffer()
         {
-            byte[] buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             BinaryData data = BinaryData.FromStream(new MemoryStream(buffer));
             Stream stream = data.ToStream();
             buffer[0] = (byte)'z';
@@ -121,7 +121,7 @@ namespace System.Tests
         [Fact]
         public async Task CanCreateBinaryDataFromStream()
         {
-            byte[] buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             using MemoryStream stream = new MemoryStream(buffer, 0, buffer.Length, true, true);
             BinaryData data = BinaryData.FromStream(stream);
             Assert.Equal(buffer, data.ToArray());
@@ -147,7 +147,7 @@ namespace System.Tests
         [Fact]
         public async Task CanCreateBinaryDataFromLongStream()
         {
-            byte[] buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             using MemoryStream stream = new OverFlowStream(offset: int.MaxValue - 10000, buffer);
             BinaryData data = BinaryData.FromStream(stream);
             Assert.Equal(buffer, data.ToArray());
@@ -178,7 +178,7 @@ namespace System.Tests
             Assert.Empty(data.ToArray());
 
             // stream at end
-            byte[] buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             stream.Write(buffer, 0, buffer.Length);
             data = BinaryData.FromStream(stream);
             Assert.Empty(data.ToArray());
@@ -190,7 +190,7 @@ namespace System.Tests
         [Fact]
         public async Task CanCreateBinaryDataFromStreamUsingBackingBuffer()
         {
-            byte[] buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             using MemoryStream stream = new MemoryStream();
             stream.Write(buffer, 0, buffer.Length);
             stream.Position = 0;
@@ -214,7 +214,7 @@ namespace System.Tests
         [Fact]
         public async Task CanCreateBinaryDataFromNonSeekableStream()
         {
-            byte[] buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             using MemoryStream stream = new NonSeekableStream(buffer);
             BinaryData data = BinaryData.FromStream(stream);
             Assert.Equal(buffer, data.ToArray());
@@ -236,7 +236,7 @@ namespace System.Tests
         [Fact]
         public async Task CanCreateBinaryDataFromFileStream()
         {
-            byte[] buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             using FileStream stream = new FileStream(Path.GetTempFileName(), FileMode.Open);
             stream.Write(buffer, 0, buffer.Length);
             stream.Position = 0;
@@ -265,7 +265,7 @@ namespace System.Tests
         public async Task StartPositionOfStreamRespected(int bufferOffset, long streamStart)
         {
             var input = "some data";
-            ArraySegment<byte> buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("some data"), bufferOffset, input.Length - bufferOffset);
+            ArraySegment<byte> buffer = new ArraySegment<byte>("some data"u8.ToArray(), bufferOffset, input.Length - bufferOffset);
             MemoryStream stream = new MemoryStream(buffer.Array, buffer.Offset, buffer.Count);
             var payload = new ReadOnlyMemory<byte>(buffer.Array, buffer.Offset, buffer.Count).Slice((int)streamStart);
 
@@ -288,7 +288,7 @@ namespace System.Tests
         public async Task StartPositionOfStreamRespectedBackingBuffer(int bufferOffset, long streamStart)
         {
             var input = "some data";
-            ArraySegment<byte> buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("some data"), bufferOffset, input.Length - bufferOffset);
+            ArraySegment<byte> buffer = new ArraySegment<byte>("some data"u8.ToArray(), bufferOffset, input.Length - bufferOffset);
             MemoryStream stream = new MemoryStream();
             stream.Write(buffer.Array, buffer.Offset, buffer.Count);
 
@@ -411,12 +411,12 @@ namespace System.Tests
         [Fact]
         public void EqualsRespectsReferenceEquality()
         {
-            byte[] payload = Encoding.UTF8.GetBytes("some data");
+            byte[] payload = "some data"u8.ToArray();
             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.ToArray());
             Assert.NotEqual(a, c);
 
             Assert.False(a.Equals("string data"));
@@ -425,7 +425,7 @@ namespace System.Tests
         [Fact]
         public void GetHashCodeWorks()
         {
-            byte[] payload = Encoding.UTF8.GetBytes("some data");
+            byte[] payload = "some data"u8.ToArray();
             BinaryData a = BinaryData.FromBytes(payload);
             BinaryData b = BinaryData.FromBytes(payload);
             HashSet<BinaryData> set = new HashSet<BinaryData>
@@ -435,7 +435,7 @@ namespace System.Tests
             // 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.ToArray());
             // c should have a different hash code
             Assert.DoesNotContain(c, set);
             set.Add(c);
@@ -445,7 +445,7 @@ namespace System.Tests
         [Fact]
         public async Task CanRead()
         {
-            var buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             var stream = new BinaryData(buffer).ToStream();
 
             var read = new byte[buffer.Length];
@@ -465,7 +465,7 @@ namespace System.Tests
         [Fact]
         public async Task CanReadPartial()
         {
-            var buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             var stream = new BinaryData(buffer).ToStream();
             var length = 4;
             var read = new byte[length];
@@ -486,7 +486,7 @@ namespace System.Tests
         [Fact]
         public void ReadAsyncRespectsCancellation()
         {
-            var buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             var stream = new BinaryData(buffer).ToStream();
 
             var read = new byte[buffer.Length];
@@ -505,7 +505,7 @@ namespace System.Tests
         [Fact]
         public async Task CanSeek()
         {
-            var buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             var stream = new BinaryData(buffer).ToStream();
 
             stream.Seek(5, SeekOrigin.Begin);
@@ -526,7 +526,7 @@ namespace System.Tests
         [Fact]
         public void ValidatesSeekArguments()
         {
-            var buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             var stream = new BinaryData(buffer).ToStream();
 
             Assert.Throws<IOException>(() => stream.Seek(-1, SeekOrigin.Begin));
@@ -539,7 +539,7 @@ namespace System.Tests
         [Fact]
         public async Task ValidatesReadArguments()
         {
-            var buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             var stream = new BinaryData(buffer).ToStream();
             stream.Seek(3, SeekOrigin.Begin);
             var read = new byte[buffer.Length - stream.Position];
@@ -556,7 +556,7 @@ namespace System.Tests
         [Fact]
         public void ValidatesPositionValue()
         {
-            var buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             var stream = new BinaryData(buffer).ToStream();
             Assert.Throws<ArgumentOutOfRangeException>(() => stream.Position = -1);
             Assert.Throws<ArgumentOutOfRangeException>(() => stream.Position = (long)int.MaxValue + 1);
@@ -565,7 +565,7 @@ namespace System.Tests
         [Fact]
         public void CloseStreamValidation()
         {
-            byte[] buffer = Encoding.UTF8.GetBytes("some data");
+            byte[] buffer = "some data"u8.ToArray();
             Stream stream = new BinaryData(buffer).ToStream();
             stream.Dispose();
             Assert.Throws<ObjectDisposedException>(() => stream.Position = -1);
index 92e88fe..1b447f8 100644 (file)
@@ -337,7 +337,7 @@ namespace System.Buffers.Text.Tests
 
             for (int j = 0; j < 8; j++)
             {
-                Span<byte> source = new byte[8] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
+                Span<byte> source = "2222PPPP"u8.ToArray(); // valid input
                 Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
 
                 for (int i = 0; i < invalidBytes.Length; i++)
@@ -368,7 +368,7 @@ namespace System.Buffers.Text.Tests
             // Input that is not a multiple of 4 is considered invalid, if isFinalBlock = true
             if (isFinalBlock)
             {
-                Span<byte> source = new byte[7] { 50, 50, 50, 50, 80, 80, 80 }; // incomplete input - "2222PPP"
+                Span<byte> source = "2222PPP"u8.ToArray(); // incomplete input
                 Span<byte> 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 @@ namespace System.Buffers.Text.Tests
             // Only last 2 bytes can be padding, all other occurrence of padding is invalid
             for (int j = 0; j < 7; j++)
             {
-                Span<byte> source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
+                Span<byte> source = "2222PPPP"u8.ToArray(); // valid input
                 Span<byte> 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));
@@ -535,7 +535,7 @@ namespace System.Buffers.Text.Tests
             {
                 for (int i = 0; i < invalidBytes.Length; i++)
                 {
-                    Span<byte> buffer = new byte[8] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
+                    Span<byte> buffer = "2222PPPP"u8.ToArray(); // valid input
 
                     // Don't test padding (byte 61 i.e. '='), which is tested in DecodeInPlaceInvalidBytesPadding
                     if (invalidBytes[i] == Base64TestHelper.EncodingPad)
@@ -562,7 +562,7 @@ namespace System.Buffers.Text.Tests
 
             // Input that is not a multiple of 4 is considered invalid
             {
-                Span<byte> buffer = new byte[7] { 50, 50, 50, 50, 80, 80, 80 }; // incomplete input - "2222PPP"
+                Span<byte> buffer = "2222PPP"u8.ToArray(); // incomplete input
                 Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten));
                 Assert.Equal(0, bytesWritten);
             }
@@ -574,7 +574,7 @@ namespace System.Buffers.Text.Tests
             // Only last 2 bytes can be padding, all other occurrence of padding is invalid
             for (int j = 0; j < 7; j++)
             {
-                Span<byte> buffer = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
+                Span<byte> buffer = "2222PPPP"u8.ToArray(); // valid input
                 buffer[j] = Base64TestHelper.EncodingPad;
                 string sourceString = Encoding.ASCII.GetString(buffer.Slice(0, 4).ToArray());
 
index fc55fbe..d3f180d 100644 (file)
@@ -13,8 +13,8 @@ namespace System.Buffers.Tests
         public void WritingToSingleSegmentBuffer()
         {
             IBufferWriter<byte> 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 @@ namespace System.Buffers.Tests
         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());
         }
index 268b59b..b3c8b9e 100644 (file)
@@ -74,7 +74,7 @@ namespace System.Text.Tests
 
             // First, a small input with no flushing and no leftover data.
 
-            ReadOnlySpan<byte> inputData = Encoding.UTF8.GetBytes("Hello");
+            ReadOnlySpan<byte> 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 @@ namespace System.Text.Tests
 
             // 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.ToArray(), writer.WrittenSpan.ToArray());
         }
 
         [Fact]
@@ -252,7 +252,7 @@ namespace System.Text.Tests
             // First try the single-segment code path.
 
             ReadOnlySequence<char> sequence = new ReadOnlySequence<char>("Hello!".ToCharArray());
-            Assert.Equal(Encoding.UTF8.GetBytes("Hello!"), EncodingExtensions.GetBytes(Encoding.UTF8, sequence));
+            Assert.Equal("Hello!"u8.ToArray(), 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 @@ namespace System.Text.Tests
                 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.ToArray(), EncodingExtensions.GetBytes(Encoding.UTF8, sequence));
         }
 
         [Fact]
@@ -278,7 +278,7 @@ namespace System.Text.Tests
             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.ToArray(), writer.WrittenSpan.ToArray());
         }
 
         [Fact]
@@ -320,7 +320,7 @@ namespace System.Text.Tests
 
             ReadOnlySequence<char> sequence = new ReadOnlySequence<char>("Hello!".ToCharArray());
             Assert.Equal(
-                expected: Encoding.UTF8.GetBytes("Hello!"),
+                expected: "Hello!"u8.ToArray(),
                 actual: destination.Slice(0, EncodingExtensions.GetBytes(Encoding.UTF8, sequence, destination)).ToArray());
 
             // Next try the multi-segment code path.
@@ -336,7 +336,7 @@ namespace System.Text.Tests
                 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.ToArray(),
                 actual: destination.Slice(0, EncodingExtensions.GetBytes(Encoding.UTF8, sequence, destination)).ToArray());
         }
 
@@ -359,7 +359,7 @@ namespace System.Text.Tests
             ReadOnlySpan<char> 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.ToArray(), 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 @@ namespace System.Text.Tests
         {
             // First try the single-segment code path.
 
-            ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("Hello!"));
+            ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>("Hello!"u8.ToArray());
             Assert.Equal("Hello!", EncodingExtensions.GetString(Encoding.UTF8, sequence));
 
             // Next try the multi-segment code path.
@@ -427,7 +427,7 @@ namespace System.Text.Tests
         [Fact]
         public static void GetChars_Encoding_ReadOnlySequence_IBufferWriter_SingleSegment()
         {
-            ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("Hello"));
+            ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>("Hello"u8.ToArray());
             ArrayBufferWriter<char> writer = new ArrayBufferWriter<char>();
 
             long charsWritten = EncodingExtensions.GetChars(Encoding.UTF8, sequence, writer);
@@ -466,7 +466,7 @@ namespace System.Text.Tests
 
             // First try the single-segment code path.
 
-            ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("Hello!"));
+            ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>("Hello!"u8.ToArray());
             Assert.Equal("Hello!", destination.Slice(0, EncodingExtensions.GetChars(Encoding.UTF8, sequence, destination)).ToString());
 
             // Next try the multi-segment code path.
@@ -507,7 +507,7 @@ namespace System.Text.Tests
 
             // First, a small input that goes through the one-shot code path.
 
-            ReadOnlySpan<byte> inputData = Encoding.UTF8.GetBytes("Hello");
+            ReadOnlySpan<byte> inputData = "Hello"u8;
             long charsWritten = EncodingExtensions.GetChars(Encoding.UTF8, inputData, writer);
             Assert.Equal(5, charsWritten);
             Assert.Equal("Hello", writer.WrittenSpan.ToString());
index 60e3a6b..0681d04 100644 (file)
@@ -44,7 +44,7 @@ namespace System.Memory.Tests
             // [padding..hello]  ->  [  world   ]
             const int blockSize = 4096;
 
-            byte[] items = Encoding.ASCII.GetBytes("Hello World");
+            byte[] items = "Hello World"u8.ToArray();
             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();
 
index b042eb9..ab7399d 100644 (file)
@@ -259,8 +259,8 @@ namespace System.Memory.Tests.SequenceReader
         public void TryReadTo_Span_At_Segments_Boundary()
         {
             Span<byte> delimiter = new byte[] { 13, 10 }; // \r\n
-            BufferSegment<byte> segment = new BufferSegment<byte>(Text.Encoding.ASCII.GetBytes("Hello\r"));
-            segment.Append(Text.Encoding.ASCII.GetBytes("\nWorld")); // add next segment
+            BufferSegment<byte> segment = new BufferSegment<byte>("Hello\r"u8.ToArray());
+            segment.Append("\nWorld"u8.ToArray()); // add next segment
             ReadOnlySequence<byte> inputSeq = new ReadOnlySequence<byte>(segment, 0, segment, 6); // span only the first segment!
             SequenceReader<byte> sr = new SequenceReader<byte>(inputSeq);
             bool r = sr.TryReadTo(out ReadOnlySpan<byte> _, delimiter);
index 526a5ff..a28b2d5 100644 (file)
@@ -12,7 +12,7 @@ namespace System.Memory.Tests.SequenceReader
         [Fact]
         public void TryReadTo_SkipDelimiter()
         {
-            byte[] expected = Encoding.UTF8.GetBytes("This is our ^|understanding^|");
+            byte[] expected = "This is our ^|understanding^|"u8.ToArray();
             ReadOnlySequence<byte> bytes = SequenceFactory.CreateUtf8("This is our ^|understanding^|| you see.");
             SequenceReader<byte> reader = new SequenceReader<byte>(bytes);
             Assert.True(reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'|', (byte)'^', advancePastDelimiter: true));
@@ -125,12 +125,12 @@ namespace System.Memory.Tests.SequenceReader
             bytes = SequenceFactory.CreateUtf8("abc^|de|");
             reader = new SequenceReader<byte>(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.ToArray(), 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.ToArray(), sequence.ToArray());
             Assert.True(reader.End);
             Assert.Equal(8, reader.Consumed);
 
@@ -138,12 +138,12 @@ namespace System.Memory.Tests.SequenceReader
             bytes = SequenceFactory.CreateUtf8("^|a|b");
             reader = new SequenceReader<byte>(bytes);
             Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true));
-            Assert.Equal(Encoding.UTF8.GetBytes("^|a"), span.ToArray());
+            Assert.Equal("^|a"u8.ToArray(), 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.ToArray(), sequence.ToArray());
             Assert.True(reader.IsNext((byte)'b'));
             Assert.Equal(4, reader.Consumed);
 
@@ -151,12 +151,12 @@ namespace System.Memory.Tests.SequenceReader
             bytes = SequenceFactory.CreateUtf8("^", "|a|b");
             reader = new SequenceReader<byte>(bytes);
             Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true));
-            Assert.Equal(Encoding.UTF8.GetBytes("^|a"), span.ToArray());
+            Assert.Equal("^|a"u8.ToArray(), 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.ToArray(), sequence.ToArray());
             Assert.True(reader.IsNext((byte)'b'));
             Assert.Equal(4, reader.Consumed);
         }
@@ -167,12 +167,12 @@ namespace System.Memory.Tests.SequenceReader
             ReadOnlySequence<byte> bytes = SequenceFactory.CreateUtf8("abc^^|def");
             SequenceReader<byte> reader = new SequenceReader<byte>(bytes);
             Assert.True(reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'|', (byte)'^', advancePastDelimiter: false));
-            Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray());
+            Assert.Equal("abc^^"u8.ToArray(), span.ToArray());
             Assert.True(reader.IsNext((byte)'|'));
             Assert.Equal(5, reader.Consumed);
             reader.Rewind(reader.Consumed);
             Assert.True(reader.TryReadTo(out ReadOnlySequence<byte> sequence, (byte)'|', (byte)'^', advancePastDelimiter: false));
-            Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), sequence.ToArray());
+            Assert.Equal("abc^^"u8.ToArray(), sequence.ToArray());
             Assert.True(reader.IsNext((byte)'|'));
             Assert.Equal(5, reader.Consumed);
 
@@ -180,12 +180,12 @@ namespace System.Memory.Tests.SequenceReader
             bytes = SequenceFactory.CreateUtf8("abc^^", "|def");
             reader = new SequenceReader<byte>(bytes);
             Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false));
-            Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray());
+            Assert.Equal("abc^^"u8.ToArray(), 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.ToArray(), sequence.ToArray());
             Assert.True(reader.IsNext((byte)'|'));
             Assert.Equal(5, reader.Consumed);
 
@@ -193,24 +193,24 @@ namespace System.Memory.Tests.SequenceReader
             bytes = SequenceFactory.CreateUtf8("abc^", "^", "|def");
             reader = new SequenceReader<byte>(bytes);
             Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false));
-            Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray());
+            Assert.Equal("abc^^"u8.ToArray(), 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.ToArray(), sequence.ToArray());
             Assert.True(reader.IsNext((byte)'|'));
             Assert.Equal(5, reader.Consumed);
 
             // Check advance past delimiter
             reader = new SequenceReader<byte>(bytes);
             Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true));
-            Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray());
+            Assert.Equal("abc^^"u8.ToArray(), 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.ToArray(), sequence.ToArray());
             Assert.True(reader.IsNext((byte)'d'));
             Assert.Equal(6, reader.Consumed);
 
@@ -218,12 +218,12 @@ namespace System.Memory.Tests.SequenceReader
             bytes = SequenceFactory.CreateUtf8("^^|abc");
             reader = new SequenceReader<byte>(bytes);
             Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false));
-            Assert.Equal(Encoding.UTF8.GetBytes("^^"), span.ToArray());
+            Assert.Equal("^^"u8.ToArray(), 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.ToArray(), sequence.ToArray());
             Assert.True(reader.IsNext((byte)'|'));
             Assert.Equal(2, reader.Consumed);
 
index 6d2fa2b..c50f09b 100644 (file)
@@ -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.ToArray();
+        private static readonly byte[] s_endChunk = "0\r\n\r\n"u8.ToArray();
 
         private volatile bool _disposed;
         private readonly WinHttpRequestState _state;
index 0277ca2..d18de54 100644 (file)
@@ -30,7 +30,7 @@ namespace System.Net.Http.WinHttpHandlerFunctional.Tests
 
         protected override Version UseVersion => new Version(2, 0);
 
-        protected static byte[] DataBytes = Encoding.ASCII.GetBytes("data");
+        protected static byte[] DataBytes = "data"u8.ToArray();
 
         protected static Frame MakeDataFrame(int streamId, byte[] data, bool endStream = false) =>
             new DataFrame(data, (endStream ? FrameFlags.EndStream : FrameFlags.None), 0, streamId);
index ac4d036..93d7e9a 100644 (file)
@@ -3,7 +3,6 @@
     <TargetFrameworks>$(NetCoreAppCurrent)-windows;net48</TargetFrameworks>
     <IncludeRemoteExecutor>true</IncludeRemoteExecutor>
     <DefineConstants>$(DefineConstants);WINHTTPHANDLER_TEST</DefineConstants>
-    <LangVersion>10.0</LangVersion>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="$(CommonTestPath)System\Net\Configuration.cs"
index 5ac753c..2d473b8 100644 (file)
@@ -28,7 +28,7 @@ namespace System.Net.Http.WinHttpHandlerFunctional.Tests
 
         protected override Version UseVersion => new Version(2, 0);
 
-        protected static byte[] DataBytes = Encoding.ASCII.GetBytes("data");
+        protected static byte[] DataBytes = "data"u8.ToArray();
 
         protected static readonly IList<HttpHeaderData> TrailingHeaders = new HttpHeaderData[] {
             new HttpHeaderData("MyCoolTrailerHeader", "amazingtrailer"),
index 90900a0..9b5e37c 100644 (file)
@@ -331,7 +331,7 @@ namespace System.Net.Http.WinHttpHandlerUnitTests
         public void Read_NoOffsetAndNotEndOfData_FillsBuffer()
         {
             Stream stream = MakeResponseStream();
-            byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
+            byte[] testData = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"u8.ToArray();
             TestServer.ResponseBody = testData;
 
             byte[] buffer = new byte[testData.Length];
@@ -348,7 +348,7 @@ namespace System.Net.Http.WinHttpHandlerUnitTests
         public void Read_UsingOffsetAndNotEndOfData_FillsBufferFromOffset()
         {
             Stream stream = MakeResponseStream();
-            byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
+            byte[] testData = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"u8.ToArray();
             TestServer.ResponseBody = testData;
 
             byte[] buffer = new byte[testData.Length];
index e522822..b0154dd 100644 (file)
@@ -477,7 +477,7 @@ namespace System.Net.Http
             private static readonly (HeaderDescriptor descriptor, byte[] value)[] s_hpackStaticHeaderTable = new (HeaderDescriptor, byte[])[LastHPackNormalHeaderId - FirstHPackNormalHeaderId + 1]
             {
                 (KnownHeaders.AcceptCharset.Descriptor, Array.Empty<byte>()),
-                (KnownHeaders.AcceptEncoding.Descriptor, Encoding.ASCII.GetBytes("gzip, deflate")),
+                (KnownHeaders.AcceptEncoding.Descriptor, "gzip, deflate"u8.ToArray()),
                 (KnownHeaders.AcceptLanguage.Descriptor, Array.Empty<byte>()),
                 (KnownHeaders.AcceptRanges.Descriptor, Array.Empty<byte>()),
                 (KnownHeaders.Accept.Descriptor, Array.Empty<byte>()),
index d3d2b39..7edd0b8 100644 (file)
@@ -41,13 +41,13 @@ namespace System.Net.Http
         /// </remarks>
         private const int MaxChunkBytesAllowed = 16 * 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_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_contentLength0NewlineAsciiBytes = "Content-Length: 0\r\n"u8.ToArray();
+        private static readonly byte[] s_spaceHttp10NewlineAsciiBytes = " HTTP/1.0\r\n"u8.ToArray();
+        private static readonly byte[] s_spaceHttp11NewlineAsciiBytes = " HTTP/1.1\r\n"u8.ToArray();
+        private static readonly byte[] s_httpSchemeAndDelimiter = "http://"u8.ToArray();
+        private static readonly byte[] s_http1DotBytes = "HTTP/1."u8.ToArray();
+        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;
index a437f14..b946c6d 100644 (file)
@@ -69,10 +69,10 @@ namespace System.Net.Http.Functional.Tests
             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.ToArray() };
 
             // 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.ToArray() };
         }
     }
 }
index da7fc5a..a067101 100644 (file)
@@ -2096,7 +2096,7 @@ namespace System.Net.Http.Functional.Tests
                 }
                 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.ToArray(), isFinal: true);
                 await connection.WaitForConnectionShutdownAsync();
             });
         }
@@ -2265,7 +2265,7 @@ namespace System.Net.Http.Functional.Tests
                 }
                 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.ToArray());
                 await connection.ShutdownIgnoringErrorsAsync(streamId);
             });
         }
@@ -2406,7 +2406,7 @@ namespace System.Net.Http.Functional.Tests
         [ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
         public async Task PostAsyncDuplex_ClientSendsEndStream_Success()
         {
-            byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+            byte[] contentBytes = "Hello world"u8.ToArray();
 
             using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
             {
@@ -2467,7 +2467,7 @@ namespace System.Net.Http.Functional.Tests
         [ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
         public async Task PostAsyncDuplex_ServerSendsEndStream_Success()
         {
-            byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+            byte[] contentBytes = "Hello world"u8.ToArray();
 
             using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
             {
@@ -2528,7 +2528,7 @@ namespace System.Net.Http.Functional.Tests
         [ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
         public async Task PostAsyncDuplex_RequestContentException_ResetsStream()
         {
-            byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+            byte[] contentBytes = "Hello world"u8.ToArray();
 
             using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
             {
@@ -2586,7 +2586,7 @@ namespace System.Net.Http.Functional.Tests
         [ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
         public async Task PostAsyncDuplex_RequestContentExceptionAfterResponseEndReceivedButBeforeConsumed_ResetsStreamAndThrowsOnResponseStreamRead()
         {
-            byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+            byte[] contentBytes = "Hello world"u8.ToArray();
 
             using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
             {
@@ -2651,7 +2651,7 @@ namespace System.Net.Http.Functional.Tests
         [ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
         public async Task PostAsyncDuplex_CancelledBeforeResponseHeadersReceived_ResetsStream()
         {
-            byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+            byte[] contentBytes = "Hello world"u8.ToArray();
 
             using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
             {
@@ -2708,7 +2708,7 @@ namespace System.Net.Http.Functional.Tests
         [ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
         public async Task PostAsyncDuplex_ServerResetsStream_Throws()
         {
-            byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+            byte[] contentBytes = "Hello world"u8.ToArray();
 
             using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
             {
@@ -2770,7 +2770,7 @@ namespace System.Net.Http.Functional.Tests
         [ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
         public async Task PostAsyncDuplex_DisposeResponseBodyBeforeEnd_ResetsStreamAndThrowsOnRequestStreamWriteAndResponseStreamRead()
         {
-            byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+            byte[] contentBytes = "Hello world"u8.ToArray();
 
             using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
             {
@@ -2838,7 +2838,7 @@ namespace System.Net.Http.Functional.Tests
         [ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
         public async Task PostAsyncDuplex_DisposeResponseBodyAfterEndReceivedButBeforeConsumed_ResetsStreamAndThrowsOnRequestStreamWriteAndResponseStreamRead()
         {
-            byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+            byte[] contentBytes = "Hello world"u8.ToArray();
 
             using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
             {
@@ -2912,7 +2912,7 @@ namespace System.Net.Http.Functional.Tests
         [ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
         public async Task PostAsyncDuplex_FinishRequestBodyAndDisposeResponseBodyAfterEndReceivedButBeforeConsumed_DoesNotResetStream()
         {
-            byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+            byte[] contentBytes = "Hello world"u8.ToArray();
 
             using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
             {
@@ -2983,7 +2983,7 @@ namespace System.Net.Http.Functional.Tests
             // 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.ToArray();
 
             using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
             {
@@ -3053,7 +3053,7 @@ namespace System.Net.Http.Functional.Tests
             // 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.ToArray();
 
             using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
             {
@@ -3316,7 +3316,7 @@ namespace System.Net.Http.Functional.Tests
                         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.ToArray(), CancellationToken.None);
                     });
 
                     Exception e = await Assert.ThrowsAsync<HttpRequestException>(() => requestTask);
@@ -3375,7 +3375,7 @@ namespace System.Net.Http.Functional.Tests
                 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.ToArray(), endStream: false);
                 await connection.SendResponseHeadersAsync(streamId, endStream : true, isTrailingHeader : true, headers: headers);
 
                 await Assert.ThrowsAsync<HttpRequestException>(() => sendTask);
index 4ddd663..276733d 100644 (file)
@@ -366,7 +366,7 @@ namespace System.Net.Http.Functional.Tests
         [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.ToArray();
             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);
@@ -961,15 +961,7 @@ namespace System.Net.Http.Functional.Tests
             public MockContent(byte[] mockData, MockOptions options)
             {
                 _options = options;
-
-                if (mockData == null)
-                {
-                    _mockData = Encoding.UTF8.GetBytes("data");
-                }
-                else
-                {
-                    _mockData = mockData;
-                }
+                _mockData = mockData ?? "data"u8.ToArray();
             }
 
             public byte[] GetMockData()
index 1ac9ae9..457085c 100644 (file)
@@ -150,7 +150,7 @@ namespace System.Net.Http.Functional.Tests
         [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.ToArray());
             subContent.Headers.Add("someHeaderName", "andSomeHeaderValue");
             subContent.Headers.Add("someOtherHeaderName", new[] { "withNotOne", "ButTwoValues" });
             subContent.Headers.Add("oneMoreHeader", new[] { "withNotOne", "AndNotTwo", "butThreeValues" });
@@ -177,7 +177,7 @@ namespace System.Net.Http.Functional.Tests
         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.ToArray()));
             mc.Add(new StringContent("This is a StringContent"));
 
             Assert.Equal(
@@ -274,9 +274,9 @@ namespace System.Net.Http.Functional.Tests
             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.ToArray()));
                 mc.Add(new StringContent("This is a StringContent"));
-                mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("Another ByteArrayContent :-)")));
+                mc.Add(new ByteArrayContent("Another ByteArrayContent :-)"u8.ToArray()));
             }
 
             var memStream = new MemoryStream();
@@ -399,7 +399,7 @@ namespace System.Net.Http.Functional.Tests
             stringContent.Headers.Add("StringContent", "foo");
             mc.Add(stringContent);
 
-            var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("foo"));
+            var byteArrayContent = new ByteArrayContent("foo"u8.ToArray());
             byteArrayContent.Headers.Add("ByteArrayContent", "foo");
             mc.Add(byteArrayContent);
 
@@ -442,19 +442,19 @@ namespace System.Net.Http.Functional.Tests
             var mc = new MultipartContent("subtype", "fooBoundary");
 
             var stringContent = new StringContent("bar1");
-            stringContent.Headers.Add("latin1", "\uD83D\uDE00");
+            stringContent.Headers.Add("latin1", "\U0001F600");
             mc.Add(stringContent);
 
-            var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar2"));
-            byteArrayContent.Headers.Add("utf8", "\uD83D\uDE00");
+            var byteArrayContent = new ByteArrayContent("bar2"u8.ToArray());
+            byteArrayContent.Headers.Add("utf8", "\U0001F600");
             mc.Add(byteArrayContent);
 
-            byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar3"));
-            byteArrayContent.Headers.Add("ascii", "\uD83D\uDE00");
+            byteArrayContent = new ByteArrayContent("bar3"u8.ToArray());
+            byteArrayContent.Headers.Add("ascii", "\U0001F600");
             mc.Add(byteArrayContent);
 
-            byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar4"));
-            byteArrayContent.Headers.Add("default", "\uD83D\uDE00");
+            byteArrayContent = new ByteArrayContent("bar4"u8.ToArray());
+            byteArrayContent.Headers.Add("default", "\U0001F600");
             mc.Add(byteArrayContent);
 
             mc.HeaderEncodingSelector = (name, _) => name switch
@@ -476,28 +476,28 @@ namespace System.Net.Http.Functional.Tests
             }
 
             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: "),
-                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: "),
-                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: "),
-                Encoding.Latin1.GetBytes("\uD83D\uDE00"),
-                Encoding.Latin1.GetBytes("\r\n\r\n"),
-                Encoding.Latin1.GetBytes("bar4"),
-                Encoding.Latin1.GetBytes("\r\n--fooBoundary--\r\n"));
+                "--fooBoundary\r\n"u8.ToArray(),
+                "Content-Type: text/plain; charset=utf-8\r\n"u8.ToArray(),
+                "latin1: "u8.ToArray(),
+                Encoding.Latin1.GetBytes("\U0001F600"),
+                "\r\n\r\n"u8.ToArray(),
+                "bar1"u8.ToArray(),
+                "\r\n--fooBoundary\r\n"u8.ToArray(),
+                "utf8: "u8.ToArray(),
+                "\U0001F600"u8.ToArray(),
+                "\r\n\r\n"u8.ToArray(),
+                "bar2"u8.ToArray(),
+                "\r\n--fooBoundary\r\n"u8.ToArray(),
+                "ascii: "u8.ToArray(),
+                Encoding.ASCII.GetBytes("\U0001F600"),
+                "\r\n\r\n"u8.ToArray(),
+                "bar3"u8.ToArray(),
+                "\r\n--fooBoundary\r\n"u8.ToArray(),
+                "default: "u8.ToArray(),
+                Encoding.Latin1.GetBytes("\U0001F600"),
+                "\r\n\r\n"u8.ToArray(),
+                "bar4"u8.ToArray(),
+                "\r\n--fooBoundary--\r\n"u8.ToArray());
 
             Assert.Equal(expected, ms.ToArray());
 
index f7f28da..200d0b1 100644 (file)
@@ -54,9 +54,9 @@ namespace System.Net.Http.Functional.Tests
                 // 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.ToArray());
             }
-            await responseStream.WriteAsync(Encoding.ASCII.GetBytes("0\r\n\r\n"));
+            await responseStream.WriteAsync("0\r\n\r\n"u8.ToArray());
         }
     }
 
@@ -70,9 +70,9 @@ namespace System.Net.Http.Functional.Tests
                 // 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.ToArray());
             }
-            await responseStream.WriteAsync(Encoding.ASCII.GetBytes("0\r\n\r\n"));
+            await responseStream.WriteAsync("0\r\n\r\n"u8.ToArray());
         }
     }
 
index 092e6a3..0d0ca2b 100644 (file)
@@ -48,7 +48,7 @@ namespace System.Net.Http.Functional.Tests
         {
             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.ToArray());
         }
     }
 
@@ -62,7 +62,7 @@ namespace System.Net.Http.Functional.Tests
             {
                 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.ToArray());
             }
         }
     }
@@ -137,7 +137,7 @@ namespace System.Net.Http.Functional.Tests
                 await sawZeroByteRead.Task.WaitAsync(TimeSpan.FromSeconds(10));
                 Assert.False(zeroByteReadTask.IsCompleted);
 
-                byte[] data = Encoding.UTF8.GetBytes("Hello");
+                byte[] data = "Hello"u8.ToArray();
                 await WriteAsync(server, data);
                 await server.FlushAsync();
 
index 1b02ca1..55ecefb 100644 (file)
@@ -591,7 +591,7 @@ namespace System.Net.Http.Functional.Tests
     {
         public SocketsHttpHandler_TrailingHeaders_Test(ITestOutputHelper output) : base(output) { }
 
-        protected static byte[] DataBytes = Encoding.ASCII.GetBytes("data");
+        protected static byte[] DataBytes = "data"u8.ToArray();
 
         protected static readonly IList<HttpHeaderData> TrailingHeaders = new HttpHeaderData[] {
             new HttpHeaderData("MyCoolTrailerHeader", "amazingtrailer"),
@@ -1307,26 +1307,26 @@ namespace System.Net.Http.Functional.Tests
                             // Validate writing APIs on clientStream
 
                             clientStream.WriteByte((byte)'!');
-                            clientStream.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2);
+                            clientStream.Write("\r\n"u8.ToArray(), 0, 2);
                             Assert.Equal("!", await connection.ReadLineAsync());
 
-                            clientStream.Write(new Span<byte>(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.ToArray(), 0, 7);
                             Assert.Equal("world", await connection.ReadLineAsync());
 
-                            await clientStream.WriteAsync(new Memory<byte>(new byte[] { (byte)'a', (byte)'n', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 5));
+                            await clientStream.WriteAsync(new Memory<byte>("and\r\n"u8.ToArray(), 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.ToArray(), 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.ToArray());
                             var buffer = new byte[1];
 
                             Assert.Equal('a', clientStream.ReadByte());
@@ -2732,8 +2732,8 @@ namespace System.Net.Http.Functional.Tests
         {
             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.ToArray();
+            byte[] ResponsePrefix = "response prefix\r\n"u8.ToArray();
 
             Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
@@ -3204,8 +3204,8 @@ namespace System.Net.Http.Functional.Tests
         [ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
         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.ToArray();
+            byte[] ResponsePrefix = "response prefix\r\n"u8.ToArray();
 
             using var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
@@ -3386,7 +3386,7 @@ namespace System.Net.Http.Functional.Tests
                         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(
index e89d38c..bfac32c 100644 (file)
@@ -18,19 +18,19 @@ namespace System.Net.Http.Tests
             var complexContent = new MultipartContent();
 
             var stringContent = new StringContent("bar1");
-            stringContent.Headers.Add("latin1", "\uD83D\uDE00");
+            stringContent.Headers.Add("latin1", "\U0001F600");
             complexContent.Add(stringContent);
 
-            var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar2"));
-            byteArrayContent.Headers.Add("utf8", "\uD83D\uDE00");
+            var byteArrayContent = new ByteArrayContent("bar2"u8.ToArray());
+            byteArrayContent.Headers.Add("utf8", "\U0001F600");
             complexContent.Add(byteArrayContent);
 
-            byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar3"));
-            byteArrayContent.Headers.Add("ascii", "\uD83D\uDE00");
+            byteArrayContent = new ByteArrayContent("bar3"u8.ToArray());
+            byteArrayContent.Headers.Add("ascii", "\U0001F600");
             complexContent.Add(byteArrayContent);
 
-            byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar4"));
-            byteArrayContent.Headers.Add("default", "\uD83D\uDE00");
+            byteArrayContent = new ByteArrayContent("bar4"u8.ToArray());
+            byteArrayContent.Headers.Add("default", "\U0001F600");
             complexContent.Add(byteArrayContent);
 
             stringContent = new StringContent("bar5");
index 84971cb..56dac20 100644 (file)
@@ -69,15 +69,7 @@ namespace System.Net.Http.Tests
         public MockContent(byte[] mockData, MockOptions options)
         {
             _options = options;
-
-            if (mockData == null)
-            {
-                _mockData = Encoding.UTF8.GetBytes("data");
-            }
-            else
-            {
-                _mockData = mockData;
-            }
+            _mockData = mockData ?? "data"u8.ToArray();
         }
 
         public byte[] GetMockData()
index d015924..e42cfb0 100644 (file)
@@ -64,7 +64,7 @@ namespace System.Net
         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.ToArray();
 
         internal HttpListenerRequest(HttpListenerContext context)
         {
index 6451497..28649cc 100644 (file)
@@ -107,7 +107,7 @@ namespace System.Net
             return Header;
         }
 
-        private static readonly byte[] s_CRLFArray = new byte[] { (byte)'\r', (byte)'\n' };
+        private static readonly byte[] s_CRLFArray = "\r\n"u8.ToArray();
 
         internal HttpResponseStreamAsyncResult(object asyncObject, object? userState, AsyncCallback? callback, byte[] buffer, int offset, int size, bool chunked, bool sentHeaders, ThreadPoolBoundHandle boundHandle) : base(asyncObject, userState, callback)
         {
index 89d5c24..900fea8 100644 (file)
@@ -102,7 +102,7 @@ namespace System.Net.Tests
         {
             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 };
         }
 
index a276a61..e7e234d 100644 (file)
@@ -101,7 +101,7 @@ namespace System.Net.Tests
         [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();
index e2d1d82..581ba91 100644 (file)
@@ -13,7 +13,7 @@ namespace System.Net.Tests
     {
         protected HttpListenerFactory Factory { get; }
         protected Socket Client { get; }
-        protected static byte[] SimpleMessage { get; } = Encoding.UTF8.GetBytes("Hello");
+        protected static byte[] SimpleMessage { get; } = "Hello"u8.ToArray();
 
         public HttpListenerResponseTestBase()
         {
index 841fae8..62fb2be 100644 (file)
@@ -62,7 +62,7 @@ namespace System.Net.Tests
                         outputStream.Close();
                     }
 
-                    byte[] extraBytesSentAfterClose = Encoding.UTF8.GetBytes("Should not be sent.");
+                    byte[] extraBytesSentAfterClose = "Should not be sent."u8.ToArray();
                     await outputStream.WriteAsync(extraBytesSentAfterClose, 0, extraBytesSentAfterClose.Length);
                 }
 
@@ -100,7 +100,7 @@ namespace System.Net.Tests
                         outputStream.Close();
                     }
 
-                    byte[] extraBytesSentAfterClose = Encoding.UTF8.GetBytes("Should not be sent.");
+                    byte[] extraBytesSentAfterClose = "Should not be sent."u8.ToArray();
                     outputStream.Write(extraBytesSentAfterClose, 0, extraBytesSentAfterClose.Length);
                 }
 
@@ -308,7 +308,7 @@ namespace System.Net.Tests
                 using (HttpListenerResponse response = serverContext.Response)
                 {
                     Stream output = response.OutputStream;
-                    byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string");
+                    byte[] responseBuffer = "A long string"u8.ToArray();
                     response.ContentLength64 = responseBuffer.Length - 1;
                     try
                     {
@@ -337,7 +337,7 @@ namespace System.Net.Tests
                 {
                     Stream output = response.OutputStream;
 
-                    byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string");
+                    byte[] responseBuffer = "A long string"u8.ToArray();
                     response.ContentLength64 = responseBuffer.Length + 1;
 
                     // Throws when there are bytes left to write
@@ -363,7 +363,7 @@ namespace System.Net.Tests
                 {
                     Stream output = response.OutputStream;
 
-                    byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string");
+                    byte[] responseBuffer = "A long string"u8.ToArray();
                     response.ContentLength64 = responseBuffer.Length + 1;
 
                     // Throws when there are bytes left to write
index 5b1001c..86d020c 100644 (file)
@@ -40,6 +40,6 @@ namespace System.Net.Mime
             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.ToArray();
     }
 }
index e269cc6..26aa458 100644 (file)
@@ -16,8 +16,8 @@ namespace Systen.Net.Mail.Tests
 {
     public class LoopbackSmtpServer : IDisposable
     {
-        private static readonly ReadOnlyMemory<byte> s_messageTerminator = new byte[] { (byte)'\r', (byte)'\n' };
-        private static readonly ReadOnlyMemory<byte> s_bodyTerminator = new byte[] { (byte)'\r', (byte)'\n', (byte)'.', (byte)'\r', (byte)'\n' };
+        private static readonly ReadOnlyMemory<byte> s_messageTerminator = "\r\n"u8.ToArray();
+        private static readonly ReadOnlyMemory<byte> s_bodyTerminator = "\r\n.\r\n"u8.ToArray();
 
         public bool ReceiveMultipleConnections = false;
         public bool SupportSmtpUTF8 = false;
index 0c66e26..0e9f66f 100644 (file)
@@ -50,12 +50,8 @@ namespace System.Net.Mime.Tests
             var outputStream = new MemoryStream();
             var testStream = new QuotedPrintableStream(outputStream, false);
 
-            byte[] bytesToWrite1 = Encoding.ASCII.GetBytes("Hello \r");
-            testStream.Write(bytesToWrite1, 0, bytesToWrite1.Length);
-
-            byte[] bytesToWrite2 = Encoding.ASCII.GetBytes("\n World");
-            testStream.Write(bytesToWrite2, 0, bytesToWrite2.Length);
-
+            testStream.Write("Hello \r"u8);
+            testStream.Write("\n World"u8);
             testStream.Flush();
 
             // We told it not to encode them, but they got split across writes so it could not
index 8a87d2f..0e48bb4 100644 (file)
@@ -18,7 +18,7 @@ namespace System.Net.NetworkInformation.Tests
         // 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.ToArray();
 
         public static IPAddress[] GetLocalIPAddresses()
         {
index 6eedee6..0cb01e7 100644 (file)
@@ -16,8 +16,6 @@ namespace System.Net.Quic.Implementations.MsQuic.Internal
 {
     internal sealed unsafe class MsQuicApi
     {
-        private static readonly byte[] s_appName = Encoding.ASCII.GetBytes("System.Net.Quic");
-
         private static readonly Version MinWindowsVersion = new Version(10, 0, 20145, 1000);
 
         private static readonly Version MsQuicVersion = new Version(2, 0);
@@ -38,7 +36,7 @@ namespace System.Net.Quic.Implementations.MsQuic.Internal
         {
             ApiTable = apiTable;
 
-            fixed (byte* pAppName = s_appName)
+            fixed (byte* pAppName = "System.Net.Quic"u8)
             {
                 var cfg = new QUIC_REGISTRATION_CONFIG {
                     AppName = (sbyte*)pAppName,
index a14b21f..65e7873 100644 (file)
@@ -25,7 +25,7 @@ namespace System.Net.Quic.Tests
     [Collection(nameof(DisableParallelization))]
     public class MsQuicTests : QuicTestBase<MsQuicProviderFactory>
     {
-        private static byte[] s_data = Encoding.UTF8.GetBytes("Hello world!");
+        private static byte[] s_data = "Hello world!"u8.ToArray();
 
         public MsQuicTests(ITestOutputHelper output) : base(output) { }
 
@@ -630,7 +630,7 @@ namespace System.Net.Quic.Tests
         {
             (QuicConnection clientConnection, QuicConnection serverConnection) = await CreateConnectedQuicConnection();
 
-            ReadOnlyMemory<byte> helloWorld = Encoding.ASCII.GetBytes("Hello world!");
+            ReadOnlyMemory<byte> helloWorld = "Hello world!"u8.ToArray();
             ReadOnlySequence<byte> ros = CreateReadOnlySequenceFromBytes(helloWorld.ToArray());
 
             Assert.False(ros.IsSingleSegment);
index 7f4e03a..0fe8068 100644 (file)
@@ -15,7 +15,7 @@ namespace System.Net.Quic.Tests
     public abstract class QuicStreamTests<T> : QuicTestBase<T>
          where T : IQuicImplProviderFactory, new()
     {
-        private static byte[] s_data = Encoding.UTF8.GetBytes("Hello world!");
+        private static byte[] s_data = "Hello world!"u8.ToArray();
         public QuicStreamTests(ITestOutputHelper output) : base(output) { }
 
         [Fact]
@@ -179,7 +179,7 @@ namespace System.Net.Quic.Tests
             {
                 byte[] buffer = new byte[64];
                 QuicStream clientStream = await clientConnection.OpenBidirectionalStreamAsync();
-                ValueTask writeTask = clientStream.WriteAsync(Encoding.UTF8.GetBytes("PING"), endStream: true);
+                ValueTask writeTask = clientStream.WriteAsync("PING"u8.ToArray(), endStream: true);
                 ValueTask<QuicStream> acceptTask = serverConnection.AcceptStreamAsync();
                 await new Task[] { writeTask.AsTask(), acceptTask.AsTask() }.WhenAllOrAnyFailed(PassingTestTimeoutMilliseconds);
                 QuicStream serverStream = acceptTask.Result;
index 8566d0c..b613b6d 100644 (file)
@@ -20,8 +20,8 @@ namespace System.Net.Quic.Tests
     public abstract class QuicTestBase<T>
         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.ToArray();
+        private static readonly byte[] s_pong = "PONG"u8.ToArray();
         private static readonly IQuicImplProviderFactory s_factory = new T();
 
         public static QuicImplementationProvider ImplementationProvider { get; } = s_factory.GetProvider();
index 6cf0d7d..d1f5e58 100644 (file)
@@ -79,7 +79,7 @@ namespace System.Net.Tests
 
         private const string absoluteUri = "ftp://localhost/";
 
-        private static readonly byte[] helloWorldBytes = Encoding.UTF8.GetBytes("Hello world");
+        private static readonly byte[] helloWorldBytes = "Hello world"u8.ToArray();
         private static readonly byte[] largeFileBytes = Enumerable.Range(0, 10 * 1024 * 1024).Select((i) => (byte)(i % 256)).ToArray();
 
         [ConditionalTheory(nameof(LocalServerAvailable))]
index f218ce2..e86c79b 100644 (file)
@@ -10,9 +10,9 @@ namespace System.Net.Security
     public readonly struct SslApplicationProtocol : IEquatable<SslApplicationProtocol>
     {
         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.ToArray();
+        private static readonly byte[] s_http2Utf8 = "h2"u8.ToArray();
+        private static readonly byte[] s_http11Utf8 = "http/1.1"u8.ToArray();
 
         // Refer to IANA on ApplicationProtocols: https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids
         /// <summary>Defines a <see cref="SslApplicationProtocol"/> instance for HTTP 3.0.</summary>
index bf8272c..d6815f5 100644 (file)
@@ -23,7 +23,7 @@ namespace System.Net.Security.Enterprise.Tests
 
         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.ToArray();
 
         private const int MaxWriteDataSize = 63 * 1024; // NegoState.MaxWriteDataSize
         private static string s_longString = new string('A', MaxWriteDataSize) + 'Z';
index bbfefa4..b61b0ef 100644 (file)
@@ -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.ToArray();
         private const string TargetName = "testTargetName";
 
         [Fact]
index 8ca45a5..df74c83 100644 (file)
@@ -157,7 +157,7 @@ namespace System.Net.Security.Tests
                     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.ToArray();
                     await auth.WriteAsync(message, 0, message.Length);
                 }
             }
index 043ab1f..76a1c31 100644 (file)
@@ -20,7 +20,7 @@ namespace System.Net.Security.Tests
         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.ToArray();
 
         private const int MaxWriteDataSize = 63 * 1024; // NegoState.MaxWriteDataSize
         private static string s_longString = new string('A', MaxWriteDataSize) + 'Z';
index 7520221..469c0a1 100644 (file)
@@ -55,7 +55,7 @@ namespace System.Net.Security.Tests
                 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.ToArray();
                 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 @@ namespace System.Net.Security.Tests
                 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.ToArray();
                 await ssl.WriteAsync(message, 0, message.Length);
 
                 // Initiate Read operation, that results in starting renegotiation as per server response to the above request.
index 2de22f5..1c8cfdb 100644 (file)
@@ -164,7 +164,7 @@ namespace System.Net.Security.Tests
                 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.ToArray();
                 if (useSync)
                 {
                     ssl.Write(message, 0, message.Length);
index 8d0dae2..873f754 100644 (file)
@@ -20,7 +20,7 @@ namespace System.Net.Security.Tests
 
     public abstract class SslStreamStreamToStreamTest
     {
-        private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
+        private readonly byte[] _sampleMsg = "Sample Test Message"u8.ToArray();
 
         protected static async Task WithServerCertificate(X509Certificate serverCertificate, Func<X509Certificate, string, Task> func)
         {
index f4cddb9..62383aa 100644 (file)
@@ -43,8 +43,8 @@ namespace System.Net.Security.Tests
         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.ToArray();
+        public static readonly byte[] s_pong = "PONG"u8.ToArray();
 
         public static bool AllowAnyServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
         {
index fe016e6..477abd6 100644 (file)
@@ -13,9 +13,9 @@ namespace System.Net.Security.Tests
         [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.ToArray()), SslApplicationProtocol.Http3);
+            Assert.Equal(new SslApplicationProtocol("h2"u8.ToArray()), SslApplicationProtocol.Http2);
+            Assert.Equal(new SslApplicationProtocol("http/1.1"u8.ToArray()), SslApplicationProtocol.Http11);
         }
 
         [Fact]
@@ -42,7 +42,7 @@ namespace System.Net.Security.Tests
         [Fact]
         public void Constructor_ByteArray_Copies()
         {
-            byte[] expected = Encoding.UTF8.GetBytes("hello");
+            byte[] expected = "hello"u8.ToArray();
             SslApplicationProtocol byteProtocol = new SslApplicationProtocol(expected);
 
             ArraySegment<byte> arraySegment;
index e9bd105..6a86b2c 100644 (file)
@@ -190,7 +190,7 @@ namespace System.Net.Sockets.Tests
 
                 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.ToArray();
                     await s.WriteAsync(getRequest, 0, getRequest.Length);
                     Assert.NotEqual(-1, s.ReadByte()); // just verify we successfully get any data back
                 }
@@ -240,7 +240,7 @@ namespace System.Net.Sockets.Tests
 
                 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.ToArray();
                     s.Write(getRequest, 0, getRequest.Length);
                     Assert.NotEqual(-1, s.ReadByte()); // just verify we successfully get any data back
                 }
index f9fd4e3..ac0035e 100644 (file)
@@ -77,7 +77,7 @@ namespace System.Net.WebSockets.Tests
         public async Task ReceiveAsync_UTF8SplitAcrossMultipleBuffers_ValidDataReceived()
         {
             // 1 character - 2 bytes
-            byte[] payload = Encoding.UTF8.GetBytes("\u00E6");
+            byte[] payload = "\u00E6"u8.ToArray();
             var frame = new byte[payload.Length + 2];
             frame[0] = 0x81; // FIN = true, Opcode = Text
             frame[1] = (byte)payload.Length;
@@ -294,7 +294,7 @@ namespace System.Net.WebSockets.Tests
                     Assert.Equal(WebSocketState.Open, socket.State);
 
                     // Ask server to send us a close
-                    await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(".close")), WebSocketMessageType.Text, true, default);
+                    await socket.SendAsync(new ArraySegment<byte>(".close"u8.ToArray()), WebSocketMessageType.Text, true, default);
 
                     // Verify received server-initiated close message.
                     WebSocketReceiveResult recvResult = await socket.ReceiveAsync(new ArraySegment<byte>(new byte[256]), default);
index 03ae598..cec40f4 100644 (file)
@@ -77,11 +77,11 @@ namespace System.Net.WebSockets.Tests
                 DangerousDeflateOptions = new WebSocketDeflateOptions()
             });
 
-            await websocket.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken);
+            await websocket.SendAsync("Hello"u8.ToArray(), 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.ToArray(), 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 @@ namespace System.Net.WebSockets.Tests
                 DangerousDeflateOptions = new WebSocketDeflateOptions()
             });
 
-            byte[] bytes = Encoding.UTF8.GetBytes("Hello");
+            byte[] bytes = "Hello"u8.ToArray();
             WebSocketMessageFlags flags = WebSocketMessageFlags.DisableCompression | WebSocketMessageFlags.EndOfMessage;
             await websocket.SendAsync(bytes, WebSocketMessageType.Text, flags, CancellationToken);
 
@@ -116,7 +116,7 @@ namespace System.Net.WebSockets.Tests
                 DangerousDeflateOptions = new WebSocketDeflateOptions()
             });
 
-            byte[] bytes = Encoding.UTF8.GetBytes("Hello");
+            byte[] bytes = "Hello"u8.ToArray();
             await websocket.SendAsync(Memory<byte>.Empty, WebSocketMessageType.Text, endOfMessage: false, CancellationToken);
             await websocket.SendAsync(bytes, WebSocketMessageType.Text, endOfMessage: true, CancellationToken);
 
@@ -181,7 +181,7 @@ namespace System.Net.WebSockets.Tests
 
             for (var i = 0; i < 100; ++i)
             {
-                await websocket.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken);
+                await websocket.SendAsync("Hello"u8.ToArray(), WebSocketMessageType.Text, true, CancellationToken);
 
                 // Without context takeover the message should look the same every time
                 Assert.Equal("C107F248CDC9C90700", Convert.ToHexString(stream.NextAvailableBytes));
index 7d9bab8..a700b71 100644 (file)
@@ -31,11 +31,11 @@ namespace System.Xml
 
         // 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.ToArray();
+        private static readonly byte[] s_encodingUTF8 = "utf-8"u8.ToArray();
+        private static readonly byte[] s_encodingUnicode = "utf-16"u8.ToArray();
+        private static readonly byte[] s_encodingUnicodeLE = "utf-16le"u8.ToArray();
+        private static readonly byte[] s_encodingUnicodeBE = "utf-16be"u8.ToArray();
 
         private SupportedEncoding _encodingCode;
         private Encoding? _encoding;
index a1cfd7e..cb6ebbe 100644 (file)
@@ -758,7 +758,7 @@ namespace System.Xml.Tests
         {
             XmlWriterSettings wSettings = new XmlWriterSettings();
             wSettings.NamespaceHandling = nsHandling;
-            byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
+            byte[] buffer = "abc"u8.ToArray();
 
             using (XmlWriter w = CreateMemWriter(utils, wSettings))
             {
@@ -780,7 +780,7 @@ namespace System.Xml.Tests
         {
             XmlWriterSettings wSettings = new XmlWriterSettings();
             wSettings.NamespaceHandling = nsHandling;
-            byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
+            byte[] buffer = "abc"u8.ToArray();
 
             using (XmlWriter w = CreateMemWriter(utils, wSettings))
             {
@@ -803,7 +803,7 @@ namespace System.Xml.Tests
             XmlWriterSettings wSettings = new XmlWriterSettings();
             wSettings.NamespaceHandling = nsHandling;
             XmlWriter w = CreateMemWriter(utils, wSettings);
-            byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
+            byte[] buffer = "abc"u8.ToArray();
 
             w.WriteStartElement("A");
             w.WriteAttributeString("xmlns", "p", null, "ns1");
index c690713..8365c4c 100644 (file)
@@ -153,7 +153,7 @@ namespace System.Xml.Tests
         [Fact]
         public void NodeReaderReadContentAsBase64WithSimpleXml()
         {
-            byte[] byteData = Encoding.ASCII.GetBytes("hello world");
+            byte[] byteData = "hello world"u8.ToArray();
             string xml = $"<root attr='{Convert.ToBase64String(byteData)}'><child /></root>"; //hello world encoded
             XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml);
             Assert.True(nodeReader.Read());
@@ -179,7 +179,7 @@ namespace System.Xml.Tests
         [Fact]
         public void NodeReaderReadContentAsBinHexWithSimpleXml()
         {
-            byte[] byteData = Encoding.ASCII.GetBytes("hello world");
+            byte[] byteData = "hello world"u8.ToArray();
             string xml = $"<root attr='{BitConverter.ToString(byteData).Replace("-", "")}'><child /></root>";
             XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml);
             Assert.True(nodeReader.Read());
@@ -205,7 +205,7 @@ namespace System.Xml.Tests
         [Fact]
         public void NodeReaderReadElementContentAsBase64WithSimpleXml()
         {
-            byte[] byteData = Encoding.ASCII.GetBytes("hello world");
+            byte[] byteData = "hello world"u8.ToArray();
             string xml = $"<root attr='val'>{Convert.ToBase64String(byteData)}</root>"; //hello world encoded
             XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml);
             Assert.True(nodeReader.Read());
@@ -229,7 +229,7 @@ namespace System.Xml.Tests
         [Fact]
         public void NodeReaderReadElementContentAsBinHexWithSimpleXml()
         {
-            byte[] byteData = Encoding.ASCII.GetBytes("hello world");
+            byte[] byteData = "hello world"u8.ToArray();
             string xml = $"<root attr='val'>{BitConverter.ToString(byteData).Replace("-", "")}</root>";
             XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml);
             Assert.True(nodeReader.Read());
index 1ca6c15..7c8afc8 100644 (file)
@@ -40,7 +40,7 @@ namespace System.Xml.XmlResolver.Tests
         {
             var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10);
 
-            byte[] data = Encoding.ASCII.GetBytes("hello world");
+            byte[] data = "hello world"u8.ToArray();
             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 @@ namespace System.Xml.XmlResolver.Tests
         public void XmlResolverRemoveWithValidData()
         {
             var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10);
-            byte[] data = Encoding.ASCII.GetBytes("hello world");
+            byte[] data = "hello world"u8.ToArray();
             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));
index 061d666..b3cf95c 100644 (file)
@@ -108,7 +108,7 @@ namespace System.Xml.XmlResolver.Tests
         [Fact]
         public void XmlResolverGetEntityAsyncWithValidUserSuppliedData()
         {
-            byte[] inpData = Encoding.ASCII.GetBytes("hello world");
+            byte[] inpData = "hello world"u8.ToArray();
             var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10);
             xmlResolver.Add(new Uri("-//W3C//DTD FAKE 1.0 Not Real//EN", UriKind.RelativeOrAbsolute), inpData);
             Task<object> output = xmlResolver.GetEntityAsync(new Uri("-//W3C//DTD FAKE 1.0 Not Real//EN",
index f02b3e2..2ae28cf 100644 (file)
@@ -126,7 +126,7 @@ namespace System.Reflection.Metadata.Tests
             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.ToArray(), headers.MetadataStartOffset);
             Assert.NotEqual(-1, mscorlibIndex);
             //mutate mscorlib
             peImage[mscorlibIndex + headers.MetadataStartOffset] = 0xFF;
@@ -145,7 +145,7 @@ namespace System.Reflection.Metadata.Tests
 
             // mutate CLR to reach MetadataKind.WindowsMetadata
             // find CLR
-            int clrIndex = IndexOf(peImage, Encoding.ASCII.GetBytes("CLR"), headers.MetadataStartOffset);
+            int clrIndex = IndexOf(peImage, "CLR"u8.ToArray(), 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 @@ namespace System.Reflection.Metadata.Tests
                 winrtDef.Attributes);
 
             var strReader = reader.GetBlobReader(winrtDef.Name);
-            Assert.Equal(Encoding.UTF8.GetBytes("Class1"), strReader.ReadBytes("Class1".Length));
+            Assert.Equal("Class1"u8.ToArray(), strReader.ReadBytes("Class1".Length));
             Assert.Equal(0, strReader.RemainingBytes);
 
             // .class /*02000003*/ private auto ansi import windowsruntime sealed beforefieldinit Lib.'<WinRT>Class1'
@@ -449,7 +449,7 @@ namespace System.Reflection.Metadata.Tests
                 clrDef.Attributes);
 
             strReader = reader.GetBlobReader(clrDef.Name);
-            Assert.Equal(Encoding.UTF8.GetBytes("<WinRT>Class1"), strReader.ReadBytes("<WinRT>Class1".Length));
+            Assert.Equal("<WinRT>Class1"u8.ToArray(), strReader.ReadBytes("<WinRT>Class1".Length));
             Assert.Equal(0, strReader.RemainingBytes);
         }
 
@@ -469,7 +469,7 @@ namespace System.Reflection.Metadata.Tests
                 winrtDef.Attributes);
 
             var strReader = reader.GetBlobReader(winrtDef.Name);
-            Assert.Equal(Encoding.UTF8.GetBytes("<CLR>Class1"), strReader.ReadBytes("<CLR>Class1".Length));
+            Assert.Equal("<CLR>Class1"u8.ToArray(), strReader.ReadBytes("<CLR>Class1".Length));
             Assert.Equal(0, strReader.RemainingBytes);
 
             // .class /*02000003*/ public auto ansi windowsruntime sealed beforefieldinit Lib.Class1
@@ -483,7 +483,7 @@ namespace System.Reflection.Metadata.Tests
                 clrDef.Attributes);
 
             strReader = reader.GetBlobReader(clrDef.Name);
-            Assert.Equal(Encoding.UTF8.GetBytes("Class1"), strReader.ReadBytes("Class1".Length));
+            Assert.Equal("Class1"u8.ToArray(), strReader.ReadBytes("Class1".Length));
             Assert.Equal(0, strReader.RemainingBytes);
         }
 
@@ -497,14 +497,14 @@ namespace System.Reflection.Metadata.Tests
             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.ToArray(), 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.ToArray(), strReader.ReadBytes("System".Length));
             Assert.Equal(0, strReader.RemainingBytes);
         }
 
index 20f68af..640a5ec 100644 (file)
@@ -31,7 +31,7 @@ namespace System.Reflection.PortableExecutable.Tests
         [Fact]
         public void ReadNullPaddedUTF8WorksWithNoNullPadding()
         {
-            var headerBytes = Encoding.UTF8.GetBytes(".abcdefg");
+            byte[] headerBytes = ".abcdefg"u8.ToArray();
             var stream = new MemoryStream(headerBytes);
             stream.Position = 0;
 
index 096846d..710871e 100644 (file)
@@ -389,7 +389,7 @@ namespace System.Reflection.Metadata.Tests
                 Assert.Equal("", block.PeekUtf8NullTerminated(4, null, stringDecoder, out bytesRead));
                 Assert.Equal(0, bytesRead);
 
-                byte[] helloPrefix = Encoding.UTF8.GetBytes("Hello");
+                byte[] helloPrefix = "Hello"u8.ToArray();
 
                 Assert.Equal("Hello\u0001", block.PeekUtf8NullTerminated(1, helloPrefix, stringDecoder, out bytesRead));
                 Assert.Equal(2, bytesRead);
index 2fd01ef..8f346de 100644 (file)
@@ -20,20 +20,20 @@ namespace System.Reflection.Metadata.Tests
                 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.ToArray()))
             {
                 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.ToArray()))
             {
                 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.ToArray()))
             {
                 Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(3, "x"));
                 Assert.False(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(3, "xyz"));
@@ -56,7 +56,7 @@ namespace System.Reflection.Metadata.Tests
                 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.ToArray(), 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 @@ namespace System.Reflection.Metadata.Tests
                 }
              );
 
-            fixed (byte* fixedPtr = (buffer = Encoding.UTF8.GetBytes("Test")))
+            fixed (byte* fixedPtr = (buffer = "Test"u8.ToArray()))
             {
                 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.ToArray(), decoder, out bytesRead));
                 Assert.Equal(buffer.Length, bytesRead);
             }
 
index d888e14..c316947 100644 (file)
@@ -21,7 +21,7 @@ namespace System.Tests
         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.ToArray();
             char[] ouputBuffer = new char[4];
             Convert.ToBase64CharArray(inputBuffer, 0, 3, ouputBuffer, 0);
             Convert.ToBase64CharArray(inputBuffer, 0, 2, ouputBuffer, 0);
index 5a9bbab..a6c0efc 100644 (file)
@@ -437,7 +437,7 @@ namespace System.Net.Tests
             // 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.ToArray();
             byte[] output = WebUtility.UrlEncodeToBytes(input, 0, input.Length);
             Assert.NotSame(input, output);
         }
@@ -445,7 +445,7 @@ namespace System.Net.Tests
         [Fact]
         public static void UrlDecodeToBytes_NoDecodingNeeded_ReturnsNewClonedArray()
         {
-            byte[] input = Encoding.UTF8.GetBytes("Dont.Need.Decoding");
+            byte[] input = "Dont.Need.Decoding"u8.ToArray();
             byte[] output = WebUtility.UrlDecodeToBytes(input, 0, input.Length);
             Assert.NotSame(input, output);
         }
index 81d2acf..56af61b 100644 (file)
@@ -4147,7 +4147,7 @@ namespace SerializationTestTypes
 
     public class IReadWriteXmlWriteBinHex_EqualityDefined : IXmlSerializable
     {
-        private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+        private byte[] _bits = "hello world"u8.ToArray();
 
         public System.Xml.Schema.XmlSchema GetSchema()
         {
@@ -4176,7 +4176,7 @@ namespace SerializationTestTypes
 
         public virtual void WriteXml(System.Xml.XmlWriter writer)
         {
-            byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+            byte[] bits = "hello world"u8.ToArray();
             writer.WriteBinHex(bits, 0, bits.Length);
         }
 
@@ -4202,7 +4202,7 @@ namespace SerializationTestTypes
 
     internal class PrivateIXmlSerializables : IXmlSerializable
     {
-        private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+        private byte[] _bits = "hello world"u8.ToArray();
 
         public System.Xml.Schema.XmlSchema GetSchema()
         {
@@ -4231,7 +4231,7 @@ namespace SerializationTestTypes
 
         public virtual void WriteXml(System.Xml.XmlWriter writer)
         {
-            byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+            byte[] bits = "hello world"u8.ToArray();
             writer.WriteBinHex(bits, 0, bits.Length);
         }
     }
@@ -4241,7 +4241,7 @@ namespace SerializationTestTypes
         private PrivateDefaultCtorIXmlSerializables() { }
         public PrivateDefaultCtorIXmlSerializables(bool init) { }
 
-        private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+        private byte[] _bits = "hello world"u8.ToArray();
 
         public System.Xml.Schema.XmlSchema GetSchema()
         {
@@ -4270,7 +4270,7 @@ namespace SerializationTestTypes
 
         public virtual void WriteXml(System.Xml.XmlWriter writer)
         {
-            byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+            byte[] bits = "hello world"u8.ToArray();
             writer.WriteBinHex(bits, 0, bits.Length);
         }
     }
@@ -4278,7 +4278,7 @@ namespace SerializationTestTypes
     [XmlSchemaProvider("MySchema")]
     public class PublicIXmlSerializablesWithPublicSchemaProvider : IXmlSerializable
     {
-        private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+        private byte[] _bits = "hello world"u8.ToArray();
 
         public System.Xml.Schema.XmlSchema GetSchema()
         {
@@ -4312,7 +4312,7 @@ namespace SerializationTestTypes
 
         public virtual void WriteXml(System.Xml.XmlWriter writer)
         {
-            byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+            byte[] bits = "hello world"u8.ToArray();
             writer.WriteBinHex(bits, 0, bits.Length);
         }
     }
@@ -4320,7 +4320,7 @@ namespace SerializationTestTypes
     [XmlSchemaProvider("MySchema")]
     public class PublicExplicitIXmlSerializablesWithPublicSchemaProvider : IXmlSerializable
     {
-        private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+        private byte[] _bits = "hello world"u8.ToArray();
 
         System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
         {
@@ -4354,7 +4354,7 @@ namespace SerializationTestTypes
 
         void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
         {
-            byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+            byte[] bits = "hello world"u8.ToArray();
             writer.WriteBinHex(bits, 0, bits.Length);
         }
     }
@@ -4362,7 +4362,7 @@ namespace SerializationTestTypes
     [XmlSchemaProvider("MySchema")]
     public class PublicIXmlSerializablesWithPrivateSchemaProvider : IXmlSerializable
     {
-        private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+        private byte[] _bits = "hello world"u8.ToArray();
 
         public System.Xml.Schema.XmlSchema GetSchema()
         {
@@ -4396,7 +4396,7 @@ namespace SerializationTestTypes
 
         public virtual void WriteXml(System.Xml.XmlWriter writer)
         {
-            byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world");
+            byte[] bits = "hello world"u8.ToArray();
             writer.WriteBinHex(bits, 0, bits.Length);
         }
     }
index 80d4eac..278e412 100644 (file)
@@ -21,7 +21,7 @@ namespace System.Security.Cryptography.Cose.Tests
         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.ToArray();
         internal const string ContentTypeDummyValue = "application/cose; cose-type=\"cose-sign1\"";
 
         internal const string NullCborHex = "F6";
index 38a29ea..30effc1 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Security.Cryptography.Pkcs.Tests
         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);
 
index dba1da3..61ed97a 100644 (file)
@@ -100,7 +100,7 @@ namespace System.Security.Cryptography.Pkcs.Tests
                 "D50DF295F1DB078C84EECBCB30F1018E939B1FEA8615B31F39F87F02EF816EFF" +
                 "FE80A39C0857ECA510882DD2D66D49B743F0E7FF8DBEE4650449");
 
-            data.MessageContent = Encoding.ASCII.GetBytes("This is a test.\n");
+            data.MessageContent = "This is a test.\n"u8.ToArray();
 
             data.TokenInfoBytes = data.FullTokenBytes.Slice(64, 412);
             data.PolicyId = "1.2.3.4.1";
@@ -283,7 +283,7 @@ DgUIrLjqguolBSdvPJ2io9O0rTi7+IQr2jb8JEgpH1WNwC3R4A==");
                 "FD6B6AB4F89DC6750F14EC2E0134BA61B4D0B2C1FB2F60F622379249CE6381AF" +
                 "667900B17A7BB6AE");
 
-            data.MessageContent = Encoding.ASCII.GetBytes("Hello, world!");
+            data.MessageContent = "Hello, world!"u8.ToArray();
 
             data.EmbeddedSigningCertificate = data.FullTokenBytes.Slice(1659, 1359);
 
@@ -422,7 +422,7 @@ DgUIrLjqguolBSdvPJ2io9O0rTi7+IQr2jb8JEgpH1WNwC3R4A==");
                 "76252A2F4605B97BD3C299D1CD79929273BB86E7DF9E113C92802380ED6D4041" +
                 "9DA4C01214D4FA24");
 
-            data.MessageContent = Encoding.UTF8.GetBytes("My TST signer attributes are sorted incorrectly.");
+            data.MessageContent = "My TST signer attributes are sorted incorrectly."u8.ToArray();
 
             data.EmbeddedSigningCertificate = data.FullTokenBytes.Slice(188, 1670);
 
index b4a4487..745049b 100644 (file)
@@ -347,7 +347,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
                 0x11, 0xE0, 0x6E, 0xD2, 0x22, 0x75, 0xE7, 0x7C,
             };
 
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
+            byte[] helloBytes = "Hello"u8.ToArray();
 
             using (var cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes))
             using (RSA rsa = cert.GetRSAPublicKey())
@@ -360,7 +360,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
         public static void TestKey_ECDsabrainpool_PublicKey(byte[] curveData, byte[] notUsed)
         {
             _ = notUsed;
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
+            byte[] helloBytes = "Hello"u8.ToArray();
 
             try
             {
@@ -386,7 +386,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
         [Fact]
         public static void TestECDsaPublicKey()
         {
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
+            byte[] helloBytes = "Hello"u8.ToArray();
 
             using (var cert = new X509Certificate2(TestData.ECDsa384Certificate))
             using (ECDsa publicKey = cert.GetECDsaPublicKey())
@@ -439,7 +439,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
                 0x08, 0xC5, 0xAA, 0xA6, 0xE5, 0xFD, 0xD0, 0x96,
             };
 
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
+            byte[] helloBytes = "Hello"u8.ToArray();
 
             using (var cert = new X509Certificate2(TestData.ECDsa384Certificate))
             using (ECDsa publicKey = cert.GetECDsaPublicKey())
@@ -476,7 +476,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
         [Theory, MemberData(nameof(BrainpoolCurves))]
         public static void TestECDsaPublicKey_BrainpoolP160r1_ValidatesSignature(byte[] curveData, byte[] existingSignature)
         {
-            byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
+            byte[] helloBytes = "Hello"u8.ToArray();
 
             try
             {
index 5e11d90..5af72f7 100644 (file)
@@ -611,7 +611,7 @@ namespace System.Security.Cryptography.Xml.Tests
         [Fact]
         public void EncryptKey_RSA_UseOAEP()
         {
-            byte[] data = Encoding.ASCII.GetBytes("12345678");
+            byte[] data = "12345678"u8.ToArray();
             using (RSA rsa = RSA.Create())
             {
                 byte[] encryptedData = EncryptedXml.EncryptKey(data, rsa, true);
@@ -852,7 +852,7 @@ namespace System.Security.Cryptography.Xml.Tests
         {
             using (TripleDES tripleDES = TripleDES.Create())
             {
-                byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678");
+                byte[] key = "123456781234567812345678"u8.ToArray();
 
                 byte[] encryptedKey = EncryptedXml.EncryptKey(key, tripleDES);
 
@@ -866,7 +866,7 @@ namespace System.Security.Cryptography.Xml.Tests
         {
             using (Aes aes = Aes.Create())
             {
-                byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678");
+                byte[] key = "123456781234567812345678"u8.ToArray();
 
                 byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes);
 
@@ -880,7 +880,7 @@ namespace System.Security.Cryptography.Xml.Tests
         {
             using (Aes aes = Aes.Create())
             {
-                byte[] key = Encoding.ASCII.GetBytes("12345678");
+                byte[] key = "12345678"u8.ToArray();
 
                 byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes);
 
@@ -894,7 +894,7 @@ namespace System.Security.Cryptography.Xml.Tests
         {
             using (Aes aes = Aes.Create())
             {
-                byte[] key = Encoding.ASCII.GetBytes("1234567");
+                byte[] key = "1234567"u8.ToArray();
 
                 Assert.Throws<CryptographicException>(() => EncryptedXml.EncryptKey(key, aes));
             }
@@ -905,7 +905,7 @@ namespace System.Security.Cryptography.Xml.Tests
         {
             using (TripleDES tripleDES = TripleDES.Create())
             {
-                byte[] key = Encoding.ASCII.GetBytes("123");
+                byte[] key = "123"u8.ToArray();
 
                 Assert.Throws<CryptographicException>(() => EncryptedXml.DecryptKey(key, tripleDES));
             }
@@ -916,7 +916,7 @@ namespace System.Security.Cryptography.Xml.Tests
         {
             using (TripleDES tripleDES = TripleDES.Create())
             {
-                byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678");
+                byte[] key = "123456781234567812345678"u8.ToArray();
 
                 byte[] encryptedKey = EncryptedXml.EncryptKey(key, tripleDES);
                 encryptedKey[0] ^= 0xFF;
@@ -930,7 +930,7 @@ namespace System.Security.Cryptography.Xml.Tests
         {
             using (Aes aes = Aes.Create())
             {
-                byte[] key = Encoding.ASCII.GetBytes("123");
+                byte[] key = "123"u8.ToArray();
 
                 Assert.Throws<CryptographicException>(() => EncryptedXml.DecryptKey(key, aes));
             }
@@ -941,7 +941,7 @@ namespace System.Security.Cryptography.Xml.Tests
         {
             using (Aes aes = Aes.Create())
             {
-                byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678");
+                byte[] key = "123456781234567812345678"u8.ToArray();
 
                 byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes);
                 encryptedKey[0] ^= 0xFF;
@@ -955,7 +955,7 @@ namespace System.Security.Cryptography.Xml.Tests
         {
             using (Aes aes = Aes.Create())
             {
-                byte[] key = Encoding.ASCII.GetBytes("12345678");
+                byte[] key = "12345678"u8.ToArray();
 
                 byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes);
                 encryptedKey[0] ^= 0xFF;
index 1265c37..ac5d356 100644 (file)
@@ -1447,7 +1447,7 @@ namespace System.Security.Cryptography.Xml.Tests
 ";
                 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.ToArray()));
             }
 
             for (int i = 1; i < 160; i++)
@@ -1483,10 +1483,10 @@ namespace System.Security.Cryptography.Xml.Tests
 ";
             SignedXml sign = GetSignedXml(xml);
 
-            CheckErratum(sign, new HMACSHA1(Encoding.ASCII.GetBytes("no clue")), "1");
+            CheckErratum(sign, new HMACSHA1("no clue"u8.ToArray()), "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("oops"u8.ToArray()), "3");
+            CheckErratum(sign, new HMACSHA1("secret"u8.ToArray()), "4");
         }
 
         [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")]
@@ -1496,7 +1496,7 @@ namespace System.Security.Cryptography.Xml.Tests
             // 72 is a multiple of 8 but smaller than the minimum of 80 bits
             string xml = @"<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /><SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#hmac-sha1""><HMACOutputLength>72</HMACOutputLength></SignatureMethod><Reference URI=""#object""><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><DigestValue>nz4GS0NbH2SrWlD/4fX313CoTzc=</DigestValue></Reference></SignedInfo><SignatureValue>2dimB+P5Aw5K</SignatureValue><Object Id=""object"">some other text</Object></Signature>";
             SignedXml sign = GetSignedXml(xml);
-            CheckErratum(sign, new HMACSHA1(Encoding.ASCII.GetBytes("secret")), "72");
+            CheckErratum(sign, new HMACSHA1("secret"u8.ToArray()), "72");
         }
 
         [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")]
@@ -1506,7 +1506,7 @@ namespace System.Security.Cryptography.Xml.Tests
             // 80 bits is the minimum (and the half-size of HMACSHA1)
             string xml = @"<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /><SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#hmac-sha1""><HMACOutputLength>80</HMACOutputLength></SignatureMethod><Reference URI=""#object""><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><DigestValue>nz4GS0NbH2SrWlD/4fX313CoTzc=</DigestValue></Reference></SignedInfo><SignatureValue>jVQPtLj61zNYjw==</SignatureValue><Object Id=""object"">some other text</Object></Signature>";
             SignedXml sign = GetSignedXml(xml);
-            Assert.True(sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("secret"))));
+            Assert.True(sign.CheckSignature(new HMACSHA1("secret"u8.ToArray())));
         }
 
         [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")]
@@ -1516,7 +1516,7 @@ namespace System.Security.Cryptography.Xml.Tests
             // 80bits is smaller than the half-size of HMACSHA256
             string xml = @"<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /><SignatureMethod Algorithm=""http://www.w3.org/2001/04/xmldsig-more#hmac-sha256""><HMACOutputLength>80</HMACOutputLength></SignatureMethod><Reference URI=""#object""><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><DigestValue>nz4GS0NbH2SrWlD/4fX313CoTzc=</DigestValue></Reference></SignedInfo><SignatureValue>vPtw7zKVV/JwQg==</SignatureValue><Object Id=""object"">some other text</Object></Signature>";
             SignedXml sign = GetSignedXml(xml);
-            CheckErratum(sign, new HMACSHA256(Encoding.ASCII.GetBytes("secret")), "80");
+            CheckErratum(sign, new HMACSHA256("secret"u8.ToArray()), "80");
         }
 
         [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")]
@@ -1526,7 +1526,7 @@ namespace System.Security.Cryptography.Xml.Tests
             // 128 is the half-size of HMACSHA256
             string xml = @"<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /><SignatureMethod Algorithm=""http://www.w3.org/2001/04/xmldsig-more#hmac-sha256""><HMACOutputLength>128</HMACOutputLength></SignatureMethod><Reference URI=""#object""><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><DigestValue>nz4GS0NbH2SrWlD/4fX313CoTzc=</DigestValue></Reference></SignedInfo><SignatureValue>aegpvkAwOL8gN/CjSnW6qw==</SignatureValue><Object Id=""object"">some other text</Object></Signature>";
             SignedXml sign = GetSignedXml(xml);
-            Assert.True(sign.CheckSignature(new HMACSHA256(Encoding.ASCII.GetBytes("secret"))));
+            Assert.True(sign.CheckSignature(new HMACSHA256("secret"u8.ToArray())));
         }
 
         [Fact]
@@ -1534,7 +1534,7 @@ namespace System.Security.Cryptography.Xml.Tests
         {
             string xml = @"<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /><SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#hmac-sha1"" /><Reference URI=""#object""><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><DigestValue>7/XTsHaBSOnJ/jXD5v0zL6VKYsk=</DigestValue></Reference></SignedInfo><SignatureValue>a0goL9esBUKPqtFYgpp2KST4huk=</SignatureValue><Object Id=""object"">some text</Object></Signature>";
             SignedXml sign = GetSignedXml(xml);
-            Assert.True(sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("secret"))));
+            Assert.True(sign.CheckSignature(new HMACSHA1("secret"u8.ToArray())));
         }
 
         [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")]
@@ -1559,7 +1559,7 @@ namespace System.Security.Cryptography.Xml.Tests
 </Signature>
 ";
             SignedXml sign = GetSignedXml(xml);
-            Assert.Throws<CryptographicException>(() => sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("no clue"))));
+            Assert.Throws<CryptographicException>(() => sign.CheckSignature(new HMACSHA1("no clue"u8.ToArray())));
         }
 
         [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")]
@@ -1584,7 +1584,7 @@ namespace System.Security.Cryptography.Xml.Tests
 </Signature>
 ";
             SignedXml sign = GetSignedXml(xml);
-            Assert.Throws<FormatException>(() => sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("no clue"))));
+            Assert.Throws<FormatException>(() => sign.CheckSignature(new HMACSHA1("no clue"u8.ToArray())));
         }
 
         [Fact]
index 6862508..a22e8b3 100644 (file)
@@ -10,9 +10,6 @@ namespace System.Security.Cryptography.X509Certificates
 {
     internal sealed partial class AppleCertificatePal : ICertificatePal
     {
-        // Byte representation of "-----BEGIN "
-        private static ReadOnlySpan<byte> PemBegin => new byte[] { 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x42, 0x45, 0x47, 0x49, 0x4E, 0x20 };
-
         internal delegate bool DerCallback(ReadOnlySpan<byte> derData, X509ContentType contentType);
 
         internal static bool TryDecodePem(ReadOnlySpan<byte> rawData, DerCallback derCallback)
@@ -27,7 +24,7 @@ namespace System.Security.Cryptography.X509Certificates
             // Look for the PEM marker. This doesn't guarantee it will be a valid PEM since we don't check whether
             // the marker is at the beginning of line or whether the line is a complete marker. It's just a quick
             // check to avoid conversion from bytes to characters if the content is DER encoded.
-            if (rawData.IndexOf(PemBegin) < 0)
+            if (rawData.IndexOf("-----BEGIN "u8) < 0)
             {
                 return false;
             }
index 72ee58f..704e2ba 100644 (file)
@@ -56,7 +56,7 @@ namespace System.Security.Cryptography.Tests
         [Fact]
         public void InvalidInput_ToBase64Transform()
         {
-            byte[] data_3bytes = Text.Encoding.ASCII.GetBytes("aaa");
+            byte[] data_3bytes = "aaa"u8.ToArray();
             ICryptoTransform transform = new ToBase64Transform();
 
             AssertExtensions.Throws<ArgumentNullException>("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0));
@@ -77,7 +77,7 @@ namespace System.Security.Cryptography.Tests
         [Fact]
         public void InvalidInput_FromBase64Transform()
         {
-            byte[] data_4bytes = Text.Encoding.ASCII.GetBytes("aaaa");
+            byte[] data_4bytes = "aaaa"u8.ToArray();
             ICryptoTransform transform = new FromBase64Transform();
 
             AssertExtensions.Throws<ArgumentNullException>("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0));
index 68e2104..6e877fb 100644 (file)
@@ -304,7 +304,7 @@ namespace System.Security.Cryptography.Tests
                 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();
                 }
 
index cd92dc9..ab413da 100644 (file)
@@ -289,7 +289,7 @@ namespace System.Security.Cryptography
             string password = "password";
             int iterations = 16777216;
             byte[] expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984".HexToByteArray();
-            byte[] salt = Encoding.UTF8.GetBytes("salt");
+            ReadOnlySpan<byte> salt = "salt"u8;
             byte[] actual = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA1, expected.Length);
             Assert.Equal(expected, actual);
         }
index 64b9c40..f12e0b1 100644 (file)
@@ -63,7 +63,7 @@ namespace System.Security.Cryptography.Tests
         [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.ToArray();
             TripleDES tripleDes = TripleDES.Create();
 
             byte[] encryptedBytes;
index 3dc2f53..c744b4b 100644 (file)
@@ -30,7 +30,7 @@ namespace EncodingTests
             // 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.ToArray(), encodedBytes);
             decodedString = asciiEncoding.GetString(encodedBytes);
             Assert.Equal(decodedString, s_asciiInputStringWinNoFallback);
         }
index cb26b48..78295e0 100644 (file)
@@ -150,7 +150,7 @@ namespace System.Text.Encodings.Web.Tests
                     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<byte>(destination, 0, expectedOutputBytesSoFar.Count + "[FFFD]".Length).ToArray());
+                    Assert.Equal(expectedOutputBytesSoFar.Concat("[FFFD]"u8.ToArray()), new Span<byte>(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 @@ namespace System.Text.Encodings.Web.Tests
         {
             // Arrange
 
-            byte[] inputBytes = Encoding.UTF8.GetBytes("\U00000040\U00000400\U00004000\U00040000"); // code units of different lengths
+            byte[] inputBytes = "\U00000040\U00000400\U00004000\U00040000"u8.ToArray(); // code units of different lengths
             var encoder = new ConfigurableScalarTextEncoder(_ => true /* allow everything */);
 
             // Act
@@ -239,7 +239,7 @@ namespace System.Text.Encodings.Web.Tests
         {
             // Arrange
 
-            byte[] inputBytes = Encoding.UTF8.GetBytes("\U00000040\U00000400\U00004000\U00040000"); // code units of different lengths
+            byte[] inputBytes = "\U00000040\U00000400\U00004000\U00040000"u8.ToArray(); // code units of different lengths
             var encoder = new ConfigurableScalarTextEncoder(codePoint => codePoint != 0x4000 /* disallow U+4000, allow all else */);
 
             // Act
index 53aa358..05f5707 100644 (file)
@@ -11,17 +11,10 @@ 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_typePropertyName
-            = new byte[] { (byte)'$', (byte)'t', (byte)'y', (byte)'p', (byte)'e' };
-
-        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.ToArray();
+        internal static readonly byte[] s_refPropertyName = "$ref"u8.ToArray();
+        internal static readonly byte[] s_typePropertyName = "$type"u8.ToArray();
+        internal static readonly byte[] s_valuesPropertyName = "$values"u8.ToArray();
 
         internal static bool TryReadMetadata(JsonConverter converter, JsonTypeInfo jsonTypeInfo, ref Utf8JsonReader reader, ref ReadStack state)
         {
index cb99fea..5c96e06 100644 (file)
@@ -148,7 +148,7 @@ namespace System.Text.Json.Serialization.Tests
                     await Assert.ThrowsAsync<NotSupportedException>(async () => await StreamingSerializer.DeserializeWrapper<T>(stream, options));
                 }
 
-                using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("{}")))
+                using (MemoryStream stream = new MemoryStream("{}"u8.ToArray()))
                 {
                     JsonSerializerOptions options = new JsonSerializerOptions
                     {
index 2898ab9..77218b2 100644 (file)
@@ -78,7 +78,6 @@ namespace System.Text.Json.Tests
                 };
 
                 const string CharLabel = "char";
-                byte[] byteUtf8 = Encoding.UTF8.GetBytes("byte");
                 using var writer = new Utf8JsonWriter(buffer, options);
 
                 if (skipValidation)
@@ -89,7 +88,7 @@ namespace System.Text.Json.Tests
                         val.WriteTo(writer);
                         writer.WritePropertyName(CharLabel.AsSpan());
                         val.WriteTo(writer);
-                        writer.WritePropertyName(byteUtf8);
+                        writer.WritePropertyName("byte"u8);
                         val.WriteTo(writer);
                         writer.WritePropertyName(JsonEncodedText.Encode(CharLabel));
                         val.WriteTo(writer);
@@ -111,7 +110,7 @@ namespace System.Text.Json.Tests
                 {
                     Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(CharLabel));
                     Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(CharLabel.AsSpan()));
-                    Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(byteUtf8));
+                    Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName("byte"u8));
                     Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(JsonEncodedText.Encode(CharLabel)));
 
                     writer.Flush();
index 5c6022f..44139de 100644 (file)
@@ -138,7 +138,7 @@ namespace System.Text.Json.Nodes.Tests
             Assert.Null(JsonSerializer.Deserialize<JsonNode>("null"));
             Assert.Null(JsonNode.Parse("null"));
 
-            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null")))
+            using (MemoryStream stream = new MemoryStream("null"u8.ToArray()))
             {
                 Assert.Null(JsonNode.Parse(stream));
             }
index 182691e..997371e 100644 (file)
@@ -103,7 +103,7 @@ namespace System.Text.Json.Tests
         [Fact]
         public static void ZeroMaxDepthDefaultsTo64()
         {
-            byte[] dataUtf8 = Encoding.UTF8.GetBytes("{}");
+            byte[] dataUtf8 = "{}"u8.ToArray();
 
             ReadOnlyMemory<byte> dataMemory = dataUtf8;
             var firstSegment = new BufferSegment<byte>(dataMemory.Slice(0, 1));
@@ -134,7 +134,7 @@ namespace System.Text.Json.Tests
         [Fact]
         public static void MaxDepthIsHonored()
         {
-            byte[] dataUtf8 = Encoding.UTF8.GetBytes("{}");
+            byte[] dataUtf8 = "{}"u8.ToArray();
 
             ReadOnlyMemory<byte> dataMemory = dataUtf8;
             var firstSegment = new BufferSegment<byte>(dataMemory.Slice(0, 1));
index 3531efd..887910a 100644 (file)
@@ -138,7 +138,7 @@ namespace System.Text.Json.Tests
             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.ToArray();
 
         [Fact]
         public void AssertShouldSerializeTest()
index 913c919..115e91c 100644 (file)
@@ -154,7 +154,7 @@ namespace System.Text.Json.Serialization.Tests
             var options = new JsonSerializerOptions();
             options.ReadCommentHandling = JsonCommentHandling.Skip;
 
-            int[][] i = JsonSerializer.Deserialize<int[][]>(Encoding.UTF8.GetBytes("[[1,2] // Inline [\n,[3, /* Multi\n]] Line*/4]]"), options);
+            int[][] i = JsonSerializer.Deserialize<int[][]>("[[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]);
index 1f8bb6b..7a5b874 100644 (file)
@@ -188,7 +188,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public static async Task ParseNullStringShouldThrowJsonExceptionAsync()
         {
-            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("null")))
+            using (var stream = new MemoryStream("null"u8.ToArray()))
             { 
                 await Assert.ThrowsAsync<JsonException>(async () => await JsonSerializer.DeserializeAsync<SimpleStruct>(stream));
 
index e7eb6f5..78cd158 100644 (file)
@@ -61,7 +61,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public static void ReaderOptionsWinMaxDepth()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("[[]]");
+            byte[] utf8 = "[[]]"u8.ToArray();
 
             var readerOptions = new JsonReaderOptions
             {
@@ -114,7 +114,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public static void ReaderOptionsWinTrailingCommas()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, 3,]");
+            byte[] utf8 = "[1, 2, 3,]"u8.ToArray();
 
             var serializerOptions = new JsonSerializerOptions
             {
@@ -151,7 +151,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public static void ReaderOptionsWinComments()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, /* some comment */ 3]");
+            byte[] utf8 = "[1, 2, /* some comment */ 3]"u8.ToArray();
 
             var serializerOptions = new JsonSerializerOptions
             {
@@ -175,7 +175,7 @@ namespace System.Text.Json.Serialization.Tests
             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.ToArray();
 
             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 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public static void OnInvalidReaderIsRestored()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, 3}");
+            byte[] utf8 = "[1, 2, 3}"u8.ToArray();
 
             var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default);
             reader.Read();
@@ -213,7 +213,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public static void DataRemaining()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("{\"Foo\":\"abc\", \"Bar\":123}");
+            byte[] utf8 = "{\"Foo\":\"abc\", \"Bar\":123}"u8.ToArray();
 
             var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default);
             reader.Read();
@@ -233,7 +233,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public static void ReadPropertyName()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("{\"Foo\":[1, 2, 3]}");
+            byte[] utf8 = "{\"Foo\":[1, 2, 3]}"u8.ToArray();
 
             var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default);
             reader.Read();
@@ -265,7 +265,7 @@ namespace System.Text.Json.Serialization.Tests
         [InlineData(false)]
         public static void ReadObjectMultiSegment(bool isFinalBlock)
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, {\"Foo\":[1, 2, 3]}]");
+            byte[] utf8 = "[1, 2, {\"Foo\":[1, 2, 3]}]"u8.ToArray();
             ReadOnlySequence<byte> sequence = JsonTestHelper.CreateSegments(utf8);
 
             var reader = new Utf8JsonReader(sequence, isFinalBlock, state: default);
@@ -292,7 +292,7 @@ namespace System.Text.Json.Serialization.Tests
         public static void NotEnoughData(bool isFinalBlock)
         {
             {
-                byte[] utf8 = Encoding.UTF8.GetBytes("\"start of string");
+                byte[] utf8 = "\"start of string"u8.ToArray();
 
                 var reader = new Utf8JsonReader(utf8, isFinalBlock, state: default);
                 Assert.Equal(0, reader.BytesConsumed);
@@ -310,7 +310,7 @@ namespace System.Text.Json.Serialization.Tests
             }
 
             {
-                byte[] utf8 = Encoding.UTF8.GetBytes("{");
+                byte[] utf8 = "{"u8.ToArray();
 
                 var reader = new Utf8JsonReader(utf8, isFinalBlock, state: default);
                 reader.Read();
@@ -333,7 +333,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public static void EndObjectOrArrayIsInvalid()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("[{}]");
+            byte[] utf8 = "[{}]"u8.ToArray();
 
             var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default);
             reader.Read();
@@ -575,7 +575,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public static void ReadPartial()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, 3]");
+            byte[] utf8 = "[1, 2, 3]"u8.ToArray();
             var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default);
             reader.Read();
             int[] array = JsonSerializer.Deserialize<int[]>(ref reader);
index c01ce57..d19f790 100644 (file)
@@ -60,8 +60,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public static void ParseUntyped()
         {
-            byte[] bytes = Encoding.UTF8.GetBytes("42");
-            object obj = JsonSerializer.Deserialize(bytes, typeof(object));
+            object obj = JsonSerializer.Deserialize("42"u8, typeof(object));
             Assert.IsType<JsonElement>(obj);
             JsonElement element = (JsonElement)obj;
             Assert.Equal(JsonValueKind.Number, element.ValueKind);
index 5112265..10bb1ed 100644 (file)
@@ -69,7 +69,7 @@ namespace System.Text.Json.Serialization.Tests
         [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.ToArray()))
             {
                 JsonSerializerOptions options = new JsonSerializerOptions
                 {
@@ -85,7 +85,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public async Task ReadReferenceTypeCollectionPassingNullValueAsync()
         {
-            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null")))
+            using (MemoryStream stream = new MemoryStream("null"u8.ToArray()))
             {
                 IList<object> referenceTypeCollection = await Serializer.DeserializeWrapper<IList<object>>(stream);
                 Assert.Null(referenceTypeCollection);
@@ -95,7 +95,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public async Task ReadValueTypeCollectionPassingNullValueAsync()
         {
-            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null")))
+            using (MemoryStream stream = new MemoryStream("null"u8.ToArray()))
             {
                 IList<int> valueTypeCollection = await Serializer.DeserializeWrapper<IList<int>>(stream);
                 Assert.Null(valueTypeCollection);
@@ -164,8 +164,7 @@ namespace System.Text.Json.Serialization.Tests
 
                 static Stream CreateStream(int count)
                 {
-                    byte[] objBytes = Encoding.UTF8.GetBytes(
-                        @"{""Test"":{},""Test2"":[],""Test3"":{""Value"":{}},""PersonType"":0,""Id"":2}");
+                    byte[] objBytes = @"{""Test"":{},""Test2"":[],""Test3"":{""Value"":{}},""PersonType"":0,""Id"":2}"u8.ToArray();
 
                     byte[] utf8Bom = Encoding.UTF8.GetPreamble();
 
index 257ec5b..af83df3 100644 (file)
@@ -49,7 +49,7 @@ namespace System.Text.Json.Serialization.Tests
 
             {
                 Span<byte> json = JsonSerializer.SerializeToUtf8Bytes(1);
-                Assert.Equal(Encoding.UTF8.GetBytes("1"), json.ToArray());
+                Assert.Equal("1"u8.ToArray(), json.ToArray());
             }
 
             {
index 66b89f1..2491f20 100644 (file)
@@ -67,7 +67,7 @@ namespace System.Text.Json.Serialization.Tests
         [Fact]
         public async static void NullValueWithNullableSuccess()
         {
-            byte[] nullUtf8Literal = Encoding.UTF8.GetBytes("null");
+            byte[] nullUtf8Literal = "null"u8.ToArray();
 
             var stream = new MemoryStream();
             Utf8JsonWriter writer = new Utf8JsonWriter(stream);
index 331b174..0a1d2a4 100644 (file)
@@ -15,7 +15,7 @@ namespace System.Text.Json.Tests
         [Fact]
         public static void InitialStateMultiSegment()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("1");
+            byte[] utf8 = "1"u8.ToArray();
             ReadOnlySequence<byte> sequence = JsonTestHelper.GetSequence(utf8, 1);
             var json = new Utf8JsonReader(sequence, isFinalBlock: true, state: default);
 
@@ -395,7 +395,7 @@ namespace System.Text.Json.Tests
         [Fact]
         public static void InitialStateSimpleCtorMultiSegment()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("1");
+            byte[] utf8 = "1"u8.ToArray();
             ReadOnlySequence<byte> sequence = JsonTestHelper.GetSequence(utf8, 1);
             var json = new Utf8JsonReader(sequence);
 
@@ -420,7 +420,7 @@ namespace System.Text.Json.Tests
         [Fact]
         public static void StateRecoveryMultiSegment()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("[1]");
+            byte[] utf8 = "[1]"u8.ToArray();
             ReadOnlySequence<byte> sequence = JsonTestHelper.GetSequence(utf8, 1);
             var json = new Utf8JsonReader(sequence, isFinalBlock: false, state: default);
 
index 69df6ce..ac092e7 100644 (file)
@@ -13,39 +13,32 @@ namespace System.Text.Json.Tests
         [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\"");
             bool foundId = false;
             bool foundTransports = false;
             bool foundValue = false;
             bool foundArrayValue = false;
 
-            string jsonString = "{\"conne\\u0063tionId\":\"123\",\"availableTransports\":[\"My name is \\\"Ahson\\\"\"]}";
-            byte[] utf8Data = Encoding.UTF8.GetBytes(jsonString);
-
-            var json = new Utf8JsonReader(utf8Data, isFinalBlock: true, state: default);
+            var json = new Utf8JsonReader("{\"conne\\u0063tionId\":\"123\",\"availableTransports\":[\"My name is \\\"Ahson\\\"\"]}"u8, isFinalBlock: true, state: default);
             while (json.Read())
             {
                 if (json.TokenType == JsonTokenType.PropertyName)
                 {
-                    if (json.ValueTextEquals(connectionId) && json.ValueTextEquals("connectionId".AsSpan()))
+                    if (json.ValueTextEquals("connectionId"u8) && json.ValueTextEquals("connectionId".AsSpan()))
                     {
                         foundId = true;
                     }
-                    else if (json.ValueTextEquals(availableTransports) && json.ValueTextEquals("availableTransports".AsSpan()))
+                    else if (json.ValueTextEquals("availableTransports"u8) && json.ValueTextEquals("availableTransports".AsSpan()))
                     {
                         foundTransports = true;
                     }
                 }
                 else if (json.TokenType == JsonTokenType.String)
                 {
-                    if (json.ValueTextEquals(value123) && json.ValueTextEquals("123".AsSpan()))
+                    if (json.ValueTextEquals("123"u8) && json.ValueTextEquals("123".AsSpan()))
                     {
                         foundValue = true;
                     }
-                    else if (json.ValueTextEquals(embeddedQuotes) && json.ValueTextEquals("My name is \"Ahson\"".AsSpan()))
+                    else if (json.ValueTextEquals("My name is \"Ahson\""u8) && json.ValueTextEquals("My name is \"Ahson\"".AsSpan()))
                     {
                         foundArrayValue = true;
                     }
@@ -549,9 +542,7 @@ namespace System.Text.Json.Tests
         [Fact]
         public static void TestTextEqualsMismatchMultiSegment()
         {
-            string jsonString = "\"Hi, \\\"Ahson\\\"!\"";
-            byte[] lookup = Encoding.UTF8.GetBytes("Hello, \"Ahson\"");
-            byte[] utf8Data = Encoding.UTF8.GetBytes(jsonString);
+            byte[] utf8Data = "\"Hi, \\\"Ahson\\\"!\""u8.ToArray();
             bool found = false;
 
             // Segment 1: "Hi, \"A
@@ -563,7 +554,7 @@ namespace System.Text.Json.Tests
             {
                 if (json.TokenType == JsonTokenType.String)
                 {
-                    if (json.ValueTextEquals(lookup) ||
+                    if (json.ValueTextEquals("Hello, \"Ahson\""u8) ||
                         json.ValueTextEquals("Hello, \"Ahson\"".AsSpan()) ||
                         json.ValueTextEquals("Hello, \"Ahson\""))
                     {
index 43f896e..0be0fc7 100644 (file)
@@ -114,7 +114,7 @@ namespace System.Text.Json.Tests
         [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);
@@ -138,7 +138,7 @@ namespace System.Text.Json.Tests
         [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);
@@ -162,7 +162,7 @@ namespace System.Text.Json.Tests
         [Fact]
         public static void StateRecovery()
         {
-            byte[] utf8 = Encoding.UTF8.GetBytes("[1]");
+            ReadOnlySpan<byte> utf8 = "[1]"u8;
             var json = new Utf8JsonReader(utf8, isFinalBlock: false, state: default);
 
             Assert.Equal(0, json.BytesConsumed);
@@ -199,7 +199,7 @@ namespace System.Text.Json.Tests
 
             JsonReaderState state = json.CurrentState;
 
-            json = new Utf8JsonReader(utf8.AsSpan((int)json.BytesConsumed), isFinalBlock: true, state);
+            json = new Utf8JsonReader(utf8.Slice((int)json.BytesConsumed), isFinalBlock: true, state);
 
             Assert.Equal(0, json.BytesConsumed);    // Not retained
             Assert.Equal(0, json.TokenStartIndex);  // Not retained
index eb59af3..5272c1b 100644 (file)
@@ -57,13 +57,13 @@ namespace System.Text.Json.Tests
             Action<byte[]> validate;
 
             validate = (data) => Assert.Equal(123456789, JsonSerializer.Deserialize<long>(data));
-            yield return new object[] { Encoding.UTF8.GetBytes("123456789"), validate };
+            yield return new object[] { "123456789"u8.ToArray(), validate };
 
             validate = (data) => Assert.Equal(1234.56789, JsonSerializer.Deserialize<double>(data));
-            yield return new object[] { Encoding.UTF8.GetBytes("1234.56789"), validate };
+            yield return new object[] { "1234.56789"u8.ToArray(), validate };
 
             validate = (data) => Assert.Equal(1234.56789, JsonSerializer.Deserialize<double>(data));
-            yield return new object[] { Encoding.UTF8.GetBytes(" 1234.56789 "), validate };
+            yield return new object[] { " 1234.56789 "u8.ToArray(), validate };
 
             validate = (data) => Assert.Equal(@"Hello", JsonSerializer.Deserialize<string>(data));
             yield return new object[] { Encoding.UTF8.GetBytes(@"""Hello"""), validate };
@@ -110,7 +110,7 @@ namespace System.Text.Json.Tests
             };
             yield return new object[] { json, validate };
 
-            json = Encoding.UTF8.GetBytes("[ 1, 1,1,1,1 ] ");
+            json = "[ 1, 1,1,1,1 ] "u8.ToArray();
             validate = (data) =>
             {
                 foreach (int val in JsonSerializer.Deserialize<int[]>(data))
index 4ce5bc0..732677f 100644 (file)
@@ -530,7 +530,7 @@ namespace System.Text.Json.Tests
                 // Account for the fact that an encoder might write a literal replacement character or its
                 // escaped representation, and both forms are equally valid.
 
-                if (span.StartsWith(new byte[] { 0xEF, 0xBF, 0xBD })) { return true; } // literal U+FFFD (as UTF-8)
+                if (span.StartsWith("\uFFFD"u8)) { return true; }
                 if (span.Length >= 6)
                 {
                     if (span[0] == (byte)'\\' && span[1] == (byte)'u'
@@ -1416,7 +1416,7 @@ namespace System.Text.Json.Tests
             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.ToArray();
 
             using var jsonUtf8 = new Utf8JsonWriter(output, options);
 
@@ -1436,7 +1436,7 @@ namespace System.Text.Json.Tests
 
             await using var jsonUtf8 = new Utf8JsonWriter(stream, options);
 
-            byte[] utf8String = Encoding.UTF8.GetBytes("some string 1234");
+            byte[] utf8String = "some string 1234"u8.ToArray();
 
             jsonUtf8.WriteStartArray();
             for (int i = 0; i < 10_000; i++)
@@ -2316,14 +2316,14 @@ namespace System.Text.Json.Tests
                     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.ToArray());
                 }
                 else
                 {
                     Assert.Throws<InvalidOperationException>(() => jsonUtf8.WritePropertyName("test name"));
                     Assert.Throws<InvalidOperationException>(() => jsonUtf8.WritePropertyName(JsonEncodedText.Encode("test name")));
                     Assert.Throws<InvalidOperationException>(() => jsonUtf8.WritePropertyName("test name".AsSpan()));
-                    Assert.Throws<InvalidOperationException>(() => jsonUtf8.WritePropertyName(Encoding.UTF8.GetBytes("test name")));
+                    Assert.Throws<InvalidOperationException>(() => jsonUtf8.WritePropertyName("test name"u8.ToArray()));
                 }
             }
 
@@ -2833,7 +2833,7 @@ namespace System.Text.Json.Tests
 
             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 @@ namespace System.Text.Json.Tests
                 jsonUtf8.WriteStartObject();
                 for (int i = 0; i < 999; i++)
                 {
-                    jsonUtf8.WriteStartObject(Encoding.UTF8.GetBytes("name"));
+                    jsonUtf8.WriteStartObject("name"u8);
                 }
-                Assert.Throws<InvalidOperationException>(() => jsonUtf8.WriteStartArray(Encoding.UTF8.GetBytes("name")));
+                Assert.Throws<InvalidOperationException>(() => jsonUtf8.WriteStartArray("name"u8));
             }
 
             using (var jsonUtf8 = new Utf8JsonWriter(output, options))
@@ -3107,7 +3107,7 @@ namespace System.Text.Json.Tests
             using (var jsonUtf8 = new Utf8JsonWriter(output, options))
             {
                 jsonUtf8.WriteStartObject();
-                Assert.Throws<ArgumentException>(() => jsonUtf8.WriteBase64String(Encoding.UTF8.GetBytes("foo"), value));
+                Assert.Throws<ArgumentException>(() => jsonUtf8.WriteBase64String("foo"u8, value));
             }
 
             using (var jsonUtf8 = new Utf8JsonWriter(output, options))
@@ -3169,7 +3169,7 @@ namespace System.Text.Json.Tests
             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 @@ namespace System.Text.Json.Tests
             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 @@ namespace System.Text.Json.Tests
             JsonEncodedText encodedPropertyName = JsonEncodedText.Encode(propertyName);
             JsonEncodedText encodedValue = JsonEncodedText.Encode(value);
 
-            byte[] utf8PropertyName = Encoding.UTF8.GetBytes("message");
-            byte[] utf8Value = Encoding.UTF8.GetBytes("Hello, World!");
+            ReadOnlySpan<byte> utf8PropertyName = "message"u8;
+            ReadOnlySpan<byte> utf8Value = "Hello, World!"u8;
 
             var options = new JsonWriterOptions { Indented = formatted, SkipValidation = skipValidation };
 
@@ -4971,7 +4971,7 @@ namespace System.Text.Json.Tests
                         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 @@ namespace System.Text.Json.Tests
                         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 @@ namespace System.Text.Json.Tests
                         jsonUtf8.WriteStartArray("message".AsSpan());
                         break;
                     case 2:
-                        jsonUtf8.WriteStartArray(Encoding.UTF8.GetBytes("message"));
+                        jsonUtf8.WriteStartArray("message"u8);
                         break;
                 }
 
@@ -5337,7 +5337,7 @@ namespace System.Text.Json.Tests
                         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 @@ namespace System.Text.Json.Tests
                         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 @@ namespace System.Text.Json.Tests
                         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 @@ namespace System.Text.Json.Tests
         public static void WriteString_NullPropertyName_ReadOnlySpan_Byte()
         {
             WriteNullPropertyName_Simple(
-                Encoding.UTF8.GetBytes("utf8"),
+                "utf8"u8.ToArray(),
                 "\"utf8\"",
                 (writer, name, value) => writer.WriteString(name, value),
                 (writer, name, value) => writer.WriteString(name, value),
@@ -7017,7 +7017,7 @@ namespace System.Text.Json.Tests
         [Fact]
         public static void WriteStringValue_ReadOnlySpanBytesProperty_NullString()
         {
-            byte[] propertyName = Encoding.UTF8.GetBytes("propUtf8");
+            byte[] propertyName = "propUtf8"u8.ToArray();
 
             WriteNullValue_InObject(
                 "\"propUtf8\":\"\"",