Last active
February 12, 2020 10:14
-
-
Save dhilip89/dadcf0527d5ec62ec19343e37c32a9d2 to your computer and use it in GitHub Desktop.
Fun Parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Console Output: