Skip to content

Instantly share code, notes, and snippets.

@LordJZ
Created May 23, 2018 16:46
Show Gist options
  • Save LordJZ/d35c3641f54b6ea4c6183c2feb61cbe0 to your computer and use it in GitHub Desktop.
Save LordJZ/d35c3641f54b6ea4c6183c2feb61cbe0 to your computer and use it in GitHub Desktop.
public class DdwrtParser
{
public JObject Read(ReadOnlySpan<char> str)
{
JObject result = new JObject();
while (str.Length > 0)
{
if (str[0] != '{')
throw new FormatException();
str = str.Slice(1);
string key = Until(ref str, "::").ToString();
ReadOnlySpan<char> value = Until(ref str, "}");
value = value.TrimStart().TrimStart(',');
if (value.IsEmpty)
{
result.Add(key, JValue.CreateNull());
continue;
}
if (value[value.Length - 1] == ';')
{
JObject item = new JObject();
foreach (ReadOnlySpan<char> pair in value.Trim(';').Split(';'))
{
ReadOnlySpan<char> itemValue = pair;
ReadOnlySpan<char> itemKey = Until(ref itemValue, "=");
item.Add(itemKey.ToString(), JValue.CreateString(itemValue.ToString()));
}
result.Add(key, item);
continue;
}
if (value.StartsWith("'".AsSpan(), StringComparison.Ordinal))
{
JArray item = new JArray();
foreach (ReadOnlySpan<char> arrayItem in value.Split(','))
item.Add(JValue.CreateString(arrayItem.Trim('\'').ToString()));
result.Add(key, item);
continue;
}
result.Add(key, JValue.CreateString(value.ToString()));
}
return result;
}
static ReadOnlySpan<char> Until(ref ReadOnlySpan<char> str, string lookup)
{
int index = str.IndexOf(lookup.AsSpan());
if (index < 0)
throw new FormatException();
ReadOnlySpan<char> result = str.Slice(0, index);
str = str.Slice(index + lookup.Length);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment