Skip to content

Instantly share code, notes, and snippets.

@dhilip89
Last active February 12, 2020 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhilip89/dadcf0527d5ec62ec19343e37c32a9d2 to your computer and use it in GitHub Desktop.
Save dhilip89/dadcf0527d5ec62ec19343e37c32a9d2 to your computer and use it in GitHub Desktop.
Fun Parser
using System;
using System.Collections.Generic;
namespace FunParser
{
class ParseResult
{
public string Method { get; set; }
public string Path { get; set; }
public IDictionary<string, string> Queries { get; set; } = new Dictionary<string, string>();
}
class Program
{
static void Main(string[] args)
{
// 'METHOD="AES-128",URI="path?key1=value1&key2=value2"'
ParseResult parseResult = Parse("METHOD=\"AES-128\",URI=\"path?key1=value1&key2=value2\"");
Console.WriteLine($"Method: {parseResult.Method}");
foreach ((string key, string value) in parseResult.Queries)
{
Console.WriteLine($"Key: {key}, Value: {value}");
}
}
public static ParseResult Parse(ReadOnlySpan<char> input)
{
Span<int> quotePositions = stackalloc int[4];
for (int i = 0, j = 0; i < input.Length; i++)
{
if (input[i] == '"')
quotePositions[j++] = i;
}
ParseResult result = new ParseResult
{
Method = input[(quotePositions[0] + 1)..quotePositions[1]].ToString(),
};
ReadOnlySpan<char> uriString = input[(quotePositions[2] + 1)..(quotePositions[3])];
int questionMarkPosition = 0;
for (int i = 0; i < uriString.Length; i++)
{
if (uriString[i] == '?')
questionMarkPosition = i;
}
ReadOnlySpan<char> queryString = uriString[(questionMarkPosition + 1)..^0];
int queryStringLength = queryString.Length;
string key = null;
string value = null;
for (int i = 0, j = 0; i < queryStringLength; i++)
{
char c = queryString[i];
if (c == '=')
{
key = queryString[j..i].ToString();
j = i;
}
if (c == '&')
{
value = queryString[(j + 1)..i].ToString();
j = i + 1;
}
if (i == queryStringLength - 1)
{
value = queryString[(j + 1)..(i + 1)].ToString();
}
if (key != null && value != null)
{
result.Queries.Add(key, value);
key = null;
value = null;
}
}
return result;
}
}
}
@dhilip89
Copy link
Author

Console Output:

Method: AES-128
Key: key1, Value: value1
Key: key2, Value: value2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment