Simple CSV parser that handles quoted fields and escaped quotes example: input: value1,"value, with, commas","value with ""escaped"" quotes",value4 output: [value1] [value, with, commas] [value with "escaped" quotes] [value4]
| 943 | // input: value1,"value, with, commas","value with ""escaped"" quotes",value4 |
| 944 | // output: [value1] [value, with, commas] [value with "escaped" quotes] [value4] |
| 945 | static std::vector<std::string> parse_csv_row(const std::string& input) { |
| 946 | std::vector<std::string> fields; |
| 947 | std::string field; |
| 948 | bool in_quotes = false; |
| 949 | |
| 950 | for (size_t i = 0; i < input.length(); ++i) { |
| 951 | char ch = input[i]; |
| 952 | |
| 953 | if (ch == '"') { |
| 954 | if (!in_quotes) { |
| 955 | // start of quoted field (only valid if at beginning of field) |
| 956 | if (!field.empty()) { |
| 957 | // quote appeared in middle of unquoted field, treat as literal |
| 958 | field += '"'; |
| 959 | } else { |
| 960 | in_quotes = true; // start |
| 961 | } |
| 962 | } else { |
| 963 | if (i + 1 < input.length() && input[i + 1] == '"') { |
| 964 | // escaped quote: "" |
| 965 | field += '"'; |
| 966 | ++i; // skip the next quote |
| 967 | } else { |
| 968 | in_quotes = false; // end |
| 969 | } |
| 970 | } |
| 971 | } else if (ch == ',') { |
| 972 | if (in_quotes) { |
| 973 | field += ','; |
| 974 | } else { |
| 975 | fields.push_back(std::move(field)); |
| 976 | field.clear(); |
| 977 | } |
| 978 | } else { |
| 979 | field += ch; |
| 980 | } |
| 981 | } |
| 982 | |
| 983 | // Add the last field |
| 984 | fields.push_back(std::move(field)); |
| 985 | |
| 986 | return fields; |
| 987 | } |
| 988 | |
| 989 | common_params_context common_params_parser_init(common_params & params, llama_example ex, void(*print_usage)(int, char **)) { |
| 990 | // per-example default params |
no test coverage detected