-
Notifications
You must be signed in to change notification settings - Fork 21
/
CsvColumnSorter_Span.cs
83 lines (70 loc) · 1.83 KB
/
CsvColumnSorter_Span.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
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections.Generic;
namespace JOS.Files.Implementations.Sorting;
public class CsvColumnSorter_Span : IComparer<string>
{
private readonly int _column;
private readonly char _separator;
public CsvColumnSorter_Span(int column, char separator = ',')
{
_column = column;
_separator = separator;
}
public int Compare(string? x, string? y)
{
if (x == null && y != null)
{
return -1;
}
if (y == null && x != null)
{
return 1;
}
if (x == null || y == null)
{
return 0;
}
var xColumn = GetColumnValue(x);
var yColumn = GetColumnValue(y);
return xColumn.CompareTo(yColumn, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Really naive implementation, just used as a POC.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private ReadOnlySpan<char> GetColumnValue(string value)
{
var span = value.AsSpan();
var columnCounter = 1;
var columnStartIndex = 0;
for (var i = 0; i < span.Length; i++)
{
if (span[i].Equals(_separator))
{
columnCounter++;
continue;
}
if (columnCounter != _column)
{
continue;
}
columnStartIndex = i;
break;
}
var columnLength = 0;
var slice = span[columnStartIndex..];
for (var i = 0; i < slice.Length; i++)
{
if (slice[i] != _separator)
{
columnLength++;
}
else
{
break;
}
}
return span.Slice(columnStartIndex, columnLength);
}
}