Skip to content

Commit

Permalink
Use u8 in more places (#69995)
Browse files Browse the repository at this point in the history
* Use u8 in more places

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

* Address PR feedback (and fix some vars)
  • Loading branch information
stephentoub committed Jun 7, 2022
1 parent 9f654ce commit 0c4ee9e
Show file tree
Hide file tree
Showing 138 changed files with 522 additions and 578 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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<byte>(), Encoding.UTF8.GetBytes("hello"), Array.Empty<byte>(), Encoding.UTF8.GetBytes("world") };
byte[][] buffers = new[] { Array.Empty<byte>(), "hello"u8.ToArray(), Array.Empty<byte>(), "world"u8.ToArray() };

using StreamPair streams = await CreateConnectedStreamsAsync();
foreach ((Stream writeable, Stream readable) in GetReadWritePairs(streams))
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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<ArgumentException>("input", () =>
dsa.ImportFromEncryptedPem(pem, passwordBytes));
dsa.ImportFromEncryptedPem(pem, "test"u8));
Assert.Contains(AmbiguousExceptionMarker, ae.Message);
}
}
Expand All @@ -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<ArgumentException>("input", () =>
dsa.ImportFromEncryptedPem(pem, passwordBytes));
dsa.ImportFromEncryptedPem(pem, "test"u8));
Assert.Contains(NoPemExceptionMarker, ae.Message);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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<ArgumentException>("input", () =>
key.ImportFromEncryptedPem(pem, passwordBytes));
key.ImportFromEncryptedPem(pem, "test"u8));

Assert.Contains(AmbiguousExceptionMarker, ae.Message);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,8 +274,6 @@ public static IEnumerable<object[]> 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];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,7 @@ public static void ReadPbes2Rc2EncryptedDiminishedDP_PasswordBytes()

ReadBase64EncryptedPkcs8(
base64,
Encoding.UTF8.GetBytes("rc2"),
"rc2"u8.ToArray(),
new PbeParameters(
PbeEncryptionAlgorithm.Aes192Cbc,
HashAlgorithmName.SHA256,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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<ArgumentException>("input", () =>
rsa.ImportFromEncryptedPem(pem, passwordBytes));
rsa.ImportFromEncryptedPem(pem, "test"u8));
Assert.Contains(AmbiguousExceptionMarker, ae.Message);
}
}
Expand All @@ -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<ArgumentException>("input", () =>
rsa.ImportFromEncryptedPem(pem, passwordBytes));
rsa.ImportFromEncryptedPem(pem, "test"u8));
Assert.Contains(NoPemExceptionMarker, ae.Message);
}
}
Expand All @@ -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<ArgumentException>("input", () =>
rsa.ImportFromEncryptedPem(pem, passwordBytes));
rsa.ImportFromEncryptedPem(pem, "test"u8));
Assert.Contains(NoPemExceptionMarker, ae.Message);
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/libraries/Common/tests/Tests/System/StringTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7418,8 +7418,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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = new byte[] { 97, 0 }; // Encoding.Unicode.GetBytes("a");

for (int i = 0; i != bytes.Length; ++i)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -479,18 +479,18 @@ private static void RunAsyncSearch(IAsyncResult asyncResult)
public static IEnumerable<object[]> TestCompareRequestTheory_TestData()
{
yield return new object[] { "input", "input", ResultCode.CompareTrue };
yield return new object[] { "input", Encoding.UTF8.GetBytes("input"), ResultCode.CompareTrue };
yield return new object[] { "input", "input"u8.ToArray(), ResultCode.CompareTrue };

yield return new object[] { "input", "false", ResultCode.CompareFalse };
yield return new object[] { "input", new byte[] { 1, 2, 3, 4, 5 }, ResultCode.CompareFalse };

yield return new object[] { "http://example.com/", "http://example.com/", ResultCode.CompareTrue };
yield return new object[] { "http://example.com/", new Uri("http://example.com/"), ResultCode.CompareTrue };
yield return new object[] { "http://example.com/", Encoding.UTF8.GetBytes("http://example.com/"), ResultCode.CompareTrue };
yield return new object[] { "http://example.com/", "http://example.com/"u8.ToArray(), ResultCode.CompareTrue };

yield return new object[] { "http://example.com/", "http://false/", ResultCode.CompareFalse };
yield return new object[] { "http://example.com/", new Uri("http://false/"), ResultCode.CompareFalse };
yield return new object[] { "http://example.com/", Encoding.UTF8.GetBytes("http://false/"), ResultCode.CompareFalse };
yield return new object[] { "http://example.com/", "http://false/"u8.ToArray(), ResultCode.CompareFalse };
}

[ConditionalTheory(nameof(IsLdapConfigurationExist))]
Expand Down
12 changes: 6 additions & 6 deletions src/libraries/System.Drawing.Common/tests/ImageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
Expand Down Expand Up @@ -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();
Expand All @@ -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<AsnContentException>(() => berReader.ReadGeneralizedTime());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ namespace System.Formats.Tar
// Writes header attributes of a tar archive entry.
internal partial struct TarHeader
{
private static ReadOnlySpan<byte> PaxMagicBytes => new byte[] { 0x75, 0x73, 0x74, 0x61, 0x72, 0x0 }; // "ustar\0"
private static ReadOnlySpan<byte> PaxVersionBytes => new byte[] { TarHelpers.ZeroChar, TarHelpers.ZeroChar }; // "00"
private static ReadOnlySpan<byte> PaxMagicBytes => "ustar\0"u8;
private static ReadOnlySpan<byte> PaxVersionBytes => "00"u8;

private static ReadOnlySpan<byte> GnuMagicBytes => new byte[] { 0x75, 0x73, 0x74, 0x61, 0x72, TarHelpers.SpaceChar }; // "ustar "
private static ReadOnlySpan<byte> GnuVersionBytes => new byte[] { TarHelpers.SpaceChar, 0x0 }; // " \0"
private static ReadOnlySpan<byte> GnuMagicBytes => "ustar "u8;
private static ReadOnlySpan<byte> GnuVersionBytes => " \0"u8;

// Extended Attribute entries have a special format in the Name field:
// "{dirName}/PaxHeaders.{processId}/{fileName}{trailingSeparator}"
Expand Down

0 comments on commit 0c4ee9e

Please sign in to comment.