-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathSimpleIni.h
2472 lines (2252 loc) · 83.5 KB
/
SimpleIni.h
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
// Library: SimpleIni
// File: SimpleIni.h
// Author: Brodie Thiesfield <[email protected]>
// Source: http://code.jellycan.com/simpleini/
// Version: 2.8
//
// INTRODUCTION
// ============
// This component allows an INI-style configuration file to be used on both
// Windows and Linux/Unix. It is fast, simple and source code using this
// component will compile unchanged on either OS.
//
// FEATURES
// ========
// * MIT Licence allows free use in all software (including GPL and commercial)
// * multi-platform (Windows 95/98/ME/NT/2K/XP/2003, Windows CE, Linux, Unix)
// * loading and saving of INI-style configuration files
// * configuration files can have any newline format on all platforms
// * liberal acceptance of file format
// - key/values with no section
// - removal of whitespace around sections, keys and values
// * support for multi-line values (values with embedded newline characters)
// * optional support for multiple keys with the same name
// * optional case-insensitive sections and keys (for ASCII characters only)
// * supports both char or wchar_t programming interfaces
// * supports both MBCS (system locale) and UTF-8 file encodings
// * system locale does not need to be UTF-8 on Linux/Unix to load UTF-8 file
// * support for non-ASCII characters in section, keys, values and comments
// * support for non-standard character types or file encodings
// via user-written converter classes
// * support for adding/modifying values programmatically
// * compiles cleanly at warning level 4 (Windows/VC.NET 2003), warning level
// 3 (Windows/VC6) and -Wall (Linux/gcc)
//
// USAGE SUMMARY
// =============
// 1. Define the appropriate symbol for the converter you wish to use and
// include the SimpleIni.h header file. If no specific converter is defined
// then the default converter is used. The default conversion mode uses
// SI_CONVERT_WIN32 on Windows and SI_CONVERT_GENERIC on all other
// platforms. If you are using ICU then SI_CONVERT_ICU is supported on all
// platforms.
//
// 2. Declare an instance the appropriate class. Note that the following
// definitions are just shortcuts for commonly used types. Other types
// (PRUnichar, unsigned short, unsigned char) are also possible.
//
// Interface Case-sensitive Load UTF-8 Load MBCS Typedef
// --------- -------------- ---------- --------- ---------------
// SI_CONVERT_GENERIC
// char No Yes Yes *1 CSimpleIniA
// char Yes Yes Yes CSimpleIniCaseA
// wchar_t No Yes Yes CSimpleIniW
// wchar_t Yes Yes Yes CSimpleIniCaseW
// SI_CONVERT_WIN32
// char No No *2 Yes CSimpleIniA
// char Yes Yes Yes CSimpleIniCaseA
// wchar_t No Yes Yes CSimpleIniW
// wchar_t Yes Yes Yes CSimpleIniCaseW
// SI_CONVERT_ICU
// char No Yes Yes CSimpleIniA
// char Yes Yes Yes CSimpleIniCaseA
// UChar No Yes Yes CSimpleIniW
// UChar Yes Yes Yes CSimpleIniCaseW
//
// *1 On Windows you are better to use CSimpleIniA with SI_CONVERT_WIN32.
// *2 Only affects Windows. On Windows this uses MBCS functions and
// so may fold case incorrectly leading to uncertain results.
//
// 2. Call LoadFile() to load and parse the INI configuration file
//
// 3. Access and modify the data of the file using the following functions
//
// GetAllSections Return all section names
// GetAllKeys Return all key names for a section
// GetSection Return all key names and values in a section
// GetSectionSize Return the number of keys in a section
// GetValue Return a value for a section & key
// GetAllValues Return all values for a section & key
// SetValue Add or update a value for a section & key
// Delete Remove a section, or a key from a section
//
// 4. Call Save(), SaveFile() or SaveString() to save the INI configuration
// data (as necessary)
//
// MULTI-LINE VALUES
// =================
// Values that span multiple lines are created using the following format.
//
// key = <<<ENDTAG
// .... multiline value ....
// ENDTAG
//
// Note the following:
// * The text used for ENDTAG can be anything and is used to find
// where the multi-line text ends.
// * The newline after ENDTAG in the start tag, and the newline
// before ENDTAG in the end tag is not included in the data value.
// * The ending tag must be on it's own line with no whitespace before
// or after it.
// * The multi-line value is not modified at load or save. This means
// that the newline format (PC, Unix, Mac) is whatever the original
// file uses.
//
// NOTES
// =====
// * To compile using Microsoft Visual Studio 6 or Embedded Visual C++ 4,
// you need to modify this header file and remove all instances of the
// "typename" keyword where error C2899 occurs.
// * To load UTF-8 data on Windows 95, you need to use Microsoft Layer for
// Unicode, or SI_CONVERT_GENERIC, or SI_CONVERT_ICU.
// * When using SI_CONVERT_GENERIC, ConvertUTF.c must be compiled and linked.
// * When using SI_CONVERT_ICU, ICU header files must be on the include
// path and icuuc.lib must be linked in.
// * To load a UTF-8 file on Windows AND expose it with SI_CHAR == char,
// you should use SI_CONVERT_GENERIC.
// * The collation (sorting) order used for sections and keys returned from
// iterators is NOT DEFINED. If collation order of the text is important
// then it should be done yourself by either supplying a replacement
// SI_STRLESS class, or by sorting the strings external to this library.
// * Usage of the <mbstring.h> header on Windows can be disabled by defining
// SI_NO_MBCS. This is defined automatically on Windows CE platforms.
//
// MIT LICENCE
// ===========
// The licence text below is the boilerplate "MIT Licence" used from:
// http://www.opensource.org/licenses/mit-license.php
//
// Copyright (c) 2006, Brodie Thiesfield
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#pragma once
// Disable these warnings in MSVC:
// 4127 "conditional expression is constant" as the conversion classes trigger
// it with the statement if (sizeof(SI_CHAR) == sizeof(char)). This test will
// be optimized away in a release build.
// 4702 "unreachable code" as the MS STL header causes it in release mode.
// Again, the code causing the warning will be cleaned up by the compiler.
#ifdef _MSC_VER
# pragma warning(disable : 4127 4702)
#endif
#include <string>
#include <map>
#include <list>
#include <assert.h>
enum SI_Error
{
SI_OK = 0, //!< No error
SI_UPDATED = 1, //!< An existing value was updated
SI_INSERTED = 2, //!< A new value was inserted
// note: test for any error with (retval < 0)
SI_FAIL = -1, //!< Generic failure
SI_NOMEM = -2, //!< Out of memory error
SI_FILE = -3, //!< File error (see errno for detail error)
};
#define SI_BOM_UTF8 "\xEF\xBB\xBF"
#ifdef _WIN32
# define SI_NEWLINE_A "\r\n"
# define SI_NEWLINE_W L"\r\n"
#else // !_WIN32
# define SI_NEWLINE_A "\n"
# define SI_NEWLINE_W L"\n"
#endif // _WIN32
#if defined(_WIN32) || defined(SI_CONVERT_ICU)
# define SI_HAS_WIDE_LOADFILE
#endif
#if defined(SI_CONVERT_ICU)
# include <unicode/ustring.h>
#endif
// ---------------------------------------------------------------------------
// MAIN TEMPLATE CLASS
// ---------------------------------------------------------------------------
/**
* Simple INI file reader. This can be instantiated with the choice of unicode
* or native characterset, and case sensitive or insensitive comparisons of
* section and key names. The supported combinations are pre-defined with the
* following typedefs:
*
* Interface Case-sensitive Typedef
* --------- -------------- ---------------
* char No CSimpleIniA
* char Yes CSimpleIniCaseA
* wchar_t No CSimpleIniW
* wchar_t Yes CSimpleIniCaseW
*
* Note that using other types for the SI_CHAR is supported. For instance,
* unsigned char, unsigned short, etc. Note that where the alternative type
* is a different size to char/wchar_t you may need to supply new helper
* classes for SI_STRLESS and SI_CONVERTER.
*/
template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
class CSimpleIniTempl
{
public:
/** map keys to values */
using TKeyVal = std::multimap<const SI_CHAR *, const SI_CHAR *, SI_STRLESS>;
/** map sections to key/value map */
using TSection = std::map<const SI_CHAR *, TKeyVal, SI_STRLESS>;
/** set of dependent string pointers. Note that these pointers are
* dependent on memory owned by CSimpleIni. */
using TNamesDepend = std::list<const SI_CHAR *>;
/** interface definition for the OutputWriter object to pass to Save()
* in order to output the INI file data. */
class OutputWriter
{
public:
OutputWriter() {}
virtual ~OutputWriter() {}
virtual void Write(const char *a_pBuf) = 0;
};
/** OutputWriter class to write the INI data to a file */
class FileWriter : public OutputWriter
{
FILE *m_file;
public:
FileWriter(FILE *a_file)
: m_file(a_file)
{
}
void Write(const char *a_pBuf)
{
fputs(a_pBuf, m_file);
}
};
/** OutputWriter class to write the INI data to a string */
class StringWriter : public OutputWriter
{
std::string &m_string;
public:
StringWriter(std::string &a_string)
: m_string(a_string)
{
}
void Write(const char *a_pBuf)
{
m_string.append(a_pBuf);
}
};
/** Characterset conversion utility class to convert strings to the
* same format as is used for the storage. */
class Converter : private SI_CONVERTER
{
public:
Converter(bool a_bStoreIsUtf8)
: SI_CONVERTER(a_bStoreIsUtf8)
{
m_scratch.resize(1024);
}
Converter(const Converter &rhs) { operator=(rhs); }
Converter &operator=(const Converter &rhs)
{
m_scratch = rhs.m_scratch;
return *this;
}
bool ConvertToStore(const SI_CHAR *a_pszString)
{
size_t uLen = SI_CONVERTER::SizeToStore(a_pszString);
if (uLen == (size_t)(-1))
{
return false;
}
while (uLen > m_scratch.size())
{
m_scratch.resize(m_scratch.size() * 2);
}
return SI_CONVERTER::ConvertToStore(
a_pszString,
const_cast<char *>(m_scratch.data()),
m_scratch.size());
}
const char *Data() { return m_scratch.data(); }
private:
std::string m_scratch;
};
public:
/**
* Default constructor.
*
* @param a_bIsUtf8 See the method SetUnicode() for details.
* @param a_bMultiKey See the method SetMultiKey() for details.
* @param a_bMultiLine See the method SetMultiLine() for details.
*/
CSimpleIniTempl(bool a_bIsUtf8 = false, bool a_bMultiKey = false, bool a_bMultiLine = false);
/**
* Destructor
*/
~CSimpleIniTempl();
/**
* Deallocate all memory stored by this object
*/
void Reset();
/**
* Set the storage format of the INI data. This affects both the loading
* and saving of the INI data using all of the Load/Save API functions.
* This value cannot be changed after any INI data has been loaded.
*
* If the file is not set to Unicode (UTF-8), then the data encoding is
* assumed to be the OS native encoding. This encoding is the system
* locale on Linux/Unix and the legacy MBCS encoding on Windows NT/2K/XP.
* If the storage format is set to Unicode then the file will be loaded
* as UTF-8 encoded data regardless of the native file encoding. If
* SI_CHAR == char then all of the char* parameters take and return UTF-8
* encoded data regardless of the system locale.
*/
void SetUnicode(bool a_bIsUtf8 = true)
{
if (!m_pData)
m_bStoreIsUtf8 = a_bIsUtf8;
}
/**
* Get the storage format of the INI data.
*/
bool IsUnicode() const { return m_bStoreIsUtf8; }
/**
* Should multiple identical keys be permitted in the file. If set to false
* then the last value encountered will be used as the value of the key.
* If set to true, then all values will be available to be queried. For
* example, with the following input:
*
* [section]
* test=value1
* test=value2
*
* Then with SetMultiKey(true), both of the values "value1" and "value2"
* will be returned for the key test. If SetMultiKey(false) is used, then
* the value for "test" will only be "value2". This value may be changed
* at any time.
*/
void SetMultiKey(bool a_bAllowMultiKey = true)
{
m_bAllowMultiKey = a_bAllowMultiKey;
}
/**
* Get the storage format of the INI data.
*/
bool IsMultiKey() const { return m_bAllowMultiKey; }
/**
* Should data values be permitted to span multiple lines in the file. If
* set to false then the multi-line construct <<<TAG as a value will be
* returned as is instead of loading the data. This value may be changed
* at any time.
*/
void SetMultiLine(bool a_bAllowMultiLine = true)
{
m_bAllowMultiLine = a_bAllowMultiLine;
}
/**
* Query the status of multi-line data.
*/
bool IsMultiLine() const { return m_bAllowMultiLine; }
/**
* Load an INI file from disk into memory
*
* @param a_pszFile Path of the file to be loaded. This will be passed
* to fopen() and so must be a valid path for the
* current platform.
*
* @return SI_Error See error definitions
*/
SI_Error LoadFile(const char *a_pszFile);
#ifdef SI_HAS_WIDE_LOADFILE
/**
* Load an INI file from disk into memory
*
* @param a_pwszFile Path of the file to be loaded in UTF-16. This will
* be passed to _wfopen() on Windows. There is no
* wchar_t fopen function on Linux/Unix so this
* function is not supported there.
*
* @return SI_Error See error definitions
*/
SI_Error LoadFile(const wchar_t *a_pwszFile);
#endif // _WIN32
/**
* Load INI file data direct from memory
*
* @param a_pData Data to be loaded
* @param a_uDataLen Length of the data in bytes
*
* @return SI_Error See error definitions
*/
SI_Error LoadFile(
const char *a_pData,
size_t a_uDataLen);
/**
* Save the INI data. The data will be written to the output device
* in a format appropriate to the current data, selected by:
*
* SI_CHAR FORMAT
* ------- ------
* char same format as when loaded (MBCS or UTF-8)
* wchar_t UTF-8
* other UTF-8
*
* Note that comments, etc from the original data are not saved. Only the
* valid data contents stored in the file are written out. Any data
* prepended or appended to the output device should use the same format
* (MBCS or UTF-8) as this data, use the GetConverter() method to convert
* text to the correct format.
*
* To add a BOM to UTF-8 data, write it out manually at the very beginning
* like is done in SaveFile when a_bUseBOM is true.
*/
SI_Error Save(OutputWriter &a_oOutput) const;
/**
* Save the INI data to a file. See Save() for details. Do not set
* a_bUseBOM to true if any information has been written to the file
* prior to calling this method.
*
* @param a_pFile Handle to a file. File should be opened for
* binary output.
* @param a_bUseBOM Prepend the UTF-8 BOM if the output stream is
* in UTF-8 format.
*/
SI_Error SaveFile(FILE *a_pFile, bool a_bUseBOM = false) const
{
FileWriter writer(a_pFile);
if (m_bStoreIsUtf8 && a_bUseBOM)
{
writer.Write(SI_BOM_UTF8);
}
return Save(writer);
}
/**
* Save the INI data to a string. See Save() for details.
*
* @param a_sBuffer String to have the INI data appended to.
*/
SI_Error SaveString(std::string &a_sBuffer) const
{
StringWriter writer(a_sBuffer);
return Save(writer);
}
/**
* Retrieve the value for a specific key. If multiple keys are enabled
* (see SetMultiKey) then only the first value associated with that key
* will be returned, see GetAllValues for getting all values with multikey.
*
* NOTE! The returned value is a pointer to string data stored in memory
* owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed
* or Reset while you are using this pointer!
*
* @param a_pSection Section to search
* @param a_pKey Key to search for
* @param a_pDefault Value to return if the key is not found
* @param a_pHasMultiple Optionally receive notification of if there are
* multiple entries for this key.
*
* @return a_pDefault Key was not found in the section
* @return other Value of the key
*/
const SI_CHAR *GetValue(
const SI_CHAR *a_pSection,
const SI_CHAR *a_pKey,
const SI_CHAR *a_pDefault = 0,
bool * a_pHasMultiple = 0) const;
/**
* Retrieve all values for a specific key. This method can be used when
* multiple keys are both enabled and disabled.
*
* NOTE! The returned values are pointers to string data stored in memory
* owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed
* or Reset while you are using this pointer!
*
* @param a_pSection Section to search
* @param a_pKey Key to search for
* @param a_values List to return if the key is not found
* @param a_pHasMultiple Optionally receive notification of if there are
* multiple entries for this key.
*
* @return a_pDefault Key was not found in the section
* @return other Value of the key
*/
bool GetAllValues(
const SI_CHAR *a_pSection,
const SI_CHAR *a_pKey,
TNamesDepend & a_values) const;
/**
* Add or update a section or value. This will always insert
* when multiple keys are enabled.
*
* @param a_pSection Section to add or update
* @param a_pKey Key to add or update. Set to nullptr to
* create an empty section.
* @param a_pValue Value to set. Set to nullptr to create an
* empty section.
*
* @return SI_Error See error definitions
* @return SI_UPDATED Value was updated
* @return SI_INSERTED Value was inserted
*/
SI_Error SetValue(
const SI_CHAR *a_pSection,
const SI_CHAR *a_pKey,
const SI_CHAR *a_pValue)
{
return AddEntry(a_pSection, a_pKey, a_pValue, true);
}
/**
* Delete an entire section, or a key from a section. Note that the
* data returned by GetSection is invalid and must not be used after
* anything has been deleted from that section using this method.
* Note when multiple keys is enabled, this will delete all keys with
* that name; there is no way to selectively delete individual key/values
* in this situation.
*
* @param a_pSection Section to delete key from, or if
* a_pKey is nullptr, the section to remove.
* @param a_pKey Key to remove from the section. Set to
* nullptr to remove the entire section.
* @param a_bRemoveEmpty If the section is empty after this key has
* been deleted, should the empty section be
* removed?
*
* @return true Key or section was deleted.
* @return false Key or section was not found.
*/
bool Delete(
const SI_CHAR *a_pSection,
const SI_CHAR *a_pKey,
bool a_bRemoveEmpty = false);
/**
* Query the number of keys in a specific section. Note that if multiple
* keys are enabled, then this value may be different to the number of
* keys returned by GetAllKeys.
*
* @param a_pSection Section to request data for
*
* @return -1 Section does not exist in the file
* @return >=0 Number of keys in the section
*/
int GetSectionSize(
const SI_CHAR *a_pSection) const;
/**
* Retrieve all key and value pairs for a section. The data is returned
* as a pointer to an STL map and can be iterated or searched as
* desired. Note that multiple entries for the same key may exist when
* multiple keys have been enabled.
*
* NOTE! This structure contains only pointers to strings. The actual
* string data is stored in memory owned by CSimpleIni. Ensure that the
* CSimpleIni object is not destroyed or Reset() while these strings
* are in use!
*
* @param a_pSection Name of the section to return
* @param a_pData Pointer to the section data.
* @return boolean Was a section matching the supplied
* name found.
*/
const TKeyVal *GetSection(
const SI_CHAR *a_pSection) const;
/**
* Retrieve all section names. The list is returned as an STL vector of
* names and can be iterated or searched as necessary. Note that the
* collation order of the returned strings is NOT DEFINED.
*
* NOTE! This structure contains only pointers to strings. The actual
* string data is stored in memory owned by CSimpleIni. Ensure that the
* CSimpleIni object is not destroyed or Reset() while these strings
* are in use!
*
* @param a_names Vector that will receive all of the section
* names. See note above!
*/
void GetAllSections(
TNamesDepend &a_names) const;
/**
* Retrieve all unique key names in a section. The collation order of the
* returned strings is NOT DEFINED. Only unique key names are returned.
*
* NOTE! This structure contains only pointers to strings. The actual
* string data is stored in memory owned by CSimpleIni. Ensure that the
* CSimpleIni object is not destroyed or Reset() while these strings
* are in use!
*
* @param a_pSection Section to request data for
* @param a_names List that will receive all of the key
* names. See note above!
*/
void GetAllKeys(
const SI_CHAR *a_pSection,
TNamesDepend & a_names) const;
/**
* Return a conversion object to convert text to the same encoding
* as is used by the Save(), SaveFile() and SaveString() functions.
* Use this to prepare the strings that you wish to append or prepend
* to the output INI data.
*/
Converter GetConverter() const
{
return Converter(m_bStoreIsUtf8);
}
private:
/** Load the file from a file pointer. */
SI_Error LoadFile(FILE *a_fpFile);
/** Parse the data looking for the next valid entry. The memory pointed to
* by a_pData is modified by inserting NULL characters. The pointer is
* updated to the current location in the block of text. */
bool FindEntry(
SI_CHAR *& a_pData,
const SI_CHAR *&a_pSection,
const SI_CHAR *&a_pKey,
const SI_CHAR *&a_pVal) const;
/** Add the section/key/value to our data. Strings will be copied only
* if a_bCopyStrings is set to true, otherwise the pointers will be
* used as is. */
SI_Error AddEntry(
const SI_CHAR *a_pSection,
const SI_CHAR *a_pKey,
const SI_CHAR *a_pValue,
bool a_bCopyStrings);
/** Is the supplied character a whitespace character? */
inline bool IsSpace(SI_CHAR ch) const
{
return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n');
}
/** Skip over a newline character (or characters) for either DOS or UNIX */
inline void SkipNewLine(SI_CHAR *& a_pData) const {
a_pData += (*a_pData == '\r' && *(a_pData+1) == '\n') ? 2 : 1;
}
/** Does the supplied character start a comment line? */
inline bool IsComment(SI_CHAR ch) const
{
return (ch == ';' || ch == '#');
}
/** Make a copy of the supplied string, replacing the original pointer. */
SI_Error CopyString(const SI_CHAR *&a_pString);
/** Delete a string from the copied strings buffer if necessary. */
void DeleteString(const SI_CHAR *a_pString);
/** Internal use of our string comparison function */
bool IsEqual(const SI_CHAR *a_pLeft, const SI_CHAR *a_pRight) const
{
static const SI_STRLESS strless = SI_STRLESS();
return !strless(a_pLeft, a_pRight) && !strless(a_pRight, a_pLeft);
}
bool IsMultiLineTag(const SI_CHAR *a_pData) const;
bool IsMultiLineData(const SI_CHAR *a_pData) const;
bool FindMultiLine(SI_CHAR *&a_pData, const SI_CHAR *&a_pVal) const;
bool IsNewLineChar(SI_CHAR a_c) const;
private:
/** Copy of the INI file data in our character format. This will be
* modified when parsed to have NULL characters added after all
* interesting string entries. All of the string pointers to sections,
* keys and values point into this block of memory.
*/
SI_CHAR *m_pData;
/** Length of the data that we have stored. Used when deleting strings
* to determine if the string is stored here or in the allocated string
* buffer.
*/
size_t m_uDataLen;
/** Parsed INI data. Section -> (Key -> Value). */
TSection m_data;
/** This vector stores allocated memory for copies of strings that have
* been supplied after the file load. It will be empty unless SetValue()
* has been called.
*/
TNamesDepend m_strings;
/** Is the format of our datafile UTF-8 or MBCS? */
bool m_bStoreIsUtf8;
/** Are multiple values permitted for the same key? */
bool m_bAllowMultiKey;
/** Are data values permitted to span multiple lines? */
bool m_bAllowMultiLine;
};
// ---------------------------------------------------------------------------
// IMPLEMENTATION
// ---------------------------------------------------------------------------
template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::CSimpleIniTempl(
bool a_bIsUtf8, bool a_bAllowMultiKey, bool a_bAllowMultiLine)
: m_pData(0)
, m_uDataLen(0)
, m_bStoreIsUtf8(a_bIsUtf8)
, m_bAllowMultiKey(a_bAllowMultiKey)
, m_bAllowMultiLine(a_bAllowMultiLine)
{
}
template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::~CSimpleIniTempl()
{
Reset();
}
template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
void CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::Reset()
{
// remove all data
delete[] m_pData;
m_pData = 0;
m_uDataLen = 0;
if (!m_data.empty())
{
m_data.erase(m_data.begin(), m_data.end());
}
// remove all strings
if (!m_strings.empty())
{
typename TNamesDepend::iterator i = m_strings.begin();
for (; i != m_strings.end(); ++i)
{
delete[] const_cast<SI_CHAR *>(*i);
}
m_strings.erase(m_strings.begin(), m_strings.end());
}
}
template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
SI_Error
CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::LoadFile(
const char *a_pszFile)
{
FILE *fp = fopen(a_pszFile, "rb");
if (!fp)
{
return SI_FILE;
}
SI_Error rc = LoadFile(fp);
fclose(fp);
return rc;
}
#ifdef SI_HAS_WIDE_LOADFILE
template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
SI_Error
CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::LoadFile(
const wchar_t *a_pwszFile)
{
# ifdef _WIN32
FILE * fp;
errno_t err = _wfopen_s(&fp, a_pwszFile, L"rb");
if ((err != 0) || (!fp))
{
return SI_FILE;
}
SI_Error rc = LoadFile(fp);
fclose(fp);
return rc;
# else // SI_CONVERT_ICU
char szFile[256];
u_austrncpy(szFile, a_pwszFile, sizeof(szFile));
return LoadFile(szFile);
# endif
}
#endif // _WIN32
template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
SI_Error
CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::LoadFile(
FILE *a_fpFile)
{
// load the raw file data
int retval = fseek(a_fpFile, 0, SEEK_END);
if (retval != 0)
{
return SI_FILE;
}
long lSize = ftell(a_fpFile);
if (lSize < 0)
{
return SI_FILE;
}
char *pData = new char[lSize];
if (!pData)
{
return SI_NOMEM;
}
fseek(a_fpFile, 0, SEEK_SET);
size_t uRead = fread(pData, sizeof(char), lSize, a_fpFile);
if (uRead != (size_t)lSize)
{
delete[] pData;
return SI_FILE;
}
// convert the raw data to unicode
SI_Error rc = LoadFile(pData, uRead);
delete[] pData;
return rc;
}
template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
SI_Error
CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::LoadFile(
const char *a_pData,
size_t a_uDataLen)
{
SI_CONVERTER converter(m_bStoreIsUtf8);
// consume the UTF-8 BOM if it exists
if (m_bStoreIsUtf8 && a_uDataLen >= 3)
{
if (memcmp(a_pData, SI_BOM_UTF8, 3) == 0)
{
a_pData += 3;
a_uDataLen -= 3;
}
}
// determine the length of the converted data
size_t uLen = converter.SizeFromStore(a_pData, a_uDataLen);
if (uLen == (size_t)(-1))
{
return SI_FAIL;
}
// allocate memory for the data, ensure that there is a NULL
// terminator wherever the converted data ends
SI_CHAR *pData = new SI_CHAR[uLen + 1];
if (!pData)
{
return SI_NOMEM;
}
memset(pData, 0, sizeof(SI_CHAR) * (uLen + 1));
// convert the data
if (!converter.ConvertFromStore(a_pData, a_uDataLen, pData, uLen))
{
delete[] pData;
return SI_FAIL;
}
// parse it
const static SI_CHAR empty = 0;
SI_CHAR * pWork = pData;
const SI_CHAR * pSection = ∅
const SI_CHAR * pKey = 0;
const SI_CHAR * pVal = 0;
// add every entry in the file to the data table. We copy the strings if
// we are loading data into this class when we already have stored some
// because we only store a single block.
SI_Error rc;
bool bCopyStrings = (m_pData != 0);
while (FindEntry(pWork, pSection, pKey, pVal))
{
rc = AddEntry(pSection, pKey, pVal, bCopyStrings);
if (rc < 0)
return rc;
}
// store these strings if we didn't copy them
if (bCopyStrings)
{
delete[] pData;
}
else
{
m_pData = pData;
m_uDataLen = uLen + 1;
}
return SI_OK;
}
template <class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
bool CSimpleIniTempl<SI_CHAR, SI_STRLESS, SI_CONVERTER>::FindEntry(
SI_CHAR *& a_pData,
const SI_CHAR *&a_pSection,
const SI_CHAR *&a_pKey,
const SI_CHAR *&a_pVal) const
{
SI_CHAR *pTrail;
while (*a_pData)
{
// skip spaces and empty lines
while (*a_pData && IsSpace(*a_pData))
{
++a_pData;
}
if (!*a_pData)
{
break;
}
// skip comment lines
if (IsComment(*a_pData))
{
while (*a_pData && !IsNewLineChar(*a_pData))
{
++a_pData;
}
continue;
}
// process section names
if (*a_pData == '[')
{
// skip leading spaces
++a_pData;
while (*a_pData && IsSpace(*a_pData))
{
++a_pData;
}
// find the end of the section name (it may contain spaces)
// and convert it to lowercase as necessary
a_pSection = a_pData;
while (*a_pData && *a_pData != ']' && !IsNewLineChar(*a_pData))
{
++a_pData;
}
// if it's an invalid line, just skip it
if (*a_pData != ']')
{
continue;
}
// remove trailing spaces from the section
pTrail = a_pData - 1;
while (pTrail >= a_pSection && IsSpace(*pTrail))
{
--pTrail;
}
++pTrail;
*pTrail = 0;
// skip to the end of the line
++a_pData; // safe as checked that it == ']' above
while (*a_pData && !IsNewLineChar(*a_pData))