Debian Codegraph @

extern/mINI/ini.h

raw symbols SCIP
1 /*
2 * The MIT License (MIT)
3 * Copyright (c) 2018 Danijel Durakovic
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 *
22 */
23
24 ///////////////////////////////////////////////////////////////////////////////
25 //
26 // /mINI/ v0.9.18
27 // An INI file reader and writer for the modern age.
28 //
29 ///////////////////////////////////////////////////////////////////////////////
30 //
31 // A tiny utility library for manipulating INI files with a straightforward
32 // API and a minimal footprint. It conforms to the (somewhat) standard INI
33 // format - sections and keys are case insensitive and all leading and
34 // trailing whitespace is ignored. Comments are lines that begin with a
35 // semicolon. Trailing comments are allowed on section lines.
36 //
37 // Files are read on demand, upon which data is kept in memory and the file
38 // is closed. This utility supports lazy writing, which only writes changes
39 // and updates to a file and preserves custom formatting and comments. A lazy
40 // write invoked by a write() call will read the output file, find what
41 // changes have been made and update the file accordingly. If you only need to
42 // generate files, use generate() instead. Section and key order is preserved
43 // on read, write and insert.
44 //
45 ///////////////////////////////////////////////////////////////////////////////
46 //
47 // /* BASIC USAGE EXAMPLE: */
48 //
49 // /* read from file */
50 // mINI::INIFile file("myfile.ini");
51 // mINI::INIStructure ini;
52 // file.read(ini);
53 //
54 // /* read value; gets a reference to actual value in the structure.
55 // if key or section don't exist, a new empty value will be created */
56 // std::string& value = ini["section"]["key"];
57 //
58 // /* read value safely; gets a copy of value in the structure.
59 // does not alter the structure */
60 // std::string value = ini.get("section").get("key");
61 //
62 // /* set or update values */
63 // ini["section"]["key"] = "value";
64 //
65 // /* set multiple values */
66 // ini["section2"].set({
67 // {"key1", "value1"},
68 // {"key2", "value2"}
69 // });
70 //
71 // /* write updates back to file, preserving comments and formatting */
72 // file.write(ini);
73 //
74 // /* or generate a file (overwrites the original) */
75 // file.generate(ini);
76 //
77 ///////////////////////////////////////////////////////////////////////////////
78 //
79 // Long live the INI file!!!
80 //
81 ///////////////////////////////////////////////////////////////////////////////
82
83 #ifndef MINI_INI_H_
84 #define MINI_INI_H_
85
86 #include <string>
87 #include <sstream>
88 #include <algorithm>
89 #include <utility>
90 #include <unordered_map>
91 #include <vector>
92 #include <memory>
93 #include <fstream>
94 #include <cctype>
95 #include <filesystem>
96
97 namespace mINI
98 {
99 namespace INIStringUtil
100 {
101 const char* const whitespaceDelimiters = " \t\n\r\f\v";
102 inline void trim(std::string& str)
103 {
104 str.erase(str.find_last_not_of(whitespaceDelimiters) + 1);
105 str.erase(0, str.find_first_not_of(whitespaceDelimiters));
106 }
107 #ifndef MINI_CASE_SENSITIVE
108 inline void toLower(std::string& str)
109 {
110 std::transform(str.begin(), str.end(), str.begin(), [](const char c) {
111 return static_cast<char>(std::tolower(c));
112 });
113 }
114 #endif
115 inline void replace(std::string& str, std::string const& a, std::string const& b)
116 {
117 if (!a.empty())
118 {
119 std::size_t pos = 0;
120 while ((pos = str.find(a, pos)) != std::string::npos)
121 {
122 str.replace(pos, a.size(), b);
123 pos += b.size();
124 }
125 }
126 }
127 #ifdef _WIN32
128 const char* const endl = "\r\n";
129 #else
130 const char* const endl = "\n";
131 #endif
132 }
133
134 template<typename T>
135 class INIMap
136 {
137 private:
138 using T_DataIndexMap = std::unordered_map<std::string, std::size_t>;
139 using T_DataItem = std::pair<std::string, T>;
140 using T_DataContainer = std::vector<T_DataItem>;
141 using T_MultiArgs = typename std::vector<std::pair<std::string, T>>;
142
143 T_DataIndexMap dataIndexMap;
144 T_DataContainer data;
145
146 std::size_t setEmpty(std::string& key)
147 {
148 const std::size_t index = data.size();
149 dataIndexMap[key] = index;
150 data.emplace_back(key, T());
151 return index;
152 }
153
154 public:
155 using const_iterator = typename T_DataContainer::const_iterator;
156
157 INIMap() = default;
158
159 INIMap(INIMap const& other) : dataIndexMap(other.dataIndexMap), data(other.data)
160 {
161 }
162
163 T& operator[](std::string key)
164 {
165 INIStringUtil::trim(key);
166 #ifndef MINI_CASE_SENSITIVE
167 INIStringUtil::toLower(key);
168 #endif
169 auto it = dataIndexMap.find(key);
170 const bool hasIt = (it != dataIndexMap.end());
171 const std::size_t index = (hasIt) ? it->second : setEmpty(key);
172 return data[index].second;
173 }
174 [[nodiscard]] T get(std::string key) const
175 {
176 INIStringUtil::trim(key);
177 #ifndef MINI_CASE_SENSITIVE
178 INIStringUtil::toLower(key);
179 #endif
180 auto it = dataIndexMap.find(key);
181 if (it == dataIndexMap.end())
182 {
183 return T();
184 }
185 return T(data[it->second].second);
186 }
187 [[nodiscard]] bool has(std::string key) const
188 {
189 INIStringUtil::trim(key);
190 #ifndef MINI_CASE_SENSITIVE
191 INIStringUtil::toLower(key);
192 #endif
193 return (dataIndexMap.count(key) == 1);
194 }
195 void set(std::string key, T obj)
196 {
197 INIStringUtil::trim(key);
198 #ifndef MINI_CASE_SENSITIVE
199 INIStringUtil::toLower(key);
200 #endif
201 auto it = dataIndexMap.find(key);
202 if (it != dataIndexMap.end())
203 {
204 data[it->second].second = obj;
205 }
206 else
207 {
208 dataIndexMap[key] = data.size();
209 data.emplace_back(key, obj);
210 }
211 }
212 void set(T_MultiArgs const& multiArgs)
213 {
214 for (auto const& it : multiArgs)
215 {
216 auto const& key = it.first;
217 auto const& obj = it.second;
218 set(key, obj);
219 }
220 }
221 bool remove(std::string key)
222 {
223 INIStringUtil::trim(key);
224 #ifndef MINI_CASE_SENSITIVE
225 INIStringUtil::toLower(key);
226 #endif
227 auto it = dataIndexMap.find(key);
228 if (it != dataIndexMap.end())
229 {
230 std::size_t index = it->second;
231 data.erase(data.begin() + index);
232 dataIndexMap.erase(it);
233 for (auto& it2 : dataIndexMap)
234 {
235 auto& vi = it2.second;
236 if (vi > index)
237 {
238 vi--;
239 }
240 }
241 return true;
242 }
243 return false;
244 }
245 void clear()
246 {
247 data.clear();
248 dataIndexMap.clear();
249 }
250 [[nodiscard]] std::size_t size() const
251 {
252 return data.size();
253 }
254 [[nodiscard]] const_iterator begin() const { return data.begin(); }
255 [[nodiscard]] const_iterator end() const { return data.end(); }
256 };
257
258 using INIStructure = INIMap<INIMap<std::string>>;
259
260 namespace INIParser
261 {
262 using T_ParseValues = std::pair<std::string, std::string>;
263
264 enum class PDataType : char
265 {
266 PDATA_NONE,
267 PDATA_COMMENT,
268 PDATA_SECTION,
269 PDATA_KEYVALUE,
270 PDATA_UNKNOWN
271 };
272
273 inline PDataType parseLine(std::string line, T_ParseValues& parseData)
274 {
275 parseData.first.clear();
276 parseData.second.clear();
277 INIStringUtil::trim(line);
278 if (line.empty())
279 {
280 return PDataType::PDATA_NONE;
281 }
282 const char firstCharacter = line[0];
283 if (firstCharacter == ';')
284 {
285 return PDataType::PDATA_COMMENT;
286 }
287 if (firstCharacter == '[')
288 {
289 auto commentAt = line.find_first_of(';');
290 if (commentAt != std::string::npos)
291 {
292 line = line.substr(0, commentAt);
293 }
294 auto closingBracketAt = line.find_last_of(']');
295 if (closingBracketAt != std::string::npos)
296 {
297 auto section = line.substr(1, closingBracketAt - 1);
298 INIStringUtil::trim(section);
299 parseData.first = section;
300 return PDataType::PDATA_SECTION;
301 }
302 }
303 auto lineNorm = line;
304 INIStringUtil::replace(lineNorm, "\\=", " ");
305 auto equalsAt = lineNorm.find_first_of('=');
306 if (equalsAt != std::string::npos)
307 {
308 auto key = line.substr(0, equalsAt);
309 INIStringUtil::trim(key);
310 INIStringUtil::replace(key, "\\=", "=");
311 auto value = line.substr(equalsAt + 1);
312 INIStringUtil::trim(value);
313 parseData.first = key;
314 parseData.second = value;
315 return PDataType::PDATA_KEYVALUE;
316 }
317 return PDataType::PDATA_UNKNOWN;
318 }
319 }
320
321 class INIReader
322 {
323 public:
324 using T_LineData = std::vector<std::string>;
325 using T_LineDataPtr = std::shared_ptr<T_LineData>;
326
327 bool isBOM = false;
328
329 private:
330 std::ifstream fileReadStream;
331 T_LineDataPtr lineData;
332
333 T_LineData readFile()
334 {
335 fileReadStream.seekg(0, std::ios::end);
336 const std::size_t fileSize = static_cast<std::size_t>(fileReadStream.tellg());
337 fileReadStream.seekg(0, std::ios::beg);
338 if (fileSize >= 3) {
339 const char header[3] = {
340 static_cast<char>(fileReadStream.get()),
341 static_cast<char>(fileReadStream.get()),
342 static_cast<char>(fileReadStream.get())
343 };
344 isBOM = (
345 header[0] == static_cast<char>(0xEF) &&
346 header[1] == static_cast<char>(0xBB) &&
347 header[2] == static_cast<char>(0xBF)
348 );
349 }
350 else {
351 isBOM = false;
352 }
353 std::string fileContents;
354 fileContents.resize(fileSize);
355 fileReadStream.seekg(isBOM ? 3 : 0, std::ios::beg);
356 fileReadStream.read(fileContents.data(), fileSize);
357 fileReadStream.close();
358 T_LineData output;
359 if (fileSize == 0)
360 {
361 return output;
362 }
363 std::string buffer;
364 buffer.reserve(50);
365 for (std::size_t i = 0; i < fileSize; ++i)
366 {
367 const char& c = fileContents[i];
368 if (c == '\n')
369 {
370 output.emplace_back(buffer);
371 buffer.clear();
372 continue;
373 }
374 if (c != '\0' && c != '\r')
375 {
376 buffer += c;
377 }
378 }
379 output.emplace_back(buffer);
380 return output;
381 }
382
383 public:
384 INIReader(std::filesystem::path const& filename, bool keepLineData = false)
385 {
386 fileReadStream.open(filename, std::ios::in | std::ios::binary);
387 if (keepLineData)
388 {
389 lineData = std::make_shared<T_LineData>();
390 }
391 }
392 ~INIReader() = default;
393
394 bool operator>>(INIStructure& data)
395 {
396 if (!fileReadStream.is_open())
397 {
398 return false;
399 }
400 const T_LineData fileLines = readFile();
401 std::string section;
402 bool inSection = false;
403 INIParser::T_ParseValues parseData;
404 for (auto const& line : fileLines)
405 {
406 auto parseResult = INIParser::parseLine(line, parseData);
407 if (parseResult == INIParser::PDataType::PDATA_SECTION)
408 {
409 inSection = true;
410 data[section = parseData.first];
411 }
412 else if (inSection && parseResult == INIParser::PDataType::PDATA_KEYVALUE)
413 {
414 auto const& key = parseData.first;
415 auto const& value = parseData.second;
416 data[section][key] = value;
417 }
418 if (lineData && parseResult != INIParser::PDataType::PDATA_UNKNOWN)
419 {
420 if (parseResult == INIParser::PDataType::PDATA_KEYVALUE && !inSection)
421 {
422 continue;
423 }
424 lineData->emplace_back(line);
425 }
426 }
427 return true;
428 }
429 T_LineDataPtr getLines()
430 {
431 return lineData;
432 }
433 };
434
435 class INIGenerator
436 {
437 private:
438 std::ofstream fileWriteStream;
439
440 public:
441 bool prettyPrint = false;
442
443 INIGenerator(std::filesystem::path const& filename)
444 {
445 fileWriteStream.open(filename, std::ios::out | std::ios::binary);
446 }
447 ~INIGenerator() = default;
448
449 bool operator<<(INIStructure const& data)
450 {
451 if (!fileWriteStream.is_open())
452 {
453 return false;
454 }
455 if (data.size() == 0U)
456 {
457 return true;
458 }
459 auto it = data.begin();
460 for (;;)
461 {
462 auto const& section = it->first;
463 auto const& collection = it->second;
464 fileWriteStream
465 << "["
466 << section
467 << "]";
468 if (collection.size() != 0U)
469 {
470 fileWriteStream << INIStringUtil::endl;
471 auto it2 = collection.begin();
472 for (;;)
473 {
474 auto key = it2->first;
475 INIStringUtil::replace(key, "=", "\\=");
476 auto value = it2->second;
477 INIStringUtil::trim(value);
478 fileWriteStream
479 << key
480 << ((prettyPrint) ? " = " : "=")
481 << value;
482 if (++it2 == collection.end())
483 {
484 break;
485 }
486 fileWriteStream << INIStringUtil::endl;
487 }
488 }
489 if (++it == data.end())
490 {
491 break;
492 }
493 fileWriteStream << INIStringUtil::endl;
494 if (prettyPrint)
495 {
496 fileWriteStream << INIStringUtil::endl;
497 }
498 }
499 return true;
500 }
501 };
502
503 class INIWriter
504 {
505 private:
506 using T_LineData = std::vector<std::string>;
507 using T_LineDataPtr = std::shared_ptr<T_LineData>;
508
509 std::filesystem::path filename;
510
511 T_LineData getLazyOutput(T_LineDataPtr const& lineData, INIStructure& data, INIStructure& original) const
512 {
513 T_LineData output;
514 INIParser::T_ParseValues parseData;
515 std::string sectionCurrent;
516 bool parsingSection = false;
517 bool continueToNextSection = false;
518 bool discardNextEmpty = false;
519 bool writeNewKeys = false;
520 std::size_t lastKeyLine = 0;
521 for (auto line = lineData->begin(); line != lineData->end(); ++line)
522 {
523 if (!writeNewKeys)
524 {
525 auto parseResult = INIParser::parseLine(*line, parseData);
526 if (parseResult == INIParser::PDataType::PDATA_SECTION)
527 {
528 if (parsingSection)
529 {
530 writeNewKeys = true;
531 parsingSection = false;
532 --line;
533 continue;
534 }
535 sectionCurrent = parseData.first;
536 if (data.has(sectionCurrent))
537 {
538 parsingSection = true;
539 continueToNextSection = false;
540 discardNextEmpty = false;
541 output.emplace_back(*line);
542 lastKeyLine = output.size();
543 }
544 else
545 {
546 continueToNextSection = true;
547 discardNextEmpty = true;
548 continue;
549 }
550 }
551 else if (parseResult == INIParser::PDataType::PDATA_KEYVALUE)
552 {
553 if (continueToNextSection)
554 {
555 continue;
556 }
557 if (data.has(sectionCurrent))
558 {
559 auto& collection = data[sectionCurrent];
560 auto const& key = parseData.first;
561 auto const& value = parseData.second;
562 if (collection.has(key))
563 {
564 auto outputValue = collection[key];
565 if (value == outputValue)
566 {
567 output.emplace_back(*line);
568 }
569 else
570 {
571 INIStringUtil::trim(outputValue);
572 auto lineNorm = *line;
573 INIStringUtil::replace(lineNorm, "\\=", " ");
574 auto equalsAt = lineNorm.find_first_of('=');
575 auto valueAt = lineNorm.find_first_not_of(
576 INIStringUtil::whitespaceDelimiters,
577 equalsAt + 1
578 );
579 std::string outputLine = line->substr(0, valueAt);
580 if (prettyPrint && equalsAt + 1 == valueAt)
581 {
582 outputLine += " ";
583 }
584 outputLine += outputValue;
585 output.emplace_back(outputLine);
586 }
587 lastKeyLine = output.size();
588 }
589 }
590 }
591 else
592 {
593 if (discardNextEmpty && line->empty())
594 {
595 discardNextEmpty = false;
596 }
597 else if (parseResult != INIParser::PDataType::PDATA_UNKNOWN)
598 {
599 output.emplace_back(*line);
600 }
601 }
602 }
603 if (writeNewKeys || std::next(line) == lineData->end())
604 {
605 T_LineData linesToAdd;
606 if (data.has(sectionCurrent) && original.has(sectionCurrent))
607 {
608 auto const& collection = data[sectionCurrent];
609 auto const& collectionOriginal = original[sectionCurrent];
610 for (auto const& it : collection)
611 {
612 auto key = it.first;
613 if (collectionOriginal.has(key))
614 {
615 continue;
616 }
617 auto value = it.second;
618 INIStringUtil::replace(key, "=", "\\=");
619 INIStringUtil::trim(value);
620 linesToAdd.emplace_back(
621 key + ((prettyPrint) ? " = " : "=") + value
622 );
623 }
624 }
625 if (!linesToAdd.empty())
626 {
627 output.insert(
628 output.begin() + lastKeyLine,
629 linesToAdd.begin(),
630 linesToAdd.end()
631 );
632 }
633 if (writeNewKeys)
634 {
635 writeNewKeys = false;
636 --line;
637 }
638 }
639 }
640 for (auto const& it : data)
641 {
642 auto const& section = it.first;
643 if (original.has(section))
644 {
645 continue;
646 }
647 if (prettyPrint && !output.empty() && !output.back().empty())
648 {
649 output.emplace_back();
650 }
651 output.emplace_back("[" + section + "]");
652 auto const& collection = it.second;
653 for (auto const& it2 : collection)
654 {
655 auto key = it2.first;
656 auto value = it2.second;
657 INIStringUtil::replace(key, "=", "\\=");
658 INIStringUtil::trim(value);
659 output.emplace_back(
660 key + ((prettyPrint) ? " = " : "=") + value
661 );
662 }
663 }
664 return output;
665 }
666
667 public:
668 bool prettyPrint = false;
669
670 INIWriter(std::filesystem::path filename)
671 : filename(std::move(filename))
672 {
673 }
674 ~INIWriter() = default;
675
676 bool operator<<(INIStructure& data)
677 {
678 if (!std::filesystem::exists(filename))
679 {
680 INIGenerator generator(filename);
681 generator.prettyPrint = prettyPrint;
682 return generator << data;
683 }
684 INIStructure originalData;
685 T_LineDataPtr lineData;
686 bool readSuccess = false;
687 bool fileIsBOM = false;
688 {
689 INIReader reader(filename, true);
690 readSuccess = reader >> originalData;
691 if (readSuccess)
692 {
693 lineData = reader.getLines();
694 fileIsBOM = reader.isBOM;
695 }
696 }
697 if (!readSuccess)
698 {
699 return false;
700 }
701 T_LineData output = getLazyOutput(lineData, data, originalData);
702 std::ofstream fileWriteStream(filename, std::ios::out | std::ios::binary);
703 if (fileWriteStream.is_open())
704 {
705 if (fileIsBOM) {
706 const char utf8_BOM[3] = {
707 static_cast<char>(0xEF),
708 static_cast<char>(0xBB),
709 static_cast<char>(0xBF)
710 };
711 fileWriteStream.write(utf8_BOM, 3);
712 }
713 if (!output.empty())
714 {
715 auto line = output.begin();
716 for (;;)
717 {
718 fileWriteStream << *line;
719 if (++line == output.end())
720 {
721 break;
722 }
723 fileWriteStream << INIStringUtil::endl;
724 }
725 }
726 return true;
727 }
728 return false;
729 }
730 };
731
732 class INIFile
733 {
734 private:
735 std::filesystem::path filename;
736
737 public:
738 INIFile(std::filesystem::path filename)
739 : filename(std::move(filename))
740 { }
741
742 ~INIFile() = default;
743
744 bool read(INIStructure& data) const
745 {
746 if (data.size() != 0U)
747 {
748 data.clear();
749 }
750 if (filename.empty())
751 {
752 return false;
753 }
754 INIReader reader(filename);
755 return reader >> data;
756 }
757 [[nodiscard]] bool generate(INIStructure const& data, bool pretty = false) const
758 {
759 if (filename.empty())
760 {
761 return false;
762 }
763 INIGenerator generator(filename);
764 generator.prettyPrint = pretty;
765 return generator << data;
766 }
767 bool write(INIStructure& data, bool pretty = false) const
768 {
769 if (filename.empty())
770 {
771 return false;
772 }
773 INIWriter writer(filename);
774 writer.prettyPrint = pretty;
775 return writer << data;
776 }
777 };
778 }
779
780 #endif // MINI_INI_H_