2
using System.Collections.Generic;
8
internal class MessageFormat
10
public static string Format (string message, params object[] args)
12
StringBuilder sb = new StringBuilder ();
14
bool inPlaceholder = false;
16
List<string> placeholderArgs = new List<string> (3);
18
for (int n=0; n<message.Length; n++) {
23
else if (n > 0 && message [n-1] == '\'') {
31
else if (c == '{' && !inQuote) {
36
else if (c == '}' && !inQuote && inPlaceholder) {
37
inPlaceholder = false;
38
placeholderArgs.Add (message.Substring (argStartPos, n - argStartPos));
39
AddFormatted (sb, placeholderArgs, args);
40
placeholderArgs.Clear ();
43
else if (c == ',' && inPlaceholder) {
44
placeholderArgs.Add (message.Substring (argStartPos, n - argStartPos));
48
else if (inPlaceholder)
53
return sb.ToString ();
56
static void AddFormatted (StringBuilder sb, List<string> placeholderArgs, object[] args)
58
if (placeholderArgs.Count > 3)
59
throw new ArgumentException ("Invalid format pattern: {" + string.Join (",", placeholderArgs.ToArray()) + "}");
62
if (!int.TryParse (placeholderArgs[0], out narg))
63
throw new ArgumentException ("Invalid argument index: " + placeholderArgs[0]);
64
if (narg < 0 || narg >= args.Length)
65
throw new ArgumentException ("Invalid argument index: " + narg);
67
object arg = args [narg];
70
// TODO: handle format types and styles