wasSharp – Blame information for rev 5

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 zed 1 ///////////////////////////////////////////////////////////////////////////
2 // Copyright (C) Wizardry and Steamworks 2013 - License: GNU GPLv3 //
3 // Please see: http://www.gnu.org/licenses/gpl.html for legal details, //
4 // rights of fair usage, the disclaimer and warranty conditions. //
5 ///////////////////////////////////////////////////////////////////////////
6  
7 using System.Collections.Generic;
8 using System.Linq;
9 using System.Text;
10 using System.Threading.Tasks;
11  
12 namespace wasSharp
13 {
14 public class CSV
15 {
16 ///////////////////////////////////////////////////////////////////////////
17 // Copyright (C) 2015 Wizardry and Steamworks - License: GNU GPLv3 //
18 ///////////////////////////////////////////////////////////////////////////
19 /// <summary>
20 /// Converts a list of string to a comma-separated values string.
21 /// </summary>
22 /// <param name="l">a list of strings</param>
23 /// <returns>a commma-separated list of values</returns>
24 /// <remarks>compliant with RFC 4180</remarks>
5 eva 25 public static string FromEnumerable(IEnumerable<string> l)
1 zed 26 {
27 string[] csv = l.Select(o => o).ToArray();
4 zed 28 char[] escapeCharacters = {'"', ' ', ',', '\r', '\n'};
1 zed 29 Parallel.ForEach(csv.Select((v, i) => new {i, v}), o =>
30 {
31 string cell = o.v.Replace("\"", "\"\"");
32  
4 zed 33 switch (cell.IndexOfAny(escapeCharacters))
1 zed 34 {
35 case -1:
36 csv[o.i] = cell;
37 break;
38 default:
39 csv[o.i] = "\"" + cell + "\"";
40 break;
41 }
42 });
43 return string.Join(",", csv);
44 }
45  
46 ///////////////////////////////////////////////////////////////////////////
47 // Copyright (C) 2015 Wizardry and Steamworks - License: GNU GPLv3 //
48 ///////////////////////////////////////////////////////////////////////////
49 /// <summary>
50 /// Converts a comma-separated list of values to a list of strings.
51 /// </summary>
52 /// <param name="csv">a comma-separated list of values</param>
53 /// <returns>a list of strings</returns>
54 /// <remarks>compliant with RFC 4180</remarks>
5 eva 55 public static IEnumerable<string> ToEnumerable(string csv)
1 zed 56 {
57 Stack<char> s = new Stack<char>();
58 StringBuilder m = new StringBuilder();
59 for (int i = 0; i < csv.Length; ++i)
60 {
61 switch (csv[i])
62 {
63 case ',':
64 if (!s.Any() || !s.Peek().Equals('"'))
65 {
66 yield return m.ToString();
67 m = new StringBuilder();
68 continue;
69 }
70 m.Append(csv[i]);
71 continue;
72 case '"':
73 if (i + 1 < csv.Length && csv[i].Equals(csv[i + 1]))
74 {
75 m.Append(csv[i]);
76 ++i;
77 continue;
78 }
79 if (!s.Any() || !s.Peek().Equals(csv[i]))
80 {
81 s.Push(csv[i]);
82 continue;
83 }
84 s.Pop();
85 continue;
86 }
87 m.Append(csv[i]);
88 }
89  
90 yield return m.ToString();
91 }
92 }
93 }