From bfca1a563b50afa5731320004c6850e8f1a71495 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Tue, 31 May 2022 15:09:47 -0400 Subject: [PATCH 1/2] Use u8 in more places Primarily replacing Encoding.UTF8/ASCII.GetBytes("literal") with "literal"u8.ToArray() --- .../System/IO/StreamConformanceTests.cs | 8 +-- .../Net/Http/Http2LoopbackConnection.cs | 2 +- .../DSA/DSAKeyFileTests.cs | 2 +- .../DSA/DSAKeyPemTests.cs | 8 ++- .../DSA/DSATestData.cs | 2 +- .../EC/ECKeyFileTests.LimitedPrivate.cs | 2 +- .../EC/ECKeyFileTests.cs | 2 +- .../EC/ECKeyPemTests.cs | 6 +-- .../ECDsa/ECDsaTests.cs | 2 - .../RSA/RSAKeyFileTests.cs | 2 +- .../RSA/RSAKeyPemTests.cs | 11 ++-- .../Common/tests/Tests/System/StringTests.cs | 3 +- .../tests/RemotelyInvokable.cs | 2 +- .../tests/DirectoryServicesProtocolsTests.cs | 6 +-- .../System.Drawing.Common/tests/ImageTests.cs | 12 ++--- .../tests/Reader/ReadGeneralizedTime.cs | 8 +-- .../src/System/Formats/Tar/TarHeader.Write.cs | 8 +-- .../tests/ZipFile.Unix.cs | 3 +- .../tests/ZipArchive/zip_UpdateTests.cs | 6 +-- .../tests/File/ReadWriteAllBytes.cs | 6 +-- .../tests/File/ReadWriteAllBytesAsync.cs | 6 +-- .../FileStream/DevicesPipesAndSockets.cs | 8 +-- .../tests/FileStream/ctor_str_fm.cs | 8 +-- .../System.IO.Hashing/tests/Crc32Tests.cs | 4 +- .../System.IO.Hashing/tests/Crc64Tests.cs | 4 +- .../tests/XxHash32Tests.007.cs | 8 +-- .../System.IO.Hashing/tests/XxHash32Tests.cs | 8 +-- .../tests/XxHash32Tests.f00d.cs | 8 +-- .../tests/XxHash64Tests.007.cs | 8 +-- .../System.IO.Hashing/tests/XxHash64Tests.cs | 8 +-- .../tests/XxHash64Tests.f00d.cs | 8 +-- .../tests/PipeReaderCopyToAsyncTests.cs | 20 +++---- .../tests/PipeReaderReadAtLeastAsyncTests.cs | 10 ++-- .../PipeReaderStreamTests.nonnetstandard.cs | 6 +-- .../tests/PipeReaderWriterFacts.cs | 10 ++-- .../tests/PipeWriterCopyToAsyncTests.cs | 8 +-- .../PipeWriterStreamTests.nonnetstandard.cs | 12 ++--- .../tests/PipeWriterTests.cs | 4 +- .../tests/ReadAsyncCancellationTests.cs | 8 +-- .../tests/SchedulerFacts.cs | 12 ++--- .../tests/SequencePipeReaderTests.cs | 8 +-- .../tests/StreamPipeReaderTests.cs | 8 +-- .../tests/StreamPipeWriterTests.cs | 32 +++++------ .../tests/UnflushedBytesTests.cs | 2 +- src/libraries/System.Memory.Data/README.md | 4 +- .../tests/BinaryDataTests.cs | 48 ++++++++--------- .../tests/Base64/Base64DecoderUnitTests.cs | 12 ++--- .../BuffersExtensionsTests.cs | 8 +-- .../EncodingExtensionsTests.cs | 24 ++++----- .../ReadOnlySequenceTests.Common.byte.cs | 2 +- .../tests/SequenceReader/ReadTo.cs | 4 +- .../tests/SequenceReader/SkipDelimiter.cs | 34 ++++++------ .../System/Net/Http/WinHttpRequestStream.cs | 4 +- .../BidirectionStreamingTest.cs | 2 +- ...ttp.WinHttpHandler.Functional.Tests.csproj | 1 - .../FunctionalTests/TrailingHeadersTest.cs | 2 +- .../UnitTests/WinHttpResponseStreamTest.cs | 4 +- .../Http/SocketsHttpHandler/Http2Stream.cs | 2 +- .../Http/SocketsHttpHandler/HttpConnection.cs | 14 ++--- .../tests/FunctionalTests/HPackTest.cs | 4 +- .../HttpClientHandlerTest.Http2.cs | 30 +++++------ .../tests/FunctionalTests/HttpContentTest.cs | 12 +---- .../FunctionalTests/MultipartContentTest.cs | 54 +++++++++---------- .../ResponseStreamConformanceTests.cs | 8 +-- .../ResponseStreamZeroByteReadTests.cs | 6 +-- .../FunctionalTests/SocketsHttpHandlerTest.cs | 24 ++++----- .../UnitTests/Headers/MultipartContentTest.cs | 6 +-- .../tests/UnitTests/MockContent.cs | 10 +--- .../Managed/HttpListenerRequest.Managed.cs | 2 +- .../Windows/HttpResponseStreamAsyncResult.cs | 2 +- .../tests/HttpListenerAuthenticationTests.cs | 2 +- .../tests/HttpListenerContextTests.cs | 2 +- .../tests/HttpListenerResponseTests.cs | 2 +- .../tests/HttpResponseStreamTests.cs | 10 ++-- .../System/Net/Mime/EncodedStreamFactory.cs | 2 +- .../tests/Functional/LoopbackSmtpServer.cs | 4 +- .../tests/Unit/QuotedPrintableStreamTest.cs | 8 +-- .../tests/FunctionalTests/TestSettings.cs | 2 +- .../MsQuic/Internal/MsQuicApi.cs | 4 +- .../tests/FunctionalTests/MsQuicTests.cs | 4 +- .../tests/FunctionalTests/QuicStreamTests.cs | 4 +- .../tests/FunctionalTests/QuicTestBase.cs | 4 +- .../tests/FtpWebRequestTest.cs | 2 +- .../Net/Security/SslApplicationProtocol.cs | 6 +-- .../NegotiateStreamLoopbackTest.cs | 2 +- .../NegotiateStreamInvalidOperationTest.cs | 2 +- .../NegotiateStreamKerberosTest.cs | 2 +- .../NegotiateStreamStreamToStreamTest.cs | 2 +- .../SslStreamAllowRenegotiationTests.cs | 4 +- .../SslStreamNetworkStreamTest.cs | 2 +- .../SslStreamStreamToStreamTest.cs | 2 +- .../tests/FunctionalTests/TestHelper.cs | 4 +- .../UnitTests/SslApplicationProtocolTests.cs | 8 +-- .../tests/FunctionalTests/TcpClientTest.cs | 4 +- .../tests/WebSocketCreateTest.cs | 4 +- .../tests/WebSocketDeflateTests.cs | 10 ++-- .../src/System/Xml/EncodingStreamWrapper.cs | 10 ++-- .../XmlWriterApi/NamespaceHandlingTests.cs | 6 +-- .../XmlNodeReaderReadTests.cs | 8 +-- .../XmlPreloadedResolverAddRemoveTests.cs | 4 +- .../XmlPreloadedResolverGetEntity.cs | 2 +- .../tests/Metadata/MetadataReaderTests.cs | 16 +++--- .../PortableExecutable/PEBinaryReaderTests.cs | 2 +- .../tests/Utilities/BlobReaderTests.cs | 2 +- .../tests/Utilities/MemoryBlockTests.cs | 12 ++--- .../tests/System/Convert.ToBase64CharArray.cs | 2 +- .../tests/System/Net/WebUtility.cs | 4 +- .../SerializationTestTypes/SampleTypes.cs | 24 ++++----- .../tests/CoseTestHelpers.cs | 2 +- .../tests/Rfc3161/TimestampRequestTests.cs | 2 +- .../tests/Rfc3161/TimestampTokenTestData.cs | 6 +-- .../tests/PublicKeyTests.cs | 10 ++-- .../tests/EncryptedXmlTest.cs | 20 +++---- .../tests/SignedXmlTest.cs | 22 ++++---- .../AppleCertificatePal.Pem.iOS.cs | 5 +- .../tests/Base64TransformsTests.cs | 4 +- .../tests/CryptoStream.cs | 2 +- .../tests/Rfc2898OneShotTests.cs | 2 +- .../tests/TripleDesTests.cs | 2 +- .../tests/Fallback.cs | 2 +- .../tests/TextEncoderTests.cs | 6 +-- .../JsonSerializer.Read.HandleMetadata.cs | 15 ++---- .../ConstructorTests.Stream.cs | 2 +- .../JsonElementWriteTests.cs | 5 +- .../JsonNode/ParseTests.cs | 2 +- .../JsonReaderStateAndOptionsTests.cs | 4 +- .../CustomObjectConverterTests.cs | 2 +- .../Serialization/Array.ReadTests.cs | 2 +- .../Serialization/Null.ReadTests.cs | 2 +- .../Serialization/ReadValueTests.cs | 24 ++++----- .../Serialization/SpanTests.cs | 3 +- .../Serialization/Stream.ReadTests.cs | 10 ++-- .../Serialization/Value.WriteTests.cs | 2 +- .../Serialization/WriteValueTests.cs | 2 +- .../Utf8JsonReaderTests.MultiSegment.cs | 6 +-- .../Utf8JsonReaderTests.ValueTextEquals.cs | 23 +++----- .../Utf8JsonReaderTests.cs | 8 +-- .../Utf8JsonWriterTests.WriteRaw.cs | 8 +-- .../Utf8JsonWriterTests.cs | 42 +++++++-------- 139 files changed, 514 insertions(+), 569 deletions(-) diff --git a/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs b/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs index f12aa873104c2..1086ffeed62a0 100644 --- a/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs +++ b/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs @@ -1855,7 +1855,7 @@ public virtual async Task Read_Eof_Returns0(ReadWriteMode mode, bool dataAvailab { write = Task.Run(async () => { - await writeable.WriteAsync(Encoding.UTF8.GetBytes("hello")); + await writeable.WriteAsync("hello"u8.ToArray()); await writeable.DisposeAsync(); }); } @@ -2206,7 +2206,7 @@ public virtual async Task ZeroByteRead_BlocksUntilDataAvailableOrNops(ReadWriteM Task write = Task.Run(async () => { - await writeable.WriteAsync(Encoding.UTF8.GetBytes("hello")); + await writeable.WriteAsync("hello"u8.ToArray()); if (FlushRequiredToWriteData) { if (FlushGuaranteesAllDataWritten) @@ -2261,7 +2261,7 @@ public virtual async Task ZeroByteRead_BlocksUntilDataAvailableOrNops(ReadWriteM [SkipOnPlatform(TestPlatforms.LinuxBionic, "SElinux blocks UNIX sockets")] public virtual async Task ZeroByteWrite_OtherDataReceivedSuccessfully(ReadWriteMode mode) { - byte[][] buffers = new[] { Array.Empty(), Encoding.UTF8.GetBytes("hello"), Array.Empty(), Encoding.UTF8.GetBytes("world") }; + byte[][] buffers = new[] { Array.Empty(), "hello"u8.ToArray(), Array.Empty(), "world"u8.ToArray() }; using StreamPair streams = await CreateConnectedStreamsAsync(); foreach ((Stream writeable, Stream readable) in GetReadWritePairs(streams)) @@ -2915,7 +2915,7 @@ public virtual async Task ZeroByteRead_PerformsZeroByteReadOnUnderlyingStreamWhe // (a) produce at least two readable bytes, so we can unblock the reader and read a single byte without clearing its buffer; and // (b) produce no more than 1K of readable bytes, so we can clear the reader buffer below. // If this isn't the case for some Stream(s), we can modify the data or parameterize it per Stream. - byte[] data = Encoding.UTF8.GetBytes("hello world"); + byte[] data = "hello world"u8.ToArray(); using StreamPair innerStreams = ConnectedStreams.CreateBidirectional(); (Stream innerWriteable, Stream innerReadable) = GetReadWritePair(innerStreams); diff --git a/src/libraries/Common/tests/System/Net/Http/Http2LoopbackConnection.cs b/src/libraries/Common/tests/System/Net/Http/Http2LoopbackConnection.cs index 2329475728c67..fbba51f0209b9 100644 --- a/src/libraries/Common/tests/System/Net/Http/Http2LoopbackConnection.cs +++ b/src/libraries/Common/tests/System/Net/Http/Http2LoopbackConnection.cs @@ -100,7 +100,7 @@ private async Task ReadPrefixAsync() // Since those tests are not set up to handle multiple retries, we instead just send back an invalid response here // so that SocketsHttpHandler will not induce retry. // The contents of what we send don't really matter, as long as it is interpreted by SocketsHttpHandler as an invalid response. - await _connectionStream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/2.0 400 Bad Request\r\n\r\n")); + await _connectionStream.WriteAsync("HTTP/2.0 400 Bad Request\r\n\r\n"u8.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. diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyFileTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyFileTests.cs index afae8f8c7a07a..980a8a9194c83 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyFileTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyFileTests.cs @@ -182,7 +182,7 @@ public static void ReadWriteDsa1024EncryptedPkcs8_PasswordBytes() qE3Db1UI4anCCnyEj/jDA8R6hZTFDjxu6bG0Z66g7I2GBDEYaaB+8x0vtiyu5LXo 6UZ53SX6S+jfIqJoF5YME9zVMoO2kwS/EGvc64+epCGcee1Nx4SGgUcr5HJYz1P4 CU+l4wPQR0rRmYHIJJIvFh5OXk84pV0crsOrekw7tHeNU6DMzw==", - Encoding.UTF8.GetBytes("Password > cipher"), + "Password > cipher"u8.ToArray(), new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyPemTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyPemTests.cs index d27137f9708b2..a00c34b0e4f9a 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyPemTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSAKeyPemTests.cs @@ -287,7 +287,7 @@ public static void ImportFromEncryptedPem_Pkcs8_Encrypted_Byte_Simple() xTL6VO9mx52x6h5WDAQAisMVeMkBoxQUWLANXiw1zSfVbsmB7mDknsRcvD3tcgMs 7YLD7LQMiPAIjDlOP8XP/w== -----END ENCRYPTED PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); + byte[] passwordBytes = "test"u8.ToArray(); dsa.ImportFromEncryptedPem(pem, passwordBytes); DSAParameters dsaParameters = dsa.ExportParameters(true); @@ -319,9 +319,8 @@ public static void ImportFromEncryptedPem_Pkcs8_Encrypted_AmbiguousPem() dVYwfovccu8ktEAwk5XAOo0r+5CCw2lDDw/hbDeO87BToC5Cc5nu3F5LxAUj8Flc v8pi3w== -----END ENCRYPTED PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); ArgumentException ae = AssertExtensions.Throws("input", () => - dsa.ImportFromEncryptedPem(pem, passwordBytes)); + dsa.ImportFromEncryptedPem(pem, "test"u8)); Assert.Contains(AmbiguousExceptionMarker, ae.Message); } } @@ -332,9 +331,8 @@ public static void ImportFromEncryptedPem_Pkcs8_Byte_NoPem() using (DSA dsa = DSAFactory.Create()) { string pem = ""; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); ArgumentException ae = AssertExtensions.Throws("input", () => - dsa.ImportFromEncryptedPem(pem, passwordBytes)); + dsa.ImportFromEncryptedPem(pem, "test"u8)); Assert.Contains(NoPemExceptionMarker, ae.Message); } } diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSATestData.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSATestData.cs index 93871baa3f222..7d6bfe307209c 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSATestData.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/DSA/DSATestData.cs @@ -171,7 +171,7 @@ internal static void GetDSA1024_186_2(out DSAParameters parameters, out byte[] s "41e2345f1f56df2458f426d155b4ba2db6dcd8c8" ).HexToByteArray(); - data = Encoding.ASCII.GetBytes("abc"); + data = "abc"u8.ToArray(); } } } diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.LimitedPrivate.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.LimitedPrivate.cs index ca0f9967c13e4..ac74a4900d58c 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.LimitedPrivate.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.LimitedPrivate.cs @@ -83,7 +83,7 @@ public void ReadNistP521EncryptedPkcs8_Pbes2_Aes128_LimitedPrivateKey_PasswordBy ReadWriteBase64EncryptedPkcs8( base64, - Encoding.UTF8.GetBytes("qwerty"), + "qwerty"u8.ToArray(), new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA1, diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs index d867f1545a919..492c9d451329c 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs @@ -195,7 +195,7 @@ public void ReadNistP521EncryptedPkcs8_Pbes2_Aes128_Sha384_PasswordBytes() ReadWriteBase64EncryptedPkcs8( base64, - Encoding.UTF8.GetBytes("qwerty"), + "qwerty"u8.ToArray(), new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA1, diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyPemTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyPemTests.cs index 3c367a4557b5a..52458f12c5695 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyPemTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyPemTests.cs @@ -342,8 +342,7 @@ public void ImportFromEncryptedPem_Pkcs8_Byte_Simple() /OMt/tWvtMSj17+dJvShsu/NYJXF5fsfpSJbd3e50Y3AisW0Ob7mmF54KBfg6Y+4 aATwwQdUIKVzUZsQctsHPjbriQKKn7GKSyUOikBUNQ+TozojX8/g7JAsl+T9jGM= -----END ENCRYPTED PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); - 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 @@ public void ImportFromEncryptedPem_AmbiguousPem_Byte() opSAJ/pvHONL5kyAJLeNyG9c/mR2qyrP2L9gL0Z5fB9NyPejKTLi0PXMGQWdDTH8 Qh0fqdrNovgFLubbJFMQN/MwwIAfIuf0Mn0WFYYeQiBJ3kg= -----END ENCRYPTED PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); ArgumentException ae = AssertExtensions.Throws("input", () => - key.ImportFromEncryptedPem(pem, passwordBytes)); + key.ImportFromEncryptedPem(pem, "test"u8)); Assert.Contains(AmbiguousExceptionMarker, ae.Message); } diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaTests.cs index 187c76ad351a9..d2b0c1a5ea49f 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaTests.cs @@ -274,8 +274,6 @@ public static IEnumerable InteroperableSignatureConfigurations() [MemberData(nameof(InteroperableSignatureConfigurations))] public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm) { - byte[] data = Encoding.UTF8.GetBytes("something to repeat and sign"); - // large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses. byte[] dataArray = new byte[33333]; diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyFileTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyFileTests.cs index a9c021ac12942..daa175dda47a9 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyFileTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyFileTests.cs @@ -781,7 +781,7 @@ public static void ReadPbes2Rc2EncryptedDiminishedDP_PasswordBytes() ReadBase64EncryptedPkcs8( base64, - Encoding.UTF8.GetBytes("rc2"), + "rc2"u8.ToArray(), new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs index 013ec21c8a65a..27438e93d36e6 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs @@ -425,7 +425,7 @@ public static void ImportFromEncryptedPem_Pkcs8Encrypted_Byte_Simple() 5QSEe7EKVF0aHXBYB5SzMGVuxR/BqydDa26jlhVzO3LNvy9FYuqLKUslCrBCmPrt raZNyk8KAsLs+FJq9T2tda0= -----END ENCRYPTED PRIVATE KEY-----"; - rsa.ImportFromEncryptedPem(pem, Encoding.UTF8.GetBytes("test")); + rsa.ImportFromEncryptedPem(pem, "test"u8); RSAParameters rsaParameters = rsa.ExportParameters(true); ImportExport.AssertKeyEquals(TestData.DiminishedDPParameters, rsaParameters); @@ -462,9 +462,8 @@ public static void ImportFromEncryptedPem_Pkcs8Encrypted_AmbiguousPem() N4lD7/hJq7b+yYPhlN3Fvvt8M9MtRg1TLAve67CA2v4TITHB06M/ELe3y42bZuLW CA7ffFk= -----END ENCRYPTED PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); ArgumentException ae = AssertExtensions.Throws("input", () => - rsa.ImportFromEncryptedPem(pem, passwordBytes)); + rsa.ImportFromEncryptedPem(pem, "test"u8)); Assert.Contains(AmbiguousExceptionMarker, ae.Message); } } @@ -475,9 +474,8 @@ public static void ImportFromEncryptedPem_Pkcs8Encrypted_Byte_NoPem() using (RSA rsa = RSAFactory.Create()) { string pem = "these aren't the PEMs we're looking for."; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); ArgumentException ae = AssertExtensions.Throws("input", () => - rsa.ImportFromEncryptedPem(pem, passwordBytes)); + rsa.ImportFromEncryptedPem(pem, "test"u8)); Assert.Contains(NoPemExceptionMarker, ae.Message); } } @@ -498,9 +496,8 @@ public static void ImportFromEncryptedPem_NoEncryptedPem() acPiMCuFTnRSFYAhozpmsqoLyTREqwIhAMLJlZTGjEB2N+sEazH5ToEczQzKqp7t 9juGNbOPhoEL -----END PRIVATE KEY-----"; - byte[] passwordBytes = Encoding.UTF8.GetBytes("test"); ArgumentException ae = AssertExtensions.Throws("input", () => - rsa.ImportFromEncryptedPem(pem, passwordBytes)); + rsa.ImportFromEncryptedPem(pem, "test"u8)); Assert.Contains(NoPemExceptionMarker, ae.Message); } } diff --git a/src/libraries/Common/tests/Tests/System/StringTests.cs b/src/libraries/Common/tests/Tests/System/StringTests.cs index 0d6281922dd6e..80796525da000 100644 --- a/src/libraries/Common/tests/Tests/System/StringTests.cs +++ b/src/libraries/Common/tests/Tests/System/StringTests.cs @@ -7288,8 +7288,7 @@ public static unsafe void Ctor_SByte_NullPointer_ReturnsEmptyString() [Fact] public static void CreateStringFromEncoding_0Length_EmptyStringReturned() // basic test for code coverage; more tests in encodings tests { - byte[] bytes = Encoding.ASCII.GetBytes("hello"); - 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 diff --git a/src/libraries/System.Diagnostics.Process/tests/RemotelyInvokable.cs b/src/libraries/System.Diagnostics.Process/tests/RemotelyInvokable.cs index 7d7fa6657c08d..cab760465132a 100644 --- a/src/libraries/System.Diagnostics.Process/tests/RemotelyInvokable.cs +++ b/src/libraries/System.Diagnostics.Process/tests/RemotelyInvokable.cs @@ -99,7 +99,7 @@ public static int ReadLineWithCustomEncodingWriteLineWithUtf8(string inputEncodi public static int WriteSlowlyByByte() { var stdout = Console.OpenStandardOutput(); - var bytes = new byte[] { 97, 0 }; //Encoding.Unicode.GetBytes("a"); + var bytes = "a\0"u8.ToArray(); for (int i = 0; i != bytes.Length; ++i) { diff --git a/src/libraries/System.DirectoryServices.Protocols/tests/DirectoryServicesProtocolsTests.cs b/src/libraries/System.DirectoryServices.Protocols/tests/DirectoryServicesProtocolsTests.cs index 39f7c9b16055b..229b6117da1b2 100644 --- a/src/libraries/System.DirectoryServices.Protocols/tests/DirectoryServicesProtocolsTests.cs +++ b/src/libraries/System.DirectoryServices.Protocols/tests/DirectoryServicesProtocolsTests.cs @@ -479,18 +479,18 @@ private static void RunAsyncSearch(IAsyncResult asyncResult) public static IEnumerable TestCompareRequestTheory_TestData() { yield return new object[] { "input", "input", ResultCode.CompareTrue }; - yield return new object[] { "input", Encoding.UTF8.GetBytes("input"), ResultCode.CompareTrue }; + yield return new object[] { "input", "input"u8.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))] diff --git a/src/libraries/System.Drawing.Common/tests/ImageTests.cs b/src/libraries/System.Drawing.Common/tests/ImageTests.cs index cfd315a96cdb0..e1b8512835f20 100644 --- a/src/libraries/System.Drawing.Common/tests/ImageTests.cs +++ b/src/libraries/System.Drawing.Common/tests/ImageTests.cs @@ -238,7 +238,7 @@ public void SetPropertyItem_InvokeMemoryBitmap_Success(int propid) // Change data. PropertyItem item = source.GetPropertyItem(PropertyTagExifUserComment); - item.Value = Encoding.ASCII.GetBytes("Hello World\0"); + item.Value = "Hello World\0"u8.ToArray(); item.Len = item.Value.Length; bitmap.SetPropertyItem(item); @@ -253,7 +253,7 @@ public void SetPropertyItem_InvokeMemoryBitmap_Success(int propid) // New data. item.Id = propid; - item.Value = Encoding.ASCII.GetBytes("New Value\0"); + item.Value = "New Value\0"u8.ToArray(); item.Len = item.Value.Length; bitmap.SetPropertyItem(item); @@ -296,7 +296,7 @@ public void SetPropertyItem_InvokeBitmapJpg_Success(int propid) // Change data. PropertyItem item = bitmap.GetPropertyItem(PropertyTagExifUserComment); - item.Value = Encoding.ASCII.GetBytes("Hello World\0"); + item.Value = "Hello World\0"u8.ToArray(); item.Len = item.Value.Length; bitmap.SetPropertyItem(item); @@ -339,7 +339,7 @@ public void SetPropertyItem_InvokeBitmapJpg_Success(int propid) // New data. item.Id = propid; - item.Value = Encoding.ASCII.GetBytes("New Value\0"); + item.Value = "New Value\0"u8.ToArray(); item.Len = item.Value.Length; bitmap.SetPropertyItem(item); @@ -439,7 +439,7 @@ public void SetPropertyItem_InvokeBitmapBmp_Success(int propid) // Change data. PropertyItem item = source.GetPropertyItem(PropertyTagExifUserComment); - item.Value = Encoding.ASCII.GetBytes("Hello World\0"); + item.Value = "Hello World\0"u8.ToArray(); item.Len = item.Value.Length; bitmap.SetPropertyItem(item); @@ -454,7 +454,7 @@ public void SetPropertyItem_InvokeBitmapBmp_Success(int propid) // New data. item.Id = propid; - item.Value = Encoding.ASCII.GetBytes("New Value\0"); + item.Value = "New Value\0"u8.ToArray(); item.Len = item.Value.Length; bitmap.SetPropertyItem(item); diff --git a/src/libraries/System.Formats.Asn1/tests/Reader/ReadGeneralizedTime.cs b/src/libraries/System.Formats.Asn1/tests/Reader/ReadGeneralizedTime.cs index 6583a7d393623..cdd3437a0070f 100644 --- a/src/libraries/System.Formats.Asn1/tests/Reader/ReadGeneralizedTime.cs +++ b/src/libraries/System.Formats.Asn1/tests/Reader/ReadGeneralizedTime.cs @@ -229,7 +229,7 @@ public static void MaximumEffectivePrecision(AsnEncodingRules ruleSet, string da [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 @@ public static void ExcessivelyPreciseFraction() [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 @@ public static void MultiSegmentExcessivelyPreciseFraction(AsnEncodingRules ruleS [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 @@ public static void ExcessivelyPreciseFraction_OneTenthPlusEpsilonAndZero() [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(() => berReader.ReadGeneralizedTime()); diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs index 0c2cf88c9c7e8..227f45af6584e 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs @@ -12,11 +12,11 @@ namespace System.Formats.Tar // Writes header attributes of a tar archive entry. internal partial struct TarHeader { - private static ReadOnlySpan PaxMagicBytes => new byte[] { 0x75, 0x73, 0x74, 0x61, 0x72, 0x0 }; // "ustar\0" - private static ReadOnlySpan PaxVersionBytes => new byte[] { TarHelpers.ZeroChar, TarHelpers.ZeroChar }; // "00" + private static ReadOnlySpan PaxMagicBytes => "ustar\0"u8; + private static ReadOnlySpan PaxVersionBytes => "00"u8; - private static ReadOnlySpan GnuMagicBytes => new byte[] { 0x75, 0x73, 0x74, 0x61, 0x72, TarHelpers.SpaceChar }; // "ustar " - private static ReadOnlySpan GnuVersionBytes => new byte[] { TarHelpers.SpaceChar, 0x0 }; // " \0" + private static ReadOnlySpan GnuMagicBytes => "ustar "u8; + private static ReadOnlySpan GnuVersionBytes => " \0"u8; // Extended Attribute entries have a special format in the Name field: // "{dirName}/PaxHeaders.{processId}/{fileName}{trailingSeparator}" diff --git a/src/libraries/System.IO.Compression.ZipFile/tests/ZipFile.Unix.cs b/src/libraries/System.IO.Compression.ZipFile/tests/ZipFile.Unix.cs index e13fec3d93565..91b6b4baf5e32 100644 --- a/src/libraries/System.IO.Compression.ZipFile/tests/ZipFile.Unix.cs +++ b/src/libraries/System.IO.Compression.ZipFile/tests/ZipFile.Unix.cs @@ -61,7 +61,6 @@ public void UnixExtractSetsFilePermissionsFromExternalAttributes() { // '7600' tests that S_ISUID, S_ISGID, and S_ISVTX bits don't get extracted to file permissions string[] testPermissions = new[] { "777", "755", "644", "754", "7600" }; - byte[] contents = Encoding.UTF8.GetBytes("contents"); string archivePath = GetTestFilePath(); using (FileStream fileStream = new FileStream(archivePath, FileMode.CreateNew)) @@ -72,7 +71,7 @@ public void UnixExtractSetsFilePermissionsFromExternalAttributes() 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(); } } diff --git a/src/libraries/System.IO.Compression/tests/ZipArchive/zip_UpdateTests.cs b/src/libraries/System.IO.Compression/tests/ZipArchive/zip_UpdateTests.cs index 637d04500d77a..93adafa337fbe 100644 --- a/src/libraries/System.IO.Compression/tests/ZipArchive/zip_UpdateTests.cs +++ b/src/libraries/System.IO.Compression/tests/ZipArchive/zip_UpdateTests.cs @@ -169,14 +169,14 @@ public static async Task AppendToEntry(bool writeWithSpans) { s.Seek(0, SeekOrigin.End); - byte[] data = Encoding.ASCII.GetBytes("\r\n\r\nThe answer my friend, is blowin' in the wind."); + byte[] data = "\r\n\r\nThe answer my friend, is blowin' in the wind."u8.ToArray(); if (writeWithSpans) { - s.Write(data, 0, data.Length); + s.Write(new ReadOnlySpan(data)); } else { - s.Write(new ReadOnlySpan(data)); + s.Write(data, 0, data.Length); } } diff --git a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs index 69c2c7208f407..bcb3de4825c73 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs @@ -97,11 +97,11 @@ public void WriteToReadOnlyFile() // Operation succeeds when being run by the Unix superuser if (PlatformDetection.IsSuperUser) { - File.WriteAllBytes(path, Encoding.UTF8.GetBytes("text")); - Assert.Equal(Encoding.UTF8.GetBytes("text"), File.ReadAllBytes(path)); + File.WriteAllBytes(path, "text"u8.ToArray()); + Assert.Equal("text"u8.ToArray(), File.ReadAllBytes(path)); } else - Assert.Throws(() => File.WriteAllBytes(path, Encoding.UTF8.GetBytes("text"))); + Assert.Throws(() => File.WriteAllBytes(path, "text"u8.ToArray())); } finally { diff --git a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs index 3ab0df3700484..2c6df24b702f0 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs @@ -108,11 +108,11 @@ public async Task WriteToReadOnlyFileAsync() // Operation succeeds when being run by the Unix superuser if (PlatformDetection.IsSuperUser) { - await File.WriteAllBytesAsync(path, Encoding.UTF8.GetBytes("text")); - Assert.Equal(Encoding.UTF8.GetBytes("text"), await File.ReadAllBytesAsync(path)); + await File.WriteAllBytesAsync(path, "text"u8.ToArray()); + Assert.Equal("text"u8.ToArray(), await File.ReadAllBytesAsync(path)); } else - await Assert.ThrowsAsync(async () => await File.WriteAllBytesAsync(path, Encoding.UTF8.GetBytes("text"))); + await Assert.ThrowsAsync(async () => await File.WriteAllBytesAsync(path, "text"u8.ToArray())); } finally { diff --git a/src/libraries/System.IO.FileSystem/tests/FileStream/DevicesPipesAndSockets.cs b/src/libraries/System.IO.FileSystem/tests/FileStream/DevicesPipesAndSockets.cs index 04d04aadaa5f2..86a4901b344ce 100644 --- a/src/libraries/System.IO.FileSystem/tests/FileStream/DevicesPipesAndSockets.cs +++ b/src/libraries/System.IO.FileSystem/tests/FileStream/DevicesPipesAndSockets.cs @@ -21,7 +21,7 @@ public void CharacterDevice_FileStream_Write(string devicePath, FileOptions file { FileStreamOptions options = new() { Options = fileOptions, Access = FileAccess.Write, Share = FileShare.Write }; using FileStream fs = new(devicePath, options); - fs.Write(Encoding.UTF8.GetBytes("foo")); + fs.Write("foo"u8); } [Theory] @@ -30,21 +30,21 @@ public async Task CharacterDevice_FileStream_WriteAsync(string devicePath, FileO { FileStreamOptions options = new() { Options = fileOptions, Access = FileAccess.Write, Share = FileShare.Write }; using FileStream fs = new(devicePath, options); - await fs.WriteAsync(Encoding.UTF8.GetBytes("foo")); + await fs.WriteAsync("foo"u8.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] diff --git a/src/libraries/System.IO.FileSystem/tests/FileStream/ctor_str_fm.cs b/src/libraries/System.IO.FileSystem/tests/FileStream/ctor_str_fm.cs index cd3b18da03422..44cafb53a891c 100644 --- a/src/libraries/System.IO.FileSystem/tests/FileStream/ctor_str_fm.cs +++ b/src/libraries/System.IO.FileSystem/tests/FileStream/ctor_str_fm.cs @@ -218,12 +218,12 @@ public virtual void FileModeAppend(string streamSpecifier) Assert.False(fs.CanRead); Assert.True(fs.CanWrite); - fs.Write(Encoding.ASCII.GetBytes("abcde")); + fs.Write("abcde"u8); Assert.Equal(5, fs.Length); Assert.Equal(5, fs.Position); Assert.Equal(1, fs.Seek(1, SeekOrigin.Begin)); - fs.Write(Encoding.ASCII.GetBytes("xyz")); + fs.Write("xyz"u8); Assert.Equal(4, fs.Position); Assert.Equal(5, fs.Length); } @@ -257,12 +257,12 @@ public virtual void FileModeAppendExisting(string streamSpecifier) Assert.Throws(() => fs.Seek(0, SeekOrigin.Begin)); Assert.Throws(() => fs.ReadByte()); - fs.Write(Encoding.ASCII.GetBytes("abcde")); + fs.Write("abcde"u8); Assert.Equal(position + 5, fs.Position); Assert.Equal(position, fs.Seek(position, SeekOrigin.Begin)); Assert.Equal(position + 1, fs.Seek(1, SeekOrigin.Current)); - fs.Write(Encoding.ASCII.GetBytes("xyz")); + fs.Write("xyz"u8); } Assert.Equal(initialContents + "axyze", File.ReadAllText(fileName)); diff --git a/src/libraries/System.IO.Hashing/tests/Crc32Tests.cs b/src/libraries/System.IO.Hashing/tests/Crc32Tests.cs index 6d2993f1509e4..0761450fb9a53 100644 --- a/src/libraries/System.IO.Hashing/tests/Crc32Tests.cs +++ b/src/libraries/System.IO.Hashing/tests/Crc32Tests.cs @@ -51,7 +51,7 @@ public static IEnumerable TestCases "FFFFFFFF"), new TestCase( "Self-test 123456789", - Encoding.ASCII.GetBytes("123456789"), + "123456789"u8.ToArray(), "2639F4CB"), new TestCase( "Self-test residue", @@ -63,7 +63,7 @@ public static IEnumerable TestCases "FFFFFFFF"), new TestCase( "The quick brown fox jumps over the lazy dog", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"), + "The quick brown fox jumps over the lazy dog"u8.ToArray(), "39A34F41"), }; diff --git a/src/libraries/System.IO.Hashing/tests/Crc64Tests.cs b/src/libraries/System.IO.Hashing/tests/Crc64Tests.cs index d647e4b958798..52971f0c9777a 100644 --- a/src/libraries/System.IO.Hashing/tests/Crc64Tests.cs +++ b/src/libraries/System.IO.Hashing/tests/Crc64Tests.cs @@ -59,7 +59,7 @@ public static IEnumerable TestCases "0000000000000000"), new TestCase( "Self-test 123456789", - Encoding.ASCII.GetBytes("123456789"), + "123456789"u8.ToArray(), "6C40DF5F0B497347"), new TestCase( "Self-test residue", @@ -67,7 +67,7 @@ public static IEnumerable TestCases "0000000000000000"), new TestCase( "The quick brown fox jumps over the lazy dog", - Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"), + "The quick brown fox jumps over the lazy dog"u8.ToArray(), "41E05242FFA9883B"), }; diff --git a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.007.cs b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.007.cs index 9ec9262dd1c5d..db17893ccca23 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.007.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.007.cs @@ -45,19 +45,19 @@ public static IEnumerable TestCases // Same inputs as the main XxHash32 tests, but with the seed applied. new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8.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", diff --git a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.cs b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.cs index abd77d8c22f97..9c6bad45f8d47 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.cs @@ -43,17 +43,17 @@ public static IEnumerable TestCases //https://asecuritysite.com/encryption/xxHash, Example 1 new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8.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 @@ public static IEnumerable TestCases // The "in three pieces" test causes this to build up in the accumulator every time. new TestCase( "abc", - Encoding.ASCII.GetBytes("abc"), + "abc"u8.ToArray(), "32D153FF"), // Accumulates every time. new TestCase( diff --git a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.f00d.cs b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.f00d.cs index 4a116bc50354e..edf94fb5cc416 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash32Tests.f00d.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash32Tests.f00d.cs @@ -45,19 +45,19 @@ public static IEnumerable TestCases // Same inputs as the main XxHash32 tests, but with the seed applied. new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8.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", diff --git a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.007.cs b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.007.cs index 836b29230f3e6..6c902b8352da6 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.007.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.007.cs @@ -47,19 +47,19 @@ public static IEnumerable TestCases // Same inputs as the main XxHash64 tests, but with the seed applied. new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8.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", diff --git a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.cs b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.cs index 213e6f91c252c..10485ba584ed8 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.cs @@ -45,17 +45,17 @@ public static IEnumerable TestCases //https://asecuritysite.com/encryption/xxHash, Example 1 new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8.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 @@ public static IEnumerable TestCases // The "in three pieces" test causes this to build up in the accumulator every time. new TestCase( "abc", - Encoding.ASCII.GetBytes("abc"), + "abc"u8.ToArray(), "44BC2CF5AD770999"), // Accumulates every time. new TestCase( diff --git a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.f00d.cs b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.f00d.cs index 75fc4f514aca9..283f1922d1d29 100644 --- a/src/libraries/System.IO.Hashing/tests/XxHash64Tests.f00d.cs +++ b/src/libraries/System.IO.Hashing/tests/XxHash64Tests.f00d.cs @@ -47,19 +47,19 @@ public static IEnumerable TestCases // Same inputs as the main XxHash64 tests, but with the seed applied. new TestCase( "Nobody inspects the spammish repetition", - Encoding.ASCII.GetBytes("Nobody inspects the spammish repetition"), + "Nobody inspects the spammish repetition"u8.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", diff --git a/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs b/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs index adf547a3c452b..0d1700aeb9bd2 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs @@ -43,9 +43,9 @@ public async Task CopyToAsyncStreamWorks() { var messages = new List() { - Encoding.UTF8.GetBytes("Hello World1"), - Encoding.UTF8.GetBytes("Hello World2"), - Encoding.UTF8.GetBytes("Hello World3"), + "Hello World1"u8.ToArray(), + "Hello World2"u8.ToArray(), + "Hello World3"u8.ToArray(), }; var stream = new WriteCheckMemoryStream(); @@ -67,9 +67,9 @@ public async Task CopyToAsyncPipeWriterWorks() { var messages = new List() { - Encoding.UTF8.GetBytes("Hello World1"), - Encoding.UTF8.GetBytes("Hello World2"), - Encoding.UTF8.GetBytes("Hello World3"), + "Hello World1"u8.ToArray(), + "Hello World2"u8.ToArray(), + "Hello World3"u8.ToArray(), }; var targetPipe = new Pipe(s_testOptions); @@ -199,7 +199,7 @@ public async Task CancelingPipeWriterViaCancellationTokenThrowsOperationCancelle // This should make the write call pause var targetPipe = new Pipe(new PipeOptions(pauseWriterThreshold: 1, resumeWriterThreshold: 1)); var cts = new CancellationTokenSource(); - await Pipe.Writer.WriteAsync(Encoding.ASCII.GetBytes("Gello World")); + await Pipe.Writer.WriteAsync("Gello World"u8.ToArray()); Task task = PipeReader.CopyToAsync(targetPipe.Writer, cts.Token); cts.Cancel(); @@ -212,7 +212,7 @@ public async Task CancelingPipeWriterViaPendingFlushThrowsOperationCancelledExce { // This should make the write call pause var targetPipe = new Pipe(new PipeOptions(pauseWriterThreshold: 1, resumeWriterThreshold: 1)); - await Pipe.Writer.WriteAsync(Encoding.ASCII.GetBytes("Gello World")); + await Pipe.Writer.WriteAsync("Gello World"u8.ToArray()); Task task = PipeReader.CopyToAsync(targetPipe.Writer); targetPipe.Writer.CancelPendingFlush(); @@ -290,7 +290,7 @@ public async Task ThrowingFromStreamCallsAdvanceToWithStartOfLastReadResult(int [Fact] public async Task CopyToAsyncStreamCopiesRemainderAfterReadingSome() { - var buffer = Encoding.UTF8.GetBytes("Hello World"); + var buffer = "Hello World"u8.ToArray(); await Pipe.Writer.WriteAsync(buffer); Pipe.Writer.Complete(); @@ -308,7 +308,7 @@ public async Task CopyToAsyncStreamCopiesRemainderAfterReadingSome() [Fact] public async Task CopyToAsyncPipeWriterCopiesRemainderAfterReadingSome() { - var buffer = Encoding.UTF8.GetBytes("Hello World"); + var buffer = "Hello World"u8.ToArray(); await Pipe.Writer.WriteAsync(buffer); Pipe.Writer.Complete(); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeReaderReadAtLeastAsyncTests.cs b/src/libraries/System.IO.Pipelines/tests/PipeReaderReadAtLeastAsyncTests.cs index 64762de5ec8ce..9a76f91cb761d 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeReaderReadAtLeastAsyncTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeReaderReadAtLeastAsyncTests.cs @@ -31,7 +31,7 @@ protected virtual void SetPipeReaderOptions(MemoryPool? pool = null, int b [Fact] public async Task CanWriteAndReadAtLeast() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); await Pipe.Writer.WriteAsync(bytes); ReadResult result = await PipeReader.ReadAtLeastAsync(11); @@ -46,7 +46,7 @@ public async Task CanWriteAndReadAtLeast() [Fact] public async Task ReadAtLeastShouldNotCompleteIfWriterWroteLessThanMinimum() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); await Pipe.Writer.WriteAsync(bytes.AsMemory(0, 5)); ValueTask task = PipeReader.ReadAtLeastAsync(11); @@ -68,7 +68,7 @@ public async Task ReadAtLeastShouldNotCompleteIfWriterWroteLessThanMinimum() [Fact] public async Task CanAlternateReadAtLeastAndRead() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); await Pipe.Writer.WriteAsync(bytes.AsMemory(0, 5)); ReadResult result = await PipeReader.ReadAtLeastAsync(3); @@ -113,7 +113,7 @@ public async Task ReadAtLeastReturnsIfCompleted() public async Task CanReadAtLeast(int bufferSize, bool bufferedRead) { SetPipeReaderOptions(bufferSize: bufferSize); - await Pipe.Writer.WriteAsync(Encoding.ASCII.GetBytes("Hello Pipelines World")); + await Pipe.Writer.WriteAsync("Hello Pipelines World"u8.ToArray()); if (bufferedRead) { @@ -148,7 +148,7 @@ public Task ReadAtLeastAsyncThrowsIfPassedCanceledCancellationToken() [Fact] public async Task WriteAndCancellingPendingReadBeforeReadAtLeastAsync() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); PipeWriter output = Pipe.Writer; output.Write(bytes); await output.FlushAsync(); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeReaderStreamTests.nonnetstandard.cs b/src/libraries/System.IO.Pipelines/tests/PipeReaderStreamTests.nonnetstandard.cs index 0e8398188c085..803c101da2447 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeReaderStreamTests.nonnetstandard.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeReaderStreamTests.nonnetstandard.cs @@ -55,7 +55,7 @@ public async Task DisposingPipeReaderStreamCompletesPipeReader(bool dataInPipe) [MemberData(nameof(ReadCalls))] public async Task ReadingFromPipeReaderStreamReadsFromUnderlyingPipeReader(ReadAsyncDelegate readAsync) { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(); await pipe.Writer.WriteAsync(helloBytes); pipe.Writer.Complete(); @@ -73,7 +73,7 @@ public async Task ReadingFromPipeReaderStreamReadsFromUnderlyingPipeReader(ReadA [MemberData(nameof(ReadCalls))] public async Task AsStreamReturnsPipeReaderStream(ReadAsyncDelegate readAsync) { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(); await pipe.Writer.WriteAsync(helloBytes); pipe.Writer.Complete(); @@ -90,7 +90,7 @@ public async Task AsStreamReturnsPipeReaderStream(ReadAsyncDelegate readAsync) [Fact] public async Task ReadingWithSmallerBufferWorks() { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(); await pipe.Writer.WriteAsync(helloBytes); pipe.Writer.Complete(); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs b/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs index 1a325e466a7ab..c5cd74d8469e5 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs @@ -34,7 +34,7 @@ public void Dispose() [Fact] public async Task CanReadAndWrite() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); await _pipe.Writer.WriteAsync(bytes); ReadResult result = await _pipe.Reader.ReadAsync(); @@ -170,7 +170,7 @@ public async Task HelloWorldAcrossTwoBlocks() var blockSize = _pipe.Writer.GetMemory().Length; byte[] paddingBytes = Enumerable.Repeat((byte)'a', blockSize - 5).ToArray(); - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); writeBuffer.Write(paddingBytes); writeBuffer.Write(bytes); @@ -338,7 +338,7 @@ public async Task ReaderShouldNotGetUnflushedBytesWithAppend() await buffer.FlushAsync(); // Write Hello to another pipeline and get the buffer - byte[] bytes = Encoding.ASCII.GetBytes("Hello"); + byte[] bytes = "Hello"u8.ToArray(); var c2 = new Pipe(new PipeOptions(_pool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline)); await c2.Writer.WriteAsync(bytes); @@ -516,7 +516,7 @@ await Assert.ThrowsAsync( public async Task SyncReadThenAsyncRead() { PipeWriter buffer = _pipe.Writer; - buffer.Write(Encoding.ASCII.GetBytes("Hello World")); + buffer.Write("Hello World"u8.ToArray()); await buffer.FlushAsync(); bool gotData = _pipe.Reader.TryRead(out ReadResult result); @@ -601,7 +601,7 @@ public void WhenTryReadReturnsFalseDontNeedToCallAdvance() [Fact] public async Task WritingDataMakesDataReadableViaPipeline() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); await _pipe.Writer.WriteAsync(bytes); ReadResult result = await _pipe.Reader.ReadAsync(); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs b/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs index 4d9fb17b9ea64..e36c938cd2e87 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs @@ -40,7 +40,7 @@ public async Task CopyToAsyncThrowsTaskCanceledExceptionForAlreadyCancelledToken [Fact] public async Task CopyToAsyncWorks() { - var helloBytes = Encoding.UTF8.GetBytes("Hello World"); + var helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(); var stream = new MemoryStream(helloBytes); @@ -79,7 +79,7 @@ public async Task CopyToAsyncCalledMultipleTimesWorks() [Fact] public async Task StreamCopyToAsyncWorks() { - var helloBytes = Encoding.UTF8.GetBytes("Hello World"); + var helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(); var stream = new MemoryStream(helloBytes); @@ -96,7 +96,7 @@ public async Task StreamCopyToAsyncWorks() [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task CancelingViaCancelPendingFlushThrows() { - var helloBytes = Encoding.UTF8.GetBytes("Hello World"); + var helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: helloBytes.Length - 1, resumeWriterThreshold: 0)); var stream = new MemoryStream(helloBytes); @@ -115,7 +115,7 @@ public async Task CancelingViaCancelPendingFlushThrows() [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task CancelingViaCancellationTokenThrows() { - var helloBytes = Encoding.UTF8.GetBytes("Hello World"); + var helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: helloBytes.Length - 1, resumeWriterThreshold: 0)); var stream = new MemoryStream(helloBytes); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeWriterStreamTests.nonnetstandard.cs b/src/libraries/System.IO.Pipelines/tests/PipeWriterStreamTests.nonnetstandard.cs index 57f6f8ee1e2ee..c7df5657c5d37 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeWriterStreamTests.nonnetstandard.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeWriterStreamTests.nonnetstandard.cs @@ -49,7 +49,7 @@ public async Task DisposingPipeWriterStreamCompletesPipeWriter() [MemberData(nameof(WriteCalls))] public async Task WritingToPipeStreamWritesToUnderlyingPipeWriter(WriteAsyncDelegate writeAsync) { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(); var stream = new PipeWriterStream(pipe.Writer, leaveOpen: false); @@ -65,7 +65,7 @@ public async Task WritingToPipeStreamWritesToUnderlyingPipeWriter(WriteAsyncDele [MemberData(nameof(WriteCalls))] public async Task AsStreamReturnsPipeWriterStream(WriteAsyncDelegate writeAsync) { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(); Stream stream = pipe.Writer.AsStream(); @@ -80,7 +80,7 @@ public async Task AsStreamReturnsPipeWriterStream(WriteAsyncDelegate writeAsync) [Fact] public async Task FlushAsyncFlushesBufferedData() { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(); Memory memory = pipe.Writer.GetMemory(); @@ -99,7 +99,7 @@ public async Task FlushAsyncFlushesBufferedData() [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 @@ public async Task ReadingFromPipeWriterStreamThrowsNotSupported() public async Task CancellingPendingFlushThrowsOperationCancelledException() { var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: 10, resumeWriterThreshold: 0)); - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8.ToArray(); Stream stream = pipe.Writer.AsStream(); ValueTask task = stream.WriteAsync(helloBytes); @@ -139,7 +139,7 @@ public async Task CancellingPendingFlushThrowsOperationCancelledException() public async Task CancellationTokenFlowsToUnderlyingPipeWriter() { var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: 10, resumeWriterThreshold: 0)); - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] helloBytes = "Hello World"u8.ToArray(); Stream stream = pipe.Writer.AsStream(); var cts = new CancellationTokenSource(); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs b/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs index d7edb408ec3a3..584cdd96a6318 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs @@ -185,7 +185,7 @@ public void ThrowsOnAdvanceWithNoMemory() [Fact] public async Task WritesUsingGetSpanWorks() { - var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz"); + var bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1)); PipeWriter writer = pipe.Writer; @@ -208,7 +208,7 @@ public async Task WritesUsingGetSpanWorks() [Fact] public async Task WritesUsingGetMemoryWorks() { - var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz"); + var bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1)); PipeWriter writer = pipe.Writer; diff --git a/src/libraries/System.IO.Pipelines/tests/ReadAsyncCancellationTests.cs b/src/libraries/System.IO.Pipelines/tests/ReadAsyncCancellationTests.cs index 8422de3073584..fb17873b6a1c5 100644 --- a/src/libraries/System.IO.Pipelines/tests/ReadAsyncCancellationTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/ReadAsyncCancellationTests.cs @@ -32,7 +32,7 @@ public async Task AdvanceShouldResetStateIfReadCanceled() [Fact] public async Task CancellingBeforeAdvance() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); PipeWriter output = Pipe.Writer; output.Write(bytes); await output.FlushAsync(); @@ -65,7 +65,7 @@ public async Task CancellingBeforeAdvance() [Fact] public async Task CancellingPendingAfterReadAsync() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); PipeWriter output = Pipe.Writer; output.Write(bytes); @@ -116,7 +116,7 @@ public async Task CancellingPendingReadBeforeReadAsync() Assert.True(result.IsCanceled); Assert.True(buffer.IsEmpty); - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); PipeWriter output = Pipe.Writer; output.Write(bytes); await output.FlushAsync(); @@ -407,7 +407,7 @@ await Assert.ThrowsAsync( [Fact] public async Task WriteAndCancellingPendingReadBeforeReadAsync() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); PipeWriter output = Pipe.Writer; output.Write(bytes); await output.FlushAsync(); diff --git a/src/libraries/System.IO.Pipelines/tests/SchedulerFacts.cs b/src/libraries/System.IO.Pipelines/tests/SchedulerFacts.cs index 000c908639f6c..ba558339b0a05 100644 --- a/src/libraries/System.IO.Pipelines/tests/SchedulerFacts.cs +++ b/src/libraries/System.IO.Pipelines/tests/SchedulerFacts.cs @@ -68,7 +68,7 @@ public async Task UseSynchronizationContextFalseIgnoresSyncContextForReaderSched Task reading = doRead(); PipeWriter buffer = pipe.Writer; - buffer.Write(Encoding.UTF8.GetBytes("Hello World")); + buffer.Write("Hello World"u8.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 @@ public async Task DefaultReaderSchedulerRunsOnSynchronizationContext() 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 @@ public async Task DefaultReaderSchedulerIgnoresSyncContextIfConfigureAwaitFalse( 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 @@ public async Task DefaultReaderSchedulerRunsOnThreadPool() 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 @@ public async Task ReadAsyncCallbackRunsOnReaderScheduler() 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 @@ async Task DoRead() null); #pragma warning restore CS0618 // Type or member is obsolete - buffer.Write(Encoding.UTF8.GetBytes("Hello World")); + buffer.Write("Hello World"u8.ToArray()); await buffer.FlushAsync(); await reading; diff --git a/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs b/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs index d12e4f1ec8470..dd1b0bf8e8c7b 100644 --- a/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs @@ -16,7 +16,7 @@ public class SequencePipeReaderTests [Fact] public async Task CanRead() { - var sequence = new ReadOnlySequence(Encoding.ASCII.GetBytes("Hello World")); + var sequence = new ReadOnlySequence("Hello World"u8.ToArray()); var reader = PipeReader.Create(sequence); ReadResult readResult = await reader.ReadAsync(); @@ -33,7 +33,7 @@ public async Task CanRead() [Fact] public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything() { - var sequence = new ReadOnlySequence(Encoding.ASCII.GetBytes("Hello World")); + var sequence = new ReadOnlySequence("Hello World"u8.ToArray()); var reader = PipeReader.Create(sequence); ReadResult readResult = await reader.ReadAsync(); @@ -53,7 +53,7 @@ public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything() [Fact] public async Task TryReadReturnsFalseIfBufferedBytesAndEverythingExamined() { - var sequence = new ReadOnlySequence(Encoding.ASCII.GetBytes("Hello World")); + var sequence = new ReadOnlySequence("Hello World"u8.ToArray()); var reader = PipeReader.Create(sequence); ReadResult readResult = await reader.ReadAsync(); @@ -86,7 +86,7 @@ public async Task ReadAsyncAfterReceivingCompletedReadResultDoesNotThrow() [Fact] public async Task DataCanBeReadMultipleTimes() { - var helloBytes = Encoding.ASCII.GetBytes("Hello World"); + var helloBytes = "Hello World"u8.ToArray(); var sequence = new ReadOnlySequence(helloBytes); PipeReader reader = PipeReader.Create(sequence); diff --git a/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs b/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs index b86151a961718..7bcf9bd8a983d 100644 --- a/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs @@ -17,7 +17,7 @@ public class StreamPipeReaderTests [Fact] public async Task CanRead() { - var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World")); + var stream = new MemoryStream("Hello World"u8.ToArray()); var reader = PipeReader.Create(stream); ReadResult readResult = await reader.ReadAsync(); @@ -34,7 +34,7 @@ public async Task CanRead() [Fact] public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything() { - var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World")); + var stream = new MemoryStream("Hello World"u8.ToArray()); var reader = PipeReader.Create(stream); ReadResult readResult = await reader.ReadAsync(); @@ -54,7 +54,7 @@ public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything() [Fact] public async Task TryReadReturnsFalseIfBufferedBytesAndEverythingExamined() { - var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World")); + var stream = new MemoryStream("Hello World"u8.ToArray()); var reader = PipeReader.Create(stream); ReadResult readResult = await reader.ReadAsync(); @@ -168,7 +168,7 @@ public async Task ReadAsyncAfterReceivingCompletedReadResultDoesNotThrow() [Fact] public async Task BufferingDataPastEndOfStreamCanBeReadAgain() { - var helloBytes = Encoding.ASCII.GetBytes("Hello World"); + var helloBytes = "Hello World"u8.ToArray(); var stream = new ThrowAfterZeroByteReadStream(helloBytes); PipeReader reader = PipeReader.Create(stream); diff --git a/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs b/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs index 4bd99672c49ac..e767f87c0eca8 100644 --- a/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs @@ -16,7 +16,7 @@ public class StreamPipeWriterTests [Fact] public void NothingWrittenToStreamUnlessFlushed() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream); @@ -33,7 +33,7 @@ public void NothingWrittenToStreamUnlessFlushed() [Fact] public void DataFlushedOnComplete() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true)); @@ -52,7 +52,7 @@ public void DataFlushedOnComplete() [Fact] public async Task DataFlushedOnCompleteAsync() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true)); @@ -71,7 +71,7 @@ public async Task DataFlushedOnCompleteAsync() [Fact] public void DataNotFlushedOnCompleteWithException() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true)); @@ -88,7 +88,7 @@ public void DataNotFlushedOnCompleteWithException() [Fact] public async Task DataNotFlushedOnCompleteAsyncWithException() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true)); @@ -105,7 +105,7 @@ public async Task DataNotFlushedOnCompleteAsyncWithException() [Fact] public async Task CompleteAsyncDoesNotThrowObjectDisposedException() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true)); @@ -124,7 +124,7 @@ public async Task CompleteAsyncDoesNotThrowObjectDisposedException() [Fact] public async Task DataWrittenOnFlushAsync() { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); var stream = new MemoryStream(); PipeWriter writer = PipeWriter.Create(stream); @@ -155,7 +155,7 @@ public async Task FlushAsyncWithoutWritingDoesNotFlushAsync() [Fact] public async Task WritesUsingGetSpanWorks() { - var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz"); + var bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); var stream = new MemoryStream(); var options = new StreamPipeWriterOptions(new HeapBufferPool(), minimumBufferSize: 1); PipeWriter writer = PipeWriter.Create(stream, options); @@ -175,7 +175,7 @@ public async Task WritesUsingGetSpanWorks() [Fact] public async Task WritesUsingGetMemoryWorks() { - var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz"); + var bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); var stream = new MemoryStream(); var options = new StreamPipeWriterOptions(new HeapBufferPool(), minimumBufferSize: 1); PipeWriter writer = PipeWriter.Create(stream, options); @@ -234,10 +234,10 @@ async Task DoReadsAsync(PipeReader reader, byte[][] reads) var data = new List { - Encoding.ASCII.GetBytes("Hello"), - Encoding.ASCII.GetBytes("World"), - Encoding.ASCII.GetBytes("This"), - Encoding.ASCII.GetBytes("Works"), + "Hello"u8.ToArray(), + "World"u8.ToArray(), + "This"u8.ToArray(), + "Works"u8.ToArray(), }. ToArray(); @@ -438,7 +438,7 @@ public void CompletingWithBufferedBytesStillReturnsMemoryToPool() { using (var pool = new DisposeTrackingBufferPool()) { - byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + byte[] bytes = "Hello World"u8.ToArray(); var stream = new MemoryStream(); var options = new StreamPipeWriterOptions(pool); PipeWriter writer = PipeWriter.Create(stream, options); @@ -484,7 +484,7 @@ public void GetMemorySameAsTheMaxPoolSizeUsesThePool() { 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 @@ public async Task OperationCancelledExceptionNotSwallowedIfNotThrownFromSpecifie [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); diff --git a/src/libraries/System.IO.Pipelines/tests/UnflushedBytesTests.cs b/src/libraries/System.IO.Pipelines/tests/UnflushedBytesTests.cs index 1c2c15e94950b..d9a4e7c8fdb29 100644 --- a/src/libraries/System.IO.Pipelines/tests/UnflushedBytesTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/UnflushedBytesTests.cs @@ -39,7 +39,7 @@ public void NonOverriddenUnflushedBytesThrows() [Fact] public void UnflushedBytesWorks() { - byte[] bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz"); + byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); Pipe.Writer.Write(bytes); Assert.True(Pipe.Writer.CanGetUnflushedBytes); Assert.Equal(bytes.Length,Pipe.Writer.UnflushedBytes); diff --git a/src/libraries/System.Memory.Data/README.md b/src/libraries/System.Memory.Data/README.md index 70cb1262e9777..c707af4837706 100644 --- a/src/libraries/System.Memory.Data/README.md +++ b/src/libraries/System.Memory.Data/README.md @@ -19,7 +19,7 @@ Console.WriteLine(data.ToString()); // prints "some data" To/From bytes: ```C# Snippet:BinaryDataToFromBytes -byte[] bytes = Encoding.UTF8.GetBytes("some data"); +byte[] bytes = "some data"u8.ToArray(); // Create BinaryData using a constructor ... BinaryData data = new BinaryData(bytes); @@ -41,7 +41,7 @@ byte[] array = data.ToArray(); ``` To/From stream: ```C# Snippet:BinaryDataToFromStream -var bytes = Encoding.UTF8.GetBytes("some data"); +var bytes = "some data"u8.ToArray(); Stream stream = new MemoryStream(bytes); var data = BinaryData.FromStream(stream); diff --git a/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs b/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs index be626539f5e32..bf9eb406448b6 100644 --- a/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs +++ b/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs @@ -20,7 +20,7 @@ public partial class BinaryDataTests [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 @@ public async Task ToStreamRespectsArraySegmentBoundaries() [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 @@ public async Task CannotWriteToReadOnlyMemoryStream() [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 @@ public async Task ToStreamIsMutatedWhenCustomerOwnsBuffer() [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 @@ public async Task ToStreamIsNotMutatedWhenBinaryDataOwnsBuffer() [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 @@ public async Task CanCreateBinaryDataFromStream() [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 @@ public async Task CanCreateBinaryDataFromEmptyStream() 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 @@ public async Task CanCreateBinaryDataFromEmptyStream() [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 @@ public async Task CanCreateBinaryDataFromStreamUsingBackingBuffer() [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 @@ public async Task CanCreateBinaryDataFromNonSeekableStream() [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 @@ public async Task CanCreateBinaryDataFromFileStream() public async Task StartPositionOfStreamRespected(int bufferOffset, long streamStart) { var input = "some data"; - ArraySegment buffer = new ArraySegment(Encoding.UTF8.GetBytes("some data"), bufferOffset, input.Length - bufferOffset); + ArraySegment buffer = new ArraySegment("some data"u8.ToArray(), bufferOffset, input.Length - bufferOffset); MemoryStream stream = new MemoryStream(buffer.Array, buffer.Offset, buffer.Count); var payload = new ReadOnlyMemory(buffer.Array, buffer.Offset, buffer.Count).Slice((int)streamStart); @@ -288,7 +288,7 @@ public async Task StartPositionOfStreamRespected(int bufferOffset, long streamSt public async Task StartPositionOfStreamRespectedBackingBuffer(int bufferOffset, long streamStart) { var input = "some data"; - ArraySegment buffer = new ArraySegment(Encoding.UTF8.GetBytes("some data"), bufferOffset, input.Length - bufferOffset); + ArraySegment buffer = new ArraySegment("some data"u8.ToArray(), bufferOffset, input.Length - bufferOffset); MemoryStream stream = new MemoryStream(); stream.Write(buffer.Array, buffer.Offset, buffer.Count); @@ -411,12 +411,12 @@ public void ToObjectThrowsExceptionOnIncompatibleType() [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 @@ public void EqualsRespectsReferenceEquality() [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 set = new HashSet @@ -435,7 +435,7 @@ public void GetHashCodeWorks() // hashcodes of a and b should not match since instances are different. Assert.DoesNotContain(b, set); - BinaryData c = BinaryData.FromBytes(Encoding.UTF8.GetBytes("some data")); + BinaryData c = BinaryData.FromBytes("some data"u8.ToArray()); // c should have a different hash code Assert.DoesNotContain(c, set); set.Add(c); @@ -445,7 +445,7 @@ public void GetHashCodeWorks() [Fact] public async Task CanRead() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); var read = new byte[buffer.Length]; @@ -465,7 +465,7 @@ public async Task CanRead() [Fact] public async Task CanReadPartial() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); var length = 4; var read = new byte[length]; @@ -486,7 +486,7 @@ public async Task CanReadPartial() [Fact] public void ReadAsyncRespectsCancellation() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); var read = new byte[buffer.Length]; @@ -505,7 +505,7 @@ public void ReadAsyncRespectsCancellation() [Fact] public async Task CanSeek() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); stream.Seek(5, SeekOrigin.Begin); @@ -526,7 +526,7 @@ public async Task CanSeek() [Fact] public void ValidatesSeekArguments() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); Assert.Throws(() => stream.Seek(-1, SeekOrigin.Begin)); @@ -539,7 +539,7 @@ public void ValidatesSeekArguments() [Fact] public async Task ValidatesReadArguments() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var 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 @@ public async Task ValidatesReadArguments() [Fact] public void ValidatesPositionValue() { - var buffer = Encoding.UTF8.GetBytes("some data"); + var buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); Assert.Throws(() => stream.Position = -1); Assert.Throws(() => stream.Position = (long)int.MaxValue + 1); @@ -565,7 +565,7 @@ public void ValidatesPositionValue() [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(() => stream.Position = -1); diff --git a/src/libraries/System.Memory/tests/Base64/Base64DecoderUnitTests.cs b/src/libraries/System.Memory/tests/Base64/Base64DecoderUnitTests.cs index 92e88fee8e900..1b447f8faa7df 100644 --- a/src/libraries/System.Memory/tests/Base64/Base64DecoderUnitTests.cs +++ b/src/libraries/System.Memory/tests/Base64/Base64DecoderUnitTests.cs @@ -337,7 +337,7 @@ public void DecodingInvalidBytes(bool isFinalBlock) for (int j = 0; j < 8; j++) { - Span source = new byte[8] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP" + Span source = "2222PPPP"u8.ToArray(); // valid input Span decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)]; for (int i = 0; i < invalidBytes.Length; i++) @@ -368,7 +368,7 @@ public void DecodingInvalidBytes(bool isFinalBlock) // Input that is not a multiple of 4 is considered invalid, if isFinalBlock = true if (isFinalBlock) { - Span source = new byte[7] { 50, 50, 50, 50, 80, 80, 80 }; // incomplete input - "2222PPP" + Span source = "2222PPP"u8.ToArray(); // incomplete input Span decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)]; Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount)); Assert.Equal(4, consumed); @@ -385,7 +385,7 @@ public void DecodingInvalidBytesPadding(bool isFinalBlock) // Only last 2 bytes can be padding, all other occurrence of padding is invalid for (int j = 0; j < 7; j++) { - Span source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP" + Span source = "2222PPPP"u8.ToArray(); // valid input Span decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)]; source[j] = Base64TestHelper.EncodingPad; Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount, isFinalBlock)); @@ -535,7 +535,7 @@ public void DecodeInPlaceInvalidBytes() { for (int i = 0; i < invalidBytes.Length; i++) { - Span buffer = new byte[8] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP" + Span buffer = "2222PPPP"u8.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 @@ public void DecodeInPlaceInvalidBytes() // Input that is not a multiple of 4 is considered invalid { - Span buffer = new byte[7] { 50, 50, 50, 50, 80, 80, 80 }; // incomplete input - "2222PPP" + Span buffer = "2222PPP"u8.ToArray(); // incomplete input Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten)); Assert.Equal(0, bytesWritten); } @@ -574,7 +574,7 @@ public void DecodeInPlaceInvalidBytesPadding() // Only last 2 bytes can be padding, all other occurrence of padding is invalid for (int j = 0; j < 7; j++) { - Span buffer = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP" + Span buffer = "2222PPPP"u8.ToArray(); // valid input buffer[j] = Base64TestHelper.EncodingPad; string sourceString = Encoding.ASCII.GetString(buffer.Slice(0, 4).ToArray()); diff --git a/src/libraries/System.Memory/tests/BuffersExtensions/BuffersExtensionsTests.cs b/src/libraries/System.Memory/tests/BuffersExtensions/BuffersExtensionsTests.cs index fc55fbe29fad4..d3f180d9230d7 100644 --- a/src/libraries/System.Memory/tests/BuffersExtensions/BuffersExtensionsTests.cs +++ b/src/libraries/System.Memory/tests/BuffersExtensions/BuffersExtensionsTests.cs @@ -13,8 +13,8 @@ public class BuffersExtensionsTests public void WritingToSingleSegmentBuffer() { IBufferWriter bufferWriter = new TestBufferWriterSingleSegment(); - bufferWriter.Write(Encoding.UTF8.GetBytes("Hello")); - bufferWriter.Write(Encoding.UTF8.GetBytes(" World!")); + bufferWriter.Write("Hello"u8); + bufferWriter.Write(" World!"u8); Assert.Equal("Hello World!", bufferWriter.ToString()); } @@ -22,8 +22,8 @@ public void WritingToSingleSegmentBuffer() public void WritingToMultiSegmentBuffer() { var bufferWriter = new TestBufferWriterMultiSegment(); - bufferWriter.Write(Encoding.UTF8.GetBytes("Hello")); - bufferWriter.Write(Encoding.UTF8.GetBytes(" World!")); + bufferWriter.Write("Hello"u8); + bufferWriter.Write(" World!"u8); Assert.Equal(12, bufferWriter.Comitted.Count); Assert.Equal("Hello World!", bufferWriter.ToString()); } diff --git a/src/libraries/System.Memory/tests/EncodingExtensions/EncodingExtensionsTests.cs b/src/libraries/System.Memory/tests/EncodingExtensions/EncodingExtensionsTests.cs index 268b59b909bda..b3c8b9e33c9fc 100644 --- a/src/libraries/System.Memory/tests/EncodingExtensions/EncodingExtensionsTests.cs +++ b/src/libraries/System.Memory/tests/EncodingExtensions/EncodingExtensionsTests.cs @@ -74,7 +74,7 @@ public static void Convert_Decoder_ReadOnlySpan_IBufferWriter() // First, a small input with no flushing and no leftover data. - ReadOnlySpan inputData = Encoding.UTF8.GetBytes("Hello"); + ReadOnlySpan inputData = "Hello"u8; EncodingExtensions.Convert(decoder, inputData, writer, flush: false, out long charsUsed, out bool completed); Assert.Equal(5, charsUsed); Assert.True(completed); @@ -236,7 +236,7 @@ public static void Convert_Encoder_ReadOnlySequence_IBufferWriter() // Now make sure all of the data was decoded properly. - Assert.Equal(Encoding.UTF8.GetBytes("\u0020\ud7ff\U00100000\ufffd"), writer.WrittenSpan.ToArray()); + Assert.Equal("\u0020\ud7ff\U00100000\ufffd"u8.ToArray(), writer.WrittenSpan.ToArray()); } [Fact] @@ -252,7 +252,7 @@ public static void GetBytes_Encoding_ReadOnlySequence() // First try the single-segment code path. ReadOnlySequence sequence = new ReadOnlySequence("Hello!".ToCharArray()); - Assert.Equal(Encoding.UTF8.GetBytes("Hello!"), EncodingExtensions.GetBytes(Encoding.UTF8, sequence)); + Assert.Equal("Hello!"u8.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 @@ public static void GetBytes_Encoding_ReadOnlySequence() new char[] { '\udfff' }, // (cont.) new char[] { '\ud800' }); // leftover data (should be replaced) - Assert.Equal(Encoding.UTF8.GetBytes("\u0020\u0061\u0080\U00010000\U0010FFFF\ufffd"), EncodingExtensions.GetBytes(Encoding.UTF8, sequence)); + Assert.Equal("\u0020\u0061\u0080\U00010000\U0010FFFF\ufffd"u8.ToArray(), EncodingExtensions.GetBytes(Encoding.UTF8, sequence)); } [Fact] @@ -278,7 +278,7 @@ public static void GetBytes_Encoding_ReadOnlySequence_IBufferWriter_SingleSegmen long bytesWritten = EncodingExtensions.GetBytes(Encoding.UTF8, sequence, writer); Assert.Equal(5, bytesWritten); - Assert.Equal(Encoding.UTF8.GetBytes("Hello"), writer.WrittenSpan.ToArray()); + Assert.Equal("Hello"u8.ToArray(), writer.WrittenSpan.ToArray()); } [Fact] @@ -320,7 +320,7 @@ public static void GetBytes_Encoding_ReadOnlySequence_Span() ReadOnlySequence sequence = new ReadOnlySequence("Hello!".ToCharArray()); Assert.Equal( - expected: Encoding.UTF8.GetBytes("Hello!"), + expected: "Hello!"u8.ToArray(), actual: destination.Slice(0, EncodingExtensions.GetBytes(Encoding.UTF8, sequence, destination)).ToArray()); // Next try the multi-segment code path. @@ -336,7 +336,7 @@ public static void GetBytes_Encoding_ReadOnlySequence_Span() new char[] { '\ud800' }); // leftover data (should be replaced) Assert.Equal( - expected: Encoding.UTF8.GetBytes("\u0020\u0061\u0080\U00010000\U0010FFFF\ufffd"), + expected: "\u0020\u0061\u0080\U00010000\U0010FFFF\ufffd"u8.ToArray(), actual: destination.Slice(0, EncodingExtensions.GetBytes(Encoding.UTF8, sequence, destination)).ToArray()); } @@ -359,7 +359,7 @@ public static void GetBytes_Encoding_ReadOnlySpan_IBufferWriter() ReadOnlySpan inputData = "Hello"; long bytesWritten = EncodingExtensions.GetBytes(Encoding.UTF8, inputData, writer); Assert.Equal(5, bytesWritten); - Assert.Equal(Encoding.UTF8.GetBytes("Hello"), writer.WrittenSpan.ToArray()); + Assert.Equal("Hello"u8.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 @@ public static void GetString_Encoding_ReadOnlySequence() { // First try the single-segment code path. - ReadOnlySequence sequence = new ReadOnlySequence(Encoding.UTF8.GetBytes("Hello!")); + ReadOnlySequence sequence = new ReadOnlySequence("Hello!"u8.ToArray()); Assert.Equal("Hello!", EncodingExtensions.GetString(Encoding.UTF8, sequence)); // Next try the multi-segment code path. @@ -427,7 +427,7 @@ public static void GetString_Encoding_ReadOnlySequence_ParamChecks() [Fact] public static void GetChars_Encoding_ReadOnlySequence_IBufferWriter_SingleSegment() { - ReadOnlySequence sequence = new ReadOnlySequence(Encoding.UTF8.GetBytes("Hello")); + ReadOnlySequence sequence = new ReadOnlySequence("Hello"u8.ToArray()); ArrayBufferWriter writer = new ArrayBufferWriter(); long charsWritten = EncodingExtensions.GetChars(Encoding.UTF8, sequence, writer); @@ -466,7 +466,7 @@ public static void GetChars_Encoding_ReadOnlySequence_Span() // First try the single-segment code path. - ReadOnlySequence sequence = new ReadOnlySequence(Encoding.UTF8.GetBytes("Hello!")); + ReadOnlySequence sequence = new ReadOnlySequence("Hello!"u8.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 @@ public static void GetChars_Encoding_ReadOnlySpan_IBufferWriter() // First, a small input that goes through the one-shot code path. - ReadOnlySpan inputData = Encoding.UTF8.GetBytes("Hello"); + ReadOnlySpan inputData = "Hello"u8; long charsWritten = EncodingExtensions.GetChars(Encoding.UTF8, inputData, writer); Assert.Equal(5, charsWritten); Assert.Equal("Hello", writer.WrittenSpan.ToString()); diff --git a/src/libraries/System.Memory/tests/ReadOnlyBuffer/ReadOnlySequenceTests.Common.byte.cs b/src/libraries/System.Memory/tests/ReadOnlyBuffer/ReadOnlySequenceTests.Common.byte.cs index 60e3a6b676db4..0681d04de2a77 100644 --- a/src/libraries/System.Memory/tests/ReadOnlyBuffer/ReadOnlySequenceTests.Common.byte.cs +++ b/src/libraries/System.Memory/tests/ReadOnlyBuffer/ReadOnlySequenceTests.Common.byte.cs @@ -44,7 +44,7 @@ public void HelloWorldAcrossTwoBlocks() // [padding..hello] -> [ world ] const int blockSize = 4096; - byte[] items = Encoding.ASCII.GetBytes("Hello World"); + byte[] items = "Hello World"u8.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(); diff --git a/src/libraries/System.Memory/tests/SequenceReader/ReadTo.cs b/src/libraries/System.Memory/tests/SequenceReader/ReadTo.cs index b042eb9d556b8..ab7399d30bce7 100644 --- a/src/libraries/System.Memory/tests/SequenceReader/ReadTo.cs +++ b/src/libraries/System.Memory/tests/SequenceReader/ReadTo.cs @@ -259,8 +259,8 @@ public void TryReadTo_SingleDelimiter() public void TryReadTo_Span_At_Segments_Boundary() { Span delimiter = new byte[] { 13, 10 }; // \r\n - BufferSegment segment = new BufferSegment(Text.Encoding.ASCII.GetBytes("Hello\r")); - segment.Append(Text.Encoding.ASCII.GetBytes("\nWorld")); // add next segment + BufferSegment segment = new BufferSegment("Hello\r"u8.ToArray()); + segment.Append("\nWorld"u8.ToArray()); // add next segment ReadOnlySequence inputSeq = new ReadOnlySequence(segment, 0, segment, 6); // span only the first segment! SequenceReader sr = new SequenceReader(inputSeq); bool r = sr.TryReadTo(out ReadOnlySpan _, delimiter); diff --git a/src/libraries/System.Memory/tests/SequenceReader/SkipDelimiter.cs b/src/libraries/System.Memory/tests/SequenceReader/SkipDelimiter.cs index 526a5fffe6b0f..a28b2d5435ebf 100644 --- a/src/libraries/System.Memory/tests/SequenceReader/SkipDelimiter.cs +++ b/src/libraries/System.Memory/tests/SequenceReader/SkipDelimiter.cs @@ -12,7 +12,7 @@ public class SkipDelimiter [Fact] public void TryReadTo_SkipDelimiter() { - byte[] expected = Encoding.UTF8.GetBytes("This is our ^|understanding^|"); + byte[] expected = "This is our ^|understanding^|"u8.ToArray(); ReadOnlySequence bytes = SequenceFactory.CreateUtf8("This is our ^|understanding^|| you see."); SequenceReader reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out ReadOnlySpan span, (byte)'|', (byte)'^', advancePastDelimiter: true)); @@ -125,12 +125,12 @@ public void TryReadTo_SkipDelimiter() bytes = SequenceFactory.CreateUtf8("abc^|de|"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^|de"), span.ToArray()); + Assert.Equal("abc^|de"u8.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 @@ public void TryReadTo_SkipDelimiter() bytes = SequenceFactory.CreateUtf8("^|a|b"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); - Assert.Equal(Encoding.UTF8.GetBytes("^|a"), span.ToArray()); + Assert.Equal("^|a"u8.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 @@ public void TryReadTo_SkipDelimiter() bytes = SequenceFactory.CreateUtf8("^", "|a|b"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); - Assert.Equal(Encoding.UTF8.GetBytes("^|a"), span.ToArray()); + Assert.Equal("^|a"u8.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 @@ public void TryReadTo_SkipDelimiter_Runs() ReadOnlySequence bytes = SequenceFactory.CreateUtf8("abc^^|def"); SequenceReader reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out ReadOnlySpan span, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray()); + Assert.Equal("abc^^"u8.ToArray(), span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(5, reader.Consumed); reader.Rewind(reader.Consumed); Assert.True(reader.TryReadTo(out ReadOnlySequence sequence, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), sequence.ToArray()); + Assert.Equal("abc^^"u8.ToArray(), sequence.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(5, reader.Consumed); @@ -180,12 +180,12 @@ public void TryReadTo_SkipDelimiter_Runs() bytes = SequenceFactory.CreateUtf8("abc^^", "|def"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray()); + Assert.Equal("abc^^"u8.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 @@ public void TryReadTo_SkipDelimiter_Runs() bytes = SequenceFactory.CreateUtf8("abc^", "^", "|def"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray()); + Assert.Equal("abc^^"u8.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(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 @@ public void TryReadTo_SkipDelimiter_Runs() bytes = SequenceFactory.CreateUtf8("^^|abc"); reader = new SequenceReader(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); - Assert.Equal(Encoding.UTF8.GetBytes("^^"), span.ToArray()); + Assert.Equal("^^"u8.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); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs index 6d2fa2bd1df22..c50f09b3e2f78 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs @@ -16,8 +16,8 @@ namespace System.Net.Http { internal sealed class WinHttpRequestStream : Stream { - private static readonly byte[] s_crLfTerminator = new byte[] { 0x0d, 0x0a }; // "\r\n" - private static readonly byte[] s_endChunk = new byte[] { 0x30, 0x0d, 0x0a, 0x0d, 0x0a }; // "0\r\n\r\n" + private static readonly byte[] s_crLfTerminator = "\r\n"u8.ToArray(); + private static readonly byte[] s_endChunk = "0\r\n\r\n"u8.ToArray(); private volatile bool _disposed; private readonly WinHttpRequestState _state; diff --git a/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/BidirectionStreamingTest.cs b/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/BidirectionStreamingTest.cs index 0277ca26e817a..d18de54bc46cb 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/BidirectionStreamingTest.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/BidirectionStreamingTest.cs @@ -30,7 +30,7 @@ public BidirectionStreamingTest(ITestOutputHelper output) : base(output) protected override Version UseVersion => new Version(2, 0); - protected static byte[] DataBytes = Encoding.ASCII.GetBytes("data"); + protected static byte[] DataBytes = "data"u8.ToArray(); protected static Frame MakeDataFrame(int streamId, byte[] data, bool endStream = false) => new DataFrame(data, (endStream ? FrameFlags.EndStream : FrameFlags.None), 0, streamId); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/System.Net.Http.WinHttpHandler.Functional.Tests.csproj b/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/System.Net.Http.WinHttpHandler.Functional.Tests.csproj index ac4d036552f14..93d7e9a899d8a 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/System.Net.Http.WinHttpHandler.Functional.Tests.csproj +++ b/src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/System.Net.Http.WinHttpHandler.Functional.Tests.csproj @@ -3,7 +3,6 @@ $(NetCoreAppCurrent)-windows;net48 true $(DefineConstants);WINHTTPHANDLER_TEST - 10.0 new Version(2, 0); - protected static byte[] DataBytes = Encoding.ASCII.GetBytes("data"); + protected static byte[] DataBytes = "data"u8.ToArray(); protected static readonly IList TrailingHeaders = new HttpHeaderData[] { new HttpHeaderData("MyCoolTrailerHeader", "amazingtrailer"), diff --git a/src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/WinHttpResponseStreamTest.cs b/src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/WinHttpResponseStreamTest.cs index 90900a0517e07..9b5e37c9581bd 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/WinHttpResponseStreamTest.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/WinHttpResponseStreamTest.cs @@ -331,7 +331,7 @@ public void Read_ReadDataFailsOnCompletionCallback_ThrowsIOException() public void Read_NoOffsetAndNotEndOfData_FillsBuffer() { Stream stream = MakeResponseStream(); - byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + byte[] testData = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"u8.ToArray(); TestServer.ResponseBody = testData; byte[] buffer = new byte[testData.Length]; @@ -348,7 +348,7 @@ public void Read_NoOffsetAndNotEndOfData_FillsBuffer() public void Read_UsingOffsetAndNotEndOfData_FillsBufferFromOffset() { Stream stream = MakeResponseStream(); - byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + byte[] testData = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"u8.ToArray(); TestServer.ResponseBody = testData; byte[] buffer = new byte[testData.Length]; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs index e522822c6caf5..b0154dda84335 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs @@ -477,7 +477,7 @@ public void OnWindowUpdate(int amount) private static readonly (HeaderDescriptor descriptor, byte[] value)[] s_hpackStaticHeaderTable = new (HeaderDescriptor, byte[])[LastHPackNormalHeaderId - FirstHPackNormalHeaderId + 1] { (KnownHeaders.AcceptCharset.Descriptor, Array.Empty()), - (KnownHeaders.AcceptEncoding.Descriptor, Encoding.ASCII.GetBytes("gzip, deflate")), + (KnownHeaders.AcceptEncoding.Descriptor, "gzip, deflate"u8.ToArray()), (KnownHeaders.AcceptLanguage.Descriptor, Array.Empty()), (KnownHeaders.AcceptRanges.Descriptor, Array.Empty()), (KnownHeaders.Accept.Descriptor, Array.Empty()), diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs index d3d2b39d2806d..7edd0b84b3948 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs @@ -41,13 +41,13 @@ internal sealed partial class HttpConnection : HttpConnectionBase /// 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; diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/HPackTest.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/HPackTest.cs index c1a4cdb314c3f..18e502f48281d 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/HPackTest.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/HPackTest.cs @@ -68,10 +68,10 @@ public static IEnumerable HeaderEncodingTestData() yield return new object[] { ":path", "/", new byte[] { 0x84 } }; // Indexed name, literal value. - yield return new object[] { "content-type", "text/plain; charset=utf-8", new byte[] { 0x0F, 0x10, 0x19, 0x74, 0x65, 0x78, 0x74, 0x2F, 0x70, 0x6C, 0x61, 0x69, 0x6E, 0x3B, 0x20, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3D, 0x75, 0x74, 0x66, 0x2D, 0x38 } }; + yield return new object[] { "content-type", "text/plain; charset=utf-8", "\u000f\u0010\u0019text/plain; charset=utf-8"u8.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() }; } } } diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.Http2.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.Http2.cs index d22e553f7a29d..35c20cda86c61 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.Http2.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.Http2.cs @@ -2048,7 +2048,7 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async url => } catch (System.OperationCanceledException) { }; Assert.Null(frame); // Make sure we do not get any frames after getting Rst. - await connection.SendResponseBodyAsync(streamId, Encoding.ASCII.GetBytes("final"), isFinal: true); + await connection.SendResponseBodyAsync(streamId, "final"u8.ToArray(), isFinal: true); await connection.WaitForConnectionShutdownAsync(); }); } @@ -2213,7 +2213,7 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async url => } await connection.ReadBodyAsync(); await connection.SendResponseHeadersAsync(streamId, endStream: false, HttpStatusCode.OK); - await connection.SendResponseBodyAsync(streamId, Encoding.ASCII.GetBytes("OK")); + await connection.SendResponseBodyAsync(streamId, "OK"u8.ToArray()); await connection.ShutdownIgnoringErrorsAsync(streamId); }); } @@ -2352,7 +2352,7 @@ private async Task SendAndReceiveRequestEOFAsync(DuplexContent duplexContent, St [Fact] public async Task PostAsyncDuplex_ClientSendsEndStream_Success() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8.ToArray(); using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2412,7 +2412,7 @@ public async Task PostAsyncDuplex_ClientSendsEndStream_Success() [Fact] public async Task PostAsyncDuplex_ServerSendsEndStream_Success() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8.ToArray(); using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2472,7 +2472,7 @@ public async Task PostAsyncDuplex_ServerSendsEndStream_Success() [Fact] public async Task PostAsyncDuplex_RequestContentException_ResetsStream() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8.ToArray(); using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2529,7 +2529,7 @@ public async Task PostAsyncDuplex_RequestContentException_ResetsStream() [Fact] public async Task PostAsyncDuplex_RequestContentExceptionAfterResponseEndReceivedButBeforeConsumed_ResetsStreamAndThrowsOnResponseStreamRead() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8.ToArray(); using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2593,7 +2593,7 @@ public async Task PostAsyncDuplex_RequestContentExceptionAfterResponseEndReceive [Fact] public async Task PostAsyncDuplex_CancelledBeforeResponseHeadersReceived_ResetsStream() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8.ToArray(); using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2649,7 +2649,7 @@ public async Task PostAsyncDuplex_CancelledBeforeResponseHeadersReceived_ResetsS [Fact] public async Task PostAsyncDuplex_ServerResetsStream_Throws() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8.ToArray(); using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2710,7 +2710,7 @@ public async Task PostAsyncDuplex_ServerResetsStream_Throws() [Fact] public async Task PostAsyncDuplex_DisposeResponseBodyBeforeEnd_ResetsStreamAndThrowsOnRequestStreamWriteAndResponseStreamRead() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8.ToArray(); using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2777,7 +2777,7 @@ public async Task PostAsyncDuplex_DisposeResponseBodyBeforeEnd_ResetsStreamAndTh [Fact] public async Task PostAsyncDuplex_DisposeResponseBodyAfterEndReceivedButBeforeConsumed_ResetsStreamAndThrowsOnRequestStreamWriteAndResponseStreamRead() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8.ToArray(); using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2850,7 +2850,7 @@ public async Task PostAsyncDuplex_DisposeResponseBodyAfterEndReceivedButBeforeCo [Fact] public async Task PostAsyncDuplex_FinishRequestBodyAndDisposeResponseBodyAfterEndReceivedButBeforeConsumed_DoesNotResetStream() { - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8.ToArray(); using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2920,7 +2920,7 @@ public async Task PostAsyncDuplex_ServerCompletesResponseBodyThenResetsStreamWit // We should stop sending the request body, but treat the request as successful and // return the completed response body to the user. - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8.ToArray(); using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -2989,7 +2989,7 @@ public async Task PostAsyncNonDuplex_ServerCompletesResponseBodyThenResetsStream // We should stop sending the request body, but treat the request as successful and // return the completed response body to the user. - byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world"); + byte[] contentBytes = "Hello world"u8.ToArray(); using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer()) { @@ -3248,7 +3248,7 @@ await server.AcceptConnectionAsync(async connection => await sslStream.AuthenticateAsServerAsync(options, CancellationToken.None).ConfigureAwait(false); // Send back HTTP/1.1 response - await sslStream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/1.1 400 Unrecognized request\r\n\r\n"), CancellationToken.None); + await sslStream.WriteAsync("HTTP/1.1 400 Unrecognized request\r\n\r\n"u8.ToArray(), CancellationToken.None); }); Exception e = await Assert.ThrowsAsync(() => requestTask); @@ -3304,7 +3304,7 @@ public async Task Http2GetAsync_TrailigPseudo_Throw() Http2LoopbackConnection connection = await server.EstablishConnectionAsync(); int streamId = await connection.ReadRequestHeaderAsync(); await connection.SendDefaultResponseHeadersAsync(streamId); - await connection.SendResponseDataAsync(streamId, Encoding.ASCII.GetBytes("hello"), endStream: false); + await connection.SendResponseDataAsync(streamId, "hello"u8.ToArray(), endStream: false); await connection.SendResponseHeadersAsync(streamId, endStream : true, isTrailingHeader : true, headers: headers); await Assert.ThrowsAsync(() => sendTask); diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/HttpContentTest.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/HttpContentTest.cs index 4ddd6633a2e97..276733d9f3700 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/HttpContentTest.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/HttpContentTest.cs @@ -366,7 +366,7 @@ public async Task LoadIntoBufferAsync_CallOnMockContentWithNullContentLength_Cop [InlineData(false)] public async Task LoadIntoBufferAsync_CallOnMockContentWithLessLengthThanContentLengthHeader_BufferedStreamLengthMatchesActualLengthNotContentLengthHeaderValue(bool readStreamAsync) { - byte[] data = Encoding.UTF8.GetBytes("16 bytes of data"); + byte[] data = "16 bytes of data"u8.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 @@ public MockContent(Exception customException, MockOptions options) 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() diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs index 1ac9ae91d01e0..bb883453333cd 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs @@ -150,7 +150,7 @@ public async Task ReadAsStringAsync_NoSubContent_MatchesExpected(MultipartConten [InlineData(MultipartContentToStringMode.CopyToAsync, true)] public async Task ReadAsStringAsync_OneSubContentWithHeaders_MatchesExpected(MultipartContentToStringMode mode, bool async) { - var subContent = new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent")); + var subContent = new ByteArrayContent("This is a ByteArrayContent"u8.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 @@ public async Task ReadAsStringAsync_OneSubContentWithHeaders_MatchesExpected(Mul public async Task ReadAsStringAsync_TwoSubContents_MatchesExpected(MultipartContentToStringMode mode, bool async) { var mc = new MultipartContent("someSubtype", "theBoundary"); - mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent"))); + mc.Add(new ByteArrayContent("This is a ByteArrayContent"u8.ToArray())); mc.Add(new StringContent("This is a StringContent")); Assert.Equal( @@ -274,9 +274,9 @@ public async Task ReadAsStreamAsync_Seek_JumpsToSpecifiedPosition(bool nestedCon var mc = new MultipartContent(); if (nestedContent) { - mc.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent"))); + mc.Add(new ByteArrayContent("This is a ByteArrayContent"u8.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 @@ public async Task ReadAsStreamAsync_CustomEncodingSelector_SelectorIsCalledWithC stringContent.Headers.Add("StringContent", "foo"); mc.Add(stringContent); - var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("foo")); + var byteArrayContent = new ByteArrayContent("foo"u8.ToArray()); byteArrayContent.Headers.Add("ByteArrayContent", "foo"); mc.Add(byteArrayContent); @@ -445,15 +445,15 @@ public async Task ReadAsStreamAsync_CustomEncodingSelector_CustomEncodingIsUsed( stringContent.Headers.Add("latin1", "\uD83D\uDE00"); mc.Add(stringContent); - var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar2")); + var byteArrayContent = new ByteArrayContent("bar2"u8.ToArray()); byteArrayContent.Headers.Add("utf8", "\uD83D\uDE00"); mc.Add(byteArrayContent); - byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar3")); + byteArrayContent = new ByteArrayContent("bar3"u8.ToArray()); byteArrayContent.Headers.Add("ascii", "\uD83D\uDE00"); mc.Add(byteArrayContent); - byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar4")); + byteArrayContent = new ByteArrayContent("bar4"u8.ToArray()); byteArrayContent.Headers.Add("default", "\uD83D\uDE00"); mc.Add(byteArrayContent); @@ -476,28 +476,28 @@ public async Task ReadAsStreamAsync_CustomEncodingSelector_CustomEncodingIsUsed( } byte[] expected = Concat( - Encoding.Latin1.GetBytes("--fooBoundary\r\n"), - Encoding.Latin1.GetBytes("Content-Type: text/plain; charset=utf-8\r\n"), - Encoding.Latin1.GetBytes("latin1: "), + "--fooBoundary\r\n"u8.ToArray(), + "Content-Type: text/plain; charset=utf-8\r\n"u8.ToArray(), + "latin1: "u8.ToArray(), Encoding.Latin1.GetBytes("\uD83D\uDE00"), - Encoding.Latin1.GetBytes("\r\n\r\n"), - Encoding.Latin1.GetBytes("bar1"), - Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"), - Encoding.Latin1.GetBytes("utf8: "), - Encoding.UTF8.GetBytes("\uD83D\uDE00"), - Encoding.Latin1.GetBytes("\r\n\r\n"), - Encoding.Latin1.GetBytes("bar2"), - Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"), - Encoding.Latin1.GetBytes("ascii: "), + "\r\n\r\n"u8.ToArray(), + "bar1"u8.ToArray(), + "\r\n--fooBoundary\r\n"u8.ToArray(), + "utf8: "u8.ToArray(), + "\uD83D\uDE00"u8.ToArray(), + "\r\n\r\n"u8.ToArray(), + "bar2"u8.ToArray(), + "\r\n--fooBoundary\r\n"u8.ToArray(), + "ascii: "u8.ToArray(), Encoding.ASCII.GetBytes("\uD83D\uDE00"), - Encoding.Latin1.GetBytes("\r\n\r\n"), - Encoding.Latin1.GetBytes("bar3"), - Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"), - Encoding.Latin1.GetBytes("default: "), + "\r\n\r\n"u8.ToArray(), + "bar3"u8.ToArray(), + "\r\n--fooBoundary\r\n"u8.ToArray(), + "default: "u8.ToArray(), Encoding.Latin1.GetBytes("\uD83D\uDE00"), - Encoding.Latin1.GetBytes("\r\n\r\n"), - Encoding.Latin1.GetBytes("bar4"), - Encoding.Latin1.GetBytes("\r\n--fooBoundary--\r\n")); + "\r\n\r\n"u8.ToArray(), + "bar4"u8.ToArray(), + "\r\n--fooBoundary--\r\n"u8.ToArray()); Assert.Equal(expected, ms.ToArray()); diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamConformanceTests.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamConformanceTests.cs index f7f28da5d192a..200d0b1e9e3e1 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamConformanceTests.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamConformanceTests.cs @@ -54,9 +54,9 @@ protected override async Task WriteResponseAsync(Stream responseStream, byte[] b // One chunk for the whole response body await responseStream.WriteAsync(Encoding.ASCII.GetBytes($"{bodyData.Length:X}\r\n")); await responseStream.WriteAsync(bodyData); - await responseStream.WriteAsync(Encoding.ASCII.GetBytes("\r\n")); + await responseStream.WriteAsync("\r\n"u8.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 @@ protected override async Task WriteResponseAsync(Stream responseStream, byte[] b // One chunk per byte of the response body await responseStream.WriteAsync(Encoding.ASCII.GetBytes($"1\r\n")); await responseStream.WriteAsync(bodyData.AsMemory(i, 1)); - await responseStream.WriteAsync(Encoding.ASCII.GetBytes("\r\n")); + await responseStream.WriteAsync("\r\n"u8.ToArray()); } - await responseStream.WriteAsync(Encoding.ASCII.GetBytes("0\r\n\r\n")); + await responseStream.WriteAsync("0\r\n\r\n"u8.ToArray()); } } diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamZeroByteReadTests.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamZeroByteReadTests.cs index 29a6b4cc99b2c..3e097d5e24829 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamZeroByteReadTests.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/ResponseStreamZeroByteReadTests.cs @@ -48,7 +48,7 @@ protected override async Task WriteAsync(Stream stream, byte[] data) { await stream.WriteAsync(Encoding.ASCII.GetBytes($"{data.Length:X}\r\n")); await stream.WriteAsync(data); - await stream.WriteAsync(Encoding.ASCII.GetBytes("\r\n")); + await stream.WriteAsync("\r\n"u8.ToArray()); } } @@ -62,7 +62,7 @@ protected override async Task WriteAsync(Stream stream, byte[] data) { await stream.WriteAsync(Encoding.ASCII.GetBytes($"1\r\n")); await stream.WriteAsync(data.AsMemory(i, 1)); - await stream.WriteAsync(Encoding.ASCII.GetBytes("\r\n")); + await stream.WriteAsync("\r\n"u8.ToArray()); } } } @@ -136,7 +136,7 @@ public async Task ZeroByteRead_IssuesZeroByteReadOnUnderlyingStream(StreamConfor await sawZeroByteRead.Task.WaitAsync(TimeSpan.FromSeconds(10)); Assert.False(zeroByteReadTask.IsCompleted); - byte[] data = Encoding.UTF8.GetBytes("Hello"); + byte[] data = "Hello"u8.ToArray(); await WriteAsync(server, data); await server.FlushAsync(); diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/SocketsHttpHandlerTest.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/SocketsHttpHandlerTest.cs index f29c5e70b936d..b7f0736da0145 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/SocketsHttpHandlerTest.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/SocketsHttpHandlerTest.cs @@ -591,7 +591,7 @@ public abstract class SocketsHttpHandler_TrailingHeaders_Test : HttpClientHandle { public SocketsHttpHandler_TrailingHeaders_Test(ITestOutputHelper output) : base(output) { } - protected static byte[] DataBytes = Encoding.ASCII.GetBytes("data"); + protected static byte[] DataBytes = "data"u8.ToArray(); protected static readonly IList TrailingHeaders = new HttpHeaderData[] { new HttpHeaderData("MyCoolTrailerHeader", "amazingtrailer"), @@ -1301,26 +1301,26 @@ await server.AcceptConnectionAsync(async (LoopbackServer.Connection connection) // Validate writing APIs on clientStream clientStream.WriteByte((byte)'!'); - clientStream.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2); + clientStream.Write("\r\n"u8.ToArray(), 0, 2); Assert.Equal("!", await connection.ReadLineAsync()); - clientStream.Write(new Span(new byte[] { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'\r', (byte)'\n' })); + clientStream.Write("hello\r\n"u8); Assert.Equal("hello", await connection.ReadLineAsync()); - await clientStream.WriteAsync(new byte[] { (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 7); + await clientStream.WriteAsync("world\r\n"u8.ToArray(), 0, 7); Assert.Equal("world", await connection.ReadLineAsync()); - await clientStream.WriteAsync(new Memory(new byte[] { (byte)'a', (byte)'n', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 5)); + await clientStream.WriteAsync(new Memory("and\r\n"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()); @@ -2710,8 +2710,8 @@ public async Task ConnectCallback_ConnectionPrefix_Success(bool useSsl) { GenericLoopbackOptions options = new GenericLoopbackOptions() { UseSsl = useSsl }; - byte[] RequestPrefix = Encoding.UTF8.GetBytes("request prefix\r\n"); - byte[] ResponsePrefix = Encoding.UTF8.GetBytes("response prefix\r\n"); + byte[] RequestPrefix = "request prefix\r\n"u8.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)); @@ -3176,8 +3176,8 @@ await LoopbackServerFactory.CreateClientAndServerAsync( [InlineData(false)] public async Task PlaintextStreamFilter_ConnectionPrefix_Success(bool useSsl) { - byte[] RequestPrefix = Encoding.UTF8.GetBytes("request prefix\r\n"); - byte[] ResponsePrefix = Encoding.UTF8.GetBytes("response prefix\r\n"); + byte[] RequestPrefix = "request prefix\r\n"u8.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)); @@ -3355,7 +3355,7 @@ await LoopbackServerFactory.CreateClientAndServerAsync( context.PlaintextStream.Dispose(); MemoryStream memoryStream = new MemoryStream(); - memoryStream.Write(Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nfoo")); + memoryStream.Write("HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nfoo"u8); memoryStream.Seek(0, SeekOrigin.Begin); DelegateStream newStream = new DelegateStream( diff --git a/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs b/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs index e89d38c204bfd..571d64d951c5d 100644 --- a/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs +++ b/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs @@ -21,15 +21,15 @@ public static IEnumerable MultipartContent_TestData() stringContent.Headers.Add("latin1", "\uD83D\uDE00"); complexContent.Add(stringContent); - var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar2")); + var byteArrayContent = new ByteArrayContent("bar2"u8.ToArray()); byteArrayContent.Headers.Add("utf8", "\uD83D\uDE00"); complexContent.Add(byteArrayContent); - byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar3")); + byteArrayContent = new ByteArrayContent("bar3"u8.ToArray()); byteArrayContent.Headers.Add("ascii", "\uD83D\uDE00"); complexContent.Add(byteArrayContent); - byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar4")); + byteArrayContent = new ByteArrayContent("bar4"u8.ToArray()); byteArrayContent.Headers.Add("default", "\uD83D\uDE00"); complexContent.Add(byteArrayContent); diff --git a/src/libraries/System.Net.Http/tests/UnitTests/MockContent.cs b/src/libraries/System.Net.Http/tests/UnitTests/MockContent.cs index 84971cbe30f04..56dac20a58af6 100644 --- a/src/libraries/System.Net.Http/tests/UnitTests/MockContent.cs +++ b/src/libraries/System.Net.Http/tests/UnitTests/MockContent.cs @@ -69,15 +69,7 @@ public MockContent(Exception customException, MockOptions options) 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() diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs index d0159245503a9..e42cfb07a05f6 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs @@ -64,7 +64,7 @@ private sealed class Context : TransportContext private HttpListenerContext _context; private bool _isChunked; - private static byte[] s_100continue = Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n"); + private static byte[] s_100continue = "HTTP/1.1 100 Continue\r\n\r\n"u8.ToArray(); internal HttpListenerRequest(HttpListenerContext context) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs index 6451497525053..28649cc6ce025 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs @@ -107,7 +107,7 @@ private static byte[] GetChunkHeader(int size, out int offset) return Header; } - private static readonly byte[] s_CRLFArray = new byte[] { (byte)'\r', (byte)'\n' }; + private static readonly byte[] s_CRLFArray = "\r\n"u8.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) { diff --git a/src/libraries/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs b/src/libraries/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs index 89d5c2428e06c..900fea8511418 100644 --- a/src/libraries/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs +++ b/src/libraries/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs @@ -102,7 +102,7 @@ public static IEnumerable BasicAuthenticationHeader_TestData() { yield return new object[] { string.Empty, HttpStatusCode.Unauthorized }; yield return new object[] { null, HttpStatusCode.Unauthorized }; - yield return new object[] { Convert.ToBase64String(Encoding.ASCII.GetBytes("username")), HttpStatusCode.BadRequest }; + yield return new object[] { Convert.ToBase64String("username"u8), HttpStatusCode.BadRequest }; yield return new object[] { "abc", HttpStatusCode.InternalServerError }; } diff --git a/src/libraries/System.Net.HttpListener/tests/HttpListenerContextTests.cs b/src/libraries/System.Net.HttpListener/tests/HttpListenerContextTests.cs index a276a610b400a..e7e234d612f7a 100644 --- a/src/libraries/System.Net.HttpListener/tests/HttpListenerContextTests.cs +++ b/src/libraries/System.Net.HttpListener/tests/HttpListenerContextTests.cs @@ -101,7 +101,7 @@ public async Task AcceptWebSocketAsync_ValidWebSocket_SetsUpContextProperties() [ConditionalFact(nameof(IsNotWindows7))] public async Task AcceptWebSocketAsync_AuthorizationInHeaders_ThrowsNotImplementedException() { - Socket.Options.SetRequestHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("user:password"))); + Socket.Options.SetRequestHeader("Authorization", "Basic " + Convert.ToBase64String("user:password"u8)); Factory.GetListener().AuthenticationSchemes = AuthenticationSchemes.Basic; HttpListenerContext context = await GetWebSocketContext(); diff --git a/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.cs b/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.cs index e2d1d826d4499..581ba91fb9dbc 100644 --- a/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.cs +++ b/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.cs @@ -13,7 +13,7 @@ public class HttpListenerResponseTestBase : IDisposable { protected HttpListenerFactory Factory { get; } protected Socket Client { get; } - protected static byte[] SimpleMessage { get; } = Encoding.UTF8.GetBytes("Hello"); + protected static byte[] SimpleMessage { get; } = "Hello"u8.ToArray(); public HttpListenerResponseTestBase() { diff --git a/src/libraries/System.Net.HttpListener/tests/HttpResponseStreamTests.cs b/src/libraries/System.Net.HttpListener/tests/HttpResponseStreamTests.cs index 841fae8c293ca..62fb2be684084 100644 --- a/src/libraries/System.Net.HttpListener/tests/HttpResponseStreamTests.cs +++ b/src/libraries/System.Net.HttpListener/tests/HttpResponseStreamTests.cs @@ -62,7 +62,7 @@ public async Task SimpleRequest_WriteAsynchronously_Succeeds(bool sendChunked) outputStream.Close(); } - byte[] extraBytesSentAfterClose = Encoding.UTF8.GetBytes("Should not be sent."); + byte[] extraBytesSentAfterClose = "Should not be sent."u8.ToArray(); await outputStream.WriteAsync(extraBytesSentAfterClose, 0, extraBytesSentAfterClose.Length); } @@ -100,7 +100,7 @@ public async Task SimpleRequest_WriteSynchronouslyNonEmpty_Succeeds(bool sendChu outputStream.Close(); } - byte[] extraBytesSentAfterClose = Encoding.UTF8.GetBytes("Should not be sent."); + byte[] extraBytesSentAfterClose = "Should not be sent."u8.ToArray(); outputStream.Write(extraBytesSentAfterClose, 0, extraBytesSentAfterClose.Length); } @@ -308,7 +308,7 @@ public async Task Write_TooMuch_ThrowsProtocolViolationException() using (HttpListenerResponse response = serverContext.Response) { Stream output = response.OutputStream; - byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string"); + byte[] responseBuffer = "A long string"u8.ToArray(); response.ContentLength64 = responseBuffer.Length - 1; try { @@ -337,7 +337,7 @@ public async Task Write_TooLittleAsynchronouslyAndClose_ThrowsInvalidOperationEx { Stream output = response.OutputStream; - byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string"); + byte[] responseBuffer = "A long string"u8.ToArray(); response.ContentLength64 = responseBuffer.Length + 1; // Throws when there are bytes left to write @@ -363,7 +363,7 @@ public async Task Write_TooLittleSynchronouslyAndClose_ThrowsInvalidOperationExc { Stream output = response.OutputStream; - byte[] responseBuffer = Encoding.UTF8.GetBytes("A long string"); + byte[] responseBuffer = "A long string"u8.ToArray(); response.ContentLength64 = responseBuffer.Length + 1; // Throws when there are bytes left to write diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs index 5b1001c6a9ad0..86d020c349e67 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs @@ -40,6 +40,6 @@ private static byte[] CreateHeader(Encoding encoding, bool useBase64Encoding) => Encoding.ASCII.GetBytes("=?" + encoding.HeaderName + "?" + (useBase64Encoding ? "B?" : "Q?")); //The footer that marks the end of a quoted string of some sort - private static readonly byte[] s_footer = new byte[] { (byte)'?', (byte)'=' }; + private static readonly byte[] s_footer = "?="u8.ToArray(); } } diff --git a/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs b/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs index e269cc6eeea77..26aa4580dd57d 100644 --- a/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs +++ b/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs @@ -16,8 +16,8 @@ namespace Systen.Net.Mail.Tests { public class LoopbackSmtpServer : IDisposable { - private static readonly ReadOnlyMemory s_messageTerminator = new byte[] { (byte)'\r', (byte)'\n' }; - private static readonly ReadOnlyMemory s_bodyTerminator = new byte[] { (byte)'\r', (byte)'\n', (byte)'.', (byte)'\r', (byte)'\n' }; + private static readonly ReadOnlyMemory s_messageTerminator = "\r\n"u8.ToArray(); + private static readonly ReadOnlyMemory s_bodyTerminator = "\r\n.\r\n"u8.ToArray(); public bool ReceiveMultipleConnections = false; public bool SupportSmtpUTF8 = false; diff --git a/src/libraries/System.Net.Mail/tests/Unit/QuotedPrintableStreamTest.cs b/src/libraries/System.Net.Mail/tests/Unit/QuotedPrintableStreamTest.cs index 0c66e26d9c6fc..0e9f66fa2bb41 100644 --- a/src/libraries/System.Net.Mail/tests/Unit/QuotedPrintableStreamTest.cs +++ b/src/libraries/System.Net.Mail/tests/Unit/QuotedPrintableStreamTest.cs @@ -50,12 +50,8 @@ public void QuotedPrintableStream_EmbededCRAndLFSpltBetweenWrites_EncodeCrlfFlag 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 diff --git a/src/libraries/System.Net.Ping/tests/FunctionalTests/TestSettings.cs b/src/libraries/System.Net.Ping/tests/FunctionalTests/TestSettings.cs index 8a87d2f0111e6..0e48bb4777b2e 100644 --- a/src/libraries/System.Net.Ping/tests/FunctionalTests/TestSettings.cs +++ b/src/libraries/System.Net.Ping/tests/FunctionalTests/TestSettings.cs @@ -18,7 +18,7 @@ internal static class TestSettings // By default, FreeBSD supports buffer only up to 56 bytes public static readonly byte[] PayloadAsBytes = Encoding.UTF8.GetBytes(OperatingSystem.IsFreeBSD() ? TestSettings.PayloadAsString.Substring(0, 55) : TestSettings.PayloadAsString); - public static readonly byte[] PayloadAsBytesShort = Encoding.UTF8.GetBytes("ABCDEF0123456789"); + public static readonly byte[] PayloadAsBytesShort = "ABCDEF0123456789"u8.ToArray(); public static IPAddress[] GetLocalIPAddresses() { diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicApi.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicApi.cs index 6eedee6a6c776..0cb01e754b0e1 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicApi.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicApi.cs @@ -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 @@ private MsQuicApi(QUIC_API_TABLE* apiTable) { ApiTable = apiTable; - fixed (byte* pAppName = s_appName) + fixed (byte* pAppName = "System.Net.Quic"u8) { var cfg = new QUIC_REGISTRATION_CONFIG { AppName = (sbyte*)pAppName, diff --git a/src/libraries/System.Net.Quic/tests/FunctionalTests/MsQuicTests.cs b/src/libraries/System.Net.Quic/tests/FunctionalTests/MsQuicTests.cs index a14b21f4f08a9..65e78735e1282 100644 --- a/src/libraries/System.Net.Quic/tests/FunctionalTests/MsQuicTests.cs +++ b/src/libraries/System.Net.Quic/tests/FunctionalTests/MsQuicTests.cs @@ -25,7 +25,7 @@ namespace System.Net.Quic.Tests [Collection(nameof(DisableParallelization))] public class MsQuicTests : QuicTestBase { - private static byte[] s_data = Encoding.UTF8.GetBytes("Hello world!"); + private static byte[] s_data = "Hello world!"u8.ToArray(); public MsQuicTests(ITestOutputHelper output) : base(output) { } @@ -630,7 +630,7 @@ public async Task CallDifferentWriteMethodsWorks() { (QuicConnection clientConnection, QuicConnection serverConnection) = await CreateConnectedQuicConnection(); - ReadOnlyMemory helloWorld = Encoding.ASCII.GetBytes("Hello world!"); + ReadOnlyMemory helloWorld = "Hello world!"u8.ToArray(); ReadOnlySequence ros = CreateReadOnlySequenceFromBytes(helloWorld.ToArray()); Assert.False(ros.IsSingleSegment); diff --git a/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicStreamTests.cs b/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicStreamTests.cs index 7f4e03a976903..0fe8068fcdcd5 100644 --- a/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicStreamTests.cs +++ b/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicStreamTests.cs @@ -15,7 +15,7 @@ namespace System.Net.Quic.Tests public abstract class QuicStreamTests : QuicTestBase where T : IQuicImplProviderFactory, new() { - private static byte[] s_data = Encoding.UTF8.GetBytes("Hello world!"); + private static byte[] s_data = "Hello world!"u8.ToArray(); public QuicStreamTests(ITestOutputHelper output) : base(output) { } [Fact] @@ -179,7 +179,7 @@ static async Task MakeStreams(QuicConnection clientConnection, QuicConnection se { byte[] buffer = new byte[64]; QuicStream clientStream = await clientConnection.OpenBidirectionalStreamAsync(); - ValueTask writeTask = clientStream.WriteAsync(Encoding.UTF8.GetBytes("PING"), endStream: true); + ValueTask writeTask = clientStream.WriteAsync("PING"u8.ToArray(), endStream: true); ValueTask acceptTask = serverConnection.AcceptStreamAsync(); await new Task[] { writeTask.AsTask(), acceptTask.AsTask() }.WhenAllOrAnyFailed(PassingTestTimeoutMilliseconds); QuicStream serverStream = acceptTask.Result; diff --git a/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicTestBase.cs b/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicTestBase.cs index 8566d0cd40f52..b613b6dd44f02 100644 --- a/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicTestBase.cs +++ b/src/libraries/System.Net.Quic/tests/FunctionalTests/QuicTestBase.cs @@ -20,8 +20,8 @@ namespace System.Net.Quic.Tests public abstract class QuicTestBase where T : IQuicImplProviderFactory, new() { - private static readonly byte[] s_ping = Encoding.UTF8.GetBytes("PING"); - private static readonly byte[] s_pong = Encoding.UTF8.GetBytes("PONG"); + private static readonly byte[] s_ping = "PING"u8.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(); diff --git a/src/libraries/System.Net.Requests/tests/FtpWebRequestTest.cs b/src/libraries/System.Net.Requests/tests/FtpWebRequestTest.cs index 6cf0d7d7740ee..d1f5e58b3492b 100644 --- a/src/libraries/System.Net.Requests/tests/FtpWebRequestTest.cs +++ b/src/libraries/System.Net.Requests/tests/FtpWebRequestTest.cs @@ -79,7 +79,7 @@ public void GetResponse_ConnectFailure_ThrowsWebException() private const string absoluteUri = "ftp://localhost/"; - private static readonly byte[] helloWorldBytes = Encoding.UTF8.GetBytes("Hello world"); + private static readonly byte[] helloWorldBytes = "Hello world"u8.ToArray(); private static readonly byte[] largeFileBytes = Enumerable.Range(0, 10 * 1024 * 1024).Select((i) => (byte)(i % 256)).ToArray(); [ConditionalTheory(nameof(LocalServerAvailable))] diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs index f218ce2875128..e86c79b2bf73f 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs @@ -10,9 +10,9 @@ namespace System.Net.Security public readonly struct SslApplicationProtocol : IEquatable { private static readonly Encoding s_utf8 = Encoding.GetEncoding(Encoding.UTF8.CodePage, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); - private static readonly byte[] s_http3Utf8 = new byte[] { 0x68, 0x33 }; // "h3" - private static readonly byte[] s_http2Utf8 = new byte[] { 0x68, 0x32 }; // "h2" - private static readonly byte[] s_http11Utf8 = new byte[] { 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31 }; // "http/1.1" + private static readonly byte[] s_http3Utf8 = "h3"u8.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 /// Defines a instance for HTTP 3.0. diff --git a/src/libraries/System.Net.Security/tests/EnterpriseTests/NegotiateStreamLoopbackTest.cs b/src/libraries/System.Net.Security/tests/EnterpriseTests/NegotiateStreamLoopbackTest.cs index bf8272c3f097e..d6815f599a217 100644 --- a/src/libraries/System.Net.Security/tests/EnterpriseTests/NegotiateStreamLoopbackTest.cs +++ b/src/libraries/System.Net.Security/tests/EnterpriseTests/NegotiateStreamLoopbackTest.cs @@ -23,7 +23,7 @@ private static Task WhenAllOrAnyFailedWithTimeout(params Task[] tasks) => private const string TargetName = "HOST/linuxclient.linux.contoso.com"; private const int PartialBytesToRead = 5; - private static readonly byte[] s_sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message"); + private static readonly byte[] s_sampleMsg = "Sample Test Message"u8.ToArray(); private const int MaxWriteDataSize = 63 * 1024; // NegoState.MaxWriteDataSize private static string s_longString = new string('A', MaxWriteDataSize) + 'Z'; diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamInvalidOperationTest.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamInvalidOperationTest.cs index bbfefa4223d6b..b61b0ef105a63 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamInvalidOperationTest.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamInvalidOperationTest.cs @@ -19,7 +19,7 @@ namespace System.Net.Security.Tests [PlatformSpecific(TestPlatforms.Windows)] // NegotiateStream only supports client-side functionality on Unix public class NegotiateStreamInvalidOperationTest { - private static readonly byte[] s_sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message"); + private static readonly byte[] s_sampleMsg = "Sample Test Message"u8.ToArray(); private const string TargetName = "testTargetName"; [Fact] diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamKerberosTest.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamKerberosTest.cs index 8ca45a58f4638..df74c839db7dc 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamKerberosTest.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamKerberosTest.cs @@ -157,7 +157,7 @@ await auth.AuthenticateAsClientAsync( Assert.True(auth.IsSigned); // Send a message to the server. Encode the test data into a byte array. - byte[] message = Encoding.UTF8.GetBytes("Hello from the client."); + byte[] message = "Hello from the client."u8.ToArray(); await auth.WriteAsync(message, 0, message.Length); } } diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs index 043ab1fd09d34..76a1c318928af 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs @@ -20,7 +20,7 @@ public abstract class NegotiateStreamStreamToStreamTest public static bool IsNtlmInstalled => Capability.IsNtlmInstalled(); private const int PartialBytesToRead = 5; - protected static readonly byte[] s_sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message"); + protected static readonly byte[] s_sampleMsg = "Sample Test Message"u8.ToArray(); private const int MaxWriteDataSize = 63 * 1024; // NegoState.MaxWriteDataSize private static string s_longString = new string('A', MaxWriteDataSize) + 'Z'; diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamAllowRenegotiationTests.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamAllowRenegotiationTests.cs index 7520221e6e9a3..469c0a13b7114 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamAllowRenegotiationTests.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamAllowRenegotiationTests.cs @@ -55,7 +55,7 @@ public async Task SslStream_AllowRenegotiation_True_Succeeds() Assert.True(ssl.IsEncrypted); // Issue request that triggers renegotiation from server. - byte[] message = Encoding.UTF8.GetBytes("GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"); + byte[] message = "GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"u8.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 @@ public async Task SslStream_AllowRenegotiation_False_Throws() Assert.True(ssl.IsEncrypted); // Issue request that triggers regotiation from server. - byte[] message = Encoding.UTF8.GetBytes("GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"); + byte[] message = "GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"u8.ToArray(); await ssl.WriteAsync(message, 0, message.Length); // Initiate Read operation, that results in starting renegotiation as per server response to the above request. diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamNetworkStreamTest.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamNetworkStreamTest.cs index 2de22f5325cd3..1c8cfdb54b4ec 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamNetworkStreamTest.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamNetworkStreamTest.cs @@ -164,7 +164,7 @@ public async Task SslStream_NetworkStream_Renegotiation_Succeeds(bool useSync) Assert.True(ssl.IsEncrypted); // Issue request that triggers regotiation from server. - byte[] message = Encoding.UTF8.GetBytes("GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"); + byte[] message = "GET /EchoClientCertificate.ashx HTTP/1.1\r\nHost: corefx-net-tls.azurewebsites.net\r\n\r\n"u8.ToArray(); if (useSync) { ssl.Write(message, 0, message.Length); diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamStreamToStreamTest.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamStreamToStreamTest.cs index 8d0dae26892b5..873f7546e65f7 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamStreamToStreamTest.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamStreamToStreamTest.cs @@ -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 func) { diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/TestHelper.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/TestHelper.cs index 0a5c14df84112..cd526ac5a27ba 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/TestHelper.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/TestHelper.cs @@ -43,8 +43,8 @@ public static class TestHelper private static readonly X509BasicConstraintsExtension s_eeConstraints = new X509BasicConstraintsExtension(false, false, 0, false); - public static readonly byte[] s_ping = Encoding.UTF8.GetBytes("PING"); - public static readonly byte[] s_pong = Encoding.UTF8.GetBytes("PONG"); + public static readonly byte[] s_ping = "PING"u8.ToArray(); + public static readonly byte[] s_pong = "PONG"u8.ToArray(); public static bool AllowAnyServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { diff --git a/src/libraries/System.Net.Security/tests/UnitTests/SslApplicationProtocolTests.cs b/src/libraries/System.Net.Security/tests/UnitTests/SslApplicationProtocolTests.cs index fe016e6c631ef..477abd602d0ef 100644 --- a/src/libraries/System.Net.Security/tests/UnitTests/SslApplicationProtocolTests.cs +++ b/src/libraries/System.Net.Security/tests/UnitTests/SslApplicationProtocolTests.cs @@ -13,9 +13,9 @@ public class SslApplicationProtocolTests [Fact] public void Constants_Values_AreCorrect() { - Assert.Equal(new SslApplicationProtocol(new byte[] { 0x68, 0x33 }), SslApplicationProtocol.Http3); - Assert.Equal(new SslApplicationProtocol(new byte[] { 0x68, 0x32 }), SslApplicationProtocol.Http2); - Assert.Equal(new SslApplicationProtocol(new byte[] { 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31 }), SslApplicationProtocol.Http11); + Assert.Equal(new SslApplicationProtocol("h3"u8.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 @@ public void Constructor_Overloads_Succeeds() [Fact] public void Constructor_ByteArray_Copies() { - byte[] expected = Encoding.UTF8.GetBytes("hello"); + byte[] expected = "hello"u8.ToArray(); SslApplicationProtocol byteProtocol = new SslApplicationProtocol(expected); ArraySegment arraySegment; diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/TcpClientTest.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/TcpClientTest.cs index e9bd105165f41..6a86b2c5fabf9 100644 --- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/TcpClientTest.cs +++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/TcpClientTest.cs @@ -190,7 +190,7 @@ public async Task ConnectAsync_DnsEndPoint_Success(int mode) using (NetworkStream s = client.GetStream()) { - byte[] getRequest = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\n\r\n"); + byte[] getRequest = "GET / HTTP/1.1\r\n\r\n"u8.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 @@ public void Connect_DnsEndPoint_Success(int mode) using (NetworkStream s = client.GetStream()) { - byte[] getRequest = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\n\r\n"); + byte[] getRequest = "GET / HTTP/1.1\r\n\r\n"u8.ToArray(); s.Write(getRequest, 0, getRequest.Length); Assert.NotEqual(-1, s.ReadByte()); // just verify we successfully get any data back } diff --git a/src/libraries/System.Net.WebSockets/tests/WebSocketCreateTest.cs b/src/libraries/System.Net.WebSockets/tests/WebSocketCreateTest.cs index f9fd4e3c564e5..ac0035eb41591 100644 --- a/src/libraries/System.Net.WebSockets/tests/WebSocketCreateTest.cs +++ b/src/libraries/System.Net.WebSockets/tests/WebSocketCreateTest.cs @@ -77,7 +77,7 @@ public async Task WebSocketProtocol_CreateFromConnectedStream_CanSendReceiveData public async Task ReceiveAsync_UTF8SplitAcrossMultipleBuffers_ValidDataReceived() { // 1 character - 2 bytes - byte[] payload = Encoding.UTF8.GetBytes("\u00E6"); + byte[] payload = "\u00E6"u8.ToArray(); var frame = new byte[payload.Length + 2]; frame[0] = 0x81; // FIN = true, Opcode = Text frame[1] = (byte)payload.Length; @@ -294,7 +294,7 @@ public async Task WebSocketProtocol_CreateFromConnectedStream_CloseAsyncAfterClo Assert.Equal(WebSocketState.Open, socket.State); // Ask server to send us a close - await socket.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes(".close")), WebSocketMessageType.Text, true, default); + await socket.SendAsync(new ArraySegment(".close"u8.ToArray()), WebSocketMessageType.Text, true, default); // Verify received server-initiated close message. WebSocketReceiveResult recvResult = await socket.ReceiveAsync(new ArraySegment(new byte[256]), default); diff --git a/src/libraries/System.Net.WebSockets/tests/WebSocketDeflateTests.cs b/src/libraries/System.Net.WebSockets/tests/WebSocketDeflateTests.cs index 03ae5981c9b89..cec40f41f87c7 100644 --- a/src/libraries/System.Net.WebSockets/tests/WebSocketDeflateTests.cs +++ b/src/libraries/System.Net.WebSockets/tests/WebSocketDeflateTests.cs @@ -77,11 +77,11 @@ public async Task SendHelloWithContextTakeover() DangerousDeflateOptions = new WebSocketDeflateOptions() }); - await websocket.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken); + await websocket.SendAsync("Hello"u8.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 @@ public async Task SendHelloWithDisableCompression() 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 @@ public async Task SendHelloWithEmptyFrame() DangerousDeflateOptions = new WebSocketDeflateOptions() }); - byte[] bytes = Encoding.UTF8.GetBytes("Hello"); + byte[] bytes = "Hello"u8.ToArray(); await websocket.SendAsync(Memory.Empty, WebSocketMessageType.Text, endOfMessage: false, CancellationToken); await websocket.SendAsync(bytes, WebSocketMessageType.Text, endOfMessage: true, CancellationToken); @@ -181,7 +181,7 @@ public async Task SendHelloWithoutContextTakeover() for (var i = 0; i < 100; ++i) { - await websocket.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken); + await websocket.SendAsync("Hello"u8.ToArray(), WebSocketMessageType.Text, true, CancellationToken); // Without context takeover the message should look the same every time Assert.Equal("C107F248CDC9C90700", Convert.ToHexString(stream.NextAvailableBytes)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs index 7d9bab87855fd..a700b7184ef06 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs @@ -31,11 +31,11 @@ private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } // UTF-8 is fastpath, so that's how these are stored // Compare methods adapt to Unicode. - private static readonly byte[] s_encodingAttr = new byte[] { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g' }; - private static readonly byte[] s_encodingUTF8 = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8' }; - private static readonly byte[] s_encodingUnicode = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6' }; - private static readonly byte[] s_encodingUnicodeLE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'l', (byte)'e' }; - private static readonly byte[] s_encodingUnicodeBE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'b', (byte)'e' }; + private static readonly byte[] s_encodingAttr = "encoding"u8.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; diff --git a/src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/NamespaceHandlingTests.cs b/src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/NamespaceHandlingTests.cs index a1cfd7ec90b65..cb6ebbe413a2e 100644 --- a/src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/NamespaceHandlingTests.cs +++ b/src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/NamespaceHandlingTests.cs @@ -758,7 +758,7 @@ public void NS_Handling_22(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; - byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; + byte[] buffer = "abc"u8.ToArray(); using (XmlWriter w = CreateMemWriter(utils, wSettings)) { @@ -780,7 +780,7 @@ public void NS_Handling_23(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; - byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; + byte[] buffer = "abc"u8.ToArray(); using (XmlWriter w = CreateMemWriter(utils, wSettings)) { @@ -803,7 +803,7 @@ public void NS_Handling_24(XmlWriterUtils utils, NamespaceHandling nsHandling) XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlWriter w = CreateMemWriter(utils, wSettings); - byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; + byte[] buffer = "abc"u8.ToArray(); w.WriteStartElement("A"); w.WriteAttributeString("xmlns", "p", null, "ns1"); diff --git a/src/libraries/System.Private.Xml/tests/XmlNodeReader/System.Xml.XmlNodeReader.Tests/XmlNodeReaderReadTests.cs b/src/libraries/System.Private.Xml/tests/XmlNodeReader/System.Xml.XmlNodeReader.Tests/XmlNodeReaderReadTests.cs index c690713172963..8365c4cd27c79 100644 --- a/src/libraries/System.Private.Xml/tests/XmlNodeReader/System.Xml.XmlNodeReader.Tests/XmlNodeReaderReadTests.cs +++ b/src/libraries/System.Private.Xml/tests/XmlNodeReader/System.Xml.XmlNodeReader.Tests/XmlNodeReaderReadTests.cs @@ -153,7 +153,7 @@ public void NodeReaderReadContentAsBase64WithEmptyXml() [Fact] public void NodeReaderReadContentAsBase64WithSimpleXml() { - byte[] byteData = Encoding.ASCII.GetBytes("hello world"); + byte[] byteData = "hello world"u8.ToArray(); string xml = $""; //hello world encoded XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml); Assert.True(nodeReader.Read()); @@ -179,7 +179,7 @@ public void NodeReaderReadContentAsBinHexWithEmptyXml() [Fact] public void NodeReaderReadContentAsBinHexWithSimpleXml() { - byte[] byteData = Encoding.ASCII.GetBytes("hello world"); + byte[] byteData = "hello world"u8.ToArray(); string xml = $""; XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml); Assert.True(nodeReader.Read()); @@ -205,7 +205,7 @@ public void NodeReaderReadElementContentAsBase64WithEmptyXml() [Fact] public void NodeReaderReadElementContentAsBase64WithSimpleXml() { - byte[] byteData = Encoding.ASCII.GetBytes("hello world"); + byte[] byteData = "hello world"u8.ToArray(); string xml = $"{Convert.ToBase64String(byteData)}"; //hello world encoded XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml); Assert.True(nodeReader.Read()); @@ -229,7 +229,7 @@ public void NodeReaderReadElementContentAsBinHexWithEmptyXml() [Fact] public void NodeReaderReadElementContentAsBinHexWithSimpleXml() { - byte[] byteData = Encoding.ASCII.GetBytes("hello world"); + byte[] byteData = "hello world"u8.ToArray(); string xml = $"{BitConverter.ToString(byteData).Replace("-", "")}"; XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml); Assert.True(nodeReader.Read()); diff --git a/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverAddRemoveTests.cs b/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverAddRemoveTests.cs index 1ca6c15354dc3..7c8afc8e34355 100644 --- a/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverAddRemoveTests.cs +++ b/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverAddRemoveTests.cs @@ -40,7 +40,7 @@ public void XmlResolverAddWithValidData() { var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10); - byte[] data = Encoding.ASCII.GetBytes("hello world"); + byte[] data = "hello world"u8.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 @@ public void XmlResolverRemoveWithInvalidData() 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)); diff --git a/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverGetEntity.cs b/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverGetEntity.cs index 061d666ac6076..b3cf95c6bffa8 100644 --- a/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverGetEntity.cs +++ b/src/libraries/System.Private.Xml/tests/XmlResolver/System.Xml.XmlResolver.Tests/XmlPreloadedResolverGetEntity.cs @@ -108,7 +108,7 @@ public void XmlResolverGetEntityAsyncWithInvalidData() [Fact] public void XmlResolverGetEntityAsyncWithValidUserSuppliedData() { - byte[] inpData = Encoding.ASCII.GetBytes("hello world"); + byte[] inpData = "hello world"u8.ToArray(); var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10); xmlResolver.Add(new Uri("-//W3C//DTD FAKE 1.0 Not Real//EN", UriKind.RelativeOrAbsolute), inpData); Task output = xmlResolver.GetEntityAsync(new Uri("-//W3C//DTD FAKE 1.0 Not Real//EN", diff --git a/src/libraries/System.Reflection.Metadata/tests/Metadata/MetadataReaderTests.cs b/src/libraries/System.Reflection.Metadata/tests/Metadata/MetadataReaderTests.cs index f02b3e292b413..2ae28cfe7c90d 100644 --- a/src/libraries/System.Reflection.Metadata/tests/Metadata/MetadataReaderTests.cs +++ b/src/libraries/System.Reflection.Metadata/tests/Metadata/MetadataReaderTests.cs @@ -126,7 +126,7 @@ public unsafe void InvalidFindMscorlibAssemblyRefNoProjection() PEHeaders headers = new PEHeaders(new MemoryStream(peImage)); //find index for mscorlib - int mscorlibIndex = IndexOf(peImage, Encoding.ASCII.GetBytes("mscorlib"), headers.MetadataStartOffset); + int mscorlibIndex = IndexOf(peImage, "mscorlib"u8.ToArray(), headers.MetadataStartOffset); Assert.NotEqual(-1, mscorlibIndex); //mutate mscorlib peImage[mscorlibIndex + headers.MetadataStartOffset] = 0xFF; @@ -145,7 +145,7 @@ public unsafe void InvalidStreamHeaderLengths() // mutate CLR to reach MetadataKind.WindowsMetadata // find CLR - int clrIndex = IndexOf(peImage, Encoding.ASCII.GetBytes("CLR"), headers.MetadataStartOffset); + int clrIndex = IndexOf(peImage, "CLR"u8.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 @@ public void GetString_WinRTPrefixed_Projected() winrtDef.Attributes); var strReader = reader.GetBlobReader(winrtDef.Name); - Assert.Equal(Encoding.UTF8.GetBytes("Class1"), strReader.ReadBytes("Class1".Length)); + Assert.Equal("Class1"u8.ToArray(), strReader.ReadBytes("Class1".Length)); Assert.Equal(0, strReader.RemainingBytes); // .class /*02000003*/ private auto ansi import windowsruntime sealed beforefieldinit Lib.'Class1' @@ -449,7 +449,7 @@ public void GetString_WinRTPrefixed_Projected() clrDef.Attributes); strReader = reader.GetBlobReader(clrDef.Name); - Assert.Equal(Encoding.UTF8.GetBytes("Class1"), strReader.ReadBytes("Class1".Length)); + Assert.Equal("Class1"u8.ToArray(), strReader.ReadBytes("Class1".Length)); Assert.Equal(0, strReader.RemainingBytes); } @@ -469,7 +469,7 @@ public void GetString_WinRTPrefixed_NotProjected() winrtDef.Attributes); var strReader = reader.GetBlobReader(winrtDef.Name); - Assert.Equal(Encoding.UTF8.GetBytes("Class1"), strReader.ReadBytes("Class1".Length)); + Assert.Equal("Class1"u8.ToArray(), strReader.ReadBytes("Class1".Length)); Assert.Equal(0, strReader.RemainingBytes); // .class /*02000003*/ public auto ansi windowsruntime sealed beforefieldinit Lib.Class1 @@ -483,7 +483,7 @@ public void GetString_WinRTPrefixed_NotProjected() clrDef.Attributes); strReader = reader.GetBlobReader(clrDef.Name); - Assert.Equal(Encoding.UTF8.GetBytes("Class1"), strReader.ReadBytes("Class1".Length)); + Assert.Equal("Class1"u8.ToArray(), strReader.ReadBytes("Class1".Length)); Assert.Equal(0, strReader.RemainingBytes); } @@ -497,14 +497,14 @@ public void GetString_DotTerminated() Assert.Equal("System.Runtime.CompilerServices", reader.GetString(typeRef.Namespace)); var strReader = reader.GetBlobReader(typeRef.Namespace); - Assert.Equal(Encoding.UTF8.GetBytes("System.Runtime.CompilerServices"), strReader.ReadBytes("System.Runtime.CompilerServices".Length)); + Assert.Equal("System.Runtime.CompilerServices"u8.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); } diff --git a/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs b/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs index 20f68af287870..657c30295fd1a 100644 --- a/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs +++ b/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs @@ -31,7 +31,7 @@ public void ReadNullPaddedUTF8RemovesNullPadding() [Fact] public void ReadNullPaddedUTF8WorksWithNoNullPadding() { - var headerBytes = Encoding.UTF8.GetBytes(".abcdefg"); + var headerBytes = ".abcdefg"u8.ToArray(); var stream = new MemoryStream(headerBytes); stream.Position = 0; diff --git a/src/libraries/System.Reflection.Metadata/tests/Utilities/BlobReaderTests.cs b/src/libraries/System.Reflection.Metadata/tests/Utilities/BlobReaderTests.cs index 096846d0ce49e..710871e0c29bd 100644 --- a/src/libraries/System.Reflection.Metadata/tests/Utilities/BlobReaderTests.cs +++ b/src/libraries/System.Reflection.Metadata/tests/Utilities/BlobReaderTests.cs @@ -389,7 +389,7 @@ public unsafe void ReadFromMemoryBlock() Assert.Equal("", block.PeekUtf8NullTerminated(4, null, stringDecoder, out bytesRead)); Assert.Equal(0, bytesRead); - byte[] helloPrefix = Encoding.UTF8.GetBytes("Hello"); + byte[] helloPrefix = "Hello"u8.ToArray(); Assert.Equal("Hello\u0001", block.PeekUtf8NullTerminated(1, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(2, bytesRead); diff --git a/src/libraries/System.Reflection.Metadata/tests/Utilities/MemoryBlockTests.cs b/src/libraries/System.Reflection.Metadata/tests/Utilities/MemoryBlockTests.cs index 2fd01ef55a10d..8f346defebe77 100644 --- a/src/libraries/System.Reflection.Metadata/tests/Utilities/MemoryBlockTests.cs +++ b/src/libraries/System.Reflection.Metadata/tests/Utilities/MemoryBlockTests.cs @@ -20,20 +20,20 @@ public unsafe void Utf8NullTerminatedStringStartsWithAsciiPrefix() Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, "")); } - fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("Hello World!\0"))) + fixed (byte* heapPtr = (heap = "Hello World!\0"u8.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 @@ public unsafe void DefaultDecodingFallbackMatchesBcl() Assert.Equal(s, Encoding.UTF8.GetString(buffer)); Assert.Equal(buffer.Length, bytesRead); - s = new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, Encoding.UTF8.GetBytes("Hello"), decoder, out bytesRead); + s = new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, "Hello"u8.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 @@ public unsafe void DecoderIsUsedCorrectly() } ); - 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); } diff --git a/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToBase64CharArray.cs b/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToBase64CharArray.cs index d888e140c4af0..c3169476f26a7 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToBase64CharArray.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToBase64CharArray.cs @@ -21,7 +21,7 @@ public static void ValidOffsetIn() public static void ShortInputArray() { // Regression test for bug where a short input array caused an exception to be thrown - byte[] inputBuffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; + byte[] inputBuffer = "abc"u8.ToArray(); char[] ouputBuffer = new char[4]; Convert.ToBase64CharArray(inputBuffer, 0, 3, ouputBuffer, 0); Convert.ToBase64CharArray(inputBuffer, 0, 2, ouputBuffer, 0); diff --git a/src/libraries/System.Runtime.Extensions/tests/System/Net/WebUtility.cs b/src/libraries/System.Runtime.Extensions/tests/System/Net/WebUtility.cs index 5a9bbab770e8a..a6c0efcfd9bf2 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/Net/WebUtility.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/Net/WebUtility.cs @@ -437,7 +437,7 @@ public static void UrlEncodeToBytes_NoEncodingNeeded_ReturnsNewClonedArray() // prevent problems where the input array is changed if // the output one is modified. - byte[] input = Encoding.UTF8.GetBytes("Dont.Need.Encoding"); + byte[] input = "Dont.Need.Encoding"u8.ToArray(); byte[] output = WebUtility.UrlEncodeToBytes(input, 0, input.Length); Assert.NotSame(input, output); } @@ -445,7 +445,7 @@ public static void UrlEncodeToBytes_NoEncodingNeeded_ReturnsNewClonedArray() [Fact] public static void UrlDecodeToBytes_NoDecodingNeeded_ReturnsNewClonedArray() { - byte[] input = Encoding.UTF8.GetBytes("Dont.Need.Decoding"); + byte[] input = "Dont.Need.Decoding"u8.ToArray(); byte[] output = WebUtility.UrlDecodeToBytes(input, 0, input.Length); Assert.NotSame(input, output); } diff --git a/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/SampleTypes.cs b/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/SampleTypes.cs index 81d2acff15d42..56af61b4e3eca 100644 --- a/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/SampleTypes.cs +++ b/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/SampleTypes.cs @@ -4147,7 +4147,7 @@ public class DCWithReadOnlyField public class IReadWriteXmlWriteBinHex_EqualityDefined : IXmlSerializable { - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8.ToArray(); public System.Xml.Schema.XmlSchema GetSchema() { @@ -4176,7 +4176,7 @@ public virtual void ReadXml(System.Xml.XmlReader reader) public virtual void WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8.ToArray(); writer.WriteBinHex(bits, 0, bits.Length); } @@ -4202,7 +4202,7 @@ public override int GetHashCode() internal class PrivateIXmlSerializables : IXmlSerializable { - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8.ToArray(); public System.Xml.Schema.XmlSchema GetSchema() { @@ -4231,7 +4231,7 @@ public virtual void ReadXml(System.Xml.XmlReader reader) public virtual void WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8.ToArray(); writer.WriteBinHex(bits, 0, bits.Length); } } @@ -4241,7 +4241,7 @@ public class PrivateDefaultCtorIXmlSerializables : IXmlSerializable private PrivateDefaultCtorIXmlSerializables() { } public PrivateDefaultCtorIXmlSerializables(bool init) { } - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8.ToArray(); public System.Xml.Schema.XmlSchema GetSchema() { @@ -4270,7 +4270,7 @@ public virtual void ReadXml(System.Xml.XmlReader reader) public virtual void WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8.ToArray(); writer.WriteBinHex(bits, 0, bits.Length); } } @@ -4278,7 +4278,7 @@ public virtual void WriteXml(System.Xml.XmlWriter writer) [XmlSchemaProvider("MySchema")] public class PublicIXmlSerializablesWithPublicSchemaProvider : IXmlSerializable { - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8.ToArray(); public System.Xml.Schema.XmlSchema GetSchema() { @@ -4312,7 +4312,7 @@ public virtual void ReadXml(System.Xml.XmlReader reader) public virtual void WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8.ToArray(); writer.WriteBinHex(bits, 0, bits.Length); } } @@ -4320,7 +4320,7 @@ public virtual void WriteXml(System.Xml.XmlWriter writer) [XmlSchemaProvider("MySchema")] public class PublicExplicitIXmlSerializablesWithPublicSchemaProvider : IXmlSerializable { - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8.ToArray(); System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() { @@ -4354,7 +4354,7 @@ void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8.ToArray(); writer.WriteBinHex(bits, 0, bits.Length); } } @@ -4362,7 +4362,7 @@ void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) [XmlSchemaProvider("MySchema")] public class PublicIXmlSerializablesWithPrivateSchemaProvider : IXmlSerializable { - private byte[] _bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + private byte[] _bits = "hello world"u8.ToArray(); public System.Xml.Schema.XmlSchema GetSchema() { @@ -4396,7 +4396,7 @@ public virtual void ReadXml(System.Xml.XmlReader reader) public virtual void WriteXml(System.Xml.XmlWriter writer) { - byte[] bits = System.Text.Encoding.UTF8.GetBytes("hello world"); + byte[] bits = "hello world"u8.ToArray(); writer.WriteBinHex(bits, 0, bits.Length); } } diff --git a/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs b/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs index 80d4eac5790bf..278e41276b4ed 100644 --- a/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs +++ b/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs @@ -21,7 +21,7 @@ public class CoseTestHelpers internal const int KnownHeaderIV = 5; internal const int KnownHeaderPartialIV = 6; internal const int KnownHeaderCounterSignature = 7; - internal static readonly byte[] s_sampleContent = Encoding.UTF8.GetBytes("This is the content."); + internal static readonly byte[] s_sampleContent = "This is the content."u8.ToArray(); internal const string ContentTypeDummyValue = "application/cose; cose-type=\"cose-sign1\""; internal const string NullCborHex = "F6"; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampRequestTests.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampRequestTests.cs index 850232f8fe22c..53662bea6c013 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampRequestTests.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampRequestTests.cs @@ -16,7 +16,7 @@ public static class TimestampRequestTests public static void BuildExpectedRequest_FromData(bool viaSpan) { Rfc3161TimestampRequest request = Rfc3161TimestampRequest.CreateFromData( - System.Text.Encoding.ASCII.GetBytes("Hello, world!!"), + "Hello, world!!"u8, HashAlgorithmName.SHA256, requestSignerCertificates: true); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampTokenTestData.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampTokenTestData.cs index dba1da3050966..61ed97aa0fc6a 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampTokenTestData.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampTokenTestData.cs @@ -100,7 +100,7 @@ internal static TimestampTokenTestData GetTestData(string testDataName) "D50DF295F1DB078C84EECBCB30F1018E939B1FEA8615B31F39F87F02EF816EFF" + "FE80A39C0857ECA510882DD2D66D49B743F0E7FF8DBEE4650449"); - data.MessageContent = Encoding.ASCII.GetBytes("This is a test.\n"); + data.MessageContent = "This is a test.\n"u8.ToArray(); data.TokenInfoBytes = data.FullTokenBytes.Slice(64, 412); data.PolicyId = "1.2.3.4.1"; @@ -283,7 +283,7 @@ internal static TimestampTokenTestData GetTestData(string testDataName) "FD6B6AB4F89DC6750F14EC2E0134BA61B4D0B2C1FB2F60F622379249CE6381AF" + "667900B17A7BB6AE"); - data.MessageContent = Encoding.ASCII.GetBytes("Hello, world!"); + data.MessageContent = "Hello, world!"u8.ToArray(); data.EmbeddedSigningCertificate = data.FullTokenBytes.Slice(1659, 1359); @@ -422,7 +422,7 @@ internal static TimestampTokenTestData GetTestData(string testDataName) "76252A2F4605B97BD3C299D1CD79929273BB86E7DF9E113C92802380ED6D4041" + "9DA4C01214D4FA24"); - data.MessageContent = Encoding.UTF8.GetBytes("My TST signer attributes are sorted incorrectly."); + data.MessageContent = "My TST signer attributes are sorted incorrectly."u8.ToArray(); data.EmbeddedSigningCertificate = data.FullTokenBytes.Slice(188, 1670); diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs b/src/libraries/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs index b4a4487a1ce5f..745049b3c7803 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs @@ -347,7 +347,7 @@ public static void TestKey_RSA384_ValidatesSignature() 0x11, 0xE0, 0x6E, 0xD2, 0x22, 0x75, 0xE7, 0x7C, }; - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); + byte[] helloBytes = "Hello"u8.ToArray(); using (var cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes)) using (RSA rsa = cert.GetRSAPublicKey()) @@ -360,7 +360,7 @@ public static void TestKey_RSA384_ValidatesSignature() public static void TestKey_ECDsabrainpool_PublicKey(byte[] curveData, byte[] notUsed) { _ = notUsed; - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); + byte[] helloBytes = "Hello"u8.ToArray(); try { @@ -386,7 +386,7 @@ public static void TestKey_ECDsabrainpool_PublicKey(byte[] curveData, byte[] not [Fact] public static void TestECDsaPublicKey() { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); + byte[] helloBytes = "Hello"u8.ToArray(); using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) @@ -439,7 +439,7 @@ public static void TestECDsaPublicKey_ValidatesSignature() 0x08, 0xC5, 0xAA, 0xA6, 0xE5, 0xFD, 0xD0, 0x96, }; - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); + byte[] helloBytes = "Hello"u8.ToArray(); using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) @@ -476,7 +476,7 @@ public static void TestECDHPublicKey_DeriveSecret() [Theory, MemberData(nameof(BrainpoolCurves))] public static void TestECDsaPublicKey_BrainpoolP160r1_ValidatesSignature(byte[] curveData, byte[] existingSignature) { - byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); + byte[] helloBytes = "Hello"u8.ToArray(); try { diff --git a/src/libraries/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs b/src/libraries/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs index 5e11d90889934..5af72f7c03d52 100644 --- a/src/libraries/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs +++ b/src/libraries/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs @@ -611,7 +611,7 @@ public void EncryptKey_RSA_RSANull() [Fact] public void EncryptKey_RSA_UseOAEP() { - byte[] data = Encoding.ASCII.GetBytes("12345678"); + byte[] data = "12345678"u8.ToArray(); using (RSA rsa = RSA.Create()) { byte[] encryptedData = EncryptedXml.EncryptKey(data, rsa, true); @@ -852,7 +852,7 @@ public void EncryptKey_TripleDES() { using (TripleDES tripleDES = TripleDES.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678"); + byte[] key = "123456781234567812345678"u8.ToArray(); byte[] encryptedKey = EncryptedXml.EncryptKey(key, tripleDES); @@ -866,7 +866,7 @@ public void EncryptKey_AES() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678"); + byte[] key = "123456781234567812345678"u8.ToArray(); byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes); @@ -880,7 +880,7 @@ public void EncryptKey_AES8Bytes() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("12345678"); + byte[] key = "12345678"u8.ToArray(); byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes); @@ -894,7 +894,7 @@ public void EncryptKey_AESNotDivisibleBy8() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("1234567"); + byte[] key = "1234567"u8.ToArray(); Assert.Throws(() => EncryptedXml.EncryptKey(key, aes)); } @@ -905,7 +905,7 @@ public void DecryptKey_TripleDESWrongKeySize() { using (TripleDES tripleDES = TripleDES.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123"); + byte[] key = "123"u8.ToArray(); Assert.Throws(() => EncryptedXml.DecryptKey(key, tripleDES)); } @@ -916,7 +916,7 @@ public void DecryptKey_TripleDESCorruptedKey() { using (TripleDES tripleDES = TripleDES.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678"); + byte[] key = "123456781234567812345678"u8.ToArray(); byte[] encryptedKey = EncryptedXml.EncryptKey(key, tripleDES); encryptedKey[0] ^= 0xFF; @@ -930,7 +930,7 @@ public void DecryptKey_AESWrongKeySize() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123"); + byte[] key = "123"u8.ToArray(); Assert.Throws(() => EncryptedXml.DecryptKey(key, aes)); } @@ -941,7 +941,7 @@ public void DecryptKey_AESCorruptedKey() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678"); + byte[] key = "123456781234567812345678"u8.ToArray(); byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes); encryptedKey[0] ^= 0xFF; @@ -955,7 +955,7 @@ public void DecryptKey_AESCorruptedKey8Bytes() { using (Aes aes = Aes.Create()) { - byte[] key = Encoding.ASCII.GetBytes("12345678"); + byte[] key = "12345678"u8.ToArray(); byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes); encryptedKey[0] ^= 0xFF; diff --git a/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs b/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs index 1265c37bc42b7..ac5d3560a32da 100644 --- a/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs +++ b/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs @@ -1447,7 +1447,7 @@ static void hmacMustBeMultipleOfEightBits(int bits) "; SignedXml sign = GetSignedXml(string.Format(xml, bits)); // only multiple of 8 bits are supported - sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("secret"))); + sign.CheckSignature(new HMACSHA1("secret"u8.ToArray())); } for (int i = 1; i < 160; i++) @@ -1483,10 +1483,10 @@ public void VerifyHMAC_ZeroLength() "; 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 @@ public void VerifyHMAC_SmallerThanMinimumLength() // 72 is a multiple of 8 but smaller than the minimum of 80 bits string xml = @"72nz4GS0NbH2SrWlD/4fX313CoTzc=2dimB+P5Aw5Ksome other text"; SignedXml sign = GetSignedXml(xml); - CheckErratum(sign, new HMACSHA1(Encoding.ASCII.GetBytes("secret")), "72"); + CheckErratum(sign, new HMACSHA1("secret"u8.ToArray()), "72"); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")] @@ -1506,7 +1506,7 @@ public void VerifyHMAC_MinimumLength() // 80 bits is the minimum (and the half-size of HMACSHA1) string xml = @"80nz4GS0NbH2SrWlD/4fX313CoTzc=jVQPtLj61zNYjw==some other text"; SignedXml sign = GetSignedXml(xml); - Assert.True(sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("secret")))); + Assert.True(sign.CheckSignature(new HMACSHA1("secret"u8.ToArray()))); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")] @@ -1516,7 +1516,7 @@ public void VerifyHMAC_SmallerHalfLength() // 80bits is smaller than the half-size of HMACSHA256 string xml = @"80nz4GS0NbH2SrWlD/4fX313CoTzc=vPtw7zKVV/JwQg==some other text"; SignedXml sign = GetSignedXml(xml); - CheckErratum(sign, new HMACSHA256(Encoding.ASCII.GetBytes("secret")), "80"); + CheckErratum(sign, new HMACSHA256("secret"u8.ToArray()), "80"); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")] @@ -1526,7 +1526,7 @@ public void VerifyHMAC_HalfLength() // 128 is the half-size of HMACSHA256 string xml = @"128nz4GS0NbH2SrWlD/4fX313CoTzc=aegpvkAwOL8gN/CjSnW6qw==some other text"; SignedXml sign = GetSignedXml(xml); - Assert.True(sign.CheckSignature(new HMACSHA256(Encoding.ASCII.GetBytes("secret")))); + Assert.True(sign.CheckSignature(new HMACSHA256("secret"u8.ToArray()))); } [Fact] @@ -1534,7 +1534,7 @@ public void VerifyHMAC_FullLength() { string xml = @"7/XTsHaBSOnJ/jXD5v0zL6VKYsk=a0goL9esBUKPqtFYgpp2KST4huk=some text"; SignedXml sign = GetSignedXml(xml); - Assert.True(sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("secret")))); + Assert.True(sign.CheckSignature(new HMACSHA1("secret"u8.ToArray()))); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")] @@ -1559,7 +1559,7 @@ public void VerifyHMAC_HMACOutputLength_Signature_Mismatch() "; SignedXml sign = GetSignedXml(xml); - Assert.Throws(() => sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("no clue")))); + Assert.Throws(() => sign.CheckSignature(new HMACSHA1("no clue"u8.ToArray()))); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20429")] @@ -1584,7 +1584,7 @@ public void VerifyHMAC_HMACOutputLength_Invalid() "; SignedXml sign = GetSignedXml(xml); - Assert.Throws(() => sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("no clue")))); + Assert.Throws(() => sign.CheckSignature(new HMACSHA1("no clue"u8.ToArray()))); } [Fact] diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.Pem.iOS.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.Pem.iOS.cs index 6862508a7845c..a22e8b3ff0d82 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.Pem.iOS.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.Pem.iOS.cs @@ -10,9 +10,6 @@ namespace System.Security.Cryptography.X509Certificates { internal sealed partial class AppleCertificatePal : ICertificatePal { - // Byte representation of "-----BEGIN " - private static ReadOnlySpan PemBegin => new byte[] { 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x42, 0x45, 0x47, 0x49, 0x4E, 0x20 }; - internal delegate bool DerCallback(ReadOnlySpan derData, X509ContentType contentType); internal static bool TryDecodePem(ReadOnlySpan rawData, DerCallback derCallback) @@ -27,7 +24,7 @@ internal static bool TryDecodePem(ReadOnlySpan rawData, DerCallback derCal // 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; } diff --git a/src/libraries/System.Security.Cryptography/tests/Base64TransformsTests.cs b/src/libraries/System.Security.Cryptography/tests/Base64TransformsTests.cs index 72ee58f6031f2..704e2ba5e5e57 100644 --- a/src/libraries/System.Security.Cryptography/tests/Base64TransformsTests.cs +++ b/src/libraries/System.Security.Cryptography/tests/Base64TransformsTests.cs @@ -56,7 +56,7 @@ public static IEnumerable TestData_Oversize() [Fact] public void InvalidInput_ToBase64Transform() { - byte[] data_3bytes = Text.Encoding.ASCII.GetBytes("aaa"); + byte[] data_3bytes = "aaa"u8.ToArray(); ICryptoTransform transform = new ToBase64Transform(); AssertExtensions.Throws("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0)); @@ -77,7 +77,7 @@ public void InvalidInput_ToBase64Transform() [Fact] public void InvalidInput_FromBase64Transform() { - byte[] data_4bytes = Text.Encoding.ASCII.GetBytes("aaaa"); + byte[] data_4bytes = "aaaa"u8.ToArray(); ICryptoTransform transform = new FromBase64Transform(); AssertExtensions.Throws("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0)); diff --git a/src/libraries/System.Security.Cryptography/tests/CryptoStream.cs b/src/libraries/System.Security.Cryptography/tests/CryptoStream.cs index 68e210472d454..6e877fbf5a027 100644 --- a/src/libraries/System.Security.Cryptography/tests/CryptoStream.cs +++ b/src/libraries/System.Security.Cryptography/tests/CryptoStream.cs @@ -304,7 +304,7 @@ public static void PaddedAes_PartialRead_Success() var memoryStream = new MemoryStream(); using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write, leaveOpen: true)) { - cryptoStream.Write(Encoding.ASCII.GetBytes("Sample string that's bigger than cryptoAlg.BlockSize")); + cryptoStream.Write("Sample string that's bigger than cryptoAlg.BlockSize"u8); cryptoStream.FlushFinalBlock(); } diff --git a/src/libraries/System.Security.Cryptography/tests/Rfc2898OneShotTests.cs b/src/libraries/System.Security.Cryptography/tests/Rfc2898OneShotTests.cs index cd92dc99b57ea..ab413da8b0f89 100644 --- a/src/libraries/System.Security.Cryptography/tests/Rfc2898OneShotTests.cs +++ b/src/libraries/System.Security.Cryptography/tests/Rfc2898OneShotTests.cs @@ -289,7 +289,7 @@ public static void Pbkdf2_Rfc6070_HighIterations() string password = "password"; int iterations = 16777216; byte[] expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984".HexToByteArray(); - byte[] salt = Encoding.UTF8.GetBytes("salt"); + ReadOnlySpan salt = "salt"u8; byte[] actual = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA1, expected.Length); Assert.Equal(expected, actual); } diff --git a/src/libraries/System.Security.Cryptography/tests/TripleDesTests.cs b/src/libraries/System.Security.Cryptography/tests/TripleDesTests.cs index 64b9c402a5da8..f12e0b1cf510e 100644 --- a/src/libraries/System.Security.Cryptography/tests/TripleDesTests.cs +++ b/src/libraries/System.Security.Cryptography/tests/TripleDesTests.cs @@ -63,7 +63,7 @@ public static void TripleDesCannotSetWeakKey() [Fact] public static void TripleDesCreate() { - byte[] inputBytes = Encoding.ASCII.GetBytes("This is a secret message and is a sentence that is longer than a block, it ensures that multi-block functions work."); + byte[] inputBytes = "This is a secret message and is a sentence that is longer than a block, it ensures that multi-block functions work."u8.ToArray(); TripleDES tripleDes = TripleDES.Create(); byte[] encryptedBytes; diff --git a/src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs b/src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs index 3dc2f53edb092..c744b4b5b2ddb 100644 --- a/src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs +++ b/src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs @@ -30,7 +30,7 @@ public static void TestEncoderReplacementFallback() // Test when the fallback will not occur encodedBytes = new byte[asciiEncoding.GetByteCount(s_asciiInputStringWinNoFallback)]; numberOfEncodedBytes = asciiEncoding.GetBytes(s_asciiInputStringWinNoFallback, 0, s_asciiInputStringWinNoFallback.Length, encodedBytes, 0); - Assert.Equal(encodedBytes, new byte[] { (byte)'a', (byte)'b', (byte)'c' }); + Assert.Equal("abc"u8.ToArray(), encodedBytes); decodedString = asciiEncoding.GetString(encodedBytes); Assert.Equal(decodedString, s_asciiInputStringWinNoFallback); } diff --git a/src/libraries/System.Text.Encodings.Web/tests/TextEncoderTests.cs b/src/libraries/System.Text.Encodings.Web/tests/TextEncoderTests.cs index cb26b483e7ce3..78295e065fc39 100644 --- a/src/libraries/System.Text.Encodings.Web/tests/TextEncoderTests.cs +++ b/src/libraries/System.Text.Encodings.Web/tests/TextEncoderTests.cs @@ -150,7 +150,7 @@ public void EncodeUtf8_MixedInputWhichRequiresEncodingOrReplacement() Assert.Equal(OperationStatus.Done, encoder.EncodeUtf8(aggregateInputBytesSoFar.ToArray(), destination, out bytesConsumed, out bytesWritten, isFinalBlock: true)); Assert.Equal(aggregateInputBytesSoFar.Count, bytesConsumed); Assert.Equal(expectedOutputBytesSoFar.Count + "[FFFD]".Length, bytesWritten); - Assert.Equal(expectedOutputBytesSoFar.Concat(Encoding.UTF8.GetBytes("[FFFD]")).ToArray(), new Span(destination, 0, expectedOutputBytesSoFar.Count + "[FFFD]".Length).ToArray()); + Assert.Equal(expectedOutputBytesSoFar.Concat("[FFFD]"u8.ToArray()), new Span(destination, 0, expectedOutputBytesSoFar.Count + "[FFFD]".Length).ToArray()); } // Consume the remainder of this entry and make sure it escaped properly (if needed). @@ -222,7 +222,7 @@ public void FindFirstCharToEncodeUtf8_WellFormedData_AllCharsAllowed() { // Arrange - byte[] inputBytes = Encoding.UTF8.GetBytes("\U00000040\U00000400\U00004000\U00040000"); // code units of different lengths + byte[] inputBytes = "\U00000040\U00000400\U00004000\U00040000"u8.ToArray(); // code units of different lengths var encoder = new ConfigurableScalarTextEncoder(_ => true /* allow everything */); // Act @@ -239,7 +239,7 @@ public void FindFirstCharToEncodeUtf8_WellFormedData_SomeCharsDisallowed() { // Arrange - byte[] inputBytes = Encoding.UTF8.GetBytes("\U00000040\U00000400\U00004000\U00040000"); // code units of different lengths + byte[] inputBytes = "\U00000040\U00000400\U00004000\U00040000"u8.ToArray(); // code units of different lengths var encoder = new ConfigurableScalarTextEncoder(codePoint => codePoint != 0x4000 /* disallow U+4000, allow all else */); // Act diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs index 53aa3580f4402..05f5707890e0c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs @@ -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) { diff --git a/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.Stream.cs b/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.Stream.cs index cb99feac24acf..5c96e06c1f23b 100644 --- a/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.Stream.cs +++ b/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.Stream.cs @@ -148,7 +148,7 @@ async Task RunTestAsync() await Assert.ThrowsAsync(async () => await StreamingSerializer.DeserializeWrapper(stream, options)); } - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("{}"))) + using (MemoryStream stream = new MemoryStream("{}"u8.ToArray())) { JsonSerializerOptions options = new JsonSerializerOptions { diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonElementWriteTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonElementWriteTests.cs index 2898ab9d862c2..77218b29b25ae 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonElementWriteTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonElementWriteTests.cs @@ -78,7 +78,6 @@ public void WritePropertyOutsideObject(bool skipValidation) }; const string CharLabel = "char"; - byte[] byteUtf8 = Encoding.UTF8.GetBytes("byte"); using var writer = new Utf8JsonWriter(buffer, options); if (skipValidation) @@ -89,7 +88,7 @@ public void WritePropertyOutsideObject(bool skipValidation) 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 @@ public void WritePropertyOutsideObject(bool skipValidation) { Assert.Throws(() => writer.WritePropertyName(CharLabel)); Assert.Throws(() => writer.WritePropertyName(CharLabel.AsSpan())); - Assert.Throws(() => writer.WritePropertyName(byteUtf8)); + Assert.Throws(() => writer.WritePropertyName("byte"u8)); Assert.Throws(() => writer.WritePropertyName(JsonEncodedText.Encode(CharLabel))); writer.Flush(); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/ParseTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/ParseTests.cs index 5c6022f503f11..44139de12a552 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/ParseTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/ParseTests.cs @@ -138,7 +138,7 @@ public static void NullLiteral() Assert.Null(JsonSerializer.Deserialize("null")); Assert.Null(JsonNode.Parse("null")); - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null"))) + using (MemoryStream stream = new MemoryStream("null"u8.ToArray())) { Assert.Null(JsonNode.Parse(stream)); } diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonReaderStateAndOptionsTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonReaderStateAndOptionsTests.cs index 182691e52f33f..997371e7bcb48 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonReaderStateAndOptionsTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonReaderStateAndOptionsTests.cs @@ -103,7 +103,7 @@ public static void DefaultJsonReaderOptions() [Fact] public static void ZeroMaxDepthDefaultsTo64() { - byte[] dataUtf8 = Encoding.UTF8.GetBytes("{}"); + byte[] dataUtf8 = "{}"u8.ToArray(); ReadOnlyMemory dataMemory = dataUtf8; var firstSegment = new BufferSegment(dataMemory.Slice(0, 1)); @@ -134,7 +134,7 @@ public static void ZeroMaxDepthDefaultsTo64() [Fact] public static void MaxDepthIsHonored() { - byte[] dataUtf8 = Encoding.UTF8.GetBytes("{}"); + byte[] dataUtf8 = "{}"u8.ToArray(); ReadOnlyMemory dataMemory = dataUtf8; var firstSegment = new BufferSegment(dataMemory.Slice(0, 1)); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/NewtonsoftTests/CustomObjectConverterTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/NewtonsoftTests/CustomObjectConverterTests.cs index 3531efddf16d3..887910ac5a32c 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/NewtonsoftTests/CustomObjectConverterTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/NewtonsoftTests/CustomObjectConverterTests.cs @@ -138,7 +138,7 @@ public void DeserializeByteArrayClass() Assert.Null(byteArrayClass.NullByteArray); } - private static readonly byte[] s_testData = Encoding.UTF8.GetBytes("This is some test data!!!"); + private static readonly byte[] s_testData = "This is some test data!!!"u8.ToArray(); [Fact] public void AssertShouldSerializeTest() diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Array.ReadTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Array.ReadTests.cs index 913c9196a0868..115e91c909db0 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Array.ReadTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Array.ReadTests.cs @@ -154,7 +154,7 @@ public static void ReadArrayWithInterleavedComments() var options = new JsonSerializerOptions(); options.ReadCommentHandling = JsonCommentHandling.Skip; - int[][] i = JsonSerializer.Deserialize(Encoding.UTF8.GetBytes("[[1,2] // Inline [\n,[3, /* Multi\n]] Line*/4]]"), options); + int[][] i = JsonSerializer.Deserialize("[[1,2] // Inline [\n,[3, /* Multi\n]] Line*/4]]"u8, options); Assert.Equal(1, i[0][0]); Assert.Equal(2, i[0][1]); Assert.Equal(3, i[1][0]); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Null.ReadTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Null.ReadTests.cs index 1f8bb6b67532c..7a5b8746b03df 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Null.ReadTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Null.ReadTests.cs @@ -188,7 +188,7 @@ public static void ParseNullStringToStructShouldThrowJsonException() [Fact] public static async Task ParseNullStringShouldThrowJsonExceptionAsync() { - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("null"))) + using (var stream = new MemoryStream("null"u8.ToArray())) { await Assert.ThrowsAsync(async () => await JsonSerializer.DeserializeAsync(stream)); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/ReadValueTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/ReadValueTests.cs index e7eb6f5b314a4..78cd158163c7b 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/ReadValueTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/ReadValueTests.cs @@ -61,7 +61,7 @@ public static void SerializerOptionsStillApply() [Fact] public static void ReaderOptionsWinMaxDepth() { - byte[] utf8 = Encoding.UTF8.GetBytes("[[]]"); + byte[] utf8 = "[[]]"u8.ToArray(); var readerOptions = new JsonReaderOptions { @@ -114,7 +114,7 @@ public static void ReaderOptionsWinMaxDepth() [Fact] public static void ReaderOptionsWinTrailingCommas() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, 3,]"); + byte[] utf8 = "[1, 2, 3,]"u8.ToArray(); var serializerOptions = new JsonSerializerOptions { @@ -151,7 +151,7 @@ public static void ReaderOptionsWinTrailingCommas() [Fact] public static void ReaderOptionsWinComments() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, /* some comment */ 3]"); + byte[] utf8 = "[1, 2, /* some comment */ 3]"u8.ToArray(); var serializerOptions = new JsonSerializerOptions { @@ -175,7 +175,7 @@ public static void ReaderOptionsWinComments() ReadAndVerify(utf8, serializerOptions: null, readerOptions, utf8.Length); ReadAndVerify(utf8, serializerOptions, readerOptions, utf8.Length); - byte[] utf8_CommentsAfter = Encoding.UTF8.GetBytes("[1, 2, 3]/* some comment */"); + byte[] utf8_CommentsAfter = "[1, 2, 3]/* some comment */"u8.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 @@ static void ReadAndVerify(byte[] utf8, JsonSerializerOptions serializerOptions, [Fact] public static void OnInvalidReaderIsRestored() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, 3}"); + byte[] utf8 = "[1, 2, 3}"u8.ToArray(); var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default); reader.Read(); @@ -213,7 +213,7 @@ public static void OnInvalidReaderIsRestored() [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 @@ public class SimpleType [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 @@ public static void ReadPropertyName() [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 sequence = JsonTestHelper.CreateSegments(utf8); var reader = new Utf8JsonReader(sequence, isFinalBlock, state: default); @@ -292,7 +292,7 @@ public static void ReadObjectMultiSegment(bool isFinalBlock) public static void NotEnoughData(bool isFinalBlock) { { - byte[] utf8 = Encoding.UTF8.GetBytes("\"start of string"); + byte[] utf8 = "\"start of string"u8.ToArray(); var reader = new Utf8JsonReader(utf8, isFinalBlock, state: default); Assert.Equal(0, reader.BytesConsumed); @@ -310,7 +310,7 @@ public static void NotEnoughData(bool isFinalBlock) } { - byte[] utf8 = Encoding.UTF8.GetBytes("{"); + byte[] utf8 = "{"u8.ToArray(); var reader = new Utf8JsonReader(utf8, isFinalBlock, state: default); reader.Read(); @@ -333,7 +333,7 @@ public static void NotEnoughData(bool isFinalBlock) [Fact] public static void EndObjectOrArrayIsInvalid() { - byte[] utf8 = Encoding.UTF8.GetBytes("[{}]"); + byte[] utf8 = "[{}]"u8.ToArray(); var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default); reader.Read(); @@ -575,7 +575,7 @@ public static void ReadClasses() [Fact] public static void ReadPartial() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, 3]"); + byte[] utf8 = "[1, 2, 3]"u8.ToArray(); var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default); reader.Read(); int[] array = JsonSerializer.Deserialize(ref reader); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/SpanTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/SpanTests.cs index c01ce57372c1f..d19f790523b0e 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/SpanTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/SpanTests.cs @@ -60,8 +60,7 @@ public static void ReadGenericApi() [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(obj); JsonElement element = (JsonElement)obj; Assert.Equal(JsonValueKind.Number, element.ValueKind); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs index 5112265009e8b..d556f4462cbea 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; +using System.Linq; using System.Threading.Tasks; using Xunit; @@ -69,7 +70,7 @@ public async Task ReadPrimitivesAsync() [Fact] public async Task ReadPrimitivesWithTrailingTriviaAsync() { - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(" 1\t// Comment\r\n/* Multi\r\nLine */"))) + using (MemoryStream stream = new MemoryStream(" 1\t// Comment\r\n/* Multi\r\nLine */"u8.ToArray())) { JsonSerializerOptions options = new JsonSerializerOptions { @@ -85,7 +86,7 @@ public async Task ReadPrimitivesWithTrailingTriviaAsync() [Fact] public async Task ReadReferenceTypeCollectionPassingNullValueAsync() { - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null"))) + using (MemoryStream stream = new MemoryStream("null"u8.ToArray())) { IList referenceTypeCollection = await Serializer.DeserializeWrapper>(stream); Assert.Null(referenceTypeCollection); @@ -95,7 +96,7 @@ public async Task ReadReferenceTypeCollectionPassingNullValueAsync() [Fact] public async Task ReadValueTypeCollectionPassingNullValueAsync() { - using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null"))) + using (MemoryStream stream = new MemoryStream("null"u8.ToArray())) { IList valueTypeCollection = await Serializer.DeserializeWrapper>(stream); Assert.Null(valueTypeCollection); @@ -164,8 +165,7 @@ IEnumerable Yield(int count, int expectedStreamLength) 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(); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Value.WriteTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Value.WriteTests.cs index 257ec5b069e10..af83df3f9696d 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Value.WriteTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Value.WriteTests.cs @@ -49,7 +49,7 @@ public static void WritePrimitives() { Span json = JsonSerializer.SerializeToUtf8Bytes(1); - Assert.Equal(Encoding.UTF8.GetBytes("1"), json.ToArray()); + Assert.Equal("1"u8.ToArray(), json.ToArray()); } { diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/WriteValueTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/WriteValueTests.cs index 66b89f1c151f8..2491f20d73411 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/WriteValueTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/WriteValueTests.cs @@ -67,7 +67,7 @@ public async static void NullValueWithValueTypeThrows() [Fact] public async static void NullValueWithNullableSuccess() { - byte[] nullUtf8Literal = Encoding.UTF8.GetBytes("null"); + byte[] nullUtf8Literal = "null"u8.ToArray(); var stream = new MemoryStream(); Utf8JsonWriter writer = new Utf8JsonWriter(stream); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.MultiSegment.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.MultiSegment.cs index 331b174a52e6d..0a1d2a41149c6 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.MultiSegment.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.MultiSegment.cs @@ -15,7 +15,7 @@ public static partial class Utf8JsonReaderTests [Fact] public static void InitialStateMultiSegment() { - byte[] utf8 = Encoding.UTF8.GetBytes("1"); + byte[] utf8 = "1"u8.ToArray(); ReadOnlySequence sequence = JsonTestHelper.GetSequence(utf8, 1); var json = new Utf8JsonReader(sequence, isFinalBlock: true, state: default); @@ -395,7 +395,7 @@ private static void InvalidReadStringHelper(ref Utf8JsonReader jsonReader, int e [Fact] public static void InitialStateSimpleCtorMultiSegment() { - byte[] utf8 = Encoding.UTF8.GetBytes("1"); + byte[] utf8 = "1"u8.ToArray(); ReadOnlySequence sequence = JsonTestHelper.GetSequence(utf8, 1); var json = new Utf8JsonReader(sequence); @@ -420,7 +420,7 @@ public static void InitialStateSimpleCtorMultiSegment() [Fact] public static void StateRecoveryMultiSegment() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1]"); + byte[] utf8 = "[1]"u8.ToArray(); ReadOnlySequence sequence = JsonTestHelper.GetSequence(utf8, 1); var json = new Utf8JsonReader(sequence, isFinalBlock: false, state: default); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.ValueTextEquals.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.ValueTextEquals.cs index 69df6ce26211e..ac092e7f439ae 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.ValueTextEquals.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.ValueTextEquals.cs @@ -13,39 +13,32 @@ public static partial class Utf8JsonReaderTests [Fact] public static void TestTextEqualsBasic() { - byte[] connectionId = Encoding.UTF8.GetBytes("connectionId"); - byte[] availableTransports = Encoding.UTF8.GetBytes("availableTransports"); - byte[] value123 = Encoding.UTF8.GetBytes("123"); - byte[] embeddedQuotes = Encoding.UTF8.GetBytes("My name is \"Ahson\""); 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 @@ public static void TextEqualsEscapedCharAtTheLastSegment() [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 @@ public static void TestTextEqualsMismatchMultiSegment() { if (json.TokenType == JsonTokenType.String) { - if (json.ValueTextEquals(lookup) || + if (json.ValueTextEquals("Hello, \"Ahson\""u8) || json.ValueTextEquals("Hello, \"Ahson\"".AsSpan()) || json.ValueTextEquals("Hello, \"Ahson\"")) { diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.cs index 43f896e83c676..0be0fc7dcb1b2 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.cs @@ -114,7 +114,7 @@ private static void TestGetMethodsOnDefault() [Fact] public static void InitialState() { - var json = new Utf8JsonReader(Encoding.UTF8.GetBytes("1"), isFinalBlock: true, state: default); + var json = new Utf8JsonReader("1"u8, isFinalBlock: true, state: default); Assert.Equal(0, json.BytesConsumed); Assert.Equal(0, json.TokenStartIndex); @@ -138,7 +138,7 @@ public static void InitialState() [Fact] public static void InitialStateSimpleCtor() { - var json = new Utf8JsonReader(Encoding.UTF8.GetBytes("1")); + var json = new Utf8JsonReader("1"u8); Assert.Equal(0, json.BytesConsumed); Assert.Equal(0, json.TokenStartIndex); @@ -162,7 +162,7 @@ public static void InitialStateSimpleCtor() [Fact] public static void StateRecovery() { - byte[] utf8 = Encoding.UTF8.GetBytes("[1]"); + ReadOnlySpan utf8 = "[1]"u8; var json = new Utf8JsonReader(utf8, isFinalBlock: false, state: default); Assert.Equal(0, json.BytesConsumed); @@ -199,7 +199,7 @@ public static void StateRecovery() 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 diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.WriteRaw.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.WriteRaw.cs index eb59af3510cb9..5272c1bb56105 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.WriteRaw.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.WriteRaw.cs @@ -57,13 +57,13 @@ public static IEnumerable GetRootLevelPrimitives() Action validate; validate = (data) => Assert.Equal(123456789, JsonSerializer.Deserialize(data)); - yield return new object[] { Encoding.UTF8.GetBytes("123456789"), validate }; + yield return new object[] { "123456789"u8.ToArray(), validate }; validate = (data) => Assert.Equal(1234.56789, JsonSerializer.Deserialize(data)); - yield return new object[] { Encoding.UTF8.GetBytes("1234.56789"), validate }; + yield return new object[] { "1234.56789"u8.ToArray(), validate }; validate = (data) => Assert.Equal(1234.56789, JsonSerializer.Deserialize(data)); - yield return new object[] { Encoding.UTF8.GetBytes(" 1234.56789 "), validate }; + yield return new object[] { " 1234.56789 "u8.ToArray(), validate }; validate = (data) => Assert.Equal(@"Hello", JsonSerializer.Deserialize(data)); yield return new object[] { Encoding.UTF8.GetBytes(@"""Hello"""), validate }; @@ -110,7 +110,7 @@ public static IEnumerable GetArrays() }; yield return new object[] { json, validate }; - json = Encoding.UTF8.GetBytes("[ 1, 1,1,1,1 ] "); + json = "[ 1, 1,1,1,1 ] "u8.ToArray(); validate = (data) => { foreach (int val in JsonSerializer.Deserialize(data)) diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs index 4ce5bc05542fc..732677fe0170a 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonWriterTests.cs @@ -530,7 +530,7 @@ static bool BeginsWithReplacementCharacter(ReadOnlySpan span) // 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 @@ public void GrowBeyondBufferSize(bool formatted, bool skipValidation) var output = new FixedSizedBufferWriter(InitialGrowthSize); var options = new JsonWriterOptions { Indented = formatted, SkipValidation = skipValidation }; - byte[] utf8String = Encoding.UTF8.GetBytes("this is a string long enough to overflow the buffer and cause an exception to be thrown."); + byte[] utf8String = "this is a string long enough to overflow the buffer and cause an exception to be thrown."u8.ToArray(); using var jsonUtf8 = new Utf8JsonWriter(output, options); @@ -1436,7 +1436,7 @@ private static async Task WriteLargeToStreamHelper(Stream stream, JsonWriterOpti await using var jsonUtf8 = new Utf8JsonWriter(stream, options); - byte[] utf8String = Encoding.UTF8.GetBytes("some string 1234"); + byte[] utf8String = "some string 1234"u8.ToArray(); jsonUtf8.WriteStartArray(); for (int i = 0; i < 10_000; i++) @@ -2316,14 +2316,14 @@ public void InvalidJsonMismatch(bool formatted, bool skipValidation) jsonUtf8.WritePropertyName("test name"); jsonUtf8.WritePropertyName(JsonEncodedText.Encode("test name")); jsonUtf8.WritePropertyName("test name".AsSpan()); - jsonUtf8.WritePropertyName(Encoding.UTF8.GetBytes("test name")); + jsonUtf8.WritePropertyName("test name"u8.ToArray()); } else { Assert.Throws(() => jsonUtf8.WritePropertyName("test name")); Assert.Throws(() => jsonUtf8.WritePropertyName(JsonEncodedText.Encode("test name"))); Assert.Throws(() => jsonUtf8.WritePropertyName("test name".AsSpan())); - Assert.Throws(() => jsonUtf8.WritePropertyName(Encoding.UTF8.GetBytes("test name"))); + Assert.Throws(() => jsonUtf8.WritePropertyName("test name"u8.ToArray())); } } @@ -2833,7 +2833,7 @@ public void WriteSeparateProperties(bool formatted, bool skipValidation) using var jsonUtf8 = new Utf8JsonWriter(output, options); jsonUtf8.WriteStartObject(); - jsonUtf8.WritePropertyName(Encoding.UTF8.GetBytes("foo1")); + jsonUtf8.WritePropertyName("foo1"u8); jsonUtf8.WriteStringValue("bar1"); jsonUtf8.WritePropertyName("foo2"); jsonUtf8.WriteStringValue("bar2"); @@ -2895,9 +2895,9 @@ public void WritingTooDeepProperty(bool formatted, bool skipValidation) jsonUtf8.WriteStartObject(); for (int i = 0; i < 999; i++) { - jsonUtf8.WriteStartObject(Encoding.UTF8.GetBytes("name")); + jsonUtf8.WriteStartObject("name"u8); } - Assert.Throws(() => jsonUtf8.WriteStartArray(Encoding.UTF8.GetBytes("name"))); + Assert.Throws(() => jsonUtf8.WriteStartArray("name"u8)); } using (var jsonUtf8 = new Utf8JsonWriter(output, options)) @@ -3107,7 +3107,7 @@ public void WritingTooLargeBase64Bytes(bool formatted, bool skipValidation) using (var jsonUtf8 = new Utf8JsonWriter(output, options)) { jsonUtf8.WriteStartObject(); - Assert.Throws(() => jsonUtf8.WriteBase64String(Encoding.UTF8.GetBytes("foo"), value)); + Assert.Throws(() => jsonUtf8.WriteBase64String("foo"u8, value)); } using (var jsonUtf8 = new Utf8JsonWriter(output, options)) @@ -3169,7 +3169,7 @@ public void WritingLargestPossibleBase64Bytes(bool formatted, bool skipValidatio using (var jsonUtf8 = new Utf8JsonWriter(output, options)) { jsonUtf8.WriteStartObject(); - jsonUtf8.WriteBase64String(Encoding.UTF8.GetBytes("foo"), value); + jsonUtf8.WriteBase64String("foo"u8, value); jsonUtf8.WriteEndObject(); } @@ -3231,7 +3231,7 @@ public void Writing3MBBase64Bytes(bool formatted, bool skipValidation) using (var jsonUtf8 = new Utf8JsonWriter(output, options)) { jsonUtf8.WriteStartObject(); - jsonUtf8.WriteBase64String(Encoding.UTF8.GetBytes("foo"), value); + jsonUtf8.WriteBase64String("foo"u8, value); jsonUtf8.WriteEndObject(); } JsonTestHelper.AssertContents(expectedJson, output); @@ -3290,8 +3290,8 @@ public void WriteHelloWorld(bool formatted, bool skipValidation) JsonEncodedText encodedPropertyName = JsonEncodedText.Encode(propertyName); JsonEncodedText encodedValue = JsonEncodedText.Encode(value); - byte[] utf8PropertyName = Encoding.UTF8.GetBytes("message"); - byte[] utf8Value = Encoding.UTF8.GetBytes("Hello, World!"); + ReadOnlySpan utf8PropertyName = "message"u8; + ReadOnlySpan utf8Value = "Hello, World!"u8; var options = new JsonWriterOptions { Indented = formatted, SkipValidation = skipValidation }; @@ -4971,7 +4971,7 @@ public void WriteStartEndWithPropertyNameArray(bool formatted, bool skipValidati jsonUtf8.WriteStartArray("property name".AsSpan()); break; case 2: - jsonUtf8.WriteStartArray(Encoding.UTF8.GetBytes("property name")); + jsonUtf8.WriteStartArray("property name"u8); break; } @@ -5060,7 +5060,7 @@ public void WriteStartEndWithPropertyNameObject(bool formatted, bool skipValidat jsonUtf8.WriteStartObject("property name".AsSpan()); break; case 2: - jsonUtf8.WriteStartObject(Encoding.UTF8.GetBytes("property name")); + jsonUtf8.WriteStartObject("property name"u8); break; } @@ -5149,7 +5149,7 @@ public void WriteArrayWithProperty(bool formatted, bool skipValidation) jsonUtf8.WriteStartArray("message".AsSpan()); break; case 2: - jsonUtf8.WriteStartArray(Encoding.UTF8.GetBytes("message")); + jsonUtf8.WriteStartArray("message"u8); break; } @@ -5337,7 +5337,7 @@ public void WriteIntegerValue(bool formatted, bool skipValidation, int value) jsonUtf8.WriteNumber("message".AsSpan(), value); break; case 2: - jsonUtf8.WriteNumber(Encoding.UTF8.GetBytes("message"), value); + jsonUtf8.WriteNumber("message"u8, value); break; case 3: jsonUtf8.WritePropertyName("message"); @@ -5383,7 +5383,7 @@ public void WriteFloatValue(bool formatted, bool skipValidation, float value) jsonUtf8.WriteNumber("message".AsSpan(), value); break; case 2: - jsonUtf8.WriteNumber(Encoding.UTF8.GetBytes("message"), value); + jsonUtf8.WriteNumber("message"u8, value); break; case 3: jsonUtf8.WritePropertyName("message"); @@ -5429,7 +5429,7 @@ public void WriteDoubleValue(bool formatted, bool skipValidation, double value) jsonUtf8.WriteNumber("message".AsSpan(), value); break; case 2: - jsonUtf8.WriteNumber(Encoding.UTF8.GetBytes("message"), value); + jsonUtf8.WriteNumber("message"u8, value); break; case 3: jsonUtf8.WritePropertyName("message"); @@ -6913,7 +6913,7 @@ public static void WriteString_NullPropertyName_Guid() public static void WriteString_NullPropertyName_ReadOnlySpan_Byte() { WriteNullPropertyName_Simple( - Encoding.UTF8.GetBytes("utf8"), + "utf8"u8.ToArray(), "\"utf8\"", (writer, name, value) => writer.WriteString(name, value), (writer, name, value) => writer.WriteString(name, value), @@ -7017,7 +7017,7 @@ public static void WriteStringValue_ReadOnlySpanCharProperty_NullString() [Fact] public static void WriteStringValue_ReadOnlySpanBytesProperty_NullString() { - byte[] propertyName = Encoding.UTF8.GetBytes("propUtf8"); + byte[] propertyName = "propUtf8"u8.ToArray(); WriteNullValue_InObject( "\"propUtf8\":\"\"", From 6197ee1a81040b525fb97cd1047bb70c11357cfd Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Mon, 6 Jun 2022 16:43:28 -0400 Subject: [PATCH 2/2] Address PR feedback (and fix some vars) --- .../tests/RemotelyInvokable.cs | 2 +- .../tests/PipeReaderCopyToAsyncTests.cs | 4 ++-- .../tests/PipeWriterCopyToAsyncTests.cs | 8 ++++---- .../System.IO.Pipelines/tests/PipeWriterTests.cs | 4 ++-- .../tests/SequencePipeReaderTests.cs | 2 +- .../tests/StreamPipeReaderTests.cs | 2 +- .../tests/StreamPipeWriterTests.cs | 4 ++-- src/libraries/System.Memory.Data/README.md | 4 ++-- .../System.Memory.Data/tests/BinaryDataTests.cs | 14 +++++++------- .../FunctionalTests/MultipartContentTest.cs | 16 ++++++++-------- .../UnitTests/Headers/MultipartContentTest.cs | 8 ++++---- .../PortableExecutable/PEBinaryReaderTests.cs | 2 +- .../Serialization/Stream.ReadTests.cs | 1 - 13 files changed, 35 insertions(+), 36 deletions(-) diff --git a/src/libraries/System.Diagnostics.Process/tests/RemotelyInvokable.cs b/src/libraries/System.Diagnostics.Process/tests/RemotelyInvokable.cs index cab760465132a..a61596b687e5c 100644 --- a/src/libraries/System.Diagnostics.Process/tests/RemotelyInvokable.cs +++ b/src/libraries/System.Diagnostics.Process/tests/RemotelyInvokable.cs @@ -99,7 +99,7 @@ public static int ReadLineWithCustomEncodingWriteLineWithUtf8(string inputEncodi public static int WriteSlowlyByByte() { var stdout = Console.OpenStandardOutput(); - var bytes = "a\0"u8.ToArray(); + var bytes = new byte[] { 97, 0 }; // Encoding.Unicode.GetBytes("a"); for (int i = 0; i != bytes.Length; ++i) { diff --git a/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs b/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs index 0d1700aeb9bd2..f6e87e2034f9f 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeReaderCopyToAsyncTests.cs @@ -290,7 +290,7 @@ public async Task ThrowingFromStreamCallsAdvanceToWithStartOfLastReadResult(int [Fact] public async Task CopyToAsyncStreamCopiesRemainderAfterReadingSome() { - var buffer = "Hello World"u8.ToArray(); + byte[] buffer = "Hello World"u8.ToArray(); await Pipe.Writer.WriteAsync(buffer); Pipe.Writer.Complete(); @@ -308,7 +308,7 @@ public async Task CopyToAsyncStreamCopiesRemainderAfterReadingSome() [Fact] public async Task CopyToAsyncPipeWriterCopiesRemainderAfterReadingSome() { - var buffer = "Hello World"u8.ToArray(); + byte[] buffer = "Hello World"u8.ToArray(); await Pipe.Writer.WriteAsync(buffer); Pipe.Writer.Complete(); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs b/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs index e36c938cd2e87..9977b6d9349fa 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeWriterCopyToAsyncTests.cs @@ -40,7 +40,7 @@ public async Task CopyToAsyncThrowsTaskCanceledExceptionForAlreadyCancelledToken [Fact] public async Task CopyToAsyncWorks() { - var helloBytes = "Hello World"u8.ToArray(); + byte[] helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(); var stream = new MemoryStream(helloBytes); @@ -79,7 +79,7 @@ public async Task CopyToAsyncCalledMultipleTimesWorks() [Fact] public async Task StreamCopyToAsyncWorks() { - var helloBytes = "Hello World"u8.ToArray(); + byte[] helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(); var stream = new MemoryStream(helloBytes); @@ -96,7 +96,7 @@ public async Task StreamCopyToAsyncWorks() [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task CancelingViaCancelPendingFlushThrows() { - var helloBytes = "Hello World"u8.ToArray(); + 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 @@ public async Task CancelingViaCancelPendingFlushThrows() [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task CancelingViaCancellationTokenThrows() { - var helloBytes = "Hello World"u8.ToArray(); + byte[] helloBytes = "Hello World"u8.ToArray(); var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: helloBytes.Length - 1, resumeWriterThreshold: 0)); var stream = new MemoryStream(helloBytes); diff --git a/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs b/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs index 584cdd96a6318..5dbbeeef1bb7e 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs @@ -185,7 +185,7 @@ public void ThrowsOnAdvanceWithNoMemory() [Fact] public async Task WritesUsingGetSpanWorks() { - var bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); + byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1)); PipeWriter writer = pipe.Writer; @@ -208,7 +208,7 @@ public async Task WritesUsingGetSpanWorks() [Fact] public async Task WritesUsingGetMemoryWorks() { - var bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); + byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1)); PipeWriter writer = pipe.Writer; diff --git a/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs b/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs index dd1b0bf8e8c7b..3c76c1568f8d6 100644 --- a/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs @@ -86,7 +86,7 @@ public async Task ReadAsyncAfterReceivingCompletedReadResultDoesNotThrow() [Fact] public async Task DataCanBeReadMultipleTimes() { - var helloBytes = "Hello World"u8.ToArray(); + byte[] helloBytes = "Hello World"u8.ToArray(); var sequence = new ReadOnlySequence(helloBytes); PipeReader reader = PipeReader.Create(sequence); diff --git a/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs b/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs index 7bcf9bd8a983d..a59af1d40f2cd 100644 --- a/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs @@ -168,7 +168,7 @@ public async Task ReadAsyncAfterReceivingCompletedReadResultDoesNotThrow() [Fact] public async Task BufferingDataPastEndOfStreamCanBeReadAgain() { - var helloBytes = "Hello World"u8.ToArray(); + byte[] helloBytes = "Hello World"u8.ToArray(); var stream = new ThrowAfterZeroByteReadStream(helloBytes); PipeReader reader = PipeReader.Create(stream); diff --git a/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs b/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs index e767f87c0eca8..6b158f8fdb225 100644 --- a/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs +++ b/src/libraries/System.IO.Pipelines/tests/StreamPipeWriterTests.cs @@ -155,7 +155,7 @@ public async Task FlushAsyncWithoutWritingDoesNotFlushAsync() [Fact] public async Task WritesUsingGetSpanWorks() { - var bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); + 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 @@ public async Task WritesUsingGetSpanWorks() [Fact] public async Task WritesUsingGetMemoryWorks() { - var bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); + byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray(); var stream = new MemoryStream(); var options = new StreamPipeWriterOptions(new HeapBufferPool(), minimumBufferSize: 1); PipeWriter writer = PipeWriter.Create(stream, options); diff --git a/src/libraries/System.Memory.Data/README.md b/src/libraries/System.Memory.Data/README.md index c707af4837706..70cb1262e9777 100644 --- a/src/libraries/System.Memory.Data/README.md +++ b/src/libraries/System.Memory.Data/README.md @@ -19,7 +19,7 @@ Console.WriteLine(data.ToString()); // prints "some data" To/From bytes: ```C# Snippet:BinaryDataToFromBytes -byte[] bytes = "some data"u8.ToArray(); +byte[] bytes = Encoding.UTF8.GetBytes("some data"); // Create BinaryData using a constructor ... BinaryData data = new BinaryData(bytes); @@ -41,7 +41,7 @@ byte[] array = data.ToArray(); ``` To/From stream: ```C# Snippet:BinaryDataToFromStream -var bytes = "some data"u8.ToArray(); +var bytes = Encoding.UTF8.GetBytes("some data"); Stream stream = new MemoryStream(bytes); var data = BinaryData.FromStream(stream); diff --git a/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs b/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs index bf9eb406448b6..3ec81641684d8 100644 --- a/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs +++ b/src/libraries/System.Memory.Data/tests/BinaryDataTests.cs @@ -445,7 +445,7 @@ public void GetHashCodeWorks() [Fact] public async Task CanRead() { - var buffer = "some data"u8.ToArray(); + byte[] buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); var read = new byte[buffer.Length]; @@ -465,7 +465,7 @@ public async Task CanRead() [Fact] public async Task CanReadPartial() { - var buffer = "some data"u8.ToArray(); + byte[] buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); var length = 4; var read = new byte[length]; @@ -486,7 +486,7 @@ public async Task CanReadPartial() [Fact] public void ReadAsyncRespectsCancellation() { - var buffer = "some data"u8.ToArray(); + byte[] buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); var read = new byte[buffer.Length]; @@ -505,7 +505,7 @@ public void ReadAsyncRespectsCancellation() [Fact] public async Task CanSeek() { - var buffer = "some data"u8.ToArray(); + byte[] buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); stream.Seek(5, SeekOrigin.Begin); @@ -526,7 +526,7 @@ public async Task CanSeek() [Fact] public void ValidatesSeekArguments() { - var buffer = "some data"u8.ToArray(); + byte[] buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); Assert.Throws(() => stream.Seek(-1, SeekOrigin.Begin)); @@ -539,7 +539,7 @@ public void ValidatesSeekArguments() [Fact] public async Task ValidatesReadArguments() { - var buffer = "some data"u8.ToArray(); + 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 @@ public async Task ValidatesReadArguments() [Fact] public void ValidatesPositionValue() { - var buffer = "some data"u8.ToArray(); + byte[] buffer = "some data"u8.ToArray(); var stream = new BinaryData(buffer).ToStream(); Assert.Throws(() => stream.Position = -1); Assert.Throws(() => stream.Position = (long)int.MaxValue + 1); diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs index bb883453333cd..457085ccb3de2 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/MultipartContentTest.cs @@ -442,19 +442,19 @@ public async Task ReadAsStreamAsync_CustomEncodingSelector_CustomEncodingIsUsed( 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("bar2"u8.ToArray()); - byteArrayContent.Headers.Add("utf8", "\uD83D\uDE00"); + byteArrayContent.Headers.Add("utf8", "\U0001F600"); mc.Add(byteArrayContent); byteArrayContent = new ByteArrayContent("bar3"u8.ToArray()); - byteArrayContent.Headers.Add("ascii", "\uD83D\uDE00"); + byteArrayContent.Headers.Add("ascii", "\U0001F600"); mc.Add(byteArrayContent); byteArrayContent = new ByteArrayContent("bar4"u8.ToArray()); - byteArrayContent.Headers.Add("default", "\uD83D\uDE00"); + byteArrayContent.Headers.Add("default", "\U0001F600"); mc.Add(byteArrayContent); mc.HeaderEncodingSelector = (name, _) => name switch @@ -479,22 +479,22 @@ public async Task ReadAsStreamAsync_CustomEncodingSelector_CustomEncodingIsUsed( "--fooBoundary\r\n"u8.ToArray(), "Content-Type: text/plain; charset=utf-8\r\n"u8.ToArray(), "latin1: "u8.ToArray(), - Encoding.Latin1.GetBytes("\uD83D\uDE00"), + Encoding.Latin1.GetBytes("\U0001F600"), "\r\n\r\n"u8.ToArray(), "bar1"u8.ToArray(), "\r\n--fooBoundary\r\n"u8.ToArray(), "utf8: "u8.ToArray(), - "\uD83D\uDE00"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("\uD83D\uDE00"), + 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("\uD83D\uDE00"), + Encoding.Latin1.GetBytes("\U0001F600"), "\r\n\r\n"u8.ToArray(), "bar4"u8.ToArray(), "\r\n--fooBoundary--\r\n"u8.ToArray()); diff --git a/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs b/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs index 571d64d951c5d..bfac32cb531f8 100644 --- a/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs +++ b/src/libraries/System.Net.Http/tests/UnitTests/Headers/MultipartContentTest.cs @@ -18,19 +18,19 @@ public static IEnumerable MultipartContent_TestData() 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("bar2"u8.ToArray()); - byteArrayContent.Headers.Add("utf8", "\uD83D\uDE00"); + byteArrayContent.Headers.Add("utf8", "\U0001F600"); complexContent.Add(byteArrayContent); byteArrayContent = new ByteArrayContent("bar3"u8.ToArray()); - byteArrayContent.Headers.Add("ascii", "\uD83D\uDE00"); + byteArrayContent.Headers.Add("ascii", "\U0001F600"); complexContent.Add(byteArrayContent); byteArrayContent = new ByteArrayContent("bar4"u8.ToArray()); - byteArrayContent.Headers.Add("default", "\uD83D\uDE00"); + byteArrayContent.Headers.Add("default", "\U0001F600"); complexContent.Add(byteArrayContent); stringContent = new StringContent("bar5"); diff --git a/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs b/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs index 657c30295fd1a..640a5ecf713ad 100644 --- a/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs +++ b/src/libraries/System.Reflection.Metadata/tests/PortableExecutable/PEBinaryReaderTests.cs @@ -31,7 +31,7 @@ public void ReadNullPaddedUTF8RemovesNullPadding() [Fact] public void ReadNullPaddedUTF8WorksWithNoNullPadding() { - var headerBytes = ".abcdefg"u8.ToArray(); + byte[] headerBytes = ".abcdefg"u8.ToArray(); var stream = new MemoryStream(headerBytes); stream.Position = 0; diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs index d556f4462cbea..10bb1edc19147 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/Stream.ReadTests.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; -using System.Linq; using System.Threading.Tasks; using Xunit;