{
write = Task.Run(async () =>
{
- await writeable.WriteAsync(Encoding.UTF8.GetBytes("hello"));
+ await writeable.WriteAsync("hello"u8.ToArray());
await writeable.DisposeAsync();
});
}
Task write = Task.Run(async () =>
{
- await writeable.WriteAsync(Encoding.UTF8.GetBytes("hello"));
+ await writeable.WriteAsync("hello"u8.ToArray());
if (FlushRequiredToWriteData)
{
if (FlushGuaranteesAllDataWritten)
[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))
// (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);
// 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.
qE3Db1UI4anCCnyEj/jDA8R6hZTFDjxu6bG0Z66g7I2GBDEYaaB+8x0vtiyu5LXo
6UZ53SX6S+jfIqJoF5YME9zVMoO2kwS/EGvc64+epCGcee1Nx4SGgUcr5HJYz1P4
CU+l4wPQR0rRmYHIJJIvFh5OXk84pV0crsOrekw7tHeNU6DMzw==",
- Encoding.UTF8.GetBytes("Password > cipher"),
+ "Password > cipher"u8.ToArray(),
new PbeParameters(
PbeEncryptionAlgorithm.Aes192Cbc,
HashAlgorithmName.SHA256,
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);
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);
}
}
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);
}
}
"41e2345f1f56df2458f426d155b4ba2db6dcd8c8"
).HexToByteArray();
- data = Encoding.ASCII.GetBytes("abc");
+ data = "abc"u8.ToArray();
}
}
}
ReadWriteBase64EncryptedPkcs8(
base64,
- Encoding.UTF8.GetBytes("qwerty"),
+ "qwerty"u8.ToArray(),
new PbeParameters(
PbeEncryptionAlgorithm.Aes256Cbc,
HashAlgorithmName.SHA1,
ReadWriteBase64EncryptedPkcs8(
base64,
- Encoding.UTF8.GetBytes("qwerty"),
+ "qwerty"u8.ToArray(),
new PbeParameters(
PbeEncryptionAlgorithm.Aes256Cbc,
HashAlgorithmName.SHA1,
/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);
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);
}
[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];
ReadBase64EncryptedPkcs8(
base64,
- Encoding.UTF8.GetBytes("rc2"),
+ "rc2"u8.ToArray(),
new PbeParameters(
PbeEncryptionAlgorithm.Aes192Cbc,
HashAlgorithmName.SHA256,
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);
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);
}
}
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);
}
}
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);
}
}
[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
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)
{
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))]
// 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);
// 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);
// 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);
// 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);
// 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);
// 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);
[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();
[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();
[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();
[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());
// 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}"
{
// '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))
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();
}
}
{
s.Seek(0, SeekOrigin.End);
- byte[] data = Encoding.ASCII.GetBytes("\r\n\r\nThe answer my friend, is blowin' in the wind.");
+ byte[] data = "\r\n\r\nThe answer my friend, is blowin' in the wind."u8.ToArray();
if (writeWithSpans)
{
- s.Write(data, 0, data.Length);
+ s.Write(new ReadOnlySpan<byte>(data));
}
else
{
- s.Write(new ReadOnlySpan<byte>(data));
+ s.Write(data, 0, data.Length);
}
}
// Operation succeeds when being run by the Unix superuser
if (PlatformDetection.IsSuperUser)
{
- File.WriteAllBytes(path, Encoding.UTF8.GetBytes("text"));
- Assert.Equal(Encoding.UTF8.GetBytes("text"), File.ReadAllBytes(path));
+ File.WriteAllBytes(path, "text"u8.ToArray());
+ Assert.Equal("text"u8.ToArray(), File.ReadAllBytes(path));
}
else
- Assert.Throws<UnauthorizedAccessException>(() => File.WriteAllBytes(path, Encoding.UTF8.GetBytes("text")));
+ Assert.Throws<UnauthorizedAccessException>(() => File.WriteAllBytes(path, "text"u8.ToArray()));
}
finally
{
// Operation succeeds when being run by the Unix superuser
if (PlatformDetection.IsSuperUser)
{
- await File.WriteAllBytesAsync(path, Encoding.UTF8.GetBytes("text"));
- Assert.Equal(Encoding.UTF8.GetBytes("text"), await File.ReadAllBytesAsync(path));
+ await File.WriteAllBytesAsync(path, "text"u8.ToArray());
+ Assert.Equal("text"u8.ToArray(), await File.ReadAllBytesAsync(path));
}
else
- await Assert.ThrowsAsync<UnauthorizedAccessException>(async () => await File.WriteAllBytesAsync(path, Encoding.UTF8.GetBytes("text")));
+ await Assert.ThrowsAsync<UnauthorizedAccessException>(async () => await File.WriteAllBytesAsync(path, "text"u8.ToArray()));
}
finally
{
{
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]
{
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]
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);
}
Assert.Throws<IOException>(() => fs.Seek(0, SeekOrigin.Begin));
Assert.Throws<NotSupportedException>(() => fs.ReadByte());
- fs.Write(Encoding.ASCII.GetBytes("abcde"));
+ fs.Write("abcde"u8);
Assert.Equal(position + 5, fs.Position);
Assert.Equal(position, fs.Seek(position, SeekOrigin.Begin));
Assert.Equal(position + 1, fs.Seek(1, SeekOrigin.Current));
- fs.Write(Encoding.ASCII.GetBytes("xyz"));
+ fs.Write("xyz"u8);
}
Assert.Equal(initialContents + "axyze", File.ReadAllText(fileName));
"FFFFFFFF"),
new TestCase(
"Self-test 123456789",
- Encoding.ASCII.GetBytes("123456789"),
+ "123456789"u8.ToArray(),
"2639F4CB"),
new TestCase(
"Self-test residue",
"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"),
};
"0000000000000000"),
new TestCase(
"Self-test 123456789",
- Encoding.ASCII.GetBytes("123456789"),
+ "123456789"u8.ToArray(),
"6C40DF5F0B497347"),
new TestCase(
"Self-test residue",
"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"),
};
// 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",
//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.
// 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(
// 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",
// 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",
//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.
// 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(
// 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",
{
var messages = new List<byte[]>()
{
- Encoding.UTF8.GetBytes("Hello World1"),
- Encoding.UTF8.GetBytes("Hello World2"),
- Encoding.UTF8.GetBytes("Hello World3"),
+ "Hello World1"u8.ToArray(),
+ "Hello World2"u8.ToArray(),
+ "Hello World3"u8.ToArray(),
};
var stream = new WriteCheckMemoryStream();
{
var messages = new List<byte[]>()
{
- Encoding.UTF8.GetBytes("Hello World1"),
- Encoding.UTF8.GetBytes("Hello World2"),
- Encoding.UTF8.GetBytes("Hello World3"),
+ "Hello World1"u8.ToArray(),
+ "Hello World2"u8.ToArray(),
+ "Hello World3"u8.ToArray(),
};
var targetPipe = new Pipe(s_testOptions);
// 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();
{
// 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();
[Fact]
public async Task CopyToAsyncStreamCopiesRemainderAfterReadingSome()
{
- var buffer = Encoding.UTF8.GetBytes("Hello World");
+ byte[] buffer = "Hello World"u8.ToArray();
await Pipe.Writer.WriteAsync(buffer);
Pipe.Writer.Complete();
[Fact]
public async Task CopyToAsyncPipeWriterCopiesRemainderAfterReadingSome()
{
- var buffer = Encoding.UTF8.GetBytes("Hello World");
+ byte[] buffer = "Hello World"u8.ToArray();
await Pipe.Writer.WriteAsync(buffer);
Pipe.Writer.Complete();
[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);
[Fact]
public async Task ReadAtLeastShouldNotCompleteIfWriterWroteLessThanMinimum()
{
- byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
+ byte[] bytes = "Hello World"u8.ToArray();
await Pipe.Writer.WriteAsync(bytes.AsMemory(0, 5));
ValueTask<ReadResult> task = PipeReader.ReadAtLeastAsync(11);
[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);
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)
{
[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();
[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();
[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();
[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();
[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();
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);
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);
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);
[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();
[Fact]
public async Task CopyToAsyncWorks()
{
- var helloBytes = Encoding.UTF8.GetBytes("Hello World");
+ byte[] helloBytes = "Hello World"u8.ToArray();
var pipe = new Pipe();
var stream = new MemoryStream(helloBytes);
[Fact]
public async Task StreamCopyToAsyncWorks()
{
- var helloBytes = Encoding.UTF8.GetBytes("Hello World");
+ byte[] helloBytes = "Hello World"u8.ToArray();
var pipe = new Pipe();
var stream = new MemoryStream(helloBytes);
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task CancelingViaCancelPendingFlushThrows()
{
- var helloBytes = Encoding.UTF8.GetBytes("Hello World");
+ byte[] helloBytes = "Hello World"u8.ToArray();
var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: helloBytes.Length - 1, resumeWriterThreshold: 0));
var stream = new MemoryStream(helloBytes);
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task CancelingViaCancellationTokenThrows()
{
- var helloBytes = Encoding.UTF8.GetBytes("Hello World");
+ byte[] helloBytes = "Hello World"u8.ToArray();
var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: helloBytes.Length - 1, resumeWriterThreshold: 0));
var stream = new MemoryStream(helloBytes);
[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);
[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();
[Fact]
public async Task FlushAsyncFlushesBufferedData()
{
- byte[] helloBytes = Encoding.ASCII.GetBytes("Hello World");
+ byte[] helloBytes = "Hello World"u8.ToArray();
var pipe = new Pipe();
Memory<byte> memory = pipe.Writer.GetMemory();
[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();
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);
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();
[Fact]
public async Task WritesUsingGetSpanWorks()
{
- var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
+ byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray();
var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1));
PipeWriter writer = pipe.Writer;
[Fact]
public async Task WritesUsingGetMemoryWorks()
{
- var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
+ byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray();
var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1));
PipeWriter writer = pipe.Writer;
[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();
[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);
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();
[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();
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
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
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);
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();
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;
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;
[Fact]
public async Task CanRead()
{
- var sequence = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("Hello World"));
+ var sequence = new ReadOnlySequence<byte>("Hello World"u8.ToArray());
var reader = PipeReader.Create(sequence);
ReadResult readResult = await reader.ReadAsync();
[Fact]
public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything()
{
- var sequence = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("Hello World"));
+ var sequence = new ReadOnlySequence<byte>("Hello World"u8.ToArray());
var reader = PipeReader.Create(sequence);
ReadResult readResult = await reader.ReadAsync();
[Fact]
public async Task TryReadReturnsFalseIfBufferedBytesAndEverythingExamined()
{
- var sequence = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("Hello World"));
+ var sequence = new ReadOnlySequence<byte>("Hello World"u8.ToArray());
var reader = PipeReader.Create(sequence);
ReadResult readResult = await reader.ReadAsync();
[Fact]
public async Task DataCanBeReadMultipleTimes()
{
- var helloBytes = Encoding.ASCII.GetBytes("Hello World");
+ byte[] helloBytes = "Hello World"u8.ToArray();
var sequence = new ReadOnlySequence<byte>(helloBytes);
PipeReader reader = PipeReader.Create(sequence);
[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();
[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();
[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();
[Fact]
public async Task BufferingDataPastEndOfStreamCanBeReadAgain()
{
- var helloBytes = Encoding.ASCII.GetBytes("Hello World");
+ byte[] helloBytes = "Hello World"u8.ToArray();
var stream = new ThrowAfterZeroByteReadStream(helloBytes);
PipeReader reader = PipeReader.Create(stream);
[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);
[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));
[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));
[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));
[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));
[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));
[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);
[Fact]
public async Task WritesUsingGetSpanWorks()
{
- var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
+ byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray();
var stream = new MemoryStream();
var options = new StreamPipeWriterOptions(new HeapBufferPool(), minimumBufferSize: 1);
PipeWriter writer = PipeWriter.Create(stream, options);
[Fact]
public async Task WritesUsingGetMemoryWorks()
{
- var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
+ byte[] bytes = "abcdefghijklmnopqrstuvwzyz"u8.ToArray();
var stream = new MemoryStream();
var options = new StreamPipeWriterOptions(new HeapBufferPool(), minimumBufferSize: 1);
PipeWriter writer = PipeWriter.Create(stream, options);
var data = new List<byte[]>
{
- Encoding.ASCII.GetBytes("Hello"),
- Encoding.ASCII.GetBytes("World"),
- Encoding.ASCII.GetBytes("This"),
- Encoding.ASCII.GetBytes("Works"),
+ "Hello"u8.ToArray(),
+ "World"u8.ToArray(),
+ "This"u8.ToArray(),
+ "Works"u8.ToArray(),
}.
ToArray();
{
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);
{
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);
[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);
[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);
[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());
[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();
[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';
[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';
[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());
[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());
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());
[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;
[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());
[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;
public async Task StartPositionOfStreamRespected(int bufferOffset, long streamStart)
{
var input = "some data";
- ArraySegment<byte> buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("some data"), bufferOffset, input.Length - bufferOffset);
+ ArraySegment<byte> buffer = new ArraySegment<byte>("some data"u8.ToArray(), bufferOffset, input.Length - bufferOffset);
MemoryStream stream = new MemoryStream(buffer.Array, buffer.Offset, buffer.Count);
var payload = new ReadOnlyMemory<byte>(buffer.Array, buffer.Offset, buffer.Count).Slice((int)streamStart);
public async Task StartPositionOfStreamRespectedBackingBuffer(int bufferOffset, long streamStart)
{
var input = "some data";
- ArraySegment<byte> buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("some data"), bufferOffset, input.Length - bufferOffset);
+ ArraySegment<byte> buffer = new ArraySegment<byte>("some data"u8.ToArray(), bufferOffset, input.Length - bufferOffset);
MemoryStream stream = new MemoryStream();
stream.Write(buffer.Array, buffer.Offset, buffer.Count);
[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"));
[Fact]
public void GetHashCodeWorks()
{
- byte[] payload = Encoding.UTF8.GetBytes("some data");
+ byte[] payload = "some data"u8.ToArray();
BinaryData a = BinaryData.FromBytes(payload);
BinaryData b = BinaryData.FromBytes(payload);
HashSet<BinaryData> set = new HashSet<BinaryData>
// 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);
[Fact]
public async Task CanRead()
{
- var buffer = Encoding.UTF8.GetBytes("some data");
+ byte[] buffer = "some data"u8.ToArray();
var stream = new BinaryData(buffer).ToStream();
var read = new byte[buffer.Length];
[Fact]
public async Task CanReadPartial()
{
- var buffer = Encoding.UTF8.GetBytes("some data");
+ byte[] buffer = "some data"u8.ToArray();
var stream = new BinaryData(buffer).ToStream();
var length = 4;
var read = new byte[length];
[Fact]
public void ReadAsyncRespectsCancellation()
{
- var buffer = Encoding.UTF8.GetBytes("some data");
+ byte[] buffer = "some data"u8.ToArray();
var stream = new BinaryData(buffer).ToStream();
var read = new byte[buffer.Length];
[Fact]
public async Task CanSeek()
{
- var buffer = Encoding.UTF8.GetBytes("some data");
+ byte[] buffer = "some data"u8.ToArray();
var stream = new BinaryData(buffer).ToStream();
stream.Seek(5, SeekOrigin.Begin);
[Fact]
public void ValidatesSeekArguments()
{
- var buffer = Encoding.UTF8.GetBytes("some data");
+ byte[] buffer = "some data"u8.ToArray();
var stream = new BinaryData(buffer).ToStream();
Assert.Throws<IOException>(() => stream.Seek(-1, SeekOrigin.Begin));
[Fact]
public async Task ValidatesReadArguments()
{
- var buffer = Encoding.UTF8.GetBytes("some data");
+ byte[] buffer = "some data"u8.ToArray();
var stream = new BinaryData(buffer).ToStream();
stream.Seek(3, SeekOrigin.Begin);
var read = new byte[buffer.Length - stream.Position];
[Fact]
public void ValidatesPositionValue()
{
- var buffer = Encoding.UTF8.GetBytes("some data");
+ byte[] buffer = "some data"u8.ToArray();
var stream = new BinaryData(buffer).ToStream();
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Position = -1);
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Position = (long)int.MaxValue + 1);
[Fact]
public void CloseStreamValidation()
{
- byte[] buffer = Encoding.UTF8.GetBytes("some data");
+ byte[] buffer = "some data"u8.ToArray();
Stream stream = new BinaryData(buffer).ToStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Position = -1);
for (int j = 0; j < 8; j++)
{
- Span<byte> source = new byte[8] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
+ Span<byte> source = "2222PPPP"u8.ToArray(); // valid input
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
for (int i = 0; i < invalidBytes.Length; i++)
// Input that is not a multiple of 4 is considered invalid, if isFinalBlock = true
if (isFinalBlock)
{
- Span<byte> source = new byte[7] { 50, 50, 50, 50, 80, 80, 80 }; // incomplete input - "2222PPP"
+ Span<byte> source = "2222PPP"u8.ToArray(); // incomplete input
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount));
Assert.Equal(4, consumed);
// Only last 2 bytes can be padding, all other occurrence of padding is invalid
for (int j = 0; j < 7; j++)
{
- Span<byte> source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
+ Span<byte> source = "2222PPPP"u8.ToArray(); // valid input
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
source[j] = Base64TestHelper.EncodingPad;
Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount, isFinalBlock));
{
for (int i = 0; i < invalidBytes.Length; i++)
{
- Span<byte> buffer = new byte[8] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
+ Span<byte> buffer = "2222PPPP"u8.ToArray(); // valid input
// Don't test padding (byte 61 i.e. '='), which is tested in DecodeInPlaceInvalidBytesPadding
if (invalidBytes[i] == Base64TestHelper.EncodingPad)
// Input that is not a multiple of 4 is considered invalid
{
- Span<byte> buffer = new byte[7] { 50, 50, 50, 50, 80, 80, 80 }; // incomplete input - "2222PPP"
+ Span<byte> buffer = "2222PPP"u8.ToArray(); // incomplete input
Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten));
Assert.Equal(0, bytesWritten);
}
// Only last 2 bytes can be padding, all other occurrence of padding is invalid
for (int j = 0; j < 7; j++)
{
- Span<byte> buffer = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
+ Span<byte> buffer = "2222PPPP"u8.ToArray(); // valid input
buffer[j] = Base64TestHelper.EncodingPad;
string sourceString = Encoding.ASCII.GetString(buffer.Slice(0, 4).ToArray());
public void WritingToSingleSegmentBuffer()
{
IBufferWriter<byte> bufferWriter = new TestBufferWriterSingleSegment();
- bufferWriter.Write(Encoding.UTF8.GetBytes("Hello"));
- bufferWriter.Write(Encoding.UTF8.GetBytes(" World!"));
+ bufferWriter.Write("Hello"u8);
+ bufferWriter.Write(" World!"u8);
Assert.Equal("Hello World!", bufferWriter.ToString());
}
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());
}
// First, a small input with no flushing and no leftover data.
- ReadOnlySpan<byte> inputData = Encoding.UTF8.GetBytes("Hello");
+ ReadOnlySpan<byte> inputData = "Hello"u8;
EncodingExtensions.Convert(decoder, inputData, writer, flush: false, out long charsUsed, out bool completed);
Assert.Equal(5, charsUsed);
Assert.True(completed);
// 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]
// First try the single-segment code path.
ReadOnlySequence<char> sequence = new ReadOnlySequence<char>("Hello!".ToCharArray());
- Assert.Equal(Encoding.UTF8.GetBytes("Hello!"), EncodingExtensions.GetBytes(Encoding.UTF8, sequence));
+ Assert.Equal("Hello!"u8.ToArray(), EncodingExtensions.GetBytes(Encoding.UTF8, sequence));
// Next try the multi-segment code path.
// We've intentionally split multi-char subsequences here to test flushing mechanisms.
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]
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]
ReadOnlySequence<char> sequence = new ReadOnlySequence<char>("Hello!".ToCharArray());
Assert.Equal(
- expected: Encoding.UTF8.GetBytes("Hello!"),
+ expected: "Hello!"u8.ToArray(),
actual: destination.Slice(0, EncodingExtensions.GetBytes(Encoding.UTF8, sequence, destination)).ToArray());
// Next try the multi-segment code path.
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());
}
ReadOnlySpan<char> inputData = "Hello";
long bytesWritten = EncodingExtensions.GetBytes(Encoding.UTF8, inputData, writer);
Assert.Equal(5, bytesWritten);
- Assert.Equal(Encoding.UTF8.GetBytes("Hello"), writer.WrittenSpan.ToArray());
+ Assert.Equal("Hello"u8.ToArray(), writer.WrittenSpan.ToArray());
// Then, a large input that goes through the chunked path.
// We alternate between 1-char and 2-char sequences so that the input will be split in
{
// First try the single-segment code path.
- ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("Hello!"));
+ ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>("Hello!"u8.ToArray());
Assert.Equal("Hello!", EncodingExtensions.GetString(Encoding.UTF8, sequence));
// Next try the multi-segment code path.
[Fact]
public static void GetChars_Encoding_ReadOnlySequence_IBufferWriter_SingleSegment()
{
- ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("Hello"));
+ ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>("Hello"u8.ToArray());
ArrayBufferWriter<char> writer = new ArrayBufferWriter<char>();
long charsWritten = EncodingExtensions.GetChars(Encoding.UTF8, sequence, writer);
// First try the single-segment code path.
- ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("Hello!"));
+ ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>("Hello!"u8.ToArray());
Assert.Equal("Hello!", destination.Slice(0, EncodingExtensions.GetChars(Encoding.UTF8, sequence, destination)).ToString());
// Next try the multi-segment code path.
// First, a small input that goes through the one-shot code path.
- ReadOnlySpan<byte> inputData = Encoding.UTF8.GetBytes("Hello");
+ ReadOnlySpan<byte> inputData = "Hello"u8;
long charsWritten = EncodingExtensions.GetChars(Encoding.UTF8, inputData, writer);
Assert.Equal(5, charsWritten);
Assert.Equal("Hello", writer.WrittenSpan.ToString());
// [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();
public void TryReadTo_Span_At_Segments_Boundary()
{
Span<byte> delimiter = new byte[] { 13, 10 }; // \r\n
- BufferSegment<byte> segment = new BufferSegment<byte>(Text.Encoding.ASCII.GetBytes("Hello\r"));
- segment.Append(Text.Encoding.ASCII.GetBytes("\nWorld")); // add next segment
+ BufferSegment<byte> segment = new BufferSegment<byte>("Hello\r"u8.ToArray());
+ segment.Append("\nWorld"u8.ToArray()); // add next segment
ReadOnlySequence<byte> inputSeq = new ReadOnlySequence<byte>(segment, 0, segment, 6); // span only the first segment!
SequenceReader<byte> sr = new SequenceReader<byte>(inputSeq);
bool r = sr.TryReadTo(out ReadOnlySpan<byte> _, delimiter);
[Fact]
public void TryReadTo_SkipDelimiter()
{
- byte[] expected = Encoding.UTF8.GetBytes("This is our ^|understanding^|");
+ byte[] expected = "This is our ^|understanding^|"u8.ToArray();
ReadOnlySequence<byte> bytes = SequenceFactory.CreateUtf8("This is our ^|understanding^|| you see.");
SequenceReader<byte> reader = new SequenceReader<byte>(bytes);
Assert.True(reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'|', (byte)'^', advancePastDelimiter: true));
bytes = SequenceFactory.CreateUtf8("abc^|de|");
reader = new SequenceReader<byte>(bytes);
Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true));
- Assert.Equal(Encoding.UTF8.GetBytes("abc^|de"), span.ToArray());
+ Assert.Equal("abc^|de"u8.ToArray(), span.ToArray());
Assert.True(reader.End);
Assert.Equal(8, reader.Consumed);
reader.Rewind(reader.Consumed);
Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true));
- Assert.Equal(Encoding.UTF8.GetBytes("abc^|de"), sequence.ToArray());
+ Assert.Equal("abc^|de"u8.ToArray(), sequence.ToArray());
Assert.True(reader.End);
Assert.Equal(8, reader.Consumed);
bytes = SequenceFactory.CreateUtf8("^|a|b");
reader = new SequenceReader<byte>(bytes);
Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true));
- Assert.Equal(Encoding.UTF8.GetBytes("^|a"), span.ToArray());
+ Assert.Equal("^|a"u8.ToArray(), span.ToArray());
Assert.True(reader.IsNext((byte)'b'));
Assert.Equal(4, reader.Consumed);
reader.Rewind(reader.Consumed);
Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true));
- Assert.Equal(Encoding.UTF8.GetBytes("^|a"), sequence.ToArray());
+ Assert.Equal("^|a"u8.ToArray(), sequence.ToArray());
Assert.True(reader.IsNext((byte)'b'));
Assert.Equal(4, reader.Consumed);
bytes = SequenceFactory.CreateUtf8("^", "|a|b");
reader = new SequenceReader<byte>(bytes);
Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true));
- Assert.Equal(Encoding.UTF8.GetBytes("^|a"), span.ToArray());
+ Assert.Equal("^|a"u8.ToArray(), span.ToArray());
Assert.True(reader.IsNext((byte)'b'));
Assert.Equal(4, reader.Consumed);
reader.Rewind(reader.Consumed);
Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true));
- Assert.Equal(Encoding.UTF8.GetBytes("^|a"), sequence.ToArray());
+ Assert.Equal("^|a"u8.ToArray(), sequence.ToArray());
Assert.True(reader.IsNext((byte)'b'));
Assert.Equal(4, reader.Consumed);
}
ReadOnlySequence<byte> bytes = SequenceFactory.CreateUtf8("abc^^|def");
SequenceReader<byte> reader = new SequenceReader<byte>(bytes);
Assert.True(reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'|', (byte)'^', advancePastDelimiter: false));
- Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray());
+ Assert.Equal("abc^^"u8.ToArray(), span.ToArray());
Assert.True(reader.IsNext((byte)'|'));
Assert.Equal(5, reader.Consumed);
reader.Rewind(reader.Consumed);
Assert.True(reader.TryReadTo(out ReadOnlySequence<byte> sequence, (byte)'|', (byte)'^', advancePastDelimiter: false));
- Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), sequence.ToArray());
+ Assert.Equal("abc^^"u8.ToArray(), sequence.ToArray());
Assert.True(reader.IsNext((byte)'|'));
Assert.Equal(5, reader.Consumed);
bytes = SequenceFactory.CreateUtf8("abc^^", "|def");
reader = new SequenceReader<byte>(bytes);
Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false));
- Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray());
+ Assert.Equal("abc^^"u8.ToArray(), span.ToArray());
Assert.True(reader.IsNext((byte)'|'));
Assert.Equal(5, reader.Consumed);
reader.Rewind(reader.Consumed);
Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: false));
- Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), sequence.ToArray());
+ Assert.Equal("abc^^"u8.ToArray(), sequence.ToArray());
Assert.True(reader.IsNext((byte)'|'));
Assert.Equal(5, reader.Consumed);
bytes = SequenceFactory.CreateUtf8("abc^", "^", "|def");
reader = new SequenceReader<byte>(bytes);
Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false));
- Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray());
+ Assert.Equal("abc^^"u8.ToArray(), span.ToArray());
Assert.True(reader.IsNext((byte)'|'));
Assert.Equal(5, reader.Consumed);
reader.Rewind(reader.Consumed);
Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: false));
- Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), sequence.ToArray());
+ Assert.Equal("abc^^"u8.ToArray(), sequence.ToArray());
Assert.True(reader.IsNext((byte)'|'));
Assert.Equal(5, reader.Consumed);
// Check advance past delimiter
reader = new SequenceReader<byte>(bytes);
Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true));
- Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray());
+ Assert.Equal("abc^^"u8.ToArray(), span.ToArray());
Assert.True(reader.IsNext((byte)'d'));
Assert.Equal(6, reader.Consumed);
reader.Rewind(reader.Consumed);
Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true));
- Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), sequence.ToArray());
+ Assert.Equal("abc^^"u8.ToArray(), sequence.ToArray());
Assert.True(reader.IsNext((byte)'d'));
Assert.Equal(6, reader.Consumed);
bytes = SequenceFactory.CreateUtf8("^^|abc");
reader = new SequenceReader<byte>(bytes);
Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false));
- Assert.Equal(Encoding.UTF8.GetBytes("^^"), span.ToArray());
+ Assert.Equal("^^"u8.ToArray(), span.ToArray());
Assert.True(reader.IsNext((byte)'|'));
Assert.Equal(2, reader.Consumed);
reader.Rewind(reader.Consumed);
Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: false));
- Assert.Equal(Encoding.UTF8.GetBytes("^^"), sequence.ToArray());
+ Assert.Equal("^^"u8.ToArray(), sequence.ToArray());
Assert.True(reader.IsNext((byte)'|'));
Assert.Equal(2, reader.Consumed);
{
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;
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);
<TargetFrameworks>$(NetCoreAppCurrent)-windows;net48</TargetFrameworks>
<IncludeRemoteExecutor>true</IncludeRemoteExecutor>
<DefineConstants>$(DefineConstants);WINHTTPHANDLER_TEST</DefineConstants>
- <LangVersion>10.0</LangVersion>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(CommonTestPath)System\Net\Configuration.cs"
protected override Version UseVersion => new Version(2, 0);
- protected static byte[] DataBytes = Encoding.ASCII.GetBytes("data");
+ protected static byte[] DataBytes = "data"u8.ToArray();
protected static readonly IList<HttpHeaderData> TrailingHeaders = new HttpHeaderData[] {
new HttpHeaderData("MyCoolTrailerHeader", "amazingtrailer"),
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];
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];
private static readonly (HeaderDescriptor descriptor, byte[] value)[] s_hpackStaticHeaderTable = new (HeaderDescriptor, byte[])[LastHPackNormalHeaderId - FirstHPackNormalHeaderId + 1]
{
(KnownHeaders.AcceptCharset.Descriptor, Array.Empty<byte>()),
- (KnownHeaders.AcceptEncoding.Descriptor, Encoding.ASCII.GetBytes("gzip, deflate")),
+ (KnownHeaders.AcceptEncoding.Descriptor, "gzip, deflate"u8.ToArray()),
(KnownHeaders.AcceptLanguage.Descriptor, Array.Empty<byte>()),
(KnownHeaders.AcceptRanges.Descriptor, Array.Empty<byte>()),
(KnownHeaders.Accept.Descriptor, Array.Empty<byte>()),
/// </remarks>
private const int MaxChunkBytesAllowed = 16 * 1024;
- private static readonly byte[] s_contentLength0NewlineAsciiBytes = Encoding.ASCII.GetBytes("Content-Length: 0\r\n");
- private static readonly byte[] s_spaceHttp10NewlineAsciiBytes = Encoding.ASCII.GetBytes(" HTTP/1.0\r\n");
- private static readonly byte[] s_spaceHttp11NewlineAsciiBytes = Encoding.ASCII.GetBytes(" HTTP/1.1\r\n");
- private static readonly byte[] s_httpSchemeAndDelimiter = Encoding.ASCII.GetBytes(Uri.UriSchemeHttp + Uri.SchemeDelimiter);
- private static readonly byte[] s_http1DotBytes = Encoding.ASCII.GetBytes("HTTP/1.");
- private static readonly ulong s_http10Bytes = BitConverter.ToUInt64(Encoding.ASCII.GetBytes("HTTP/1.0"));
- private static readonly ulong s_http11Bytes = BitConverter.ToUInt64(Encoding.ASCII.GetBytes("HTTP/1.1"));
+ private static readonly byte[] s_contentLength0NewlineAsciiBytes = "Content-Length: 0\r\n"u8.ToArray();
+ private static readonly byte[] s_spaceHttp10NewlineAsciiBytes = " HTTP/1.0\r\n"u8.ToArray();
+ private static readonly byte[] s_spaceHttp11NewlineAsciiBytes = " HTTP/1.1\r\n"u8.ToArray();
+ private static readonly byte[] s_httpSchemeAndDelimiter = "http://"u8.ToArray();
+ private static readonly byte[] s_http1DotBytes = "HTTP/1."u8.ToArray();
+ private static readonly ulong s_http10Bytes = BitConverter.ToUInt64("HTTP/1.0"u8);
+ private static readonly ulong s_http11Bytes = BitConverter.ToUInt64("HTTP/1.1"u8);
private readonly HttpConnectionPool _pool;
private readonly Stream _stream;
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() };
}
}
}
}
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();
});
}
}
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);
});
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
public async Task PostAsyncDuplex_ClientSendsEndStream_Success()
{
- byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+ byte[] contentBytes = "Hello world"u8.ToArray();
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
public async Task PostAsyncDuplex_ServerSendsEndStream_Success()
{
- byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+ byte[] contentBytes = "Hello world"u8.ToArray();
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
public async Task PostAsyncDuplex_RequestContentException_ResetsStream()
{
- byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+ byte[] contentBytes = "Hello world"u8.ToArray();
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
public async Task PostAsyncDuplex_RequestContentExceptionAfterResponseEndReceivedButBeforeConsumed_ResetsStreamAndThrowsOnResponseStreamRead()
{
- byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+ byte[] contentBytes = "Hello world"u8.ToArray();
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
public async Task PostAsyncDuplex_CancelledBeforeResponseHeadersReceived_ResetsStream()
{
- byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+ byte[] contentBytes = "Hello world"u8.ToArray();
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
public async Task PostAsyncDuplex_ServerResetsStream_Throws()
{
- byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+ byte[] contentBytes = "Hello world"u8.ToArray();
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
public async Task PostAsyncDuplex_DisposeResponseBodyBeforeEnd_ResetsStreamAndThrowsOnRequestStreamWriteAndResponseStreamRead()
{
- byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+ byte[] contentBytes = "Hello world"u8.ToArray();
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
public async Task PostAsyncDuplex_DisposeResponseBodyAfterEndReceivedButBeforeConsumed_ResetsStreamAndThrowsOnRequestStreamWriteAndResponseStreamRead()
{
- byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+ byte[] contentBytes = "Hello world"u8.ToArray();
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
public async Task PostAsyncDuplex_FinishRequestBodyAndDisposeResponseBodyAfterEndReceivedButBeforeConsumed_DoesNotResetStream()
{
- byte[] contentBytes = Encoding.UTF8.GetBytes("Hello world");
+ byte[] contentBytes = "Hello world"u8.ToArray();
using (Http2LoopbackServer server = Http2LoopbackServer.CreateServer())
{
// 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())
{
// 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())
{
await sslStream.AuthenticateAsServerAsync(options, CancellationToken.None).ConfigureAwait(false);
// Send back HTTP/1.1 response
- await sslStream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/1.1 400 Unrecognized request\r\n\r\n"), CancellationToken.None);
+ await sslStream.WriteAsync("HTTP/1.1 400 Unrecognized request\r\n\r\n"u8.ToArray(), CancellationToken.None);
});
Exception e = await Assert.ThrowsAsync<HttpRequestException>(() => requestTask);
Http2LoopbackConnection connection = await server.EstablishConnectionAsync();
int streamId = await connection.ReadRequestHeaderAsync();
await connection.SendDefaultResponseHeadersAsync(streamId);
- await connection.SendResponseDataAsync(streamId, Encoding.ASCII.GetBytes("hello"), endStream: false);
+ await connection.SendResponseDataAsync(streamId, "hello"u8.ToArray(), endStream: false);
await connection.SendResponseHeadersAsync(streamId, endStream : true, isTrailingHeader : true, headers: headers);
await Assert.ThrowsAsync<HttpRequestException>(() => sendTask);
[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);
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()
[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" });
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(
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();
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);
var mc = new MultipartContent("subtype", "fooBoundary");
var stringContent = new StringContent("bar1");
- stringContent.Headers.Add("latin1", "\uD83D\uDE00");
+ stringContent.Headers.Add("latin1", "\U0001F600");
mc.Add(stringContent);
- var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar2"));
- byteArrayContent.Headers.Add("utf8", "\uD83D\uDE00");
+ var byteArrayContent = new ByteArrayContent("bar2"u8.ToArray());
+ byteArrayContent.Headers.Add("utf8", "\U0001F600");
mc.Add(byteArrayContent);
- byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar3"));
- byteArrayContent.Headers.Add("ascii", "\uD83D\uDE00");
+ byteArrayContent = new ByteArrayContent("bar3"u8.ToArray());
+ byteArrayContent.Headers.Add("ascii", "\U0001F600");
mc.Add(byteArrayContent);
- byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar4"));
- byteArrayContent.Headers.Add("default", "\uD83D\uDE00");
+ byteArrayContent = new ByteArrayContent("bar4"u8.ToArray());
+ byteArrayContent.Headers.Add("default", "\U0001F600");
mc.Add(byteArrayContent);
mc.HeaderEncodingSelector = (name, _) => name switch
}
byte[] expected = Concat(
- Encoding.Latin1.GetBytes("--fooBoundary\r\n"),
- Encoding.Latin1.GetBytes("Content-Type: text/plain; charset=utf-8\r\n"),
- Encoding.Latin1.GetBytes("latin1: "),
- Encoding.Latin1.GetBytes("\uD83D\uDE00"),
- Encoding.Latin1.GetBytes("\r\n\r\n"),
- Encoding.Latin1.GetBytes("bar1"),
- Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"),
- Encoding.Latin1.GetBytes("utf8: "),
- Encoding.UTF8.GetBytes("\uD83D\uDE00"),
- Encoding.Latin1.GetBytes("\r\n\r\n"),
- Encoding.Latin1.GetBytes("bar2"),
- Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"),
- Encoding.Latin1.GetBytes("ascii: "),
- Encoding.ASCII.GetBytes("\uD83D\uDE00"),
- Encoding.Latin1.GetBytes("\r\n\r\n"),
- Encoding.Latin1.GetBytes("bar3"),
- Encoding.Latin1.GetBytes("\r\n--fooBoundary\r\n"),
- Encoding.Latin1.GetBytes("default: "),
- Encoding.Latin1.GetBytes("\uD83D\uDE00"),
- Encoding.Latin1.GetBytes("\r\n\r\n"),
- Encoding.Latin1.GetBytes("bar4"),
- Encoding.Latin1.GetBytes("\r\n--fooBoundary--\r\n"));
+ "--fooBoundary\r\n"u8.ToArray(),
+ "Content-Type: text/plain; charset=utf-8\r\n"u8.ToArray(),
+ "latin1: "u8.ToArray(),
+ Encoding.Latin1.GetBytes("\U0001F600"),
+ "\r\n\r\n"u8.ToArray(),
+ "bar1"u8.ToArray(),
+ "\r\n--fooBoundary\r\n"u8.ToArray(),
+ "utf8: "u8.ToArray(),
+ "\U0001F600"u8.ToArray(),
+ "\r\n\r\n"u8.ToArray(),
+ "bar2"u8.ToArray(),
+ "\r\n--fooBoundary\r\n"u8.ToArray(),
+ "ascii: "u8.ToArray(),
+ Encoding.ASCII.GetBytes("\U0001F600"),
+ "\r\n\r\n"u8.ToArray(),
+ "bar3"u8.ToArray(),
+ "\r\n--fooBoundary\r\n"u8.ToArray(),
+ "default: "u8.ToArray(),
+ Encoding.Latin1.GetBytes("\U0001F600"),
+ "\r\n\r\n"u8.ToArray(),
+ "bar4"u8.ToArray(),
+ "\r\n--fooBoundary--\r\n"u8.ToArray());
Assert.Equal(expected, ms.ToArray());
// 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());
}
}
// 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());
}
}
{
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());
}
}
{
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());
}
}
}
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();
{
public SocketsHttpHandler_TrailingHeaders_Test(ITestOutputHelper output) : base(output) { }
- protected static byte[] DataBytes = Encoding.ASCII.GetBytes("data");
+ protected static byte[] DataBytes = "data"u8.ToArray();
protected static readonly IList<HttpHeaderData> TrailingHeaders = new HttpHeaderData[] {
new HttpHeaderData("MyCoolTrailerHeader", "amazingtrailer"),
// Validate writing APIs on clientStream
clientStream.WriteByte((byte)'!');
- clientStream.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2);
+ clientStream.Write("\r\n"u8.ToArray(), 0, 2);
Assert.Equal("!", await connection.ReadLineAsync());
- clientStream.Write(new Span<byte>(new byte[] { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'\r', (byte)'\n' }));
+ clientStream.Write("hello\r\n"u8);
Assert.Equal("hello", await connection.ReadLineAsync());
- await clientStream.WriteAsync(new byte[] { (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 7);
+ await clientStream.WriteAsync("world\r\n"u8.ToArray(), 0, 7);
Assert.Equal("world", await connection.ReadLineAsync());
- await clientStream.WriteAsync(new Memory<byte>(new byte[] { (byte)'a', (byte)'n', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 5));
+ await clientStream.WriteAsync(new Memory<byte>("and\r\n"u8.ToArray(), 0, 5));
Assert.Equal("and", await connection.ReadLineAsync());
- await Task.Factory.FromAsync(clientStream.BeginWrite, clientStream.EndWrite, new byte[] { (byte)'b', (byte)'e', (byte)'y', (byte)'o', (byte)'n', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 8, null);
+ await Task.Factory.FromAsync(clientStream.BeginWrite, clientStream.EndWrite, "beyond\r\n"u8.ToArray(), 0, 8, null);
Assert.Equal("beyond", await connection.ReadLineAsync());
clientStream.Flush();
await clientStream.FlushAsync();
// Validate reading APIs on clientStream
- await connection.Stream.WriteAsync(Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwxyz"));
+ await connection.Stream.WriteAsync("abcdefghijklmnopqrstuvwxyz"u8.ToArray());
var buffer = new byte[1];
Assert.Equal('a', clientStream.ReadByte());
{
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));
[ActiveIssue("https://github.com/dotnet/runtime/issues/69870", TestPlatforms.Android)]
public async Task PlaintextStreamFilter_ConnectionPrefix_Success(bool useSsl)
{
- byte[] RequestPrefix = Encoding.UTF8.GetBytes("request prefix\r\n");
- byte[] ResponsePrefix = Encoding.UTF8.GetBytes("response prefix\r\n");
+ byte[] RequestPrefix = "request prefix\r\n"u8.ToArray();
+ byte[] ResponsePrefix = "response prefix\r\n"u8.ToArray();
using var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
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(
var complexContent = new MultipartContent();
var stringContent = new StringContent("bar1");
- stringContent.Headers.Add("latin1", "\uD83D\uDE00");
+ stringContent.Headers.Add("latin1", "\U0001F600");
complexContent.Add(stringContent);
- var byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar2"));
- byteArrayContent.Headers.Add("utf8", "\uD83D\uDE00");
+ var byteArrayContent = new ByteArrayContent("bar2"u8.ToArray());
+ byteArrayContent.Headers.Add("utf8", "\U0001F600");
complexContent.Add(byteArrayContent);
- byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar3"));
- byteArrayContent.Headers.Add("ascii", "\uD83D\uDE00");
+ byteArrayContent = new ByteArrayContent("bar3"u8.ToArray());
+ byteArrayContent.Headers.Add("ascii", "\U0001F600");
complexContent.Add(byteArrayContent);
- byteArrayContent = new ByteArrayContent(Encoding.ASCII.GetBytes("bar4"));
- byteArrayContent.Headers.Add("default", "\uD83D\uDE00");
+ byteArrayContent = new ByteArrayContent("bar4"u8.ToArray());
+ byteArrayContent.Headers.Add("default", "\U0001F600");
complexContent.Add(byteArrayContent);
stringContent = new StringContent("bar5");
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()
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)
{
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)
{
{
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 };
}
[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();
{
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()
{
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);
}
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);
}
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
{
{
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
{
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
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();
}
}
{
public class LoopbackSmtpServer : IDisposable
{
- private static readonly ReadOnlyMemory<byte> s_messageTerminator = new byte[] { (byte)'\r', (byte)'\n' };
- private static readonly ReadOnlyMemory<byte> s_bodyTerminator = new byte[] { (byte)'\r', (byte)'\n', (byte)'.', (byte)'\r', (byte)'\n' };
+ private static readonly ReadOnlyMemory<byte> s_messageTerminator = "\r\n"u8.ToArray();
+ private static readonly ReadOnlyMemory<byte> s_bodyTerminator = "\r\n.\r\n"u8.ToArray();
public bool ReceiveMultipleConnections = false;
public bool SupportSmtpUTF8 = false;
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
// 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()
{
{
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);
{
ApiTable = apiTable;
- fixed (byte* pAppName = s_appName)
+ fixed (byte* pAppName = "System.Net.Quic"u8)
{
var cfg = new QUIC_REGISTRATION_CONFIG {
AppName = (sbyte*)pAppName,
[Collection(nameof(DisableParallelization))]
public class MsQuicTests : QuicTestBase<MsQuicProviderFactory>
{
- private static byte[] s_data = Encoding.UTF8.GetBytes("Hello world!");
+ private static byte[] s_data = "Hello world!"u8.ToArray();
public MsQuicTests(ITestOutputHelper output) : base(output) { }
{
(QuicConnection clientConnection, QuicConnection serverConnection) = await CreateConnectedQuicConnection();
- ReadOnlyMemory<byte> helloWorld = Encoding.ASCII.GetBytes("Hello world!");
+ ReadOnlyMemory<byte> helloWorld = "Hello world!"u8.ToArray();
ReadOnlySequence<byte> ros = CreateReadOnlySequenceFromBytes(helloWorld.ToArray());
Assert.False(ros.IsSingleSegment);
public abstract class QuicStreamTests<T> : QuicTestBase<T>
where T : IQuicImplProviderFactory, new()
{
- private static byte[] s_data = Encoding.UTF8.GetBytes("Hello world!");
+ private static byte[] s_data = "Hello world!"u8.ToArray();
public QuicStreamTests(ITestOutputHelper output) : base(output) { }
[Fact]
{
byte[] buffer = new byte[64];
QuicStream clientStream = await clientConnection.OpenBidirectionalStreamAsync();
- ValueTask writeTask = clientStream.WriteAsync(Encoding.UTF8.GetBytes("PING"), endStream: true);
+ ValueTask writeTask = clientStream.WriteAsync("PING"u8.ToArray(), endStream: true);
ValueTask<QuicStream> acceptTask = serverConnection.AcceptStreamAsync();
await new Task[] { writeTask.AsTask(), acceptTask.AsTask() }.WhenAllOrAnyFailed(PassingTestTimeoutMilliseconds);
QuicStream serverStream = acceptTask.Result;
public abstract class QuicTestBase<T>
where T : IQuicImplProviderFactory, new()
{
- private static readonly byte[] s_ping = Encoding.UTF8.GetBytes("PING");
- private static readonly byte[] s_pong = Encoding.UTF8.GetBytes("PONG");
+ private static readonly byte[] s_ping = "PING"u8.ToArray();
+ private static readonly byte[] s_pong = "PONG"u8.ToArray();
private static readonly IQuicImplProviderFactory s_factory = new T();
public static QuicImplementationProvider ImplementationProvider { get; } = s_factory.GetProvider();
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))]
public readonly struct SslApplicationProtocol : IEquatable<SslApplicationProtocol>
{
private static readonly Encoding s_utf8 = Encoding.GetEncoding(Encoding.UTF8.CodePage, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
- private static readonly byte[] s_http3Utf8 = new byte[] { 0x68, 0x33 }; // "h3"
- private static readonly byte[] s_http2Utf8 = new byte[] { 0x68, 0x32 }; // "h2"
- private static readonly byte[] s_http11Utf8 = new byte[] { 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31 }; // "http/1.1"
+ private static readonly byte[] s_http3Utf8 = "h3"u8.ToArray();
+ private static readonly byte[] s_http2Utf8 = "h2"u8.ToArray();
+ private static readonly byte[] s_http11Utf8 = "http/1.1"u8.ToArray();
// Refer to IANA on ApplicationProtocols: https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids
/// <summary>Defines a <see cref="SslApplicationProtocol"/> instance for HTTP 3.0.</summary>
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';
[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]
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);
}
}
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';
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.
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.
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);
public abstract class SslStreamStreamToStreamTest
{
- private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
+ private readonly byte[] _sampleMsg = "Sample Test Message"u8.ToArray();
protected static async Task WithServerCertificate(X509Certificate serverCertificate, Func<X509Certificate, string, Task> func)
{
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)
{
[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]
[Fact]
public void Constructor_ByteArray_Copies()
{
- byte[] expected = Encoding.UTF8.GetBytes("hello");
+ byte[] expected = "hello"u8.ToArray();
SslApplicationProtocol byteProtocol = new SslApplicationProtocol(expected);
ArraySegment<byte> arraySegment;
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
}
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
}
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;
Assert.Equal(WebSocketState.Open, socket.State);
// Ask server to send us a close
- await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(".close")), WebSocketMessageType.Text, true, default);
+ await socket.SendAsync(new ArraySegment<byte>(".close"u8.ToArray()), WebSocketMessageType.Text, true, default);
// Verify received server-initiated close message.
WebSocketReceiveResult recvResult = await socket.ReceiveAsync(new ArraySegment<byte>(new byte[256]), default);
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.
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);
DangerousDeflateOptions = new WebSocketDeflateOptions()
});
- byte[] bytes = Encoding.UTF8.GetBytes("Hello");
+ byte[] bytes = "Hello"u8.ToArray();
await websocket.SendAsync(Memory<byte>.Empty, WebSocketMessageType.Text, endOfMessage: false, CancellationToken);
await websocket.SendAsync(bytes, WebSocketMessageType.Text, endOfMessage: true, CancellationToken);
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));
// 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;
{
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))
{
{
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))
{
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");
[Fact]
public void NodeReaderReadContentAsBase64WithSimpleXml()
{
- byte[] byteData = Encoding.ASCII.GetBytes("hello world");
+ byte[] byteData = "hello world"u8.ToArray();
string xml = $"<root attr='{Convert.ToBase64String(byteData)}'><child /></root>"; //hello world encoded
XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml);
Assert.True(nodeReader.Read());
[Fact]
public void NodeReaderReadContentAsBinHexWithSimpleXml()
{
- byte[] byteData = Encoding.ASCII.GetBytes("hello world");
+ byte[] byteData = "hello world"u8.ToArray();
string xml = $"<root attr='{BitConverter.ToString(byteData).Replace("-", "")}'><child /></root>";
XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml);
Assert.True(nodeReader.Read());
[Fact]
public void NodeReaderReadElementContentAsBase64WithSimpleXml()
{
- byte[] byteData = Encoding.ASCII.GetBytes("hello world");
+ byte[] byteData = "hello world"u8.ToArray();
string xml = $"<root attr='val'>{Convert.ToBase64String(byteData)}</root>"; //hello world encoded
XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml);
Assert.True(nodeReader.Read());
[Fact]
public void NodeReaderReadElementContentAsBinHexWithSimpleXml()
{
- byte[] byteData = Encoding.ASCII.GetBytes("hello world");
+ byte[] byteData = "hello world"u8.ToArray();
string xml = $"<root attr='val'>{BitConverter.ToString(byteData).Replace("-", "")}</root>";
XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml);
Assert.True(nodeReader.Read());
{
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),
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));
[Fact]
public void XmlResolverGetEntityAsyncWithValidUserSuppliedData()
{
- byte[] inpData = Encoding.ASCII.GetBytes("hello world");
+ byte[] inpData = "hello world"u8.ToArray();
var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10);
xmlResolver.Add(new Uri("-//W3C//DTD FAKE 1.0 Not Real//EN", UriKind.RelativeOrAbsolute), inpData);
Task<object> output = xmlResolver.GetEntityAsync(new Uri("-//W3C//DTD FAKE 1.0 Not Real//EN",
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;
// 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);
winrtDef.Attributes);
var strReader = reader.GetBlobReader(winrtDef.Name);
- Assert.Equal(Encoding.UTF8.GetBytes("Class1"), strReader.ReadBytes("Class1".Length));
+ Assert.Equal("Class1"u8.ToArray(), strReader.ReadBytes("Class1".Length));
Assert.Equal(0, strReader.RemainingBytes);
// .class /*02000003*/ private auto ansi import windowsruntime sealed beforefieldinit Lib.'<WinRT>Class1'
clrDef.Attributes);
strReader = reader.GetBlobReader(clrDef.Name);
- Assert.Equal(Encoding.UTF8.GetBytes("<WinRT>Class1"), strReader.ReadBytes("<WinRT>Class1".Length));
+ Assert.Equal("<WinRT>Class1"u8.ToArray(), strReader.ReadBytes("<WinRT>Class1".Length));
Assert.Equal(0, strReader.RemainingBytes);
}
winrtDef.Attributes);
var strReader = reader.GetBlobReader(winrtDef.Name);
- Assert.Equal(Encoding.UTF8.GetBytes("<CLR>Class1"), strReader.ReadBytes("<CLR>Class1".Length));
+ Assert.Equal("<CLR>Class1"u8.ToArray(), strReader.ReadBytes("<CLR>Class1".Length));
Assert.Equal(0, strReader.RemainingBytes);
// .class /*02000003*/ public auto ansi windowsruntime sealed beforefieldinit Lib.Class1
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);
}
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);
}
[Fact]
public void ReadNullPaddedUTF8WorksWithNoNullPadding()
{
- var headerBytes = Encoding.UTF8.GetBytes(".abcdefg");
+ byte[] headerBytes = ".abcdefg"u8.ToArray();
var stream = new MemoryStream(headerBytes);
stream.Position = 0;
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);
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"));
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);
}
);
- 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);
}
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);
// 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);
}
[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);
}
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()
{
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);
}
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()
{
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);
}
}
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()
{
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);
}
}
[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()
{
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);
}
}
[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()
{
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);
}
}
[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()
{
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);
}
}
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";
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);
"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";
"FD6B6AB4F89DC6750F14EC2E0134BA61B4D0B2C1FB2F60F622379249CE6381AF" +
"667900B17A7BB6AE");
- data.MessageContent = Encoding.ASCII.GetBytes("Hello, world!");
+ data.MessageContent = "Hello, world!"u8.ToArray();
data.EmbeddedSigningCertificate = data.FullTokenBytes.Slice(1659, 1359);
"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);
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())
public static void TestKey_ECDsabrainpool_PublicKey(byte[] curveData, byte[] notUsed)
{
_ = notUsed;
- byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
+ byte[] helloBytes = "Hello"u8.ToArray();
try
{
[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())
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())
[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
{
[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);
{
using (TripleDES tripleDES = TripleDES.Create())
{
- byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678");
+ byte[] key = "123456781234567812345678"u8.ToArray();
byte[] encryptedKey = EncryptedXml.EncryptKey(key, tripleDES);
{
using (Aes aes = Aes.Create())
{
- byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678");
+ byte[] key = "123456781234567812345678"u8.ToArray();
byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes);
{
using (Aes aes = Aes.Create())
{
- byte[] key = Encoding.ASCII.GetBytes("12345678");
+ byte[] key = "12345678"u8.ToArray();
byte[] encryptedKey = EncryptedXml.EncryptKey(key, aes);
{
using (Aes aes = Aes.Create())
{
- byte[] key = Encoding.ASCII.GetBytes("1234567");
+ byte[] key = "1234567"u8.ToArray();
Assert.Throws<CryptographicException>(() => EncryptedXml.EncryptKey(key, aes));
}
{
using (TripleDES tripleDES = TripleDES.Create())
{
- byte[] key = Encoding.ASCII.GetBytes("123");
+ byte[] key = "123"u8.ToArray();
Assert.Throws<CryptographicException>(() => EncryptedXml.DecryptKey(key, tripleDES));
}
{
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;
{
using (Aes aes = Aes.Create())
{
- byte[] key = Encoding.ASCII.GetBytes("123");
+ byte[] key = "123"u8.ToArray();
Assert.Throws<CryptographicException>(() => EncryptedXml.DecryptKey(key, aes));
}
{
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;
{
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;
";
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++)
";
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")]
// 72 is a multiple of 8 but smaller than the minimum of 80 bits
string xml = @"<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /><SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#hmac-sha1""><HMACOutputLength>72</HMACOutputLength></SignatureMethod><Reference URI=""#object""><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><DigestValue>nz4GS0NbH2SrWlD/4fX313CoTzc=</DigestValue></Reference></SignedInfo><SignatureValue>2dimB+P5Aw5K</SignatureValue><Object Id=""object"">some other text</Object></Signature>";
SignedXml sign = GetSignedXml(xml);
- CheckErratum(sign, new HMACSHA1(Encoding.ASCII.GetBytes("secret")), "72");
+ CheckErratum(sign, new HMACSHA1("secret"u8.ToArray()), "72");
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/20429")]
// 80 bits is the minimum (and the half-size of HMACSHA1)
string xml = @"<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /><SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#hmac-sha1""><HMACOutputLength>80</HMACOutputLength></SignatureMethod><Reference URI=""#object""><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><DigestValue>nz4GS0NbH2SrWlD/4fX313CoTzc=</DigestValue></Reference></SignedInfo><SignatureValue>jVQPtLj61zNYjw==</SignatureValue><Object Id=""object"">some other text</Object></Signature>";
SignedXml sign = GetSignedXml(xml);
- Assert.True(sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("secret"))));
+ Assert.True(sign.CheckSignature(new HMACSHA1("secret"u8.ToArray())));
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/20429")]
// 80bits is smaller than the half-size of HMACSHA256
string xml = @"<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /><SignatureMethod Algorithm=""http://www.w3.org/2001/04/xmldsig-more#hmac-sha256""><HMACOutputLength>80</HMACOutputLength></SignatureMethod><Reference URI=""#object""><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><DigestValue>nz4GS0NbH2SrWlD/4fX313CoTzc=</DigestValue></Reference></SignedInfo><SignatureValue>vPtw7zKVV/JwQg==</SignatureValue><Object Id=""object"">some other text</Object></Signature>";
SignedXml sign = GetSignedXml(xml);
- CheckErratum(sign, new HMACSHA256(Encoding.ASCII.GetBytes("secret")), "80");
+ CheckErratum(sign, new HMACSHA256("secret"u8.ToArray()), "80");
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/20429")]
// 128 is the half-size of HMACSHA256
string xml = @"<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /><SignatureMethod Algorithm=""http://www.w3.org/2001/04/xmldsig-more#hmac-sha256""><HMACOutputLength>128</HMACOutputLength></SignatureMethod><Reference URI=""#object""><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><DigestValue>nz4GS0NbH2SrWlD/4fX313CoTzc=</DigestValue></Reference></SignedInfo><SignatureValue>aegpvkAwOL8gN/CjSnW6qw==</SignatureValue><Object Id=""object"">some other text</Object></Signature>";
SignedXml sign = GetSignedXml(xml);
- Assert.True(sign.CheckSignature(new HMACSHA256(Encoding.ASCII.GetBytes("secret"))));
+ Assert.True(sign.CheckSignature(new HMACSHA256("secret"u8.ToArray())));
}
[Fact]
{
string xml = @"<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" /><SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#hmac-sha1"" /><Reference URI=""#object""><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><DigestValue>7/XTsHaBSOnJ/jXD5v0zL6VKYsk=</DigestValue></Reference></SignedInfo><SignatureValue>a0goL9esBUKPqtFYgpp2KST4huk=</SignatureValue><Object Id=""object"">some text</Object></Signature>";
SignedXml sign = GetSignedXml(xml);
- Assert.True(sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("secret"))));
+ Assert.True(sign.CheckSignature(new HMACSHA1("secret"u8.ToArray())));
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/20429")]
</Signature>
";
SignedXml sign = GetSignedXml(xml);
- Assert.Throws<CryptographicException>(() => sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("no clue"))));
+ Assert.Throws<CryptographicException>(() => sign.CheckSignature(new HMACSHA1("no clue"u8.ToArray())));
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/20429")]
</Signature>
";
SignedXml sign = GetSignedXml(xml);
- Assert.Throws<FormatException>(() => sign.CheckSignature(new HMACSHA1(Encoding.ASCII.GetBytes("no clue"))));
+ Assert.Throws<FormatException>(() => sign.CheckSignature(new HMACSHA1("no clue"u8.ToArray())));
}
[Fact]
{
internal sealed partial class AppleCertificatePal : ICertificatePal
{
- // Byte representation of "-----BEGIN "
- private static ReadOnlySpan<byte> PemBegin => new byte[] { 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x42, 0x45, 0x47, 0x49, 0x4E, 0x20 };
-
internal delegate bool DerCallback(ReadOnlySpan<byte> derData, X509ContentType contentType);
internal static bool TryDecodePem(ReadOnlySpan<byte> rawData, DerCallback derCallback)
// 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;
}
[Fact]
public void InvalidInput_ToBase64Transform()
{
- byte[] data_3bytes = Text.Encoding.ASCII.GetBytes("aaa");
+ byte[] data_3bytes = "aaa"u8.ToArray();
ICryptoTransform transform = new ToBase64Transform();
AssertExtensions.Throws<ArgumentNullException>("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0));
[Fact]
public void InvalidInput_FromBase64Transform()
{
- byte[] data_4bytes = Text.Encoding.ASCII.GetBytes("aaaa");
+ byte[] data_4bytes = "aaaa"u8.ToArray();
ICryptoTransform transform = new FromBase64Transform();
AssertExtensions.Throws<ArgumentNullException>("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0));
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();
}
string password = "password";
int iterations = 16777216;
byte[] expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984".HexToByteArray();
- byte[] salt = Encoding.UTF8.GetBytes("salt");
+ ReadOnlySpan<byte> salt = "salt"u8;
byte[] actual = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA1, expected.Length);
Assert.Equal(expected, actual);
}
[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;
// 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);
}
Assert.Equal(OperationStatus.Done, encoder.EncodeUtf8(aggregateInputBytesSoFar.ToArray(), destination, out bytesConsumed, out bytesWritten, isFinalBlock: true));
Assert.Equal(aggregateInputBytesSoFar.Count, bytesConsumed);
Assert.Equal(expectedOutputBytesSoFar.Count + "[FFFD]".Length, bytesWritten);
- Assert.Equal(expectedOutputBytesSoFar.Concat(Encoding.UTF8.GetBytes("[FFFD]")).ToArray(), new Span<byte>(destination, 0, expectedOutputBytesSoFar.Count + "[FFFD]".Length).ToArray());
+ Assert.Equal(expectedOutputBytesSoFar.Concat("[FFFD]"u8.ToArray()), new Span<byte>(destination, 0, expectedOutputBytesSoFar.Count + "[FFFD]".Length).ToArray());
}
// Consume the remainder of this entry and make sure it escaped properly (if needed).
{
// 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
{
// 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
{
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)
{
await Assert.ThrowsAsync<NotSupportedException>(async () => await StreamingSerializer.DeserializeWrapper<T>(stream, options));
}
- using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("{}")))
+ using (MemoryStream stream = new MemoryStream("{}"u8.ToArray()))
{
JsonSerializerOptions options = new JsonSerializerOptions
{
};
const string CharLabel = "char";
- byte[] byteUtf8 = Encoding.UTF8.GetBytes("byte");
using var writer = new Utf8JsonWriter(buffer, options);
if (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);
{
Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(CharLabel));
Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(CharLabel.AsSpan()));
- Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(byteUtf8));
+ Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName("byte"u8));
Assert.Throws<InvalidOperationException>(() => writer.WritePropertyName(JsonEncodedText.Encode(CharLabel)));
writer.Flush();
Assert.Null(JsonSerializer.Deserialize<JsonNode>("null"));
Assert.Null(JsonNode.Parse("null"));
- using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null")))
+ using (MemoryStream stream = new MemoryStream("null"u8.ToArray()))
{
Assert.Null(JsonNode.Parse(stream));
}
[Fact]
public static void ZeroMaxDepthDefaultsTo64()
{
- byte[] dataUtf8 = Encoding.UTF8.GetBytes("{}");
+ byte[] dataUtf8 = "{}"u8.ToArray();
ReadOnlyMemory<byte> dataMemory = dataUtf8;
var firstSegment = new BufferSegment<byte>(dataMemory.Slice(0, 1));
[Fact]
public static void MaxDepthIsHonored()
{
- byte[] dataUtf8 = Encoding.UTF8.GetBytes("{}");
+ byte[] dataUtf8 = "{}"u8.ToArray();
ReadOnlyMemory<byte> dataMemory = dataUtf8;
var firstSegment = new BufferSegment<byte>(dataMemory.Slice(0, 1));
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()
var options = new JsonSerializerOptions();
options.ReadCommentHandling = JsonCommentHandling.Skip;
- int[][] i = JsonSerializer.Deserialize<int[][]>(Encoding.UTF8.GetBytes("[[1,2] // Inline [\n,[3, /* Multi\n]] Line*/4]]"), options);
+ int[][] i = JsonSerializer.Deserialize<int[][]>("[[1,2] // Inline [\n,[3, /* Multi\n]] Line*/4]]"u8, options);
Assert.Equal(1, i[0][0]);
Assert.Equal(2, i[0][1]);
Assert.Equal(3, i[1][0]);
[Fact]
public static async Task ParseNullStringShouldThrowJsonExceptionAsync()
{
- using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("null")))
+ using (var stream = new MemoryStream("null"u8.ToArray()))
{
await Assert.ThrowsAsync<JsonException>(async () => await JsonSerializer.DeserializeAsync<SimpleStruct>(stream));
[Fact]
public static void ReaderOptionsWinMaxDepth()
{
- byte[] utf8 = Encoding.UTF8.GetBytes("[[]]");
+ byte[] utf8 = "[[]]"u8.ToArray();
var readerOptions = new JsonReaderOptions
{
[Fact]
public static void ReaderOptionsWinTrailingCommas()
{
- byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, 3,]");
+ byte[] utf8 = "[1, 2, 3,]"u8.ToArray();
var serializerOptions = new JsonSerializerOptions
{
[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
{
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);
[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();
[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();
[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();
[InlineData(false)]
public static void ReadObjectMultiSegment(bool isFinalBlock)
{
- byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, {\"Foo\":[1, 2, 3]}]");
+ byte[] utf8 = "[1, 2, {\"Foo\":[1, 2, 3]}]"u8.ToArray();
ReadOnlySequence<byte> sequence = JsonTestHelper.CreateSegments(utf8);
var reader = new Utf8JsonReader(sequence, isFinalBlock, state: default);
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);
}
{
- byte[] utf8 = Encoding.UTF8.GetBytes("{");
+ byte[] utf8 = "{"u8.ToArray();
var reader = new Utf8JsonReader(utf8, isFinalBlock, state: default);
reader.Read();
[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();
[Fact]
public static void ReadPartial()
{
- byte[] utf8 = Encoding.UTF8.GetBytes("[1, 2, 3]");
+ byte[] utf8 = "[1, 2, 3]"u8.ToArray();
var reader = new Utf8JsonReader(utf8, isFinalBlock: true, state: default);
reader.Read();
int[] array = JsonSerializer.Deserialize<int[]>(ref reader);
[Fact]
public static void ParseUntyped()
{
- byte[] bytes = Encoding.UTF8.GetBytes("42");
- object obj = JsonSerializer.Deserialize(bytes, typeof(object));
+ object obj = JsonSerializer.Deserialize("42"u8, typeof(object));
Assert.IsType<JsonElement>(obj);
JsonElement element = (JsonElement)obj;
Assert.Equal(JsonValueKind.Number, element.ValueKind);
[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
{
[Fact]
public async Task ReadReferenceTypeCollectionPassingNullValueAsync()
{
- using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null")))
+ using (MemoryStream stream = new MemoryStream("null"u8.ToArray()))
{
IList<object> referenceTypeCollection = await Serializer.DeserializeWrapper<IList<object>>(stream);
Assert.Null(referenceTypeCollection);
[Fact]
public async Task ReadValueTypeCollectionPassingNullValueAsync()
{
- using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null")))
+ using (MemoryStream stream = new MemoryStream("null"u8.ToArray()))
{
IList<int> valueTypeCollection = await Serializer.DeserializeWrapper<IList<int>>(stream);
Assert.Null(valueTypeCollection);
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();
{
Span<byte> json = JsonSerializer.SerializeToUtf8Bytes(1);
- Assert.Equal(Encoding.UTF8.GetBytes("1"), json.ToArray());
+ Assert.Equal("1"u8.ToArray(), json.ToArray());
}
{
[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);
[Fact]
public static void InitialStateMultiSegment()
{
- byte[] utf8 = Encoding.UTF8.GetBytes("1");
+ byte[] utf8 = "1"u8.ToArray();
ReadOnlySequence<byte> sequence = JsonTestHelper.GetSequence(utf8, 1);
var json = new Utf8JsonReader(sequence, isFinalBlock: true, state: default);
[Fact]
public static void InitialStateSimpleCtorMultiSegment()
{
- byte[] utf8 = Encoding.UTF8.GetBytes("1");
+ byte[] utf8 = "1"u8.ToArray();
ReadOnlySequence<byte> sequence = JsonTestHelper.GetSequence(utf8, 1);
var json = new Utf8JsonReader(sequence);
[Fact]
public static void StateRecoveryMultiSegment()
{
- byte[] utf8 = Encoding.UTF8.GetBytes("[1]");
+ byte[] utf8 = "[1]"u8.ToArray();
ReadOnlySequence<byte> sequence = JsonTestHelper.GetSequence(utf8, 1);
var json = new Utf8JsonReader(sequence, isFinalBlock: false, state: default);
[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;
}
[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
{
if (json.TokenType == JsonTokenType.String)
{
- if (json.ValueTextEquals(lookup) ||
+ if (json.ValueTextEquals("Hello, \"Ahson\""u8) ||
json.ValueTextEquals("Hello, \"Ahson\"".AsSpan()) ||
json.ValueTextEquals("Hello, \"Ahson\""))
{
[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);
[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);
[Fact]
public static void StateRecovery()
{
- byte[] utf8 = Encoding.UTF8.GetBytes("[1]");
+ ReadOnlySpan<byte> utf8 = "[1]"u8;
var json = new Utf8JsonReader(utf8, isFinalBlock: false, state: default);
Assert.Equal(0, json.BytesConsumed);
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
Action<byte[]> validate;
validate = (data) => Assert.Equal(123456789, JsonSerializer.Deserialize<long>(data));
- yield return new object[] { Encoding.UTF8.GetBytes("123456789"), validate };
+ yield return new object[] { "123456789"u8.ToArray(), validate };
validate = (data) => Assert.Equal(1234.56789, JsonSerializer.Deserialize<double>(data));
- yield return new object[] { Encoding.UTF8.GetBytes("1234.56789"), validate };
+ yield return new object[] { "1234.56789"u8.ToArray(), validate };
validate = (data) => Assert.Equal(1234.56789, JsonSerializer.Deserialize<double>(data));
- yield return new object[] { Encoding.UTF8.GetBytes(" 1234.56789 "), validate };
+ yield return new object[] { " 1234.56789 "u8.ToArray(), validate };
validate = (data) => Assert.Equal(@"Hello", JsonSerializer.Deserialize<string>(data));
yield return new object[] { Encoding.UTF8.GetBytes(@"""Hello"""), validate };
};
yield return new object[] { json, validate };
- json = Encoding.UTF8.GetBytes("[ 1, 1,1,1,1 ] ");
+ json = "[ 1, 1,1,1,1 ] "u8.ToArray();
validate = (data) =>
{
foreach (int val in JsonSerializer.Deserialize<int[]>(data))
// 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'
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);
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++)
jsonUtf8.WritePropertyName("test name");
jsonUtf8.WritePropertyName(JsonEncodedText.Encode("test name"));
jsonUtf8.WritePropertyName("test name".AsSpan());
- jsonUtf8.WritePropertyName(Encoding.UTF8.GetBytes("test name"));
+ jsonUtf8.WritePropertyName("test name"u8.ToArray());
}
else
{
Assert.Throws<InvalidOperationException>(() => jsonUtf8.WritePropertyName("test name"));
Assert.Throws<InvalidOperationException>(() => jsonUtf8.WritePropertyName(JsonEncodedText.Encode("test name")));
Assert.Throws<InvalidOperationException>(() => jsonUtf8.WritePropertyName("test name".AsSpan()));
- Assert.Throws<InvalidOperationException>(() => jsonUtf8.WritePropertyName(Encoding.UTF8.GetBytes("test name")));
+ Assert.Throws<InvalidOperationException>(() => jsonUtf8.WritePropertyName("test name"u8.ToArray()));
}
}
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");
jsonUtf8.WriteStartObject();
for (int i = 0; i < 999; i++)
{
- jsonUtf8.WriteStartObject(Encoding.UTF8.GetBytes("name"));
+ jsonUtf8.WriteStartObject("name"u8);
}
- Assert.Throws<InvalidOperationException>(() => jsonUtf8.WriteStartArray(Encoding.UTF8.GetBytes("name")));
+ Assert.Throws<InvalidOperationException>(() => jsonUtf8.WriteStartArray("name"u8));
}
using (var jsonUtf8 = new Utf8JsonWriter(output, options))
using (var jsonUtf8 = new Utf8JsonWriter(output, options))
{
jsonUtf8.WriteStartObject();
- Assert.Throws<ArgumentException>(() => jsonUtf8.WriteBase64String(Encoding.UTF8.GetBytes("foo"), value));
+ Assert.Throws<ArgumentException>(() => jsonUtf8.WriteBase64String("foo"u8, value));
}
using (var jsonUtf8 = new Utf8JsonWriter(output, options))
using (var jsonUtf8 = new Utf8JsonWriter(output, options))
{
jsonUtf8.WriteStartObject();
- jsonUtf8.WriteBase64String(Encoding.UTF8.GetBytes("foo"), value);
+ jsonUtf8.WriteBase64String("foo"u8, value);
jsonUtf8.WriteEndObject();
}
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);
JsonEncodedText encodedPropertyName = JsonEncodedText.Encode(propertyName);
JsonEncodedText encodedValue = JsonEncodedText.Encode(value);
- byte[] utf8PropertyName = Encoding.UTF8.GetBytes("message");
- byte[] utf8Value = Encoding.UTF8.GetBytes("Hello, World!");
+ ReadOnlySpan<byte> utf8PropertyName = "message"u8;
+ ReadOnlySpan<byte> utf8Value = "Hello, World!"u8;
var options = new JsonWriterOptions { Indented = formatted, SkipValidation = skipValidation };
jsonUtf8.WriteStartArray("property name".AsSpan());
break;
case 2:
- jsonUtf8.WriteStartArray(Encoding.UTF8.GetBytes("property name"));
+ jsonUtf8.WriteStartArray("property name"u8);
break;
}
jsonUtf8.WriteStartObject("property name".AsSpan());
break;
case 2:
- jsonUtf8.WriteStartObject(Encoding.UTF8.GetBytes("property name"));
+ jsonUtf8.WriteStartObject("property name"u8);
break;
}
jsonUtf8.WriteStartArray("message".AsSpan());
break;
case 2:
- jsonUtf8.WriteStartArray(Encoding.UTF8.GetBytes("message"));
+ jsonUtf8.WriteStartArray("message"u8);
break;
}
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");
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");
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");
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),
[Fact]
public static void WriteStringValue_ReadOnlySpanBytesProperty_NullString()
{
- byte[] propertyName = Encoding.UTF8.GetBytes("propUtf8");
+ byte[] propertyName = "propUtf8"u8.ToArray();
WriteNullValue_InObject(
"\"propUtf8\":\"\"",