/usr/include/d/4.8/std/csv.d is in libphobos-4.8-dev 4.8.4-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 | //Written in the D programming language
/**
* Implements functionality to read Comma Separated Values and its variants
* from a input range of $(D dchar).
*
* Comma Separated Values provide a simple means to transfer and store
* tabular data. It has been common for programs to use their own
* variant of the CSV format. This parser will loosely follow the
* $(WEB tools.ietf.org/html/rfc4180, RFC-4180). CSV input should adhered
* to the following criteria, differences from RFC-4180 in parentheses.
*
* $(UL
* $(LI A record is separated by a new line (CRLF,LF,CR))
* $(LI A final record may end with a new line)
* $(LI A header may be provided as the first record in input)
* $(LI A record has fields separated by a comma (customizable))
* $(LI A field containing new lines, commas, or double quotes
* should be enclosed in double quotes (customizable))
* $(LI Double quotes in a field are escaped with a double quote)
* $(LI Each record should contain the same number of fields)
* )
*
* Example:
*
* -------
* import std.algorithm;
* import std.array;
* import std.csv;
* import std.stdio;
* import std.typecons;
*
* void main()
* {
* auto text = "Joe,Carpenter,300000\nFred,Blacksmith,400000\r\n";
*
* foreach(record; csvReader!(Tuple!(string,string,int))(text))
* {
* writefln("%s works as a %s and earns $%d per year",
* record[0], record[1], record[2]);
* }
* }
* -------
*
* When an input contains a header the $(D Contents) can be specified as an
* associative array. Passing null to signify that a header is present.
*
* -------
* auto text = "Name,Occupation,Salary\r"
* "Joe,Carpenter,300000\nFred,Blacksmith,400000\r\n";
*
* foreach(record; csvReader!(string[string])
* (text, null))
* {
* writefln("%s works as a %s and earns $%s per year.",
* record["Name"], record["Occupation"],
* record["Salary"]);
* }
* -------
*
* This module allows content to be iterated by record stored in a struct,
* class, associative array, or as a range of fields. Upon detection of an
* error an CSVException is thrown (can be disabled). csvNextToken has been
* made public to allow for attempted recovery.
*
* Disabling exceptions will lift many restrictions specified above. A quote
* can appear in a field if the field was not quoted. If in a quoted field any
* quote by itself, not at the end of a field, will end processing for that
* field. The field is ended when there is no input, even if the quote was not
* closed.
*
* See_Also:
* $(WEB en.wikipedia.org/wiki/Comma-separated_values, Wikipedia
* Comma-separated values)
*
* Copyright: Copyright 2011
* License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: Jesse Phillips
* Source: $(PHOBOSSRC std/_csv.d)
*/
module std.csv;
import std.algorithm;
import std.array;
import std.conv;
import std.exception;
import std.range;
import std.string;
import std.traits;
/**
* Exception containing the row and column for when an exception was thrown.
*
* Numbering of both row and col start at one and corresponds to the location
* in the file rather than any specified header. Special consideration should
* be made when there is failure to match the header see $(LREF
* HeaderMismatchException) for details.
*
* When performing type conversions, $(XREF ConvException) is stored in the $(D
* next) field.
*/
class CSVException : Exception
{
///
size_t row, col;
this(string msg, string file = __FILE__, size_t line = __LINE__,
Throwable next = null)
{
super(msg, file, line);
}
this(string msg, Throwable next, string file = __FILE__,
size_t line = __LINE__)
{
super(msg, file, line, next);
}
this(string msg, size_t row, size_t col, Throwable next = null,
string file = __FILE__, size_t line = __LINE__)
{
super(msg, next, file, line);
this.row = row;
this.col = col;
}
override string toString() {
return "(Row: " ~ to!string(row) ~
", Col: " ~ to!string(col) ~ ") " ~ msg;
}
}
/**
* Exception thrown when a Token is identified to not be completed: a quote is
* found in an unquoted field, data continues after a closing quote, or the
* quoted field was not closed before data was empty.
*/
class IncompleteCellException : CSVException
{
/// Data pulled from input before finding a problem
///
/// This field is populated when using $(LREF csvReader)
/// but not by $(LREF csvNextToken) as this data will have
/// already been fed to the output range.
dstring partialData;
this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
{
super(msg, file, line);
}
this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
{
super(msg, file, line, next);
}
}
/**
* Exception thrown under different conditions based on the type of $(D
* Contents).
*
* Structure, Class, and Associative Array
* $(UL
* $(LI When a header is provided but a matching column is not found)
* )
*
* Other
* $(UL
* $(LI When a header is provided but a matching column is not found)
* $(LI Order did not match that found in the input)
* )
*
* Since a row and column is not meaningful when a column specified by the
* header is not found in the data, both row and col will be zero. Otherwise
* row is always one and col is the first instance found in header that
* occurred before the previous starting at one.
*/
class HeaderMismatchException : CSVException
{
this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
{
super(msg, file, line);
}
this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
{
super(msg, file, line, next);
}
}
/**
* Determines the behavior for when an error is detected.
*
* Disabling exception will follow these rules:
* $(UL
* $(LI A quote can appear in a field if the field was not quoted.)
* $(LI If in a quoted field any quote by itself, not at the end of a
* field, will end processing for that field.)
* $(LI The field is ended when there is no input, even if the quote was
* not closed.)
* $(LI If the given header does not match the order in the input, the
* content will return as it is found in the input.)
* $(LI If the given header contains columns not found in the input they
* will be ignored.)
* )
*/
enum Malformed
{
/// No exceptions are thrown due to incorrect CSV.
ignore,
/// Use exceptions when input has incorrect CSV.
throwException
}
/**
* Returns an input range for iterating over records found in $(D
* input).
*
* The $(D Contents) of the input can be provided if all the records are the
* same type such as all integer data:
*
* -------
* string str = `76,26,22`;
* int[] ans = [76,26,22];
* auto records = csvReader!int(str);
*
* foreach(record; records)
* {
* assert(equal(record, ans));
* }
* -------
*
* Example using a struct with modified delimiter:
*
* -------
* string str = "Hello;65;63.63\nWorld;123;3673.562";
* struct Layout
* {
* string name;
* int value;
* double other;
* }
*
* auto records = csvReader!Layout(str,';');
*
* foreach(record; records)
* {
* writeln(record.name);
* writeln(record.value);
* writeln(record.other);
* }
* -------
*
* Specifying $(D ErrorLevel) as Malformed.ignore will lift restrictions
* on the format. This example shows that an exception is not thrown when
* finding a quote in a field not quoted.
*
* -------
* string str = "A \" is now part of the data";
* auto records = csvReader!(string,Malformed.ignore)(str);
* auto record = records.front;
*
* assert(record.front == str);
* -------
*
* Returns:
* An input range R as defined by $(XREF range, isInputRange). When $(D
* Contents) is a struct, class, or an associative array, the element
* type of R is $(D Contents), otherwise the element type of R is itself
* a range with element type $(D Contents).
*
* Throws:
* $(LREF CSVException) When a quote is found in an unquoted field,
* data continues after a closing quote, the quoted field was not
* closed before data was empty, a conversion failed, or when the row's
* length does not match the previous length.
*
* $(LREF HeaderMismatchException) when a header is provided but a
* matching column is not found or the order did not match that found in
* the input. Read the exception documentation for specific details of
* when the exception is thrown for different types of $(D Contents).
*/
auto csvReader(Contents = string,Malformed ErrorLevel = Malformed.throwException, Range, Separator = char)(Range input,
Separator delimiter = ',', Separator quote = '"')
if(isInputRange!Range && is(ElementType!Range == dchar)
&& isSomeChar!(Separator)
&& !is(Contents T : T[U], U : string))
{
return CsvReader!(Contents,ErrorLevel,Range,
ElementType!Range,string[])
(input, delimiter, quote);
}
/**
* An optional $(D header) can be provided. The first record will be read in
* as the header. If $(D Contents) is a struct then the header provided is
* expected to correspond to the fields in the struct. When $(D Contents) is
* not a type which can contain the entire record, the $(D header) must be
* provided in the same order as the input or an exception is thrown.
*
* Read only column "b":
*
* -------
* string str = "a,b,c\nHello,65,63.63\nWorld,123,3673.562";
* auto records = csvReader!int(str, ["b"]);
*
* auto ans = [[65],[123]];
* foreach(record; records)
* {
* assert(equal(record, ans.front));
* ans.popFront();
* }
* -------
*
* Read from header of different order:
*
* -------
* string str = "a,b,c\nHello,65,63.63\nWorld,123,3673.562";
* struct Layout
* {
* int value;
* double other;
* string name;
* }
*
* auto records = csvReader!Layout(str, ["b","c","a"]);
* -------
*
* The header can also be left empty if the input contains a header but
* all columns should be iterated. The header from the input can always
* be accessed from the header field.
*
* -------
* string str = "a,b,c\nHello,65,63.63\nWorld,123,3673.562";
* auto records = csvReader(str, null);
*
* assert(records.header == ["a","b","c"]);
* -------
*
* Returns:
* An input range R as defined by $(XREF range, isInputRange). When $(D
* Contents) is a struct, class, or an associative array, the element
* type of R is $(D Contents), otherwise the element type of R is itself
* a range with element type $(D Contents).
*
* The returned range provides a header field for accessing the header
* from the input in array form.
*
* -------
* string str = "a,b,c\nHello,65,63.63";
* auto records = csvReader(str, ["a"]);
*
* assert(records.header == ["a","b","c"]);
* -------
*
* Throws:
* $(LREF CSVException) When a quote is found in an unquoted field,
* data continues after a closing quote, the quoted field was not
* closed before data was empty, a conversion failed, or when the row's
* length does not match the previous length.
*
* $(LREF HeaderMismatchException) when a header is provided but a
* matching column is not found or the order did not match that found in
* the input. Read the exception documentation for specific details of
* when the exception is thrown for different types of $(D Contents).
*/
auto csvReader(Contents = string,
Malformed ErrorLevel = Malformed.throwException,
Range, Header, Separator = char)
(Range input, Header header,
Separator delimiter = ',', Separator quote = '"')
if(isInputRange!Range && is(ElementType!Range == dchar)
&& isSomeChar!(Separator)
&& isForwardRange!Header
&& isSomeString!(ElementType!Header))
{
return CsvReader!(Contents,ErrorLevel,Range,
ElementType!Range,Header)
(input, header, delimiter, quote);
}
auto csvReader(Contents = string,
Malformed ErrorLevel = Malformed.throwException,
Range, Header, Separator = char)
(Range input, Header header,
Separator delimiter = ',', Separator quote = '"')
if(isInputRange!Range && is(ElementType!Range == dchar)
&& isSomeChar!(Separator)
&& is(Header : typeof(null)))
{
return CsvReader!(Contents,ErrorLevel,Range,
ElementType!Range,string[])
(input, cast(string[])null, delimiter, quote);
}
// Test standard iteration over input.
unittest
{
string str = `one,"two ""quoted"""` ~ "\n\"three\nnew line\",""\nfive,six";
auto records = csvReader(str);
int count;
foreach(record; records)
{
foreach(cell; record)
{
count++;
}
}
assert(count == 6);
}
// Test newline on last record
unittest
{
string str = "one,two\nthree,four\n";
auto records = csvReader(str);
records.popFront();
records.popFront();
assert(records.empty);
}
// Test shorter row length
unittest
{
wstring str = "one,1\ntwo\nthree"w;
struct Layout
{
string name;
int value;
}
Layout[3] ans;
ans[0].name = "one";
ans[0].value = 1;
ans[1].name = "two";
ans[1].value = 0;
ans[2].name = "three";
ans[2].value = 0;
auto records = csvReader!(Layout,Malformed.ignore)(str);
int count;
foreach(record; records)
{
assert(ans[count].name == record.name);
assert(ans[count].value == record.value);
count++;
}
}
// Test shorter row length exception
unittest
{
struct A
{
string a,b,c;
}
auto strs = ["one,1\ntwo",
"one\ntwo,2,二\nthree,3,三",
"one\ntwo,2\nthree,3",
"one,1\ntwo\nthree,3"];
foreach(str; strs)
{
auto records = csvReader!A(str);
assertThrown!CSVException((){foreach(record; records) { }}());
}
}
// Test structure conversion interface with unicode.
unittest
{
wstring str = "\U00010143Hello,65,63.63\nWorld,123,3673.562"w;
struct Layout
{
string name;
int value;
double other;
}
Layout[2] ans;
ans[0].name = "\U00010143Hello";
ans[0].value = 65;
ans[0].other = 63.63;
ans[1].name = "World";
ans[1].value = 123;
ans[1].other = 3673.562;
auto records = csvReader!Layout(str);
int count;
foreach(record; records)
{
assert(ans[count].name == record.name);
assert(ans[count].value == record.value);
assert(ans[count].other == record.other);
count++;
}
assert(count == ans.length);
}
// Test input conversion interface
unittest
{
string str = `76,26,22`;
int[] ans = [76,26,22];
auto records = csvReader!int(str);
foreach(record; records)
{
assert(equal(record, ans));
}
}
// Test struct & header interface and same unicode
unittest
{
string str = "a,b,c\nHello,65,63.63\n➊➋➂❹,123,3673.562";
struct Layout
{
int value;
double other;
string name;
}
auto records = csvReader!Layout(str, ["b","c","a"]);
Layout[2] ans;
ans[0].name = "Hello";
ans[0].value = 65;
ans[0].other = 63.63;
ans[1].name = "➊➋➂❹";
ans[1].value = 123;
ans[1].other = 3673.562;
int count;
foreach (record; records)
{
assert(ans[count].name == record.name);
assert(ans[count].value == record.value);
assert(ans[count].other == record.other);
count++;
}
assert(count == ans.length);
}
// Test header interface
unittest
{
string str = "a,b,c\nHello,65,63.63\nWorld,123,3673.562";
auto records = csvReader!int(str, ["b"]);
auto ans = [[65],[123]];
foreach(record; records)
{
assert(equal(record, ans.front));
ans.popFront();
}
try
{
csvReader(str, ["c","b"]);
assert(0);
}
catch(HeaderMismatchException e)
{
assert(e.col == 2);
}
auto records2 = csvReader!(string,Malformed.ignore)
(str, ["b","a"], ',', '"');
auto ans2 = [["Hello","65"],["World","123"]];
foreach(record; records2) {
assert(equal(record, ans2.front));
ans2.popFront();
}
str = "a,c,e\nJoe,Carpenter,300000\nFred,Fly,4";
records2 = csvReader!(string,Malformed.ignore)
(str, ["a","b","c","d"], ',', '"');
ans2 = [["Joe","Carpenter"],["Fred","Fly"]];
foreach(record; records2) {
assert(equal(record, ans2.front));
ans2.popFront();
}
}
// Test null header interface
unittest
{
string str = "a,b,c\nHello,65,63.63\nWorld,123,3673.562";
auto records = csvReader(str, ["a"]);
assert(records.header == ["a","b","c"]);
}
// Test unchecked read
unittest
{
string str = "one \"quoted\"";
foreach(record; csvReader!(string,Malformed.ignore)(str))
{
foreach(cell; record)
{
assert(cell == "one \"quoted\"");
}
}
str = "one \"quoted\",two \"quoted\" end";
struct Ans
{
string a,b;
}
foreach(record; csvReader!(Ans,Malformed.ignore)(str))
{
assert(record.a == "one \"quoted\"");
assert(record.b == "two \"quoted\" end");
}
}
// Test partial data returned
unittest
{
string str = "\"one\nnew line";
try
{
foreach(record; csvReader(str))
{}
assert(0);
}
catch (IncompleteCellException ice)
{
assert(ice.partialData == "one\nnew line");
}
}
// Test Windows line break
unittest
{
string str = "one,two\r\nthree";
auto records = csvReader(str);
auto record = records.front;
assert(record.front == "one");
record.popFront();
assert(record.front == "two");
records.popFront();
record = records.front;
assert(record.front == "three");
}
// Test associative array support with unicode separator
unittest
{
string str = "1❁2❁3\n34❁65❁63\n34❁65❁63";
auto records = csvReader!(string[string])(str,["3","1"],'❁');
int count;
foreach(record; records)
{
count++;
assert(record["1"] == "34");
assert(record["3"] == "63");
}
assert(count == 2);
}
// Test restricted range
unittest
{
import std.typecons;
struct InputRange
{
dstring text;
this(dstring txt)
{
text = txt;
}
@property auto empty()
{
return text.empty;
}
auto popFront()
{
text.popFront();
}
@property dchar front()
{
return text[0];
}
}
auto ir = InputRange("Name,Occupation,Salary\r"d
"Joe,Carpenter,300000\nFred,Blacksmith,400000\r\n"d);
foreach(record; csvReader(ir, cast(string[])null))
foreach(cell; record) {}
foreach(record; csvReader!(Tuple!(string,string,int))
(ir,cast(string[])null)) {}
foreach(record; csvReader!(string[string])
(ir,cast(string[])null)) {}
}
/*
* This struct is stored on the heap for when the structures
* are passed around.
*/
private struct Input(Range, Malformed ErrorLevel)
{
Range range;
size_t row, col;
static if(ErrorLevel == Malformed.throwException)
size_t rowLength;
}
/*
* Range for iterating CSV records.
*
* This range is returned by the $(LREF csvReader) functions. It can be
* created in a similar manner to allow $(D ErrorLevel) be set to $(LREF
* Malformed).ignore if best guess processing should take place.
*
* Example for integer data:
*
* -------
* string str = `76;^26^;22`;
* int[] ans = [76,26,22];
* auto records = CsvReader!(int,Malformed.ignore,string,char,string[])
* (str, ';', '^');
*
* foreach(record; records) {
* assert(equal(record, ans));
* }
* -------
*
*/
private struct CsvReader(Contents, Malformed ErrorLevel, Range, Separator, Header)
if(isSomeChar!Separator && isInputRange!Range
&& is(ElementType!Range == dchar)
&& isForwardRange!Header && isSomeString!(ElementType!Header))
{
private:
Input!(Range, ErrorLevel)* _input;
Separator _separator;
Separator _quote;
size_t[] indices;
bool _empty;
static if(is(Contents == struct) || is(Contents == class))
{
Contents recordContent;
CsvRecord!(string, ErrorLevel, Range, Separator) recordRange;
}
else static if(is(Contents T : T[U], U : string))
{
Contents recordContent;
CsvRecord!(T, ErrorLevel, Range, Separator) recordRange;
}
else
CsvRecord!(Contents, ErrorLevel, Range, Separator) recordRange;
public:
/**
* Header from the input in array form.
*
* -------
* string str = "a,b,c\nHello,65,63.63";
* auto records = csvReader(str, ["a"]);
*
* assert(records.header == ["a","b","c"]);
* -------
*/
string[] header;
/**
* Constructor to initialize the input, delimiter and quote for input
* without a header.
*
* -------
* string str = `76;^26^;22`;
* int[] ans = [76,26,22];
* auto records = CsvReader!(int,Malformed.ignore,string,char,string[])
* (str, ';', '^');
*
* foreach(record; records) {
* assert(equal(record, ans));
* }
* -------
*/
this(Range input, Separator delimiter, Separator quote)
{
_input = new Input!(Range, ErrorLevel);
_input.range = input;
_separator = delimiter;
_quote = quote;
prime();
}
/**
* Constructor to initialize the input, delimiter and quote for input
* with a header.
*
* -------
* string str = `high;mean;low\n76;^26^;22`;
* auto records = CsvReader!(int,Malformed.ignore,string,char,string[])
* (str, ["high","low"], ';', '^');
*
* int[] ans = [76,22];
* foreach(record; records) {
* assert(equal(record, ans));
* }
* -------
*
* Throws:
* $(LREF HeaderMismatchException) when a header is provided but a
* matching column is not found or the order did not match that found
* in the input (non-struct).
*/
this(Range input, Header colHeaders, Separator delimiter, Separator quote)
{
_input = new Input!(Range, ErrorLevel);
_input.range = input;
_separator = delimiter;
_quote = quote;
size_t[string] colToIndex;
foreach(h; colHeaders)
{
colToIndex[h] = size_t.max;
}
auto r = CsvRecord!(string, ErrorLevel, Range, Separator)
(_input, _separator, _quote, indices);
size_t colIndex;
foreach(col; r)
{
header ~= col;
auto ptr = col in colToIndex;
if(ptr)
*ptr = colIndex;
colIndex++;
}
// The above loop empties the header row.
recordRange._empty = true;
indices.length = colToIndex.length;
int i;
foreach(h; colHeaders)
{
immutable index = colToIndex[h];
static if(ErrorLevel != Malformed.ignore)
if(index == size_t.max)
throw new HeaderMismatchException
("Header not found: " ~ to!string(h));
indices[i++] = index;
}
static if(!is(Contents == struct) && !is(Contents == class))
{
static if(is(Contents T : T[U], U : string))
{
sort(indices);
}
else static if(ErrorLevel == Malformed.ignore)
{
sort(indices);
}
else
{
if(!isSorted(indices))
{
auto ex = new HeaderMismatchException
("Header in input does not match specified header.");
findAdjacent!"a > b"(indices);
ex.row = 1;
ex.col = indices.front;
throw ex;
}
}
}
popFront();
}
/**
* Part of an input range as defined by $(XREF range, isInputRange).
*
* Returns:
* If $(D Contents) is a struct, will be filled with record data.
*
* If $(D Contents) is a class, will be filled with record data.
*
* If $(D Contents) is a associative array, will be filled
* with record data.
*
* If $(D Contents) is non-struct, a $(LREF CsvRecord) will be
* returned.
*/
@property auto front()
{
assert(!empty);
static if(is(Contents == struct) || is(Contents == class))
{
return recordContent;
}
else static if(is(Contents T : T[U], U : string))
{
return recordContent;
}
else
{
return recordRange;
}
}
/**
* Part of an input range as defined by $(XREF range, isInputRange).
*/
@property bool empty()
{
return _empty;
}
/**
* Part of an input range as defined by $(XREF range, isInputRange).
*
* Throws:
* $(LREF CSVException) When a quote is found in an unquoted field,
* data continues after a closing quote, the quoted field was not
* closed before data was empty, a conversion failed, or when the
* row's length does not match the previous length.
*/
void popFront()
{
while(!recordRange.empty)
{
recordRange.popFront();
}
static if(ErrorLevel == Malformed.throwException)
if(_input.rowLength == 0)
_input.rowLength = _input.col;
_input.col = 0;
if(!_input.range.empty)
{
if(_input.range.front == '\r')
{
_input.range.popFront();
if(_input.range.front == '\n')
_input.range.popFront();
}
else if(_input.range.front == '\n')
_input.range.popFront();
}
if(_input.range.empty)
{
_empty = true;
return;
}
prime();
}
private void prime()
{
if(_empty)
return;
_input.row++;
static if(is(Contents == struct) || is(Contents == class))
{
recordRange = typeof(recordRange)
(_input, _separator, _quote, null);
}
else
{
recordRange = typeof(recordRange)
(_input, _separator, _quote, indices);
}
static if(is(Contents T : T[U], U : string))
{
T[U] aa;
try
{
for(; !recordRange.empty; recordRange.popFront())
{
aa[header[_input.col-1]] = recordRange.front;
}
}
catch(ConvException e)
{
throw new CSVException(e.msg, _input.row, _input.col, e);
}
recordContent = aa;
}
else static if(is(Contents == struct) || is(Contents == class))
{
static if(is(Contents == class))
recordContent = new typeof(recordContent)();
else
recordContent = typeof(recordContent).init;
size_t colIndex;
try
{
for(; !recordRange.empty;)
{
auto colData = recordRange.front;
scope(exit) colIndex++;
if(indices.length > 0)
{
foreach(ti, ToType; FieldTypeTuple!(Contents))
{
if(indices[ti] == colIndex)
{
static if (!isSomeString!ToType) skipWS(colData);
recordContent.tupleof[ti] = to!ToType(colData);
}
}
}
else
{
foreach(ti, ToType; FieldTypeTuple!(Contents))
{
if(ti == colIndex)
{
static if (!isSomeString!ToType) skipWS(colData);
recordContent.tupleof[ti] = to!ToType(colData);
}
}
}
recordRange.popFront();
}
}
catch(ConvException e)
{
throw new CSVException(e.msg, _input.row, colIndex, e);
}
}
}
}
unittest
{
string str = `76;^26^;22`;
int[] ans = [76,26,22];
auto records = CsvReader!(int,Malformed.ignore,string,char,string[])
(str, ';', '^');
foreach(record; records)
{
assert(equal(record, ans));
}
}
/*
* This input range is accessible through $(LREF CsvReader) when the
* requested $(D Contents) type is neither a structure or an associative array.
*/
private struct CsvRecord(Contents, Malformed ErrorLevel, Range, Separator)
if(!is(Contents == class) && !is(Contents == struct))
{
private:
Input!(Range, ErrorLevel)* _input;
Separator _separator;
Separator _quote;
Contents curContentsoken;
typeof(appender!(dchar[])()) _front;
bool _empty;
size_t[] _popCount;
public:
/*
* params:
* input = Pointer to a character input range
* delimiter = Separator for each column
* quote = Character used for quotation
* indices = An array containing which columns will be returned.
* If empty, all columns are returned. List must be in order.
*/
this(Input!(Range, ErrorLevel)* input, Separator delimiter,
Separator quote, size_t[] indices)
{
_input = input;
_separator = delimiter;
_quote = quote;
_front = appender!(dchar[])();
_popCount = indices.dup;
// If a header was given, each call to popFront will need
// to eliminate so many tokens. This calculates
// how many will be skipped to get to the next header column
size_t normalizer;
foreach(ref c; _popCount) {
static if(ErrorLevel == Malformed.ignore)
{
// If we are not throwing exceptions
// a header may not exist, indices are sorted
// and will be size_t.max if not found.
if(c == size_t.max)
break;
}
c -= normalizer;
normalizer += c + 1;
}
prime();
}
/**
* Part of an input range as defined by $(XREF range, isInputRange).
*/
@property Contents front()
{
assert(!empty);
return curContentsoken;
}
/**
* Part of an input range as defined by $(XREF range, isInputRange).
*/
@property bool empty()
{
return _empty;
}
/*
* CsvRecord is complete when input
* is empty or starts with record break
*/
private bool recordEnd()
{
if(_input.range.empty
|| _input.range.front == '\n'
|| _input.range.front == '\r')
{
return true;
}
return false;
}
/**
* Part of an input range as defined by $(XREF range, isInputRange).
*
* Throws:
* $(LREF CSVException) When a quote is found in an unquoted field,
* data continues after a closing quote, the quoted field was not
* closed before data was empty, a conversion failed, or when the
* row's length does not match the previous length.
*/
void popFront()
{
// Skip last of record when header is depleted.
if(_popCount && _popCount.empty)
while(!recordEnd())
{
prime(1);
}
if(recordEnd())
{
_empty = true;
static if(ErrorLevel == Malformed.throwException)
if(_input.rowLength != 0)
if(_input.col != _input.rowLength)
throw new CSVException(
format("Row %s's length %s does not match "
"previous length of %s.", _input.row,
_input.col, _input.rowLength));
return;
} else {
static if(ErrorLevel == Malformed.throwException)
if(_input.rowLength != 0)
if(_input.col > _input.rowLength)
throw new CSVException(
format("Row %s's length %s does not match "
"previous length of %s.", _input.row,
_input.col, _input.rowLength));
}
// Separator is left on the end of input from the last call.
// This cannot be moved to after the call to csvNextToken as
// there may be an empty record after it.
if(_input.range.front == _separator)
_input.range.popFront();
_front.shrinkTo(0);
prime();
}
/*
* Handles moving to the next skipNum token.
*/
private void prime(size_t skipNum)
{
foreach(i; 0..skipNum)
{
_input.col++;
_front.shrinkTo(0);
if(_input.range.front == _separator)
_input.range.popFront();
try
csvNextToken!(Range, ErrorLevel, Separator)
(_input.range, _front, _separator, _quote,false);
catch(IncompleteCellException ice)
{
ice.row = _input.row;
ice.col = _input.col;
ice.partialData = _front.data.idup;
throw ice;
}
catch(ConvException e)
{
throw new CSVException(e.msg, _input.row, _input.col, e);
}
}
}
private void prime()
{
try
{
_input.col++;
csvNextToken!(Range, ErrorLevel, Separator)
(_input.range, _front, _separator, _quote,false);
}
catch(IncompleteCellException ice)
{
ice.row = _input.row;
ice.col = _input.col;
ice.partialData = _front.data.idup;
throw ice;
}
auto skipNum = _popCount.empty ? 0 : _popCount.front;
if(!_popCount.empty)
_popCount.popFront();
if(skipNum == size_t.max) {
while(!recordEnd())
prime(1);
_empty = true;
return;
}
if(skipNum)
prime(skipNum);
auto data = _front.data;
static if (!isSomeString!Contents) skipWS(data);
try curContentsoken = to!Contents(data);
catch(ConvException e)
{
throw new CSVException(e.msg, _input.row, _input.col, e);
}
}
}
/**
* Lower level control over parsing CSV
*
* This function consumes the input. After each call the input will
* start with either a delimiter or record break (\n, \r\n, \r) which
* must be removed for subsequent calls.
*
* -------
* string str = "65,63\n123,3673";
*
* auto a = appender!(char[])();
*
* csvNextToken(str,a,',','"');
* assert(a.data == "65");
* assert(str == ",63\n123,3673");
*
* str.popFront();
* a.shrinkTo(0);
* csvNextToken(str,a,',','"');
* assert(a.data == "63");
* assert(str == "\n123,3673");
*
* str.popFront();
* a.shrinkTo(0);
* csvNextToken(str,a,',','"');
* assert(a.data == "123");
* assert(str == ",3673");
* -------
*
* params:
* input = Any CSV input
* ans = The first field in the input
* sep = The character to represent a comma in the specification
* quote = The character to represent a quote in the specification
* startQuoted = Whether the input should be considered to already be in
* quotes
*
* Throws:
* $(LREF IncompleteCellException) When a quote is found in an unquoted
* field, data continues after a closing quote, or the quoted field was
* not closed before data was empty.
*/
void csvNextToken(Range, Malformed ErrorLevel = Malformed.throwException,
Separator, Output)
(ref Range input, ref Output ans,
Separator sep, Separator quote,
bool startQuoted = false)
if(isSomeChar!Separator && isInputRange!Range
&& is(ElementType!Range == dchar)
&& isOutputRange!(Output, dchar))
{
bool quoted = startQuoted;
bool escQuote;
if(input.empty)
return;
if(input.front == '\n')
return;
if(input.front == '\r')
return;
if(input.front == quote)
{
quoted = true;
input.popFront();
}
while(!input.empty)
{
assert(!(quoted && escQuote));
if(!quoted)
{
// When not quoted the token ends at sep
if(input.front == sep)
break;
if(input.front == '\r')
break;
if(input.front == '\n')
break;
}
if(!quoted && !escQuote)
{
if(input.front == quote)
{
// Not quoted, but quote found
static if(ErrorLevel == Malformed.throwException)
throw new IncompleteCellException(
"Quote located in unquoted token");
else static if(ErrorLevel == Malformed.ignore)
ans.put(quote);
}
else
{
// Not quoted, non-quote character
ans.put(input.front);
}
}
else
{
if(input.front == quote)
{
// Quoted, quote found
// By turning off quoted and turning on escQuote
// I can tell when to add a quote to the string
// escQuote is turned to false when it escapes a
// quote or is followed by a non-quote (see outside else).
// They are mutually exclusive, but provide different
// information.
if(escQuote)
{
escQuote = false;
quoted = true;
ans.put(quote);
} else
{
escQuote = true;
quoted = false;
}
}
else
{
// Quoted, non-quote character
if(escQuote)
{
static if(ErrorLevel == Malformed.throwException)
throw new IncompleteCellException(
"Content continues after end quote, " ~
"or needs to be escaped.");
else static if(ErrorLevel == Malformed.ignore)
break;
}
ans.put(input.front);
}
}
input.popFront();
}
static if(ErrorLevel == Malformed.throwException)
if(quoted && (input.empty || input.front == '\n' || input.front == '\r'))
throw new IncompleteCellException(
"Data continues on future lines or trailing quote");
}
// Test csvNextToken on simplest form and correct format.
unittest
{
string str = "\U00010143Hello,65,63.63\nWorld,123,3673.562";
auto a = appender!(dchar[])();
csvNextToken!string(str,a,',','"');
assert(a.data == "\U00010143Hello");
assert(str == ",65,63.63\nWorld,123,3673.562");
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
assert(a.data == "65");
assert(str == ",63.63\nWorld,123,3673.562");
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
assert(a.data == "63.63");
assert(str == "\nWorld,123,3673.562");
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
assert(a.data == "World");
assert(str == ",123,3673.562");
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
assert(a.data == "123");
assert(str == ",3673.562");
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
assert(a.data == "3673.562");
assert(str == "");
}
// Test quoted tokens
unittest
{
string str = `one,two,"three ""quoted""","",` ~ "\"five\nnew line\"\nsix";
auto a = appender!(dchar[])();
csvNextToken!string(str,a,',','"');
assert(a.data == "one");
assert(str == `,two,"three ""quoted""","",` ~ "\"five\nnew line\"\nsix");
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
assert(a.data == "two");
assert(str == `,"three ""quoted""","",` ~ "\"five\nnew line\"\nsix");
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
assert(a.data == "three \"quoted\"");
assert(str == `,"",` ~ "\"five\nnew line\"\nsix");
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
assert(a.data == "");
assert(str == ",\"five\nnew line\"\nsix");
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
assert(a.data == "five\nnew line");
assert(str == "\nsix");
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a,',','"');
assert(a.data == "six");
assert(str == "");
}
// Test empty data is pulled at end of record.
unittest
{
string str = "one,";
auto a = appender!(dchar[])();
csvNextToken(str,a,',','"');
assert(a.data == "one");
assert(str == ",");
a.shrinkTo(0);
csvNextToken(str,a,',','"');
assert(a.data == "");
}
// Test exceptions
unittest
{
string str = "\"one\nnew line";
typeof(appender!(dchar[])()) a;
try
{
a = appender!(dchar[])();
csvNextToken(str,a,',','"');
assert(0);
}
catch (IncompleteCellException ice)
{
assert(a.data == "one\nnew line");
assert(str == "");
}
str = "Hello world\"";
try
{
a = appender!(dchar[])();
csvNextToken(str,a,',','"');
assert(0);
}
catch (IncompleteCellException ice)
{
assert(a.data == "Hello world");
assert(str == "\"");
}
str = "one, two \"quoted\" end";
a = appender!(dchar[])();
csvNextToken!(string,Malformed.ignore)(str,a,',','"');
assert(a.data == "one");
str.popFront();
a.shrinkTo(0);
csvNextToken!(string,Malformed.ignore)(str,a,',','"');
assert(a.data == " two \"quoted\" end");
}
// Test modifying token delimiter
unittest
{
string str = `one|two|/three "quoted"/|//`;
auto a = appender!(dchar[])();
csvNextToken(str,a, '|','/');
assert(a.data == "one"d);
assert(str == `|two|/three "quoted"/|//`);
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a, '|','/');
assert(a.data == "two"d);
assert(str == `|/three "quoted"/|//`);
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a, '|','/');
assert(a.data == `three "quoted"`);
assert(str == `|//`);
str.popFront();
a.shrinkTo(0);
csvNextToken(str,a, '|','/');
assert(a.data == ""d);
}
// Bugzilla 8908
unittest
{
string csv = ` 1.0, 2.0, 3.0
4.0, 5.0, 6.0`;
static struct Data { real a, b, c; }
size_t i = 0;
foreach (data; csvReader!Data(csv)) with (data)
{
int[] row = [cast(int)a, cast(int)b, cast(int)c];
if (i == 0)
assert(row == [1, 2, 3]);
else
assert(row == [4, 5, 6]);
++i;
}
i = 0;
foreach (data; csvReader!real(csv))
{
auto a = data.front; data.popFront();
auto b = data.front; data.popFront();
auto c = data.front;
int[] row = [cast(int)a, cast(int)b, cast(int)c];
if (i == 0)
assert(row == [1, 2, 3]);
else
assert(row == [4, 5, 6]);
++i;
}
}
|