/
RedisDataInfoExtensions.cs
71 lines (60 loc) · 1.99 KB
/
RedisDataInfoExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ServiceStack.Redis;
public static class RedisDataInfoExtensions
{
public static string ToJsonInfo(this RedisText redisText)
{
var source = redisText.GetResult();
return Parse(source);
}
private static string Parse(string source)
{
var result = new Dictionary<string, Dictionary<string, string>>();
var section = new Dictionary<string, string>();
var rows = SplitRows(source);
foreach (var row in rows)
{
if (row.IndexOf("#", StringComparison.Ordinal) == 0)
{
var name = ParseSection(row);
section = new Dictionary<string, string>();
result.Add(name, section);
}
else
{
var pair = ParseKeyValue(row);
if (pair.HasValue)
{
section.Add(pair.Value.Key, pair.Value.Value);
}
}
}
return JsonSerializer.SerializeToString(result);
}
private static string[] CRLF = { "\r\n" };
private static IEnumerable<string> SplitRows(string source)
{
return source.Split(CRLF, StringSplitOptions.None).Where(n => !string.IsNullOrWhiteSpace(n));
}
private static string ParseSection(string source)
{
return (source.IndexOf("#", StringComparison.Ordinal) == 0)
? source.Trim('#').Trim()
: string.Empty;
}
private static KeyValuePair<string, string>? ParseKeyValue(string source)
{
KeyValuePair<string, string>? result = null;
var divider = source.IndexOf(":", StringComparison.Ordinal);
if (divider > 0)
{
var name = source.Substring(0, divider);
var value = source.Substring(divider + 1);
result = new KeyValuePair<string, string>(name.Trim(), value.Trim());
}
return result;
}
}