Skip to content

Commit

Permalink
avoid duplicate UTF8Preamble (#542)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonCropp authored Jun 8, 2022
1 parent 1c54a14 commit 791c0b8
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<Project>
<PropertyGroup>
<NoWarn>CS1591;CS0649;xUnit1026;xUnit1013;msb3277;CS0436</NoWarn>
<Version>17.1.2</Version>
<Version>17.1.3</Version>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>10</LangVersion>
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
Expand Down
1 change: 1 addition & 0 deletions src/Verify.Tests/Tests.StringWithUtf8Bom.verified.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a
10 changes: 10 additions & 0 deletions src/Verify.Tests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,16 @@ public Task ShouldThrowForExtensionOnSerialization()
return Verifier.ThrowsTask(() => Verify(element, settings))
.IgnoreStackTrace();
}
#if NET6_0
[Fact]
public async Task StringWithUtf8Bom()
{
var utf8 = Encoding.UTF8;
var preamble = utf8.GetString(utf8.GetPreamble());
await Verify($"{preamble}a").AutoVerify();
await Verify("a").DisableRequireUniquePrefix();
}
#endif

[Fact]
public Task StringExtension()
Expand Down
16 changes: 14 additions & 2 deletions src/Verify/IoHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
{
static readonly UTF8Encoding Utf8 = new(true, true);

static readonly string UTF8Preamble = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());

public static void DeleteIfEmpty(string path)
{
var info = new FileInfo(path);
Expand Down Expand Up @@ -43,9 +45,19 @@ static async Task<string> ReadStringWithFixedLines(this Stream stream)
return builder.ToString();
}

static string TrimPreamble(string text)
{
if (text.StartsWith(UTF8Preamble))
{
return text.Substring(UTF8Preamble.Length);
}

return text;
}

#if NETSTANDARD2_1 || NET5_0_OR_GREATER
public static Task WriteText(string path, string text) =>
File.WriteAllTextAsync(path, text, Utf8);
File.WriteAllTextAsync(path, TrimPreamble(text), Utf8);

public static async Task<string> ReadStringWithFixedLines(string path)
{
Expand All @@ -68,7 +80,7 @@ public static async Task WriteStream(string path, Stream stream)
#else
public static async Task WriteText(string path, string text)
{
var encodedText = Utf8.GetBytes(text);
var encodedText = Utf8.GetBytes(TrimPreamble(text));

using var stream = OpenWrite(path);
await stream.WriteAsync(encodedText, 0, encodedText.Length);
Expand Down

0 comments on commit 791c0b8

Please sign in to comment.