private static unsafe string FormatPrintF(string format, object arg)
{
Debug.Assert(arg is string || arg is Int32);
// Determine how much space is needed to store the formatted string.
string stringArg = arg as string;
int neededLength = stringArg != null ?
Interop.Sys.SNPrintF(null, 0, format, stringArg) :
Interop.Sys.SNPrintF(null, 0, format, (int)arg);
if (neededLength == 0)
{
return string.Empty;
}
if (neededLength < 0)
{
throw new InvalidOperationException(SR.InvalidOperation_PrintF);
}
// Allocate the needed space, format into it, and return the data as a string.
byte[] bytes = new byte[neededLength + 1]; // extra byte for the null terminator
fixed (byte* ptr = bytes)
{
int length = stringArg != null ?
Interop.Sys.SNPrintF(ptr, bytes.Length, format, stringArg) :
Interop.Sys.SNPrintF(ptr, bytes.Length, format, (int)arg);
if (length != neededLength)
{
throw new InvalidOperationException(SR.InvalidOperation_PrintF);
}
}
return Encoding.ASCII.GetString(bytes, 0, neededLength);
}