Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Console.Write on iOS #56713

Merged
merged 33 commits into from
Sep 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
71b3888
Fix Console.Write on iOS
MaximLipnin Aug 2, 2021
8f6f7bc
Move the helper method to iOS-specific location
MaximLipnin Aug 2, 2021
a97f0d5
Add a test
MaximLipnin Aug 2, 2021
90bf33c
Remove unused using
MaximLipnin Aug 2, 2021
e6806e4
Apply Ralf's suggestion
MaximLipnin Aug 2, 2021
2bdb6e7
Move Interop.Sys.Log to a local function
MaximLipnin Aug 2, 2021
612dc1c
Merge branch 'main' into fix_console_write_on_ios
MaximLipnin Aug 3, 2021
6f8542b
Merge branch 'main' into fix_console_write_on_ios
MaximLipnin Aug 9, 2021
47d8f01
Move the caching logic over to StreamWriter
MaximLipnin Aug 10, 2021
4f0653a
Merge branch 'main' into fix_console_write_on_ios
MaximLipnin Aug 10, 2021
14545a8
Merge branch 'main' into fix_console_write_on_ios
MaximLipnin Aug 11, 2021
725e64c
feedback
MaximLipnin Aug 11, 2021
5b8499c
Remove unused usings
MaximLipnin Aug 12, 2021
61bb68b
Derive from StreamWriter
MaximLipnin Aug 12, 2021
68e10e7
Merge branch 'main' into fix_console_write_on_ios
MaximLipnin Aug 12, 2021
ac45868
Feedback
MaximLipnin Aug 12, 2021
2e57d54
Merge branch 'main' into fix_console_write_on_ios
MaximLipnin Aug 16, 2021
c8aa30f
Try a solution not changing public API surface and using NSLogStream …
MaximLipnin Aug 16, 2021
b76ddfe
Some feedback
MaximLipnin Aug 17, 2021
b999fff
Use ArrayPool
MaximLipnin Aug 17, 2021
49f5c41
Not rely on the length of the rented array
MaximLipnin Aug 17, 2021
aaa1f35
Merge branch 'main' into fix_console_write_on_ios
MaximLipnin Aug 18, 2021
90da2a0
Address the feedback
MaximLipnin Aug 27, 2021
88685c7
Merge branch 'main' into fix_console_write_on_ios
MaximLipnin Aug 27, 2021
976954b
not use _ prefix for local variable
MaximLipnin Aug 27, 2021
245edb3
Address the feedback
MaximLipnin Aug 27, 2021
a234df5
Merge branch 'fix_console_write_on_ios' of https://github.com/maximli…
MaximLipnin Aug 27, 2021
34d215f
Fix an error
MaximLipnin Aug 30, 2021
1eb7528
Merge branch 'main' into fix_console_write_on_ios
MaximLipnin Aug 30, 2021
a2e118e
Print a span rather than a string
MaximLipnin Aug 30, 2021
732a62f
Slice the char span to the exact used length
MaximLipnin Sep 1, 2021
9375848
Address Stephen's feedback
MaximLipnin Sep 1, 2021
7504d30
Remove a redundant using
MaximLipnin Sep 1, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 65 additions & 5 deletions src/libraries/System.Console/src/System/ConsolePal.iOS.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,82 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace System
{
internal sealed class NSLogStream : ConsoleStream
{
public NSLogStream() : base(FileAccess.Write) {}
private readonly StringBuilder _buffer = new StringBuilder();
private readonly Encoding _encoding;
private readonly Decoder _decoder;

public NSLogStream(Encoding encoding) : base(FileAccess.Write)
{
_encoding = encoding;
_decoder = _encoding.GetDecoder();
}

public override int Read(Span<byte> buffer) => throw Error.GetReadNotSupported();

public override unsafe void Write(ReadOnlySpan<byte> buffer)
{
fixed (byte* ptr = buffer)
int maxCharCount = _encoding.GetMaxCharCount(buffer.Length);
char[]? pooledBuffer = null;
Span<char> charSpan = maxCharCount <= 512 ? stackalloc char[512] : (pooledBuffer = ArrayPool<char>.Shared.Rent(maxCharCount));
try
{
int count = _decoder.GetChars(buffer, charSpan, false);
if (count > 0)
{
WriteOrCache(_buffer, charSpan.Slice(0, count));
}
}
finally
{
if (pooledBuffer != null)
{
ArrayPool<char>.Shared.Return(pooledBuffer);
}
}
}

private static void WriteOrCache(StringBuilder cache, Span<char> charBuffer)
{
int lastNewLine = charBuffer.LastIndexOf('\n');
if (lastNewLine != -1)
{
Span<char> lineSpan = charBuffer.Slice(0, lastNewLine);
if (cache.Length > 0)
{
Print(cache.Append(lineSpan).ToString());
cache.Clear();
}
else
{
Print(lineSpan);
}

if (lastNewLine + 1 < charBuffer.Length)
{
cache.Append(charBuffer.Slice(lastNewLine + 1));
}

return;
}

// no newlines found, add the entire buffer to the cache
cache.Append(charBuffer);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

General question about this change... it seems like this change means that if I have code that does:

while (true)
{
    Console.Write(".");
    await Task.Delay(1000);
}

to print out a period to the console once a second, for example as you might find with a progress indicator in a console app, that the data will never be emitted to the console, because newlines are never found. Am I understanding correctly? Is that not an issue, e.g. because Console is only used for diagnostic messages in an iOS app?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is a thing I wasn't able to beat. I mentioned it a bit earlier #56713 (comment). The current Xamarin implementation has the same drawback so it won't surprise the existing customers.


static unsafe void Print(ReadOnlySpan<char> line)
{
Interop.Sys.Log(ptr, buffer.Length);
fixed (char* ptr = line)
{
Interop.Sys.Log((byte*)ptr, line.Length * 2);
}
}
}
}
Expand All @@ -28,9 +88,9 @@ internal static void EnsureConsoleInitialized()

public static Stream OpenStandardInput() => throw new PlatformNotSupportedException();

public static Stream OpenStandardOutput() => new NSLogStream();
public static Stream OpenStandardOutput() => new NSLogStream(OutputEncoding);

public static Stream OpenStandardError() => new NSLogStream();
public static Stream OpenStandardError() => new NSLogStream(OutputEncoding);

public static Encoding InputEncoding => throw new PlatformNotSupportedException();

Expand Down
19 changes: 19 additions & 0 deletions src/libraries/System.Console/tests/ReadAndWrite.cs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,25 @@ public static async Task OutWriteAndWriteLineOverloads()
}
}

[Fact]
[PlatformSpecific(TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS)]
public void TestConsoleWrite()
MaximLipnin marked this conversation as resolved.
Show resolved Hide resolved
{
Stream s = new MemoryStream();
TextWriter w = new StreamWriter(s);
((StreamWriter)w).AutoFlush = true;
TextReader r = new StreamReader(s);
Console.SetOut(w);

Console.Write("A");
Console.Write("B");
Console.Write("C");

s.Position = 0;
string line = r.ReadToEnd();
Assert.Equal("ABC", line);
}

private static unsafe void ValidateConsoleEncoding(Encoding encoding)
{
Assert.NotNull(encoding);
Expand Down