/
persistence.cpp
2669 lines (2334 loc) · 76.6 KB
/
persistence.cpp
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
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "precomp.hpp"
#include "persistence.hpp"
#include <unordered_map>
#include <iterator>
namespace cv
{
namespace fs
{
int strcasecmp(const char* s1, const char* s2)
{
const char* dummy="";
if(!s1) s1=dummy;
if(!s2) s2=dummy;
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
size_t i, len = std::min(len1, len2);
for( i = 0; i < len; i++ )
{
int d = tolower((int)s1[i]) - tolower((int)s2[i]);
if( d != 0 )
return d;
}
return len1 < len2 ? -1 : len1 > len2 ? 1 : 0;
}
char* itoa( int _val, char* buffer, int /*radix*/ )
{
const int radix = 10;
char* ptr=buffer + 23 /* enough even for 64-bit integers */;
unsigned val = abs(_val);
*ptr = '\0';
do
{
unsigned r = val / radix;
*--ptr = (char)(val - (r*radix) + '0');
val = r;
}
while( val != 0 );
if( _val < 0 )
*--ptr = '-';
return ptr;
}
char* doubleToString( char* buf, double value, bool explicitZero )
{
Cv64suf val;
unsigned ieee754_hi;
val.f = value;
ieee754_hi = (unsigned)(val.u >> 32);
if( (ieee754_hi & 0x7ff00000) != 0x7ff00000 )
{
int ivalue = cvRound(value);
if( ivalue == value )
{
if( explicitZero )
sprintf( buf, "%d.0", ivalue );
else
sprintf( buf, "%d.", ivalue );
}
else
{
static const char* fmt = "%.16e";
char* ptr = buf;
sprintf( buf, fmt, value );
if( *ptr == '+' || *ptr == '-' )
ptr++;
for( ; cv_isdigit(*ptr); ptr++ )
;
if( *ptr == ',' )
*ptr = '.';
}
}
else
{
unsigned ieee754_lo = (unsigned)val.u;
if( (ieee754_hi & 0x7fffffff) + (ieee754_lo != 0) > 0x7ff00000 )
strcpy( buf, ".Nan" );
else
strcpy( buf, (int)ieee754_hi < 0 ? "-.Inf" : ".Inf" );
}
return buf;
}
char* floatToString( char* buf, float value, bool halfprecision, bool explicitZero )
{
Cv32suf val;
unsigned ieee754;
val.f = value;
ieee754 = val.u;
if( (ieee754 & 0x7f800000) != 0x7f800000 )
{
int ivalue = cvRound(value);
if( ivalue == value )
{
if( explicitZero )
sprintf( buf, "%d.0", ivalue );
else
sprintf( buf, "%d.", ivalue );
}
else
{
char* ptr = buf;
if (halfprecision)
sprintf(buf, "%.4e", value);
else
sprintf(buf, "%.8e", value);
if( *ptr == '+' || *ptr == '-' )
ptr++;
for( ; cv_isdigit(*ptr); ptr++ )
;
if( *ptr == ',' )
*ptr = '.';
}
}
else
{
if( (ieee754 & 0x7fffffff) != 0x7f800000 )
strcpy( buf, ".Nan" );
else
strcpy( buf, (int)ieee754 < 0 ? "-.Inf" : ".Inf" );
}
return buf;
}
static const char symbols[9] = "ucwsifdh";
static char typeSymbol(int depth)
{
CV_StaticAssert(CV_64F == 6, "");
CV_Assert(depth >=0 && depth <= CV_64F);
return symbols[depth];
}
static int symbolToType(char c)
{
const char* pos = strchr( symbols, c );
if( !pos )
CV_Error( CV_StsBadArg, "Invalid data type specification" );
if (c == 'r')
return CV_SEQ_ELTYPE_PTR;
return static_cast<int>(pos - symbols);
}
char* encodeFormat(int elem_type, char* dt)
{
int cn = (elem_type == CV_SEQ_ELTYPE_PTR/*CV_USRTYPE1*/) ? 1 : CV_MAT_CN(elem_type);
char symbol = (elem_type == CV_SEQ_ELTYPE_PTR/*CV_USRTYPE1*/) ? 'r' : typeSymbol(CV_MAT_DEPTH(elem_type));
sprintf(dt, "%d%c", cn, symbol);
return dt + (cn == 1 ? 1 : 0);
}
int decodeFormat( const char* dt, int* fmt_pairs, int max_len )
{
int fmt_pair_count = 0;
int i = 0, k = 0, len = dt ? (int)strlen(dt) : 0;
if( !dt || !len )
return 0;
assert( fmt_pairs != 0 && max_len > 0 );
fmt_pairs[0] = 0;
max_len *= 2;
for( ; k < len; k++ )
{
char c = dt[k];
if( cv_isdigit(c) )
{
int count = c - '0';
if( cv_isdigit(dt[k+1]) )
{
char* endptr = 0;
count = (int)strtol( dt+k, &endptr, 10 );
k = (int)(endptr - dt) - 1;
}
if( count <= 0 )
CV_Error( CV_StsBadArg, "Invalid data type specification" );
fmt_pairs[i] = count;
}
else
{
int depth = symbolToType(c);
if( fmt_pairs[i] == 0 )
fmt_pairs[i] = 1;
fmt_pairs[i+1] = depth;
if( i > 0 && fmt_pairs[i+1] == fmt_pairs[i-1] )
fmt_pairs[i-2] += fmt_pairs[i];
else
{
i += 2;
if( i >= max_len )
CV_Error( CV_StsBadArg, "Too long data type specification" );
}
fmt_pairs[i] = 0;
}
}
fmt_pair_count = i/2;
return fmt_pair_count;
}
int calcElemSize( const char* dt, int initial_size )
{
int size = 0;
int fmt_pairs[CV_FS_MAX_FMT_PAIRS], i, fmt_pair_count;
int comp_size;
fmt_pair_count = decodeFormat( dt, fmt_pairs, CV_FS_MAX_FMT_PAIRS );
fmt_pair_count *= 2;
for( i = 0, size = initial_size; i < fmt_pair_count; i += 2 )
{
comp_size = CV_ELEM_SIZE(fmt_pairs[i+1]);
size = cvAlign( size, comp_size );
size += comp_size * fmt_pairs[i];
}
if( initial_size == 0 )
{
comp_size = CV_ELEM_SIZE(fmt_pairs[1]);
size = cvAlign( size, comp_size );
}
return size;
}
int calcStructSize( const char* dt, int initial_size )
{
int size = calcElemSize( dt, initial_size );
size_t elem_max_size = 0;
for ( const char * type = dt; *type != '\0'; type++ ) {
switch ( *type )
{
case 'u': { elem_max_size = std::max( elem_max_size, sizeof(uchar ) ); break; }
case 'c': { elem_max_size = std::max( elem_max_size, sizeof(schar ) ); break; }
case 'w': { elem_max_size = std::max( elem_max_size, sizeof(ushort) ); break; }
case 's': { elem_max_size = std::max( elem_max_size, sizeof(short ) ); break; }
case 'i': { elem_max_size = std::max( elem_max_size, sizeof(int ) ); break; }
case 'f': { elem_max_size = std::max( elem_max_size, sizeof(float ) ); break; }
case 'd': { elem_max_size = std::max( elem_max_size, sizeof(double) ); break; }
default: break;
}
}
size = cvAlign( size, static_cast<int>(elem_max_size) );
return size;
}
int decodeSimpleFormat( const char* dt )
{
int elem_type = -1;
int fmt_pairs[CV_FS_MAX_FMT_PAIRS], fmt_pair_count;
fmt_pair_count = decodeFormat( dt, fmt_pairs, CV_FS_MAX_FMT_PAIRS );
if( fmt_pair_count != 1 || fmt_pairs[0] >= CV_CN_MAX)
CV_Error( CV_StsError, "Too complex format for the matrix" );
elem_type = CV_MAKETYPE( fmt_pairs[1], fmt_pairs[0] );
return elem_type;
}
}
#if defined __i386__ || defined(_M_IX86) || defined __x86_64__ || defined(_M_X64)
#define CV_UNALIGNED_LITTLE_ENDIAN_MEM_ACCESS 1
#else
#define CV_UNALIGNED_LITTLE_ENDIAN_MEM_ACCESS 0
#endif
static inline int readInt(const uchar* p)
{
#if CV_UNALIGNED_LITTLE_ENDIAN_MEM_ACCESS
return *(const int*)p;
#else
int val = (int)(p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24));
return val;
#endif
}
static inline double readReal(const uchar* p)
{
#if CV_UNALIGNED_LITTLE_ENDIAN_MEM_ACCESS
return *(const double*)p;
#else
unsigned val0 = (unsigned)(p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24));
unsigned val1 = (unsigned)(p[4] | (p[5] << 8) | (p[6] << 16) | (p[7] << 24));
Cv64suf val;
val.u = val0 | ((uint64)val1 << 32);
return val.f;
#endif
}
static inline void writeInt(uchar* p, int ival)
{
#if CV_UNALIGNED_LITTLE_ENDIAN_MEM_ACCESS
int* ip = (int*)p;
*ip = ival;
#else
p[0] = (uchar)ival;
p[1] = (uchar)(ival >> 8);
p[2] = (uchar)(ival >> 16);
p[3] = (uchar)(ival >> 24);
#endif
}
static inline void writeReal(uchar* p, double fval)
{
#if CV_UNALIGNED_LITTLE_ENDIAN_MEM_ACCESS
double* fp = (double*)p;
*fp = fval;
#else
Cv64suf v;
v.f = fval;
p[0] = (uchar)v.u;
p[1] = (uchar)(v.u >> 8);
p[2] = (uchar)(v.u >> 16);
p[3] = (uchar)(v.u >> 24);
p[4] = (uchar)(v.u >> 32);
p[5] = (uchar)(v.u >> 40);
p[6] = (uchar)(v.u >> 48);
p[7] = (uchar)(v.u >> 56);
#endif
}
class FileStorage::Impl : public FileStorage_API
{
public:
void init()
{
flags = 0;
buffer.clear();
bufofs = 0;
state = UNDEFINED;
is_opened = false;
dummy_eof = false;
write_mode = false;
mem_mode = false;
space = 0;
wrap_margin = 71;
fmt = 0;
file = 0;
gzfile = 0;
empty_stream = true;
strbufv.clear();
strbuf = 0;
strbufsize = strbufpos = 0;
roots.clear();
fs_data.clear();
fs_data_ptrs.clear();
fs_data_blksz.clear();
freeSpaceOfs = 0;
str_hash.clear();
str_hash_data.clear();
str_hash_data.resize(1);
str_hash_data[0] = '\0';
filename.clear();
lineno = 0;
}
Impl(FileStorage* _fs)
{
fs_ext = _fs;
init();
}
virtual ~Impl()
{
release();
}
void release(String* out=0)
{
if( is_opened )
{
if(out)
out->clear();
if( write_mode )
{
while( write_stack.size() > 1 )
{
endWriteStruct();
}
flush();
if( fmt == FileStorage::FORMAT_XML )
puts( "</opencv_storage>\n" );
else if ( fmt == FileStorage::FORMAT_JSON )
puts( "}\n" );
}
if( mem_mode && out )
{
*out = cv::String(outbuf.begin(), outbuf.end());
}
}
closeFile();
init();
}
void analyze_file_name( const std::string& file_name, std::vector<std::string>& params )
{
params.clear();
static const char not_file_name = '\n';
static const char parameter_begin = '?';
static const char parameter_separator = '&';
if( file_name.find(not_file_name, (size_t)0) != std::string::npos )
return;
size_t beg = file_name.find_last_of(parameter_begin);
params.push_back(file_name.substr((size_t)0, beg));
if( beg != std::string::npos )
{
size_t end = file_name.size();
beg++;
for( size_t param_beg = beg, param_end = beg;
param_end < end;
param_beg = param_end + 1 )
{
param_end = file_name.find_first_of( parameter_separator, param_beg );
if( (param_end == std::string::npos || param_end != param_beg) && param_beg + 1 < end )
{
params.push_back( file_name.substr( param_beg, param_end - param_beg ) );
}
}
}
}
bool open( const char* filename_or_buf, int _flags, const char* encoding )
{
_flags &= ~FileStorage::BASE64;
bool ok = true;
release();
bool append = (_flags & 3) == FileStorage::APPEND;
mem_mode = (_flags & FileStorage::MEMORY) != 0;
write_mode = (_flags & 3) != 0;
bool isGZ = false;
size_t fnamelen = 0;
std::vector<std::string> params;
//if ( !mem_mode )
{
analyze_file_name( filename_or_buf, params );
if( !params.empty() )
filename = params[0];
/*if( !write_base64 && params.size() >= 2 &&
std::find(params.begin()+1, params.end(), std::string("base64")) != params.end())
write_base64 = (write_mode || append);*/
}
if( filename.size() == 0 && !mem_mode && !write_mode )
CV_Error( CV_StsNullPtr, "NULL or empty filename" );
if( mem_mode && append )
CV_Error( CV_StsBadFlag, "FileStorage::APPEND and FileStorage::MEMORY are not currently compatible" );
flags = _flags;
if( !mem_mode )
{
char* dot_pos = strrchr((char*)filename.c_str(), '.');
char compression = '\0';
if( dot_pos && dot_pos[1] == 'g' && dot_pos[2] == 'z' &&
(dot_pos[3] == '\0' || (cv_isdigit(dot_pos[3]) && dot_pos[4] == '\0')) )
{
if( append )
{
CV_Error(CV_StsNotImplemented, "Appending data to compressed file is not implemented" );
}
isGZ = true;
compression = dot_pos[3];
if( compression )
dot_pos[3] = '\0', fnamelen--;
}
if( !isGZ )
{
file = fopen(filename.c_str(), !write_mode ? "rt" : !append ? "wt" : "a+t" );
if( !file )
return false;
}
else
{
#if USE_ZLIB
char mode[] = { write_mode ? 'w' : 'r', 'b', compression ? compression : '3', '\0' };
gzfile = gzopen(filename.c_str(), mode);
if( !gzfile )
return false;
#else
CV_Error(CV_StsNotImplemented, "There is no compressed file storage support in this configuration");
#endif
}
}
roots.clear();
fs_data.clear();
wrap_margin = 71;
fmt = FileStorage::FORMAT_AUTO;
if( write_mode )
{
fmt = flags & FileStorage::FORMAT_MASK;
if( mem_mode )
outbuf.clear();
if( fmt == FileStorage::FORMAT_AUTO && !filename.empty() )
{
const char* dot_pos = NULL;
const char* dot_pos2 = NULL;
// like strrchr() implementation, but save two last positions simultaneously
for (const char* pos = &filename[0]; pos[0] != 0; pos++)
{
if( pos[0] == '.' )
{
dot_pos2 = dot_pos;
dot_pos = pos;
}
}
if (fs::strcasecmp(dot_pos, ".gz") == 0 && dot_pos2 != NULL)
{
dot_pos = dot_pos2;
}
fmt = (fs::strcasecmp(dot_pos, ".xml") == 0 || fs::strcasecmp(dot_pos, ".xml.gz") == 0 )
? FileStorage::FORMAT_XML
: (fs::strcasecmp(dot_pos, ".json") == 0 || fs::strcasecmp(dot_pos, ".json.gz") == 0)
? FileStorage::FORMAT_JSON
: FileStorage::FORMAT_YAML;
}
else if( fmt == FileStorage::FORMAT_AUTO )
{
fmt = FileStorage::FORMAT_XML;
}
// we use factor=6 for XML (the longest characters (' and ") are encoded with 6 bytes (' and ")
// and factor=4 for YAML ( as we use 4 bytes for non ASCII characters (e.g. \xAB))
int buf_size = CV_FS_MAX_LEN*(fmt == FileStorage::FORMAT_XML ? 6 : 4) + 1024;
if (append)
{
fseek( file, 0, SEEK_END );
if (ftell(file) == 0)
append = false;
}
write_stack.clear();
empty_stream = true;
write_stack.push_back(FStructData("", FileNode::MAP | FileNode::EMPTY, 0));
buffer.reserve(buf_size + 1024);
buffer.resize(buf_size);
bufofs = 0;
if( fmt == FileStorage::FORMAT_XML )
{
size_t file_size = file ? (size_t)ftell(file) : (size_t)0;
if( !append || file_size == 0 )
{
if( encoding && *encoding != '\0' )
{
if( fs::strcasecmp(encoding, "UTF-16" ) == 0 )
{
release();
CV_Error( CV_StsBadArg, "UTF-16 XML encoding is not supported! Use 8-bit encoding\n");
}
CV_Assert( strlen(encoding) < 1000 );
char buf[1100];
sprintf(buf, "<?xml version=\"1.0\" encoding=\"%s\"?>\n", encoding);
puts( buf );
}
else
puts( "<?xml version=\"1.0\"?>\n" );
puts( "<opencv_storage>\n" );
}
else
{
int xml_buf_size = 1 << 10;
char substr[] = "</opencv_storage>";
int last_occurrence = -1;
xml_buf_size = MIN(xml_buf_size, int(file_size));
fseek( file, -xml_buf_size, SEEK_END );
// find the last occurrence of </opencv_storage>
for(;;)
{
int line_offset = (int)ftell( file );
const char* ptr0 = this->gets(xml_buf_size);
const char* ptr = NULL;
if( !ptr0 )
break;
ptr = ptr0;
for(;;)
{
ptr = strstr( ptr, substr );
if( !ptr )
break;
last_occurrence = line_offset + (int)(ptr - ptr0);
ptr += strlen(substr);
}
}
if( last_occurrence < 0 )
{
release();
CV_Error( CV_StsError, "Could not find </opencv_storage> in the end of file.\n" );
}
closeFile();
file = fopen( filename.c_str(), "r+t" );
CV_Assert(file != 0);
fseek( file, last_occurrence, SEEK_SET );
// replace the last "</opencv_storage>" with " <!-- resumed -->", which has the same length
puts( " <!-- resumed -->" );
fseek( file, 0, SEEK_END );
puts( "\n" );
}
emitter = createXMLEmitter(this);
}
else if( fmt == FileStorage::FORMAT_YAML )
{
if( !append)
puts( "%YAML:1.0\n---\n" );
else
puts( "...\n---\n" );
emitter = createYAMLEmitter(this);
}
else
{
CV_Assert( fmt == FileStorage::FORMAT_JSON );
if( !append )
puts( "{\n" );
else
{
bool valid = false;
long roffset = 0;
for ( ;
fseek( file, roffset, SEEK_END ) == 0;
roffset -= 1 )
{
const char end_mark = '}';
if ( fgetc( file ) == end_mark )
{
fseek( file, roffset, SEEK_END );
valid = true;
break;
}
}
if ( valid )
{
closeFile();
file = fopen( filename.c_str(), "r+t" );
CV_Assert(file != 0);
fseek( file, roffset, SEEK_END );
fputs( ",", file );
}
else
{
CV_Error( CV_StsError, "Could not find '}' in the end of file.\n" );
}
}
write_stack.back().indent = 4;
emitter = createJSONEmitter(this);
}
is_opened = true;
}
else
{
const size_t buf_size0 = 40;
buffer.resize(buf_size0);
if( mem_mode )
{
strbuf = (char*)filename_or_buf;
strbufsize = strlen(strbuf);
}
const char* yaml_signature = "%YAML";
const char* json_signature = "{";
const char* xml_signature = "<?xml";
char* buf = this->gets(16);
CV_Assert(buf);
char* bufPtr = cv_skip_BOM(buf);
size_t bufOffset = bufPtr - buf;
if(strncmp( bufPtr, yaml_signature, strlen(yaml_signature) ) == 0)
fmt = FileStorage::FORMAT_YAML;
else if(strncmp( bufPtr, json_signature, strlen(json_signature) ) == 0)
fmt = FileStorage::FORMAT_JSON;
else if(strncmp( bufPtr, xml_signature, strlen(xml_signature) ) == 0)
fmt = FileStorage::FORMAT_XML;
else if(strbufsize == bufOffset)
CV_Error(CV_BADARG_ERR, "Input file is invalid");
else
CV_Error(CV_BADARG_ERR, "Unsupported file storage format");
rewind();
strbufpos = bufOffset;
bufofs = 0;
try
{
char* ptr = bufferStart();
ptr[0] = ptr[1] = ptr[2] = '\0';
FileNode root_nodes(fs_ext, 0, 0);
uchar* rptr = reserveNodeSpace(root_nodes, 9);
*rptr = FileNode::SEQ;
writeInt(rptr + 1, 4);
writeInt(rptr + 5, 0);
roots.clear();
switch (fmt)
{
case FileStorage::FORMAT_XML: parser = createXMLParser(this); break;
case FileStorage::FORMAT_YAML: parser = createYAMLParser(this); break;
case FileStorage::FORMAT_JSON: parser = createJSONParser(this); break;
default: parser = Ptr<FileStorageParser>();
}
if( !parser.empty() )
{
ok = parser->parse(ptr);
if( ok )
{
finalizeCollection(root_nodes);
CV_Assert( !fs_data_ptrs.empty() );
FileNode roots_node(fs_ext, 0, 0);
size_t i, nroots = roots_node.size();
FileNodeIterator it = roots_node.begin();
for( i = 0; i < nroots; i++, ++it )
roots.push_back(*it);
}
}
}
catch(...)
{
is_opened = true;
release();
throw;
}
// release resources that we do not need anymore
closeFile();
is_opened = true;
std::vector<char> tmpbuf;
std::swap(buffer, tmpbuf);
bufofs = 0;
}
return ok;
}
void puts( const char* str )
{
CV_Assert( write_mode );
if( mem_mode )
std::copy(str, str + strlen(str), std::back_inserter(outbuf));
else if( file )
fputs( str, file );
#if USE_ZLIB
else if( gzfile )
gzputs( gzfile, str );
#endif
else
CV_Error( CV_StsError, "The storage is not opened" );
}
char* getsFromFile( char* buf, int count )
{
if( file )
return fgets( buf, count, file );
#if USE_ZLIB
if( gzfile )
return gzgets( gzfile, buf, count );
#endif
CV_Error(CV_StsError, "The storage is not opened");
}
char* gets( size_t maxCount )
{
if( strbuf )
{
size_t i = strbufpos, len = strbufsize;
const char* instr = strbuf;
for( ; i < len; i++ )
{
char c = instr[i];
if( c == '\0' || c == '\n' )
{
if( c == '\n' )
i++;
break;
}
}
size_t count = i - strbufpos;
if( maxCount == 0 || maxCount > count )
maxCount = count;
buffer.resize(std::max(buffer.size(), maxCount + 8));
memcpy(&buffer[0], instr + strbufpos, maxCount);
buffer[maxCount] = '\0';
strbufpos = i;
return maxCount > 0 ? &buffer[0] : 0;
}
const size_t MAX_BLOCK_SIZE = INT_MAX/2; // hopefully, that will be enough
if( maxCount == 0 )
maxCount = MAX_BLOCK_SIZE;
else
CV_Assert(maxCount < MAX_BLOCK_SIZE);
size_t ofs = 0;
for(;;)
{
int count = (int)std::min(buffer.size() - ofs - 16, maxCount);
char* ptr = getsFromFile( &buffer[ofs], count+1 );
if( !ptr )
break;
int delta = (int)strlen(ptr);
ofs += delta;
maxCount -= delta;
if( ptr[delta-1] == '\n' || maxCount == 0 )
break;
if( delta == count )
buffer.resize((size_t)(buffer.size()*1.5));
}
return ofs > 0 ? &buffer[0] : 0;
}
char* gets()
{
char* ptr = this->gets(0);
if( !ptr )
{
ptr = bufferStart(); // FIXIT Why do we need this hack? What is about other parsers JSON/YAML?
*ptr = '\0';
setEof();
return 0;
}
else
{
size_t l = strlen(ptr);
if( l > 0 && ptr[l-1] != '\n' && ptr[l-1] != '\r' && !eof() )
{
ptr[l] = '\n';
ptr[l+1] = '\0';
}
}
lineno++;
return ptr;
}
bool eof()
{
if( dummy_eof )
return true;
if( strbuf )
return strbufpos >= strbufsize;
if( file )
return feof(file) != 0;
#if USE_ZLIB
if( gzfile )
return gzeof(gzfile) != 0;
#endif
return false;
}
void setEof()
{
dummy_eof = true;
}
void closeFile()
{
if( file )
fclose( file );
#if USE_ZLIB
else if( gzfile )
gzclose( gzfile );
#endif
file = 0;
gzfile = 0;
strbuf = 0;
strbufpos = 0;
is_opened = false;
}
void rewind()
{
if( file )
::rewind(file);
#if USE_ZLIB
else if( gzfile )
gzrewind(gzfile);
#endif
strbufpos = 0;
}
char* resizeWriteBuffer( char* ptr, int len )
{
const char* buffer_end = &buffer[0] + buffer.size();
if( ptr + len < buffer_end )
return ptr;
const char* buffer_start = &buffer[0];
int written_len = (int)(ptr - buffer_start);
CV_Assert(written_len <= (int)buffer.size());
int new_size = (int)((buffer_end - buffer_start)*3/2);
new_size = MAX( written_len + len, new_size );
buffer.reserve( new_size + 256 );
buffer.resize( new_size );
bufofs = written_len;
return &buffer[0] + bufofs;
}
char* flush()
{
char* buffer_start = &buffer[0];
char* ptr = buffer_start + bufofs;
if( ptr > buffer_start + space )
{
ptr[0] = '\n';
ptr[1] = '\0';
puts( buffer_start );
bufofs = 0;
}
int indent = write_stack.back().indent;
if( space != indent )
{
memset( buffer_start, ' ', indent );
space = indent;
}
bufofs = space;
ptr = buffer_start + bufofs;
return ptr;
}
void endWriteStruct()
{
CV_Assert( write_mode );
CV_Assert( !write_stack.empty() );
FStructData& current_struct = write_stack.back();
if( fmt == FileStorage::FORMAT_JSON && !FileNode::isFlow(current_struct.flags) && write_stack.size() > 1 )
current_struct.indent = write_stack[write_stack.size() - 2].indent;
emitter->endWriteStruct(current_struct);
write_stack.pop_back();
if( !write_stack.empty() )
write_stack.back().flags &= ~FileNode::EMPTY;
}
void startWriteStruct( const char* key, int struct_flags,
const char* type_name )
{
CV_Assert( write_mode );
struct_flags = (struct_flags & (FileNode::TYPE_MASK|FileNode::FLOW)) | FileNode::EMPTY;
if( !FileNode::isCollection(struct_flags))
CV_Error( CV_StsBadArg,
"Some collection type: FileNode::SEQ or FileNode::MAP must be specified" );
if( type_name && type_name[0] == '\0' )
type_name = 0;
FStructData s = emitter->startWriteStruct( write_stack.back(), key, struct_flags, type_name );
write_stack.push_back(s);
size_t write_stack_size = write_stack.size();