persistence.cpp 80.1 KB
Newer Older
1 2 3
// 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
4

5 6
#include "precomp.hpp"
#include "persistence.hpp"
S
Smirnov Egor 已提交
7 8
#include "persistence_impl.hpp"
#include "persistence_base64_encoding.hpp"
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
#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;
}
V
Vladislav Sovrasov 已提交
35

36
char* itoa( int _val, char* buffer, int /*radix*/ )
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
{
    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;
}

57
char* doubleToString( char* buf, double value, bool explicitZero )
58 59 60 61 62 63 64 65 66 67 68
{
    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 )
69 70 71 72 73 74
        {
            if( explicitZero )
                sprintf( buf, "%d.0", ivalue );
            else
                sprintf( buf, "%d.", ivalue );
        }
75 76
        else
        {
77
            static const char* fmt = "%.16e";
78 79 80 81
            char* ptr = buf;
            sprintf( buf, fmt, value );
            if( *ptr == '+' || *ptr == '-' )
                ptr++;
82
            for( ; cv_isdigit(*ptr); ptr++ )
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
                ;
            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;
}

100
char* floatToString( char* buf, float value, bool halfprecision, bool explicitZero )
101 102 103 104 105 106 107 108 109 110
{
    Cv32suf val;
    unsigned ieee754;
    val.f = value;
    ieee754 = val.u;

    if( (ieee754 & 0x7f800000) != 0x7f800000 )
    {
        int ivalue = cvRound(value);
        if( ivalue == value )
111 112 113 114 115 116
        {
            if( explicitZero )
                sprintf( buf, "%d.0", ivalue );
            else
                sprintf( buf, "%d.", ivalue );
        }
117 118 119
        else
        {
            char* ptr = buf;
120 121 122 123
            if (halfprecision)
                sprintf(buf, "%.4e", value);
            else
                sprintf(buf, "%.8e", value);
124 125
            if( *ptr == '+' || *ptr == '-' )
                ptr++;
126
            for( ; cv_isdigit(*ptr); ptr++ )
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
                ;
            if( *ptr == ',' )
                *ptr = '.';
        }
    }
    else
    {
        if( (ieee754 & 0x7fffffff) != 0x7f800000 )
            strcpy( buf, ".Nan" );
        else
            strcpy( buf, (int)ieee754 < 0 ? "-.Inf" : ".Inf" );
    }

    return buf;
}

143
static const char symbols[9] = "ucwsifdh";
144

145
static char typeSymbol(int depth)
146
{
147
    CV_StaticAssert(CV_64F == 6, "");
148
    CV_CheckDepth(depth, depth >=0 && depth <= CV_16F, "");
149
    return symbols[depth];
150 151
}

152
static int symbolToType(char c)
M
MYLS 已提交
153
{
154 155
    if (c == 'r')
        return CV_SEQ_ELTYPE_PTR;
156 157
    const char* pos = strchr( symbols, c );
    if( !pos )
S
Smirnov Egor 已提交
158
        CV_Error( cv::Error::StsBadArg, "Invalid data type specification" );
159
    return static_cast<int>(pos - symbols);
M
MYLS 已提交
160 161
}

162
char* encodeFormat(int elem_type, char* dt)
M
MYLS 已提交
163
{
164
    int cn = (elem_type == CV_SEQ_ELTYPE_PTR/*CV_USRTYPE1*/) ? 1 : CV_MAT_CN(elem_type);
165
    char symbol = (elem_type == CV_SEQ_ELTYPE_PTR/*CV_USRTYPE1*/) ? 'r' : typeSymbol(CV_MAT_DEPTH(elem_type));
166 167
    sprintf(dt, "%d%c", cn, symbol);
    return dt + (cn == 1 ? 1 : 0);
M
MYLS 已提交
168 169
}

170
int decodeFormat( const char* dt, int* fmt_pairs, int max_len )
171
{
172 173
    int fmt_pair_count = 0;
    int i = 0, k = 0, len = dt ? (int)strlen(dt) : 0;
174

175 176
    if( !dt || !len )
        return 0;
177

178
    CV_Assert( fmt_pairs != 0 && max_len > 0 );
179 180
    fmt_pairs[0] = 0;
    max_len *= 2;
181

182
    for( ; k < len; k++ )
183
    {
184
        char c = dt[k];
185

186 187 188 189
        if( cv_isdigit(c) )
        {
            int count = c - '0';
            if( cv_isdigit(dt[k+1]) )
190
            {
191 192 193
                char* endptr = 0;
                count = (int)strtol( dt+k, &endptr, 10 );
                k = (int)(endptr - dt) - 1;
194
            }
195

196
            if( count <= 0 )
S
Smirnov Egor 已提交
197
                CV_Error( cv::Error::StsBadArg, "Invalid data type specification" );
198

199
            fmt_pairs[i] = count;
200
        }
201
        else
M
MYLS 已提交
202
        {
203
            int depth = symbolToType(c);
204 205 206 207 208 209 210 211 212
            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 )
S
Smirnov Egor 已提交
213
                    CV_Error( cv::Error::StsBadArg, "Too long data type specification" );
M
MYLS 已提交
214
            }
215
            fmt_pairs[i] = 0;
216 217 218
        }
    }

219 220 221
    fmt_pair_count = i/2;
    return fmt_pair_count;
}
222

223
int calcElemSize( const char* dt, int initial_size )
224 225 226 227
{
    int size = 0;
    int fmt_pairs[CV_FS_MAX_FMT_PAIRS], i, fmt_pair_count;
    int comp_size;
228

229
    fmt_pair_count = decodeFormat( dt, fmt_pairs, CV_FS_MAX_FMT_PAIRS );
230 231
    fmt_pair_count *= 2;
    for( i = 0, size = initial_size; i < fmt_pair_count; i += 2 )
232
    {
233 234 235
        comp_size = CV_ELEM_SIZE(fmt_pairs[i+1]);
        size = cvAlign( size, comp_size );
        size += comp_size * fmt_pairs[i];
236
    }
237
    if( initial_size == 0 )
238
    {
239 240 241 242 243
        comp_size = CV_ELEM_SIZE(fmt_pairs[1]);
        size = cvAlign( size, comp_size );
    }
    return size;
}
244 245


246
int calcStructSize( const char* dt, int initial_size )
247
{
248
    int size = calcElemSize( dt, initial_size );
249
    size_t elem_max_size = 0;
250 251 252 253 254 255
    for ( const char * type = dt; *type != '\0'; type++ )
    {
        char v = *type;
        if (v >= '0' && v <= '9')
            continue;  // skip vector size
        switch (v)
256
        {
257 258 259 260 261 262 263
        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; }
264 265 266
        case 'h': { elem_max_size = std::max(elem_max_size, sizeof(float16_t)); break; }
        default:
            CV_Error_(Error::StsNotImplemented, ("Unknown type identifier: '%c' in '%s'", (char)(*type), dt));
267 268
        }
    }
269 270 271
    size = cvAlign( size, static_cast<int>(elem_max_size) );
    return size;
}
272

273
int decodeSimpleFormat( const char* dt )
274 275 276
{
    int elem_type = -1;
    int fmt_pairs[CV_FS_MAX_FMT_PAIRS], fmt_pair_count;
277

278
    fmt_pair_count = decodeFormat( dt, fmt_pairs, CV_FS_MAX_FMT_PAIRS );
279
    if( fmt_pair_count != 1 || fmt_pairs[0] >= CV_CN_MAX)
S
Smirnov Egor 已提交
280
        CV_Error( cv::Error::StsError, "Too complex format for the matrix" );
281

282
    elem_type = CV_MAKETYPE( fmt_pairs[1], fmt_pairs[0] );
283

284 285
    return elem_type;
}
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
}

#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)
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
#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
}



S
Smirnov Egor 已提交
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
void FileStorage::Impl::init() {
    flags = 0;
    buffer.clear();
    bufofs = 0;
    state = UNDEFINED;
    is_using_base64 = false;
    state_of_writing_base64 = FileStorage_API::Base64State::Uncertain;
    is_write_struct_delayed = false;
    delayed_struct_key = nullptr;
    delayed_struct_flags = 0;
    delayed_type_name = nullptr;
    base64_writer = nullptr;
    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;
}
393

S
Smirnov Egor 已提交
394 395 396 397
FileStorage::Impl::Impl(FileStorage *_fs) {
    fs_ext = _fs;
    init();
}
398

S
Smirnov Egor 已提交
399 400 401
FileStorage::Impl::~Impl() {
    release();
}
402

S
Smirnov Egor 已提交
403 404 405 406 407 408 409
void FileStorage::Impl::release(String *out) {
    if (is_opened) {
        if (out)
            out->clear();
        if (write_mode) {
            while (write_stack.size() > 1) {
                endWriteStruct();
410
            }
S
Smirnov Egor 已提交
411 412 413 414 415 416 417 418
            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());
419 420
        }
    }
S
Smirnov Egor 已提交
421 422 423
    closeFile();
    init();
}
424

S
Smirnov Egor 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
void FileStorage::Impl::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));
446 447
            }
        }
M
MYLS 已提交
448
    }
S
Smirnov Egor 已提交
449
}
450

S
Smirnov Egor 已提交
451 452 453
bool FileStorage::Impl::open(const char *filename_or_buf, int _flags, const char *encoding) {
    bool ok = true;
    release();
454

S
Smirnov Egor 已提交
455 456
    bool append = (_flags & 3) == FileStorage::APPEND;
    mem_mode = (_flags & FileStorage::MEMORY) != 0;
457

S
Smirnov Egor 已提交
458 459
    write_mode = (_flags & 3) != 0;
    bool write_base64 = (write_mode || append) && (_flags & FileStorage::BASE64) != 0;
460

S
Smirnov Egor 已提交
461 462
    bool isGZ = false;
    size_t fnamelen = 0;
463

S
Smirnov Egor 已提交
464 465 466 467 468 469
    std::vector<std::string> params;
    //if ( !mem_mode )
    {
        analyze_file_name(filename_or_buf, params);
        if (!params.empty())
            filename = params[0];
470

S
Smirnov Egor 已提交
471 472 473 474
        if (!write_base64 && params.size() >= 2 &&
            std::find(params.begin() + 1, params.end(), std::string("base64")) != params.end())
            write_base64 = (write_mode || append);
    }
475

S
Smirnov Egor 已提交
476 477
    if (filename.size() == 0 && !mem_mode && !write_mode)
        CV_Error(cv::Error::StsNullPtr, "NULL or empty filename");
478

S
Smirnov Egor 已提交
479 480
    if (mem_mode && append)
        CV_Error(cv::Error::StsBadFlag, "FileStorage::APPEND and FileStorage::MEMORY are not currently compatible");
481

S
Smirnov Egor 已提交
482
    flags = _flags;
483

S
Smirnov Egor 已提交
484 485 486
    if (!mem_mode) {
        char *dot_pos = strrchr((char *) filename.c_str(), '.');
        char compression = '\0';
487

S
Smirnov Egor 已提交
488 489 490 491
        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::Error::StsNotImplemented, "Appending data to compressed file is not implemented");
492
            }
S
Smirnov Egor 已提交
493 494 495 496 497
            isGZ = true;
            compression = dot_pos[3];
            if (compression)
                dot_pos[3] = '\0', fnamelen--;
        }
498

S
Smirnov Egor 已提交
499 500 501 502 503
        if (!isGZ) {
            file = fopen(filename.c_str(), !write_mode ? "rt" : !append ? "wt" : "a+t");
            if (!file)
                return false;
        } else {
504
#if USE_ZLIB
S
Smirnov Egor 已提交
505 506 507 508
            char mode[] = {write_mode ? 'w' : 'r', 'b', compression ? compression : '3', '\0'};
            gzfile = gzopen(filename.c_str(), mode);
            if (!gzfile)
                return false;
509
#else
S
Smirnov Egor 已提交
510
            CV_Error(cv::Error::StsNotImplemented, "There is no compressed file storage support in this configuration");
511 512
#endif
        }
S
Smirnov Egor 已提交
513
    }
514

S
Smirnov Egor 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
    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;
534 535
                }
            }
S
Smirnov Egor 已提交
536 537
            if (fs::strcasecmp(dot_pos, ".gz") == 0 && dot_pos2 != NULL) {
                dot_pos = dot_pos2;
538
            }
S
Smirnov Egor 已提交
539 540 541 542 543 544 545 546
            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;
        }
547

S
Smirnov Egor 已提交
548 549 550
        // we use factor=6 for XML (the longest characters (' and ") are encoded with 6 bytes (&apos; and &quot;)
        // 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;
551

S
Smirnov Egor 已提交
552 553 554 555 556
        if (append) {
            fseek(file, 0, SEEK_END);
            if (ftell(file) == 0)
                append = false;
        }
557

S
Smirnov Egor 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
        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;
        is_using_base64 = write_base64;
        state_of_writing_base64 = FileStorage_API::Base64State::Uncertain;

        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::Error::StsBadArg, "UTF-16 XML encoding is not supported! Use 8-bit encoding\n");
574
                    }
S
Smirnov Egor 已提交
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

                    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)
600
                            break;
S
Smirnov Egor 已提交
601 602
                        last_occurrence = line_offset + (int) (ptr - ptr0);
                        ptr += strlen(substr);
603 604
                    }
                }
S
Smirnov Egor 已提交
605 606 607 608 609 610 611 612 613 614 615 616
                if (last_occurrence < 0) {
                    release();
                    CV_Error(cv::Error::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");
617 618
            }

S
Smirnov Egor 已提交
619 620 621 622
            emitter = createXMLEmitter(this);
        } else if (fmt == FileStorage::FORMAT_YAML) {
            if (!append)
                puts("%YAML:1.0\n---\n");
623
            else
S
Smirnov Egor 已提交
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
                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;
642
                    }
S
Smirnov Egor 已提交
643
                }
644

S
Smirnov Egor 已提交
645 646 647 648 649 650 651 652
                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::Error::StsError, "Could not find '}' in the end of file.\n");
653 654
                }
            }
S
Smirnov Egor 已提交
655 656 657 658 659 660 661 662 663 664
            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);
665 666
        }

S
Smirnov Egor 已提交
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
        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::Error::StsBadArg, "Input file is invalid");
        else
            CV_Error(cv::Error::StsBadArg, "Unsupported file storage format");
685

S
Smirnov Egor 已提交
686 687 688
        rewind();
        strbufpos = bufOffset;
        bufofs = 0;
689

S
Smirnov Egor 已提交
690 691 692 693
        try {
            char *ptr = bufferStart();
            ptr[0] = ptr[1] = ptr[2] = '\0';
            FileNode root_nodes(fs_ext, 0, 0);
694

S
Smirnov Egor 已提交
695 696 697 698
            uchar *rptr = reserveNodeSpace(root_nodes, 9);
            *rptr = FileNode::SEQ;
            writeInt(rptr + 1, 4);
            writeInt(rptr + 5, 0);
699

S
Smirnov Egor 已提交
700
            roots.clear();
701

S
Smirnov Egor 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714
            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>();
            }
715

S
Smirnov Egor 已提交
716 717 718 719
            if (!parser.empty()) {
                ok = parser->parse(ptr);
                if (ok) {
                    finalizeCollection(root_nodes);
720

S
Smirnov Egor 已提交
721 722 723 724
                    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();
725

S
Smirnov Egor 已提交
726 727
                    for (i = 0; i < nroots; i++, ++it)
                        roots.push_back(*it);
728 729
                }
            }
S
Smirnov Egor 已提交
730 731
        }
        catch (...) {
732
            is_opened = true;
S
Smirnov Egor 已提交
733 734
            release();
            throw;
735
        }
S
Smirnov Egor 已提交
736 737 738 739 740 741 742

        // release resources that we do not need anymore
        closeFile();
        is_opened = true;
        std::vector<char> tmpbuf;
        std::swap(buffer, tmpbuf);
        bufofs = 0;
743
    }
S
Smirnov Egor 已提交
744 745
    return ok;
}
746

S
Smirnov Egor 已提交
747 748 749 750 751 752
void FileStorage::Impl::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);
753
#if USE_ZLIB
S
Smirnov Egor 已提交
754 755
    else if (gzfile)
        gzputs(gzfile, str);
756
#endif
S
Smirnov Egor 已提交
757 758 759
    else
        CV_Error(cv::Error::StsError, "The storage is not opened");
}
760

S
Smirnov Egor 已提交
761 762 763 764 765 766 767 768 769
char *FileStorage::Impl::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::Error::StsError, "The storage is not opened");
}
770

S
Smirnov Egor 已提交
771 772 773 774 775 776 777 778 779 780
char *FileStorage::Impl::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;
781 782
            }
        }
S
Smirnov Egor 已提交
783 784 785 786 787 788 789 790 791
        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;
    }
792

S
Smirnov Egor 已提交
793 794 795 796 797 798
    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;
799

S
Smirnov Egor 已提交
800 801 802 803 804 805 806 807 808 809 810 811
    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));
812
    }
S
Smirnov Egor 已提交
813 814
    return ofs > 0 ? &buffer[0] : 0;
}
815

S
Smirnov Egor 已提交
816 817 818 819 820 821 822 823 824 825 826 827
char *FileStorage::Impl::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';
828 829
        }
    }
S
Smirnov Egor 已提交
830 831 832
    lineno++;
    return ptr;
}
833

S
Smirnov Egor 已提交
834 835 836 837 838 839 840
bool FileStorage::Impl::eof() {
    if (dummy_eof)
        return true;
    if (strbuf)
        return strbufpos >= strbufsize;
    if (file)
        return feof(file) != 0;
841
#if USE_ZLIB
S
Smirnov Egor 已提交
842 843
    if (gzfile)
        return gzeof(gzfile) != 0;
844
#endif
S
Smirnov Egor 已提交
845 846
    return false;
}
847

S
Smirnov Egor 已提交
848 849 850
void FileStorage::Impl::setEof() {
    dummy_eof = true;
}
851

S
Smirnov Egor 已提交
852 853 854
void FileStorage::Impl::closeFile() {
    if (file)
        fclose(file);
855
#if USE_ZLIB
S
Smirnov Egor 已提交
856 857
    else if (gzfile)
        gzclose(gzfile);
858
#endif
S
Smirnov Egor 已提交
859 860 861 862 863 864
    file = 0;
    gzfile = 0;
    strbuf = 0;
    strbufpos = 0;
    is_opened = false;
}
865

S
Smirnov Egor 已提交
866 867 868
void FileStorage::Impl::rewind() {
    if (file)
        ::rewind(file);
869
#if USE_ZLIB
S
Smirnov Egor 已提交
870 871
    else if (gzfile)
        gzrewind(gzfile);
872
#endif
S
Smirnov Egor 已提交
873 874
    strbufpos = 0;
}
875

S
Smirnov Egor 已提交
876 877 878 879
char *FileStorage::Impl::resizeWriteBuffer(char *ptr, int len) {
    const char *buffer_end = &buffer[0] + buffer.size();
    if (ptr + len < buffer_end)
        return ptr;
880

S
Smirnov Egor 已提交
881 882
    const char *buffer_start = &buffer[0];
    int written_len = (int) (ptr - buffer_start);
883

S
Smirnov Egor 已提交
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
    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 *FileStorage::Impl::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;
902 903
    }

S
Smirnov Egor 已提交
904
    int indent = write_stack.back().indent;
905

S
Smirnov Egor 已提交
906 907 908 909 910 911
    if (space != indent) {
        memset(buffer_start, ' ', indent);
        space = indent;
    }
    bufofs = space;
    ptr = buffer_start + bufofs;
912

S
Smirnov Egor 已提交
913 914
    return ptr;
}
915

S
Smirnov Egor 已提交
916 917
void FileStorage::Impl::endWriteStruct() {
    CV_Assert(write_mode);
918

S
Smirnov Egor 已提交
919 920 921
    check_if_write_struct_is_delayed(false);
    if (state_of_writing_base64 != FileStorage_API::Uncertain)
        switch_to_Base64_state(FileStorage_API::Uncertain);
922

S
Smirnov Egor 已提交
923
    CV_Assert(!write_stack.empty());
924

S
Smirnov Egor 已提交
925 926 927
    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;
928

S
Smirnov Egor 已提交
929
    emitter->endWriteStruct(current_struct);
930

S
Smirnov Egor 已提交
931 932 933 934
    write_stack.pop_back();
    if (!write_stack.empty())
        write_stack.back().flags &= ~FileNode::EMPTY;
}
935

S
Smirnov Egor 已提交
936 937 938
void FileStorage::Impl::startWriteStruct_helper(const char *key, int struct_flags,
                                                const char *type_name) {
    CV_Assert(write_mode);
939

S
Smirnov Egor 已提交
940 941 942 943
    struct_flags = (struct_flags & (FileNode::TYPE_MASK | FileNode::FLOW)) | FileNode::EMPTY;
    if (!FileNode::isCollection(struct_flags))
        CV_Error(cv::Error::StsBadArg,
                 "Some collection type: FileNode::SEQ or FileNode::MAP must be specified");
944

S
Smirnov Egor 已提交
945 946
    if (type_name && type_name[0] == '\0')
        type_name = 0;
947

S
Smirnov Egor 已提交
948
    FStructData s = emitter->startWriteStruct(write_stack.back(), key, struct_flags, type_name);
949

S
Smirnov Egor 已提交
950 951 952 953
    write_stack.push_back(s);
    size_t write_stack_size = write_stack.size();
    if (write_stack_size > 1)
        write_stack[write_stack_size - 2].flags &= ~FileNode::EMPTY;
954

S
Smirnov Egor 已提交
955 956
    if (fmt != FileStorage::FORMAT_JSON && !FileNode::isFlow(s.flags))
        flush();
957

S
Smirnov Egor 已提交
958 959
    if (fmt == FileStorage::FORMAT_JSON && type_name && type_name[0] && FileNode::isMap(struct_flags)) {
        emitter->write("type_id", type_name, false);
960
    }
S
Smirnov Egor 已提交
961
}
962

S
Smirnov Egor 已提交
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
void FileStorage::Impl::startWriteStruct(const char *key, int struct_flags,
                                         const char *type_name) {
    check_if_write_struct_is_delayed(false);
    if (state_of_writing_base64 == FileStorage_API::NotUse)
        switch_to_Base64_state(FileStorage_API::Uncertain);

    if (state_of_writing_base64 == FileStorage_API::Uncertain && FileNode::isSeq(struct_flags)
        && is_using_base64 && type_name == 0) {
        /* Uncertain whether output Base64 data */
        make_write_struct_delayed(key, struct_flags, type_name);
    } else if (type_name && memcmp(type_name, "binary", 6) == 0) {
        /* Must output Base64 data */
        if ((FileNode::TYPE_MASK & struct_flags) != FileNode::SEQ)
            CV_Error(cv::Error::StsBadArg, "must set 'struct_flags |= CV_NODE_SEQ' if using Base64.");
        else if (state_of_writing_base64 != FileStorage_API::Uncertain)
            CV_Error(cv::Error::StsError, "function \'cvStartWriteStruct\' calls cannot be nested if using Base64.");

        startWriteStruct_helper(key, struct_flags, "binary");

        if (state_of_writing_base64 != FileStorage_API::Uncertain)
            switch_to_Base64_state(FileStorage_API::Uncertain);
        switch_to_Base64_state(FileStorage_API::InUse);
    } else {
        /* Won't output Base64 data */
        if (state_of_writing_base64 == FileStorage_API::InUse)
            CV_Error(cv::Error::StsError, "At the end of the output Base64, `cvEndWriteStruct` is needed.");

        startWriteStruct_helper(key, struct_flags, type_name);

        if (state_of_writing_base64 != FileStorage_API::Uncertain)
            switch_to_Base64_state(FileStorage_API::Uncertain);
        switch_to_Base64_state(FileStorage_API::NotUse);
995
    }
S
Smirnov Egor 已提交
996
}
997

S
Smirnov Egor 已提交
998 999 1000 1001
void FileStorage::Impl::writeComment(const char *comment, bool eol_comment) {
    CV_Assert(write_mode);
    emitter->writeComment(comment, eol_comment);
}
1002

S
Smirnov Egor 已提交
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
void FileStorage::Impl::startNextStream() {
    CV_Assert(write_mode);
    if (!empty_stream) {
        while (!write_stack.empty())
            endWriteStruct();
        flush();
        emitter->startNextStream();
        empty_stream = true;
        write_stack.push_back(FStructData("", FileNode::EMPTY, 0));
        bufofs = 0;
1013
    }
S
Smirnov Egor 已提交
1014
}
1015

S
Smirnov Egor 已提交
1016 1017 1018 1019
void FileStorage::Impl::write(const String &key, int value) {
    CV_Assert(write_mode);
    emitter->write(key.c_str(), value);
}
1020

S
Smirnov Egor 已提交
1021 1022 1023 1024
void FileStorage::Impl::write(const String &key, double value) {
    CV_Assert(write_mode);
    emitter->write(key.c_str(), value);
}
1025

S
Smirnov Egor 已提交
1026 1027 1028 1029
void FileStorage::Impl::write(const String &key, const String &value) {
    CV_Assert(write_mode);
    emitter->write(key.c_str(), value.c_str(), false);
}
1030

S
Smirnov Egor 已提交
1031 1032
void FileStorage::Impl::writeRawData(const std::string &dt, const void *_data, size_t len) {
    CV_Assert(write_mode);
1033

S
Smirnov Egor 已提交
1034 1035 1036 1037 1038 1039
    if (is_using_base64 || state_of_writing_base64 == FileStorage_API::Base64State::InUse) {
        writeRawDataBase64(_data, len, dt.c_str());
        return;
    } else if (state_of_writing_base64 == FileStorage_API::Base64State::Uncertain) {
        switch_to_Base64_state(FileStorage_API::Base64State::NotUse);
    }
1040

S
Smirnov Egor 已提交
1041 1042 1043 1044
    size_t elemSize = fs::calcStructSize(dt.c_str(), 0);
    CV_Assert(elemSize);
    CV_Assert(len % elemSize == 0);
    len /= elemSize;
1045

S
Smirnov Egor 已提交
1046 1047 1048 1049
    bool explicitZero = fmt == FileStorage::FORMAT_JSON;
    const uchar *data0 = (const uchar *) _data;
    int fmt_pairs[CV_FS_MAX_FMT_PAIRS * 2], k, fmt_pair_count;
    char buf[256] = "";
1050

S
Smirnov Egor 已提交
1051
    fmt_pair_count = fs::decodeFormat(dt.c_str(), fmt_pairs, CV_FS_MAX_FMT_PAIRS);
1052

S
Smirnov Egor 已提交
1053 1054
    if (!len)
        return;
1055

S
Smirnov Egor 已提交
1056 1057
    if (!data0)
        CV_Error(cv::Error::StsNullPtr, "Null data pointer");
1058

S
Smirnov Egor 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    if (fmt_pair_count == 1) {
        fmt_pairs[0] *= (int) len;
        len = 1;
    }

    for (; len--; data0 += elemSize) {
        int offset = 0;
        for (k = 0; k < fmt_pair_count; k++) {
            int i, count = fmt_pairs[k * 2];
            int elem_type = fmt_pairs[k * 2 + 1];
            int elem_size = CV_ELEM_SIZE(elem_type);
            const char *ptr;

            offset = cvAlign(offset, elem_size);
            const uchar *data = data0 + offset;

            for (i = 0; i < count; i++) {
                switch (elem_type) {
1077
                    case CV_8U:
S
Smirnov Egor 已提交
1078
                        ptr = fs::itoa(*(uchar *) data, buf, 10);
1079 1080 1081
                        data++;
                        break;
                    case CV_8S:
S
Smirnov Egor 已提交
1082
                        ptr = fs::itoa(*(char *) data, buf, 10);
1083 1084 1085
                        data++;
                        break;
                    case CV_16U:
S
Smirnov Egor 已提交
1086
                        ptr = fs::itoa(*(ushort *) data, buf, 10);
1087 1088 1089
                        data += sizeof(ushort);
                        break;
                    case CV_16S:
S
Smirnov Egor 已提交
1090
                        ptr = fs::itoa(*(short *) data, buf, 10);
1091 1092 1093
                        data += sizeof(short);
                        break;
                    case CV_32S:
S
Smirnov Egor 已提交
1094
                        ptr = fs::itoa(*(int *) data, buf, 10);
1095 1096 1097
                        data += sizeof(int);
                        break;
                    case CV_32F:
S
Smirnov Egor 已提交
1098
                        ptr = fs::floatToString(buf, *(float *) data, false, explicitZero);
1099 1100 1101
                        data += sizeof(float);
                        break;
                    case CV_64F:
S
Smirnov Egor 已提交
1102
                        ptr = fs::doubleToString(buf, *(double *) data, explicitZero);
1103 1104 1105
                        data += sizeof(double);
                        break;
                    case CV_16F: /* reference */
S
Smirnov Egor 已提交
1106
                        ptr = fs::floatToString(buf, (float) *(float16_t *) data, true, explicitZero);
1107 1108 1109
                        data += sizeof(float16_t);
                        break;
                    default:
S
Smirnov Egor 已提交
1110
                        CV_Error(cv::Error::StsUnsupportedFormat, "Unsupported type");
1111 1112 1113
                        return;
                }

S
Smirnov Egor 已提交
1114
                emitter->writeScalar(0, ptr);
1115
            }
S
Smirnov Egor 已提交
1116 1117

            offset = (int) (data - data0);
1118 1119
        }
    }
S
Smirnov Egor 已提交
1120
}
1121

S
Smirnov Egor 已提交
1122 1123
void FileStorage::Impl::workaround() {
    check_if_write_struct_is_delayed(false);
1124

S
Smirnov Egor 已提交
1125 1126 1127
    if (state_of_writing_base64 != FileStorage_API::Base64State::Uncertain)
        switch_to_Base64_state(FileStorage_API::Base64State::Uncertain);
}
1128

S
Smirnov Egor 已提交
1129 1130 1131
void FileStorage::Impl::switch_to_Base64_state(FileStorage_API::Base64State new_state) {
    const char *err_unkonwn_state = "Unexpected error, unable to determine the Base64 state.";
    const char *err_unable_to_switch = "Unexpected error, unable to switch to this state.";
1132

S
Smirnov Egor 已提交
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
    /* like a finite state machine */
    switch (state_of_writing_base64) {
        case FileStorage_API::Base64State::Uncertain:
            switch (new_state) {
                case FileStorage_API::Base64State::InUse:
                {
                    CV_DbgAssert(base64_writer == 0);
                    bool can_indent = (fmt != cv::FileStorage::Mode::FORMAT_JSON);
                    base64_writer = new base64::Base64Writer(*this, can_indent);
                    if (!can_indent) {
                        char *ptr = bufferPtr();
                        *ptr++ = '\0';
                        puts(bufferStart());
                        setBufferPtr(bufferStart());
                        memset(bufferStart(), 0, static_cast<int>(space));
                        puts("\"$base64$");
                    }
                    break;
                }
                case FileStorage_API::Base64State::Uncertain:
                    break;
                case FileStorage_API::Base64State::NotUse:
                    break;
                default:
                    CV_Error(cv::Error::StsError, err_unkonwn_state);
                    break;
            }
            break;
        case FileStorage_API::Base64State::InUse:
            switch (new_state) {
                case FileStorage_API::Base64State::InUse:
                case FileStorage_API::Base64State::NotUse:
                    CV_Error(cv::Error::StsError, err_unable_to_switch);
                    break;
                case FileStorage_API::Base64State::Uncertain:
                    delete base64_writer;
                    base64_writer = 0;
                    if ( fmt == cv::FileStorage::FORMAT_JSON )
                    {
                        puts("\"");
                        setBufferPtr(bufferStart());
                        flush();
                        memset(bufferStart(), 0, static_cast<int>(space) );
                        setBufferPtr(bufferStart());
                    }
                    break;
                default:
                    CV_Error(cv::Error::StsError, err_unkonwn_state);
                    break;
            }
            break;
        case FileStorage_API::Base64State::NotUse:
            switch (new_state) {
                case FileStorage_API::Base64State::InUse:
                case FileStorage_API::Base64State::NotUse:
                    CV_Error(cv::Error::StsError, err_unable_to_switch);
                    break;
                case FileStorage_API::Base64State::Uncertain:
                    break;
                default:
                    CV_Error(cv::Error::StsError, err_unkonwn_state);
                    break;
            }
            break;
        default:
            CV_Error(cv::Error::StsError, err_unkonwn_state);
            break;
1200 1201
    }

S
Smirnov Egor 已提交
1202 1203
    state_of_writing_base64 = new_state;
}
1204

S
Smirnov Egor 已提交
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
void FileStorage::Impl::make_write_struct_delayed(const char *key, int struct_flags, const char *type_name) {
    CV_Assert(is_write_struct_delayed == false);
    CV_DbgAssert(delayed_struct_key == nullptr);
    CV_DbgAssert(delayed_struct_flags == 0);
    CV_DbgAssert(delayed_type_name == nullptr);

    delayed_struct_flags = struct_flags;

    if (key != nullptr) {
        delayed_struct_key = new char[strlen(key) + 1U];
        strcpy(delayed_struct_key, key);
1216 1217
    }

S
Smirnov Egor 已提交
1218 1219 1220
    if (type_name != nullptr) {
        delayed_type_name = new char[strlen(type_name) + 1U];
        strcpy(delayed_type_name, type_name);
1221 1222
    }

S
Smirnov Egor 已提交
1223 1224
    is_write_struct_delayed = true;
}
1225

S
Smirnov Egor 已提交
1226 1227 1228 1229 1230 1231
void FileStorage::Impl::check_if_write_struct_is_delayed(bool change_type_to_base64) {
    if (is_write_struct_delayed) {
        /* save data to prevent recursive call errors */
        std::string struct_key;
        std::string type_name;
        int struct_flags = delayed_struct_flags;
1232

S
Smirnov Egor 已提交
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
        if (delayed_struct_key != nullptr && *delayed_struct_key != '\0') {
            struct_key.assign(delayed_struct_key);
        }
        if (delayed_type_name != nullptr && *delayed_type_name != '\0') {
            type_name.assign(delayed_type_name);
        }

        /* reset */
        delete[] delayed_struct_key;
        delete[] delayed_type_name;
        delayed_struct_key = nullptr;
        delayed_struct_flags = 0;
        delayed_type_name = nullptr;

        is_write_struct_delayed = false;

        /* call */
        if (change_type_to_base64) {
            startWriteStruct_helper(struct_key.c_str(), struct_flags, "binary");
            if (state_of_writing_base64 != FileStorage_API::Uncertain)
                switch_to_Base64_state(FileStorage_API::Uncertain);
            switch_to_Base64_state(FileStorage_API::InUse);
        } else {
            startWriteStruct_helper(struct_key.c_str(), struct_flags, type_name.c_str());
            if (state_of_writing_base64 != FileStorage_API::Uncertain)
                switch_to_Base64_state(FileStorage_API::Uncertain);
            switch_to_Base64_state(FileStorage_API::NotUse);
        }
1261
    }
S
Smirnov Egor 已提交
1262
}
1263

S
Smirnov Egor 已提交
1264 1265 1266 1267 1268 1269 1270 1271 1272
void FileStorage::Impl::writeRawDataBase64(const void *_data, size_t len, const char *dt) {
    CV_Assert(write_mode);

    check_if_write_struct_is_delayed(true);

    if (state_of_writing_base64 == FileStorage_API::Base64State::Uncertain) {
        switch_to_Base64_state(FileStorage_API::Base64State::InUse);
    } else if (state_of_writing_base64 != FileStorage_API::Base64State::InUse) {
        CV_Error(cv::Error::StsError, "Base64 should not be used at present.");
1273 1274
    }

S
Smirnov Egor 已提交
1275 1276
    base64_writer->write(_data, len, dt);
}
1277

S
Smirnov Egor 已提交
1278 1279 1280
FileNode FileStorage::Impl::getFirstTopLevelNode() const {
    return roots.empty() ? FileNode() : roots[0];
}
1281

S
Smirnov Egor 已提交
1282 1283 1284
FileNode FileStorage::Impl::root(int streamIdx) const {
    return streamIdx >= 0 && streamIdx < (int) roots.size() ? roots[streamIdx] : FileNode();
}
1285

S
Smirnov Egor 已提交
1286 1287 1288
FileNode FileStorage::Impl::operator[](const String &nodename) const {
    return this->operator[](nodename.c_str());
}
1289

S
Smirnov Egor 已提交
1290 1291 1292
FileNode FileStorage::Impl::operator[](const char * /*nodename*/) const {
    return FileNode();
}
1293

S
Smirnov Egor 已提交
1294
int FileStorage::Impl::getFormat() const { return fmt; }
1295

S
Smirnov Egor 已提交
1296
char *FileStorage::Impl::bufferPtr() const { return (char *) (&buffer[0] + bufofs); }
1297

S
Smirnov Egor 已提交
1298
char *FileStorage::Impl::bufferStart() const { return (char *) &buffer[0]; }
1299

S
Smirnov Egor 已提交
1300
char *FileStorage::Impl::bufferEnd() const { return (char *) (&buffer[0] + buffer.size()); }
1301

S
Smirnov Egor 已提交
1302 1303 1304 1305 1306
void FileStorage::Impl::setBufferPtr(char *ptr) {
    char *bufferstart = bufferStart();
    CV_Assert(ptr >= bufferstart && ptr <= bufferEnd());
    bufofs = ptr - bufferstart;
}
1307

S
Smirnov Egor 已提交
1308
int FileStorage::Impl::wrapMargin() const { return wrap_margin; }
1309

S
Smirnov Egor 已提交
1310 1311 1312 1313
FStructData &FileStorage::Impl::getCurrentStruct() {
    CV_Assert(!write_stack.empty());
    return write_stack.back();
}
1314

S
Smirnov Egor 已提交
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
void FileStorage::Impl::setNonEmpty() {
    empty_stream = false;
}

void FileStorage::Impl::processSpecialDouble(char *buf, double *value, char **endptr) {
    FileStorage_API *fs = this;
    char c = buf[0];
    int inf_hi = 0x7ff00000;

    if (c == '-' || c == '+') {
        inf_hi = c == '-' ? 0xfff00000 : 0x7ff00000;
        c = *++buf;
1327 1328
    }

S
Smirnov Egor 已提交
1329 1330
    if (c != '.')
        CV_PARSE_ERROR_CPP("Bad format of floating-point constant");
1331

S
Smirnov Egor 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    Cv64suf v;
    v.f = 0.;
    if (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'N' && toupper(buf[3]) == 'F')
        v.u = (uint64) inf_hi << 32;
    else if (toupper(buf[1]) == 'N' && toupper(buf[2]) == 'A' && toupper(buf[3]) == 'N')
        v.u = (uint64) -1;
    else
        CV_PARSE_ERROR_CPP("Bad format of floating-point constant");
    *value = v.f;
    *endptr = buf + 4;
}
1343

S
Smirnov Egor 已提交
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
double FileStorage::Impl::strtod(char *ptr, char **endptr) {
    double fval = ::strtod(ptr, endptr);
    if (**endptr == '.') {
        char *dot_pos = *endptr;
        *dot_pos = ',';
        double fval2 = ::strtod(ptr, endptr);
        *dot_pos = '.';
        if (*endptr > dot_pos)
            fval = fval2;
        else
            *endptr = dot_pos;
    }
1356

S
Smirnov Egor 已提交
1357 1358
    if (*endptr == ptr || cv_isalpha(**endptr))
        processSpecialDouble(ptr, &fval, endptr);
1359

S
Smirnov Egor 已提交
1360 1361
    return fval;
}
1362

S
Smirnov Egor 已提交
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
void FileStorage::Impl::convertToCollection(int type, FileNode &node) {
    CV_Assert(type == FileNode::SEQ || type == FileNode::MAP);

    int node_type = node.type();
    if (node_type == type)
        return;

    bool named = node.isNamed();
    uchar *ptr = node.ptr() + 1 + (named ? 4 : 0);

    int ival = 0;
    double fval = 0;
    std::string sval;
    bool add_first_scalar = false;

    if (node_type != FileNode::NONE) {
        // scalar nodes can only be converted to sequences, e.g. in XML:
        // <a>5[parser_position]... => create 5 with name "a"
        // <a>5 6[parser_position]... => 5 is converted to [5] and then 6 is added to it
        //
        // otherwise we don't know where to get the element names from
        CV_Assert(type == FileNode::SEQ);
        if (node_type == FileNode::INT) {
            ival = readInt(ptr);
            add_first_scalar = true;
        } else if (node_type == FileNode::REAL) {
            fval = readReal(ptr);
            add_first_scalar = true;
        } else if (node_type == FileNode::STRING) {
            sval = std::string(node);
            add_first_scalar = true;
        } else
            CV_Error_(Error::StsError, ("The node of type %d cannot be converted to collection", node_type));
    }

    ptr = reserveNodeSpace(node, 1 + (named ? 4 : 0) + 4 + 4);
    *ptr++ = (uchar) (type | (named ? FileNode::NAMED : 0));
    // name has been copied automatically
    if (named)
        ptr += 4;
    // set raw_size(collection)==4, nelems(collection)==1
    writeInt(ptr, 4);
    writeInt(ptr + 4, 0);

    if (add_first_scalar)
        addNode(node, std::string(), node_type,
                node_type == FileNode::INT ? (const void *) &ival :
                node_type == FileNode::REAL ? (const void *) &fval :
                node_type == FileNode::STRING ? (const void *) sval.c_str() : 0,
                -1);
}

// a) allocates new FileNode (for that just set blockIdx to the last block and ofs to freeSpaceOfs) or
// b) reallocates just created new node (blockIdx and ofs must be taken from FileNode).
//    If there is no enough space in the current block (it should be the last block added so far),
//    the last block is shrunk so that it ends immediately before the reallocated node. Then,
//    a new block of sufficient size is allocated and the FileNode is placed in the beginning of it.
// The case (a) can be used to allocate the very first node by setting blockIdx == ofs == 0.
// In the case (b) the existing tag and the name are copied automatically.
uchar *FileStorage::Impl::reserveNodeSpace(FileNode &node, size_t sz) {
    bool shrinkBlock = false;
    size_t shrinkBlockIdx = 0, shrinkSize = 0;

    uchar *ptr = 0, *blockEnd = 0;

    if (!fs_data_ptrs.empty()) {
        size_t blockIdx = node.blockIdx;
        size_t ofs = node.ofs;
        CV_Assert(blockIdx == fs_data_ptrs.size() - 1);
        CV_Assert(ofs <= fs_data_blksz[blockIdx]);
        CV_Assert(freeSpaceOfs <= fs_data_blksz[blockIdx]);
        //CV_Assert( freeSpaceOfs <= ofs + sz );

        ptr = fs_data_ptrs[blockIdx] + ofs;
        blockEnd = fs_data_ptrs[blockIdx] + fs_data_blksz[blockIdx];

        CV_Assert(ptr >= fs_data_ptrs[blockIdx] && ptr <= blockEnd);
        if (ptr + sz <= blockEnd) {
            freeSpaceOfs = ofs + sz;
            return ptr;
1443 1444
        }

S
Smirnov Egor 已提交
1445 1446
        if (ofs ==
            0)  // FileNode is a first component of this block. Resize current block instead of allocation of new one.
1447
        {
S
Smirnov Egor 已提交
1448 1449 1450 1451 1452 1453
            fs_data[blockIdx]->resize(sz);
            ptr = &fs_data[blockIdx]->at(0);
            fs_data_ptrs[blockIdx] = ptr;
            fs_data_blksz[blockIdx] = sz;
            freeSpaceOfs = sz;
            return ptr;
1454 1455
        }

S
Smirnov Egor 已提交
1456 1457 1458
        shrinkBlock = true;
        shrinkBlockIdx = blockIdx;
        shrinkSize = ofs;
1459 1460
    }

S
Smirnov Egor 已提交
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
    size_t blockSize = std::max((size_t) CV_FS_MAX_LEN * 4 - 256, sz) + 256;
    Ptr<std::vector<uchar> > pv = makePtr<std::vector<uchar> >(blockSize);
    fs_data.push_back(pv);
    uchar *new_ptr = &pv->at(0);
    fs_data_ptrs.push_back(new_ptr);
    fs_data_blksz.push_back(blockSize);
    node.blockIdx = fs_data_ptrs.size() - 1;
    node.ofs = 0;
    freeSpaceOfs = sz;

    if (ptr && ptr + 5 <= blockEnd) {
        new_ptr[0] = ptr[0];
        if (ptr[0] & FileNode::NAMED) {
            new_ptr[1] = ptr[1];
            new_ptr[2] = ptr[2];
            new_ptr[3] = ptr[3];
            new_ptr[4] = ptr[4];
        }
1479 1480
    }

S
Smirnov Egor 已提交
1481 1482 1483 1484
    if (shrinkBlock) {
        fs_data[shrinkBlockIdx]->resize(shrinkSize);
        fs_data_blksz[shrinkBlockIdx] = shrinkSize;
    }
1485

S
Smirnov Egor 已提交
1486 1487
    return new_ptr;
}
1488

S
Smirnov Egor 已提交
1489 1490 1491 1492
unsigned FileStorage::Impl::getStringOfs(const std::string &key) const {
    str_hash_t::const_iterator it = str_hash.find(key);
    return it != str_hash.end() ? it->second : 0;
}
1493

S
Smirnov Egor 已提交
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
FileNode FileStorage::Impl::addNode(FileNode &collection, const std::string &key,
                                    int elem_type, const void *value, int len) {
    FileStorage_API *fs = this;
    bool noname = key.empty() || (fmt == FileStorage::FORMAT_XML && strcmp(key.c_str(), "_") == 0);
    convertToCollection(noname ? FileNode::SEQ : FileNode::MAP, collection);

    bool isseq = collection.empty() ? false : collection.isSeq();
    if (noname != isseq)
        CV_PARSE_ERROR_CPP(noname ? "Map element should have a name" :
                           "Sequence element should not have name (use <_></_>)");
    unsigned strofs = 0;
    if (!noname) {
        strofs = getStringOfs(key);
        if (!strofs) {
            strofs = (unsigned) str_hash_data.size();
            size_t keysize = key.size() + 1;
            str_hash_data.resize(strofs + keysize);
            memcpy(&str_hash_data[0] + strofs, &key[0], keysize);
            str_hash.insert(std::make_pair(key, strofs));
        }
    }
1515

S
Smirnov Egor 已提交
1516
    uchar *cp = collection.ptr();
1517

S
Smirnov Egor 已提交
1518 1519 1520
    size_t blockIdx = fs_data_ptrs.size() - 1;
    size_t ofs = freeSpaceOfs;
    FileNode node(fs_ext, blockIdx, ofs);
1521

S
Smirnov Egor 已提交
1522 1523
    size_t sz0 = 1 + (noname ? 0 : 4) + 8;
    uchar *ptr = reserveNodeSpace(node, sz0);
1524

S
Smirnov Egor 已提交
1525 1526 1527
    *ptr++ = (uchar) (elem_type | (noname ? 0 : FileNode::NAMED));
    if (elem_type == FileNode::NONE)
        freeSpaceOfs -= 8;
1528

S
Smirnov Egor 已提交
1529 1530 1531 1532
    if (!noname) {
        writeInt(ptr, (int) strofs);
        ptr += 4;
    }
1533

S
Smirnov Egor 已提交
1534 1535 1536
    if (elem_type == FileNode::SEQ || elem_type == FileNode::MAP) {
        writeInt(ptr, 4);
        writeInt(ptr, 0);
1537 1538
    }

S
Smirnov Egor 已提交
1539 1540
    if (value)
        node.setValue(elem_type, value, len);
1541

S
Smirnov Egor 已提交
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
    if (collection.isNamed())
        cp += 4;
    int nelems = readInt(cp + 5);
    writeInt(cp + 5, nelems + 1);

    return node;
}

void FileStorage::Impl::finalizeCollection(FileNode &collection) {
    if (!collection.isSeq() && !collection.isMap())
        return;
    uchar *ptr0 = collection.ptr(), *ptr = ptr0 + 1;
    if (*ptr0 & FileNode::NAMED)
        ptr += 4;
    size_t blockIdx = collection.blockIdx;
    size_t ofs = collection.ofs + (size_t) (ptr + 8 - ptr0);
    size_t rawSize = 4;
    unsigned sz = (unsigned) readInt(ptr + 4);
    if (sz > 0) {
        size_t lastBlockIdx = fs_data_ptrs.size() - 1;

        for (; blockIdx < lastBlockIdx; blockIdx++) {
            rawSize += fs_data_blksz[blockIdx] - ofs;
            ofs = 0;
1566 1567
        }
    }
S
Smirnov Egor 已提交
1568 1569 1570
    rawSize += freeSpaceOfs - ofs;
    writeInt(ptr, (int) rawSize);
}
1571

S
Smirnov Egor 已提交
1572 1573 1574 1575 1576
void FileStorage::Impl::normalizeNodeOfs(size_t &blockIdx, size_t &ofs) const {
    while (ofs >= fs_data_blksz[blockIdx]) {
        if (blockIdx == fs_data_blksz.size() - 1) {
            CV_Assert(ofs == fs_data_blksz[blockIdx]);
            break;
1577
        }
S
Smirnov Egor 已提交
1578 1579
        ofs -= fs_data_blksz[blockIdx];
        blockIdx++;
1580
    }
S
Smirnov Egor 已提交
1581
}
1582

S
Smirnov Egor 已提交
1583 1584 1585
FileStorage::Impl::Base64State FileStorage::Impl::get_state_of_writing_base64() {
    return state_of_writing_base64;
}
1586

S
Smirnov Egor 已提交
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
int FileStorage::Impl::get_space() {
    return space;
}


FileStorage::Impl::Base64Decoder::Base64Decoder() {
    ofs = 0;
    ptr = 0;
    indent = 0;
    totalchars = 0;
    eos = true;
}

void FileStorage::Impl::Base64Decoder::init(Ptr<FileStorageParser> &_parser, char *_ptr, int _indent) {
    parser = _parser;
    ptr = _ptr;
    indent = _indent;
    encoded.clear();
    decoded.clear();
    ofs = 0;
    totalchars = 0;
    eos = false;
}

bool FileStorage::Impl::Base64Decoder::readMore(int needed) {
    static const uchar base64tab[] =
1613
            {
S
Smirnov Egor 已提交
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63,
                    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0,
                    0, 0, 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, 0, 0, 0, 0, 0,
                    0, 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, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1630 1631
            };

S
Smirnov Egor 已提交
1632 1633
    if (eos)
        return false;
1634

S
Smirnov Egor 已提交
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
    size_t sz = decoded.size();
    CV_Assert(ofs <= sz);
    sz -= ofs;
    for (size_t i = 0; i < sz; i++)
        decoded[i] = decoded[ofs + i];

    decoded.resize(sz);
    ofs = 0;

    CV_Assert(!parser.empty() && ptr);
    char *beg = 0, *end = 0;
    bool ok = parser->getBase64Row(ptr, indent, beg, end);
    ptr = end;
    std::copy(beg, end, std::back_inserter(encoded));
    totalchars += end - beg;

    if (!ok || beg == end) {
        // in the end of base64 sequence pad it with '=' characters so that
        // its total length is multiple of
        eos = true;
        size_t tc = totalchars;
        for (; tc % 4 != 0; tc++)
            encoded.push_back('=');
    }
1659

S
Smirnov Egor 已提交
1660 1661 1662 1663
    int i = 0, j, n = (int) encoded.size();
    if (n > 0) {
        const uchar *tab = base64tab;
        char *src = &encoded[0];
1664

S
Smirnov Egor 已提交
1665 1666 1667 1668
        for (; i <= n - 4; i += 4) {
            // dddddd cccccc bbbbbb aaaaaa => ddddddcc ccccbbbb bbaaaaaa
            uchar d = tab[(int) (uchar) src[i]], c = tab[(int) (uchar) src[i + 1]];
            uchar b = tab[(int) (uchar) src[i + 2]], a = tab[(int) (uchar) src[i + 3]];
1669

S
Smirnov Egor 已提交
1670 1671 1672 1673 1674
            decoded.push_back((uchar) ((d << 2) | (c >> 4)));
            decoded.push_back((uchar) ((c << 4) | (b >> 2)));
            decoded.push_back((uchar) ((b << 6) | a));
        }
    }
1675

S
Smirnov Egor 已提交
1676 1677 1678 1679 1680 1681
    if (i > 0 && encoded[i - 1] == '=') {
        if (i > 1 && encoded[i - 2] == '=' && !decoded.empty())
            decoded.pop_back();
        if (!decoded.empty())
            decoded.pop_back();
    }
1682

S
Smirnov Egor 已提交
1683 1684 1685 1686
    n -= i;
    for (j = 0; j < n; j++)
        encoded[j] = encoded[i + j];
    encoded.resize(n);
1687

S
Smirnov Egor 已提交
1688 1689
    return (int) decoded.size() >= needed;
}
1690

S
Smirnov Egor 已提交
1691 1692 1693 1694 1695 1696
uchar FileStorage::Impl::Base64Decoder::getUInt8() {
    size_t sz = decoded.size();
    if (ofs >= sz && !readMore(1))
        return (uchar) 0;
    return decoded[ofs++];
}
1697

S
Smirnov Egor 已提交
1698 1699 1700 1701 1702 1703 1704 1705
ushort FileStorage::Impl::Base64Decoder::getUInt16() {
    size_t sz = decoded.size();
    if (ofs + 2 > sz && !readMore(2))
        return (ushort) 0;
    ushort val = (decoded[ofs] + (decoded[ofs + 1] << 8));
    ofs += 2;
    return val;
}
1706

S
Smirnov Egor 已提交
1707 1708 1709 1710 1711 1712 1713 1714
int FileStorage::Impl::Base64Decoder::getInt32() {
    size_t sz = decoded.size();
    if (ofs + 4 > sz && !readMore(4))
        return 0;
    int ival = readInt(&decoded[ofs]);
    ofs += 4;
    return ival;
}
1715

S
Smirnov Egor 已提交
1716 1717 1718 1719 1720 1721 1722 1723
double FileStorage::Impl::Base64Decoder::getFloat64() {
    size_t sz = decoded.size();
    if (ofs + 8 > sz && !readMore(8))
        return 0;
    double fval = readReal(&decoded[ofs]);
    ofs += 8;
    return fval;
}
1724

S
Smirnov Egor 已提交
1725
bool FileStorage::Impl::Base64Decoder::endOfStream() const { return eos; }
1726

S
Smirnov Egor 已提交
1727
char *FileStorage::Impl::Base64Decoder::getPtr() const { return ptr; }
1728 1729


S
Smirnov Egor 已提交
1730 1731 1732 1733
char *FileStorage::Impl::parseBase64(char *ptr, int indent, FileNode &collection) {
    const int BASE64_HDR_SIZE = 24;
    char dt[BASE64_HDR_SIZE + 1] = {0};
    base64decoder.init(parser, ptr, indent);
1734

S
Smirnov Egor 已提交
1735
    int i, k;
1736

S
Smirnov Egor 已提交
1737 1738 1739 1740 1741 1742
    for (i = 0; i < BASE64_HDR_SIZE; i++)
        dt[i] = (char) base64decoder.getUInt8();
    for (i = 0; i < BASE64_HDR_SIZE; i++)
        if (isspace(dt[i]))
            break;
    dt[i] = '\0';
1743

S
Smirnov Egor 已提交
1744
    CV_Assert(!base64decoder.endOfStream());
1745

S
Smirnov Egor 已提交
1746 1747 1748 1749
    int fmt_pairs[CV_FS_MAX_FMT_PAIRS * 2];
    int fmt_pair_count = fs::decodeFormat(dt, fmt_pairs, CV_FS_MAX_FMT_PAIRS);
    int ival = 0;
    double fval = 0;
1750

S
Smirnov Egor 已提交
1751 1752 1753 1754
    for (;;) {
        for (k = 0; k < fmt_pair_count; k++) {
            int elem_type = fmt_pairs[k * 2 + 1];
            int count = fmt_pairs[k * 2];
1755

S
Smirnov Egor 已提交
1756 1757 1758
            for (i = 0; i < count; i++) {
                int node_type = FileNode::INT;
                switch (elem_type) {
1759 1760 1761 1762
                    case CV_8U:
                        ival = base64decoder.getUInt8();
                        break;
                    case CV_8S:
S
Smirnov Egor 已提交
1763
                        ival = (char) base64decoder.getUInt8();
1764 1765 1766 1767 1768
                        break;
                    case CV_16U:
                        ival = base64decoder.getUInt16();
                        break;
                    case CV_16S:
S
Smirnov Egor 已提交
1769
                        ival = (short) base64decoder.getUInt16();
1770 1771 1772 1773
                        break;
                    case CV_32S:
                        ival = base64decoder.getInt32();
                        break;
S
Smirnov Egor 已提交
1774
                    case CV_32F: {
1775 1776 1777 1778
                        Cv32suf v;
                        v.i = base64decoder.getInt32();
                        fval = v.f;
                        node_type = FileNode::REAL;
S
Smirnov Egor 已提交
1779
                    }
1780 1781 1782 1783 1784 1785
                        break;
                    case CV_64F:
                        fval = base64decoder.getFloat64();
                        node_type = FileNode::REAL;
                        break;
                    case CV_16F:
S
Smirnov Egor 已提交
1786
                        fval = (float) float16_t::fromBits(base64decoder.getUInt16());
1787 1788 1789
                        node_type = FileNode::REAL;
                        break;
                    default:
S
Smirnov Egor 已提交
1790
                        CV_Error(Error::StsUnsupportedFormat, "Unsupported type");
1791
                }
S
Smirnov Egor 已提交
1792 1793 1794 1795 1796

                if (base64decoder.endOfStream())
                    break;
                addNode(collection, std::string(), node_type,
                        node_type == FileNode::INT ? (void *) &ival : (void *) &fval, -1);
1797 1798
            }
        }
S
Smirnov Egor 已提交
1799 1800
        if (base64decoder.endOfStream())
            break;
1801 1802
    }

S
Smirnov Egor 已提交
1803 1804 1805
    finalizeCollection(collection);
    return base64decoder.getPtr();
}
1806

S
Smirnov Egor 已提交
1807 1808 1809 1810 1811
void FileStorage::Impl::parseError(const char *func_name, const std::string &err_msg, const char *source_file,
                                   int source_line) {
    std::string msg = format("%s(%d): %s", filename.c_str(), lineno, err_msg.c_str());
    error(Error::StsParseError, func_name, msg.c_str(), source_file, source_line);
}
1812

S
Smirnov Egor 已提交
1813 1814 1815
const uchar *FileStorage::Impl::getNodePtr(size_t blockIdx, size_t ofs) const {
    CV_Assert(blockIdx < fs_data_ptrs.size());
    CV_Assert(ofs < fs_data_blksz[blockIdx]);
1816

S
Smirnov Egor 已提交
1817 1818
    return fs_data_ptrs[blockIdx] + ofs;
}
1819

S
Smirnov Egor 已提交
1820 1821 1822 1823
std::string FileStorage::Impl::getName(size_t nameofs) const {
    CV_Assert(nameofs < str_hash_data.size());
    return std::string(&str_hash_data[nameofs]);
}
1824

S
Smirnov Egor 已提交
1825
FileStorage *FileStorage::Impl::getFS() { return fs_ext; }
1826 1827 1828


FileStorage::FileStorage()
1829
    : state(0)
1830 1831 1832 1833 1834
{
    p = makePtr<FileStorage::Impl>(this);
}

FileStorage::FileStorage(const String& filename, int flags, const String& encoding)
1835
    : state(0)
1836 1837 1838 1839 1840 1841 1842 1843 1844
{
    p = makePtr<FileStorage::Impl>(this);
    bool ok = p->open(filename.c_str(), flags, encoding.c_str());
    if(ok)
        state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP;
}

void FileStorage::startWriteStruct(const String& name, int struct_flags, const String& typeName)
{
S
Smirnov Egor 已提交
1845
    p->startWriteStruct(name.size() ? name.c_str() : 0, struct_flags, typeName.size() ? typeName.c_str() : 0);
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
    elname = String();
    if ((struct_flags & FileNode::TYPE_MASK) == FileNode::SEQ)
        state = FileStorage::VALUE_EXPECTED;
    else
        state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP;
}

void FileStorage::endWriteStruct()
{
    p->endWriteStruct();
    state = p->write_stack.empty() || FileNode::isMap(p->write_stack.back().flags) ?
        FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP :
        FileStorage::VALUE_EXPECTED;
    elname = String();
}

FileStorage::~FileStorage()
{
}

bool FileStorage::open(const String& filename, int flags, const String& encoding)
{
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
    try
    {
        bool ok = p->open(filename.c_str(), flags, encoding.c_str());
        if(ok)
            state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP;
        return ok;
    }
    catch (...)
    {
        release();
        throw;  // re-throw
    }
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
}

bool FileStorage::isOpened() const { return p->is_opened; }

void FileStorage::release()
{
    p->release();
}

FileNode FileStorage::root(int i) const
{
    if( p.empty() || p->roots.empty() || i < 0 || i >= (int)p->roots.size() )
        return FileNode();

    return p->roots[i];
}

FileNode FileStorage::getFirstTopLevelNode() const
{
    FileNode r = root();
    FileNodeIterator it = r.begin();
    return it != r.end() ? *it : FileNode();
}

std::string FileStorage::getDefaultObjectName(const std::string& _filename)
{
    static const char* stubname = "unnamed";
    const char* filename = _filename.c_str();
    const char* ptr2 = filename + _filename.size();
    const char* ptr = ptr2 - 1;
    cv::AutoBuffer<char> name_buf(_filename.size()+1);

    while( ptr >= filename && *ptr != '\\' && *ptr != '/' && *ptr != ':' )
    {
        if( *ptr == '.' && (!*ptr2 || strncmp(ptr2, ".gz", 3) == 0) )
            ptr2 = ptr;
        ptr--;
    }
    ptr++;
    if( ptr == ptr2 )
S
Smirnov Egor 已提交
1920
        CV_Error( cv::Error::StsBadArg, "Invalid filename" );
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950

    char* name = name_buf.data();

    // name must start with letter or '_'
    if( !cv_isalpha(*ptr) && *ptr!= '_' ){
        *name++ = '_';
    }

    while( ptr < ptr2 )
    {
        char c = *ptr++;
        if( !cv_isalnum(c) && c != '-' && c != '_' )
            c = '_';
        *name++ = c;
    }
    *name = '\0';
    name = name_buf.data();
    if( strcmp( name, "_" ) == 0 )
        strcpy( name, stubname );
    return name;
}


int FileStorage::getFormat() const
{
    return p->fmt;
}

FileNode FileStorage::operator [](const char* key) const
{
1951
    return this->operator[](std::string(key));
1952 1953 1954 1955
}

FileNode FileStorage::operator [](const std::string& key) const
{
1956 1957 1958 1959 1960 1961 1962 1963
    FileNode res;
    for (size_t i = 0; i < p->roots.size(); i++)
    {
        res = p->roots[i][key];
        if (!res.empty())
            break;
    }
    return res;
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
}

String FileStorage::releaseAndGetString()
{
    String buf;
    p->release(&buf);
    return buf;
}

void FileStorage::writeRaw( const String& fmt, const void* vec, size_t len )
{
    p->writeRawData(fmt, (const uchar*)vec, len);
}

void FileStorage::writeComment( const String& comment, bool eol_comment )
{
    p->writeComment(comment.c_str(), eol_comment);
}

void writeScalar( FileStorage& fs, int value )
{
    fs.p->write(String(), value);
}

void writeScalar( FileStorage& fs, float value )
{
    fs.p->write(String(), (double)value);
}

void writeScalar( FileStorage& fs, double value )
{
    fs.p->write(String(), value);
}

void writeScalar( FileStorage& fs, const String& value )
{
    fs.p->write(String(), value);
}

void write( FileStorage& fs, const String& name, int value )
{
    fs.p->write(name, value);
}

void write( FileStorage& fs, const String& name, float value )
{
    fs.p->write(name, (double)value);
}

void write( FileStorage& fs, const String& name, double value )
{
    fs.p->write(name, value);
}

void write( FileStorage& fs, const String& name, const String& value )
{
    fs.p->write(name, value);
}

void FileStorage::write(const String& name, int val) { p->write(name, val); }
void FileStorage::write(const String& name, double val) { p->write(name, val); }
void FileStorage::write(const String& name, const String& val) { p->write(name, val); }
void FileStorage::write(const String& name, const Mat& val) { cv::write(*this, name, val); }
void FileStorage::write(const String& name, const std::vector<String>& val) { cv::write(*this, name, val); }

FileStorage& operator << (FileStorage& fs, const String& str)
{
    enum { NAME_EXPECTED = FileStorage::NAME_EXPECTED,
        VALUE_EXPECTED = FileStorage::VALUE_EXPECTED,
        INSIDE_MAP = FileStorage::INSIDE_MAP };
    const char* _str = str.c_str();
    if( !fs.isOpened() || !_str )
        return fs;
    Ptr<FileStorage::Impl>& fs_impl = fs.p;
    char c = *_str;

    if( c == '}' || c == ']' )
    {
        if( fs_impl->write_stack.empty() )
S
Smirnov Egor 已提交
2043 2044 2045
            CV_Error_( cv::Error::StsError, ("Extra closing '%c'", *_str) );

        fs_impl->workaround();
2046 2047 2048 2049

        int struct_flags = fs_impl->write_stack.back().flags;
        char expected_bracket = FileNode::isMap(struct_flags) ? '}' : ']';
        if( c != expected_bracket )
S
Smirnov Egor 已提交
2050
            CV_Error_( cv::Error::StsError, ("The closing '%c' does not match the opening '%c'", c, expected_bracket));
2051 2052 2053 2054 2055 2056 2057 2058 2059
        fs_impl->endWriteStruct();
        CV_Assert(!fs_impl->write_stack.empty());
        struct_flags = fs_impl->write_stack.back().flags;
        fs.state = FileNode::isMap(struct_flags) ? INSIDE_MAP + NAME_EXPECTED : VALUE_EXPECTED;
        fs.elname = String();
    }
    else if( fs.state == NAME_EXPECTED + INSIDE_MAP )
    {
        if (!cv_isalpha(c) && c != '_')
S
Smirnov Egor 已提交
2060
            CV_Error_( cv::Error::StsError, ("Incorrect element name %s; should start with a letter or '_'", _str) );
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
        fs.elname = str;
        fs.state = VALUE_EXPECTED + INSIDE_MAP;
    }
    else if( (fs.state & 3) == VALUE_EXPECTED )
    {
        if( c == '{' || c == '[' )
        {
            int struct_flags = c == '{' ? FileNode::MAP : FileNode::SEQ;
            fs.state = struct_flags == FileNode::MAP ? INSIDE_MAP + NAME_EXPECTED : VALUE_EXPECTED;
            _str++;
            if( *_str == ':' )
            {
                _str++;
                if( !*_str )
                    struct_flags |= FileNode::FLOW;
            }
            fs_impl->startWriteStruct(!fs.elname.empty() ? fs.elname.c_str() : 0, struct_flags, *_str ? _str : 0 );
            fs.elname = String();
        }
        else
        {
            write( fs, fs.elname, (c == '\\' && (_str[1] == '{' || _str[1] == '}' ||
                                _str[1] == '[' || _str[1] == ']')) ? String(_str+1) : str );
            if( fs.state == INSIDE_MAP + VALUE_EXPECTED )
                fs.state = INSIDE_MAP + NAME_EXPECTED;
        }
    }
    else
S
Smirnov Egor 已提交
2089
        CV_Error( cv::Error::StsError, "Invalid fs.state" );
2090 2091 2092 2093 2094
    return fs;
}


FileNode::FileNode()
2095
    : fs(NULL)
2096 2097 2098 2099
{
    blockIdx = ofs = 0;
}

2100 2101
FileNode::FileNode(FileStorage::Impl* _fs, size_t _blockIdx, size_t _ofs)
    : fs(_fs)
2102 2103 2104 2105 2106
{
    blockIdx = _blockIdx;
    ofs = _ofs;
}

2107 2108 2109 2110 2111 2112
FileNode::FileNode(const FileStorage* _fs, size_t _blockIdx, size_t _ofs)
    : FileNode(_fs->p.get(), _blockIdx, _ofs)
{
    // nothing
}

2113 2114 2115 2116 2117 2118 2119
FileNode::FileNode(const FileNode& node)
{
    fs = node.fs;
    blockIdx = node.blockIdx;
    ofs = node.ofs;
}

2120 2121 2122 2123 2124 2125 2126 2127
FileNode& FileNode::operator=(const FileNode& node)
{
    fs = node.fs;
    blockIdx = node.blockIdx;
    ofs = node.ofs;
    return *this;
}

2128 2129 2130 2131 2132 2133 2134
FileNode FileNode::operator[](const std::string& nodename) const
{
    if(!fs)
        return FileNode();

    CV_Assert( isMap() );

2135
    unsigned key = fs->getStringOfs(nodename);
2136 2137 2138 2139 2140 2141 2142 2143
    size_t i, sz = size();
    FileNodeIterator it = begin();

    for( i = 0; i < sz; i++, ++it )
    {
        FileNode n = *it;
        const uchar* p = n.ptr();
        unsigned key2 = (unsigned)readInt(p + 1);
2144
        CV_Assert( key2 < fs->str_hash_data.size() );
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
        if( key == key2 )
            return n;
    }
    return FileNode();
}

FileNode FileNode::operator[](const char* nodename) const
{
    return this->operator[](std::string(nodename));
}

FileNode FileNode::operator[](int i) const
{
    if(!fs)
        return FileNode();

    CV_Assert( isSeq() );

    int sz = (int)size();
    CV_Assert( 0 <= i && i < sz );

    FileNodeIterator it = begin();
    it += i;

    return *it;
}

2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
std::vector<String> FileNode::keys() const
{
    CV_Assert(isMap());

    std::vector<String> res;
    res.reserve(size());
    for (FileNodeIterator it = begin(); it != end(); ++it)
    {
        res.push_back((*it).name());
    }
    return res;
}

2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
int FileNode::type() const
{
    const uchar* p = ptr();
    if(!p)
        return NONE;
    return (*p & TYPE_MASK);
}

bool FileNode::isMap(int flags) { return (flags & TYPE_MASK) == MAP; }
bool FileNode::isSeq(int flags) { return (flags & TYPE_MASK) == SEQ; }
bool FileNode::isCollection(int flags) { return isMap(flags) || isSeq(flags); }
bool FileNode::isFlow(int flags) { return (flags & FLOW) != 0; }
bool FileNode::isEmptyCollection(int flags) { return (flags & EMPTY) != 0; }

bool FileNode::empty() const   { return fs == 0; }
bool FileNode::isNone() const  { return type() == NONE; }
bool FileNode::isSeq() const   { return type() == SEQ; }
bool FileNode::isMap() const   { return type() == MAP; }
bool FileNode::isInt() const   { return type() == INT;  }
bool FileNode::isReal() const  { return type() == REAL; }
bool FileNode::isString() const { return type() == STRING;  }
bool FileNode::isNamed() const
{
    const uchar* p = ptr();
    if(!p)
        return false;
    return (*p & NAMED) != 0;
}

std::string FileNode::name() const
{
    const uchar* p = ptr();
    if(!p)
        return std::string();
    size_t nameofs = p[1] | (p[2]<<8) | (p[3]<<16) | (p[4]<<24);
2220
    return fs->getName(nameofs);
2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
}

FileNode::operator int() const
{
    const uchar* p = ptr();
    if(!p)
        return 0;
    int tag = *p;
    int type = (tag & TYPE_MASK);
    p += (tag & NAMED) ? 5 : 1;

    if( type == INT )
    {
        return readInt(p);
    }
    else if( type == REAL )
    {
        return cvRound(readReal(p));
    }
    else
        return 0x7fffffff;
}

FileNode::operator float() const
{
    const uchar* p = ptr();
    if(!p)
        return 0.f;
    int tag = *p;
    int type = (tag & TYPE_MASK);
    p += (tag & NAMED) ? 5 : 1;

    if( type == INT )
    {
        return (float)readInt(p);
    }
    else if( type == REAL )
    {
        return (float)readReal(p);
    }
    else
        return FLT_MAX;
}

FileNode::operator double() const
{
    const uchar* p = ptr();
    if(!p)
        return 0.f;
    int tag = *p;
    int type = (tag & TYPE_MASK);
    p += (tag & NAMED) ? 5 : 1;

    if( type == INT )
    {
        return (double)readInt(p);
    }
    else if( type == REAL )
    {
        return readReal(p);
    }
    else
        return DBL_MAX;
}

2286 2287
double FileNode::real() const  { return double(*this); }
std::string FileNode::string() const
2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
{
    const uchar* p = ptr();
    if( !p || (*p & TYPE_MASK) != STRING )
        return std::string();
    p += (*p & NAMED) ? 5 : 1;
    size_t sz = (size_t)(unsigned)readInt(p);
    return std::string((const char*)(p + 4), sz - 1);
}
Mat FileNode::mat() const { Mat value; read(*this, value, Mat()); return value; }

FileNodeIterator FileNode::begin() const { return FileNodeIterator(*this, false); }
FileNodeIterator FileNode::end() const   { return FileNodeIterator(*this, true); }

void FileNode::readRaw( const std::string& fmt, void* vec, size_t len ) const
{
    FileNodeIterator it = begin();
    it.readRaw( fmt, vec, len );
}

size_t FileNode::size() const
{
    const uchar* p = ptr();
    if( !p )
        return 0;
    int tag = *p;
    int tp = tag & TYPE_MASK;
    if( tp == MAP || tp == SEQ )
    {
        if( tag & NAMED )
            p += 4;
        return (size_t)(unsigned)readInt(p + 5);
    }
    return tp != NONE;
}

size_t FileNode::rawSize() const
{
    const uchar* p0 = ptr(), *p = p0;
    if( !p )
        return 0;
    int tag = *p++;
    int tp = tag & TYPE_MASK;
    if( tag & NAMED )
        p += 4;
    size_t sz0 = (size_t)(p - p0);
    if( tp == INT )
        return sz0 + 4;
    if( tp == REAL )
        return sz0 + 8;
    if( tp == NONE )
        return sz0;
    CV_Assert( tp == STRING || tp == SEQ || tp == MAP );
    return sz0 + 4 + readInt(p);
}

uchar* FileNode::ptr()
{
2345
    return !fs ? 0 : (uchar*)fs->getNodePtr(blockIdx, ofs);
2346 2347 2348 2349
}

const uchar* FileNode::ptr() const
{
2350
    return !fs ? 0 : fs->getNodePtr(blockIdx, ofs);
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
}

void FileNode::setValue( int type, const void* value, int len )
{
    uchar *p = ptr();
    CV_Assert(p != 0);

    int tag = *p;
    int current_type = tag & TYPE_MASK;
    CV_Assert( current_type == NONE || current_type == type );

    int sz = 1;

    if( tag & NAMED )
        sz += 4;

    if( type == INT )
        sz += 4;
    else if( type == REAL )
        sz += 8;
    else if( type == STRING )
    {
        if( len < 0 )
            len = (int)strlen((const char*)value);
        sz += 4 + len + 1; // besides the string content,
                           // take the size (4 bytes) and the final '\0' into account
    }
    else
        CV_Error(Error::StsNotImplemented, "Only scalar types can be dynamically assigned to a file node");

2381
    p = fs->reserveNodeSpace(*this, sz);
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
    *p++ = (uchar)(type | (tag & NAMED));
    if( tag & NAMED )
        p += 4;

    if( type == INT )
    {
        int ival = *(const int*)value;
        writeInt(p, ival);
    }
    else if( type == REAL )
    {
        double dbval = *(const double*)value;
        writeReal(p, dbval);
    }
    else if( type == STRING )
    {
        const char* str = (const char*)value;
        writeInt(p, len + 1);
        memcpy(p + 4, str, len);
        p[4 + len] = (uchar)'\0';
    }
}

FileNodeIterator::FileNodeIterator()
{
    fs = 0;
    blockIdx = 0;
    ofs = 0;
    blockSize = 0;
    nodeNElems = 0;
    idx = 0;
}

FileNodeIterator::FileNodeIterator( const FileNode& node, bool seekEnd )
{
    fs = node.fs;
    idx = 0;
    if( !fs )
        blockIdx = ofs = blockSize = nodeNElems = 0;
    else
    {
        blockIdx = node.blockIdx;
        ofs = node.ofs;

        bool collection = node.isSeq() || node.isMap();
        if( node.isNone() )
        {
            nodeNElems = 0;
        }
        else if( !collection )
        {
            nodeNElems = 1;
            if( seekEnd )
            {
                idx = 1;
                ofs += node.rawSize();
            }
        }
        else
        {
            nodeNElems = node.size();
            const uchar* p0 = node.ptr(), *p = p0 + 1;
            if(*p0 & FileNode::NAMED )
                p += 4;
            if( !seekEnd )
                ofs += (p - p0) + 8;
            else
            {
                size_t rawsz = (size_t)(unsigned)readInt(p);
                ofs += (p - p0) + 4 + rawsz;
                idx = nodeNElems;
            }
        }
2455 2456
        fs->normalizeNodeOfs(blockIdx, ofs);
        blockSize = fs->fs_data_blksz[blockIdx];
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
    }
}

FileNodeIterator::FileNodeIterator(const FileNodeIterator& it)
{
    fs = it.fs;
    blockIdx = it.blockIdx;
    ofs = it.ofs;
    blockSize = it.blockSize;
    nodeNElems = it.nodeNElems;
    idx = it.idx;
}
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479

FileNodeIterator& FileNodeIterator::operator=(const FileNodeIterator& it)
{
    fs = it.fs;
    blockIdx = it.blockIdx;
    ofs = it.ofs;
    blockSize = it.blockSize;
    nodeNElems = it.nodeNElems;
    idx = it.idx;
    return *this;
}
2480 2481 2482

FileNode FileNodeIterator::operator *() const
{
2483
    return FileNode(idx < nodeNElems ? fs : NULL, blockIdx, ofs);
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
}

FileNodeIterator& FileNodeIterator::operator ++ ()
{
    if( idx == nodeNElems || !fs )
        return *this;
    idx++;
    FileNode n(fs, blockIdx, ofs);
    ofs += n.rawSize();
    if( ofs >= blockSize )
    {
2495 2496
        fs->normalizeNodeOfs(blockIdx, ofs);
        blockSize = fs->fs_data_blksz[blockIdx];
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712
    }
    return *this;
}

FileNodeIterator FileNodeIterator::operator ++ (int)
{
    FileNodeIterator it = *this;
    ++(*this);
    return it;
}

FileNodeIterator& FileNodeIterator::operator += (int _ofs)
{
    CV_Assert( _ofs >= 0 );
    for( ; _ofs > 0; _ofs-- )
        this->operator ++();
    return *this;
}

FileNodeIterator& FileNodeIterator::readRaw( const String& fmt, void* _data0, size_t maxsz)
{
    if( fs && idx < nodeNElems )
    {
        uchar* data0 = (uchar*)_data0;
        int fmt_pairs[CV_FS_MAX_FMT_PAIRS*2];
        int fmt_pair_count = fs::decodeFormat( fmt.c_str(), fmt_pairs, CV_FS_MAX_FMT_PAIRS );
        size_t esz = fs::calcStructSize( fmt.c_str(), 0 );

        CV_Assert( maxsz % esz == 0 );
        maxsz /= esz;

        for( ; maxsz > 0; maxsz--, data0 += esz )
        {
            size_t offset = 0;
            for( int k = 0; k < fmt_pair_count; k++ )
            {
                int elem_type = fmt_pairs[k*2+1];
                int elem_size = CV_ELEM_SIZE(elem_type);

                int count = fmt_pairs[k*2];
                offset = alignSize( offset, elem_size );
                uchar* data = data0 + offset;

                for( int i = 0; i < count; i++, ++(*this) )
                {
                    FileNode node = *(*this);
                    if( node.isInt() )
                    {
                        int ival = (int)node;
                        switch( elem_type )
                        {
                        case CV_8U:
                            *(uchar*)data = saturate_cast<uchar>(ival);
                            data++;
                            break;
                        case CV_8S:
                            *(char*)data = saturate_cast<schar>(ival);
                            data++;
                            break;
                        case CV_16U:
                            *(ushort*)data = saturate_cast<ushort>(ival);
                            data += sizeof(ushort);
                            break;
                        case CV_16S:
                            *(short*)data = saturate_cast<short>(ival);
                            data += sizeof(short);
                            break;
                        case CV_32S:
                            *(int*)data = ival;
                            data += sizeof(int);
                            break;
                        case CV_32F:
                            *(float*)data = (float)ival;
                            data += sizeof(float);
                            break;
                        case CV_64F:
                            *(double*)data = (double)ival;
                            data += sizeof(double);
                            break;
                        case CV_16F:
                            *(float16_t*)data = float16_t((float)ival);
                            data += sizeof(float16_t);
                            break;
                        default:
                            CV_Error( Error::StsUnsupportedFormat, "Unsupported type" );
                        }
                    }
                    else if( node.isReal() )
                    {
                        double fval = (double)node;

                        switch( elem_type )
                        {
                        case CV_8U:
                            *(uchar*)data = saturate_cast<uchar>(fval);
                            data++;
                            break;
                        case CV_8S:
                            *(char*)data = saturate_cast<schar>(fval);
                            data++;
                            break;
                        case CV_16U:
                            *(ushort*)data = saturate_cast<ushort>(fval);
                            data += sizeof(ushort);
                            break;
                        case CV_16S:
                            *(short*)data = saturate_cast<short>(fval);
                            data += sizeof(short);
                            break;
                        case CV_32S:
                            *(int*)data = saturate_cast<int>(fval);
                            data += sizeof(int);
                            break;
                        case CV_32F:
                            *(float*)data = (float)fval;
                            data += sizeof(float);
                            break;
                        case CV_64F:
                            *(double*)data = fval;
                            data += sizeof(double);
                            break;
                        case CV_16F:
                            *(float16_t*)data = float16_t((float)fval);
                            data += sizeof(float16_t);
                            break;
                        default:
                            CV_Error( Error::StsUnsupportedFormat, "Unsupported type" );
                        }
                    }
                    else
                        CV_Error( Error::StsError, "readRawData can only be used to read plain sequences of numbers" );
                }
                offset = (int)(data - data0);
            }
        }
    }

    return *this;
}

bool FileNodeIterator::equalTo(const FileNodeIterator& it) const
{
    return fs == it.fs && blockIdx == it.blockIdx && ofs == it.ofs &&
           idx == it.idx && nodeNElems == it.nodeNElems;
}

size_t FileNodeIterator::remaining() const
{
    return nodeNElems - idx;
}

bool operator == ( const FileNodeIterator& it1, const FileNodeIterator& it2 )
{
    return it1.equalTo(it2);
}

bool operator != ( const FileNodeIterator& it1, const FileNodeIterator& it2 )
{
    return !it1.equalTo(it2);
}

void read(const FileNode& node, int& val, int default_val)
{
    val = default_val;
    if( !node.empty() )
    {
        val = (int)node;
    }
}

void read(const FileNode& node, double& val, double default_val)
{
    val = default_val;
    if( !node.empty() )
    {
        val = (double)node;
    }
}

void read(const FileNode& node, float& val, float default_val)
{
    val = default_val;
    if( !node.empty() )
    {
        val = (float)node;
    }
}

void read(const FileNode& node, std::string& val, const std::string& default_val)
{
    val = default_val;
    if( !node.empty() )
    {
        val = (std::string)node;
    }
}

FileStorage_API::~FileStorage_API() {}

namespace internal
{

WriteStructContext::WriteStructContext(FileStorage& _fs, const std::string& name,
                                       int flags, const std::string& typeName)
{
    fs = &_fs;
    fs->startWriteStruct(name, flags, typeName);
}

WriteStructContext::~WriteStructContext()
{
    fs->endWriteStruct();
}

}

2713
}