private static unsafe void WriteStdoutAnsiString(string value)
{
if (string.IsNullOrEmpty(value))
return;
// Except for extremely rare cases, ANSI escape strings should be very short.
const int StackAllocThreshold = 256;
if (value.Length <= StackAllocThreshold)
{
int dataLen = Encoding.UTF8.GetMaxByteCount(value.Length);
byte* data = stackalloc byte[dataLen];
fixed (char* chars = value)
{
int bytesToWrite = Encoding.UTF8.GetBytes(chars, value.Length, data, dataLen);
Debug.Assert(bytesToWrite <= dataLen);
lock (Console.Out) // synchronize with other writers
{
Write(Interop.Sys.FileDescriptors.STDOUT_FILENO, data, bytesToWrite);
}
}
}
else
{
byte[] data = Encoding.UTF8.GetBytes(value);
lock (Console.Out) // synchronize with other writers
{
Write(Interop.Sys.FileDescriptors.STDOUT_FILENO, data, 0, data.Length);
}
}
}