summaryrefslogtreecommitdiffstats
path: root/src/Cepis/Csv.cs
blob: ca11558c5c61d92f964b8027b57e852c876e7a9a (plain)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
using System.Text;

namespace Cepis;

/// <summary>
/// An RFC 4180 reader for the batch endpoint.
/// </summary>
/// <remarks>
/// Values may contain commas, quotes and newlines, so they arrive
/// double-quoted with <c>""</c> escaping; splitting on commas would corrupt
/// exactly the addresses that need care. A leading byte order mark is dropped,
/// and CR, LF and CRLF all end a record. The BCL ships no CSV reader, and the
/// shape this endpoint returns is small enough not to justify a dependency.
/// </remarks>
internal static class Csv
{
    /// <summary>
    /// Parse a CSV document whose first record is the header.
    /// </summary>
    /// <remarks>
    /// Each record becomes a dictionary from column name to value. A record
    /// with fewer fields than the header has the missing ones filled with
    /// <c>""</c>; extra fields are dropped.
    /// </remarks>
    /// <param name="text">the document</param>
    /// <returns>one dictionary per data record, in order</returns>
    internal static List<Dictionary<string, string>> Parse(string text)
    {
        var records = Split(text);
        var rows = new List<Dictionary<string, string>>();
        if (records.Count == 0)
        {
            return rows;
        }

        var header = records[0];
        for (var r = 1; r < records.Count; r++)
        {
            var record = records[r];
            var row = new Dictionary<string, string>(header.Count, StringComparer.Ordinal);
            for (var i = 0; i < header.Count; i++)
            {
                row[header[i]] = i < record.Count ? record[i] : "";
            }

            rows.Add(row);
        }

        return rows;
    }

    private static List<List<string>> Split(string text)
    {
        var records = new List<List<string>>();
        var record = new List<string>();
        var field = new StringBuilder();
        var quoted = false;
        var pending = false;

        var i = text.Length > 0 && text[0] == '\uFEFF' ? 1 : 0;
        for (; i < text.Length; i++)
        {
            var c = text[i];
            if (quoted)
            {
                if (c != '"')
                {
                    field.Append(c);
                }
                else if (i + 1 < text.Length && text[i + 1] == '"')
                {
                    field.Append('"');
                    i++;
                }
                else
                {
                    quoted = false;
                }

                continue;
            }

            switch (c)
            {
                case '"':
                    quoted = true;
                    pending = true;
                    break;
                case ',':
                    record.Add(field.ToString());
                    field.Clear();
                    pending = true;
                    break;
                case '\r':
                case '\n':
                    if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n')
                    {
                        i++;
                    }

                    record.Add(field.ToString());
                    field.Clear();
                    records.Add(record);
                    record = [];
                    pending = false;
                    break;
                default:
                    field.Append(c);
                    pending = true;
                    break;
            }
        }

        if (pending || field.Length > 0)
        {
            record.Add(field.ToString());
            records.Add(record);
        }

        return records;
    }
}