persistence.cpp 80.9 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
#include <unordered_map>
#include <iterator>

12 13
#include <opencv2/core/utils/logger.hpp>

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
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 已提交
37

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

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

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

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

    return buf;
}

145
static const char symbols[9] = "ucwsifdh";
146

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

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

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

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

177 178
    if( !dt || !len )
        return 0;
179

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

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

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

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

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

221 222 223
    fmt_pair_count = i/2;
    return fmt_pair_count;
}
224

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

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


248
int calcStructSize( const char* dt, int initial_size )
249
{
250
    int size = calcElemSize( dt, initial_size );
251
    size_t elem_max_size = 0;
252 253 254 255 256 257
    for ( const char * type = dt; *type != '\0'; type++ )
    {
        char v = *type;
        if (v >= '0' && v <= '9')
            continue;  // skip vector size
        switch (v)
258
        {
259 260 261 262 263 264 265
        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; }
266 267 268
        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));
269 270
        }
    }
271 272 273
    size = cvAlign( size, static_cast<int>(elem_max_size) );
    return size;
}
274

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

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

284
    elem_type = CV_MAKETYPE( fmt_pairs[1], fmt_pairs[0] );
285

286 287
    return elem_type;
}
288

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
}

#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)
321
{
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
#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 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
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;
}
395

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

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

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

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

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

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

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

S
Smirnov Egor 已提交
463 464
    bool isGZ = false;
    size_t fnamelen = 0;
465

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

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

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

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

S
Smirnov Egor 已提交
484
    flags = _flags;
485

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

S
Smirnov Egor 已提交
490 491 492 493
        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");
494
            }
S
Smirnov Egor 已提交
495 496 497 498 499
            isGZ = true;
            compression = dot_pos[3];
            if (compression)
                dot_pos[3] = '\0', fnamelen--;
        }
500

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

523
    // FIXIT release() must do that, use CV_Assert() here instead
S
Smirnov Egor 已提交
524 525
    roots.clear();
    fs_data.clear();
526

S
Smirnov Egor 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
    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;
544 545
                }
            }
S
Smirnov Egor 已提交
546 547
            if (fs::strcasecmp(dot_pos, ".gz") == 0 && dot_pos2 != NULL) {
                dot_pos = dot_pos2;
548
            }
S
Smirnov Egor 已提交
549 550 551 552 553 554 555 556
            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;
        }
557

S
Smirnov Egor 已提交
558 559 560
        // 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;
561

S
Smirnov Egor 已提交
562 563 564 565 566
        if (append) {
            fseek(file, 0, SEEK_END);
            if (ftell(file) == 0)
                append = false;
        }
567

S
Smirnov Egor 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
        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");
584
                    }
S
Smirnov Egor 已提交
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609

                    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)
610
                            break;
S
Smirnov Egor 已提交
611 612
                        last_occurrence = line_offset + (int) (ptr - ptr0);
                        ptr += strlen(substr);
613 614
                    }
                }
S
Smirnov Egor 已提交
615 616 617 618 619 620 621 622 623 624 625 626
                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");
627 628
            }

629
            emitter_do_not_use_direct_dereference = createXMLEmitter(this);
S
Smirnov Egor 已提交
630 631 632
        } else if (fmt == FileStorage::FORMAT_YAML) {
            if (!append)
                puts("%YAML:1.0\n---\n");
633
            else
S
Smirnov Egor 已提交
634 635
                puts("...\n---\n");

636
            emitter_do_not_use_direct_dereference = createYAMLEmitter(this);
S
Smirnov Egor 已提交
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
        } 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;
652
                    }
S
Smirnov Egor 已提交
653
                }
654

S
Smirnov Egor 已提交
655 656 657 658 659 660 661 662
                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");
663 664
                }
            }
S
Smirnov Egor 已提交
665
            write_stack.back().indent = 4;
666
            emitter_do_not_use_direct_dereference = createJSONEmitter(this);
S
Smirnov Egor 已提交
667 668 669 670 671 672 673 674
        }
        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);
675 676
        }

S
Smirnov Egor 已提交
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
        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");
695

S
Smirnov Egor 已提交
696 697 698
        rewind();
        strbufpos = bufOffset;
        bufofs = 0;
699

S
Smirnov Egor 已提交
700 701 702 703
        try {
            char *ptr = bufferStart();
            ptr[0] = ptr[1] = ptr[2] = '\0';
            FileNode root_nodes(fs_ext, 0, 0);
704

S
Smirnov Egor 已提交
705 706 707 708
            uchar *rptr = reserveNodeSpace(root_nodes, 9);
            *rptr = FileNode::SEQ;
            writeInt(rptr + 1, 4);
            writeInt(rptr + 5, 0);
709

S
Smirnov Egor 已提交
710
            roots.clear();
711

S
Smirnov Egor 已提交
712 713
            switch (fmt) {
                case FileStorage::FORMAT_XML:
714
                    parser_do_not_use_direct_dereference = createXMLParser(this);
S
Smirnov Egor 已提交
715 716
                    break;
                case FileStorage::FORMAT_YAML:
717
                    parser_do_not_use_direct_dereference = createYAMLParser(this);
S
Smirnov Egor 已提交
718 719
                    break;
                case FileStorage::FORMAT_JSON:
720
                    parser_do_not_use_direct_dereference = createJSONParser(this);
S
Smirnov Egor 已提交
721 722
                    break;
                default:
723
                    parser_do_not_use_direct_dereference = Ptr<FileStorageParser>();
S
Smirnov Egor 已提交
724
            }
725

726 727
            if (!parser_do_not_use_direct_dereference.empty()) {
                ok = getParser().parse(ptr);
S
Smirnov Egor 已提交
728 729
                if (ok) {
                    finalizeCollection(root_nodes);
730

S
Smirnov Egor 已提交
731 732 733 734
                    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();
735

S
Smirnov Egor 已提交
736 737
                    for (i = 0; i < nroots; i++, ++it)
                        roots.push_back(*it);
738 739
                }
            }
S
Smirnov Egor 已提交
740
        }
741 742 743
        catch (...)
        {
            // FIXIT log error message
744
            is_opened = true;
S
Smirnov Egor 已提交
745 746
            release();
            throw;
747
        }
S
Smirnov Egor 已提交
748 749 750 751 752 753 754

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

S
Smirnov Egor 已提交
759 760 761 762 763 764
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);
765
#if USE_ZLIB
S
Smirnov Egor 已提交
766 767
    else if (gzfile)
        gzputs(gzfile, str);
768
#endif
S
Smirnov Egor 已提交
769 770 771
    else
        CV_Error(cv::Error::StsError, "The storage is not opened");
}
772

S
Smirnov Egor 已提交
773 774 775 776 777 778 779 780 781
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");
}
782

S
Smirnov Egor 已提交
783 784 785 786 787 788 789 790 791 792
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;
793 794
            }
        }
S
Smirnov Egor 已提交
795 796 797 798 799 800 801 802 803
        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;
    }
804

S
Smirnov Egor 已提交
805 806 807 808 809 810
    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;
811

S
Smirnov Egor 已提交
812 813 814 815 816 817 818 819 820 821 822 823
    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));
824
    }
S
Smirnov Egor 已提交
825 826
    return ofs > 0 ? &buffer[0] : 0;
}
827

S
Smirnov Egor 已提交
828 829 830 831 832 833 834 835 836 837 838 839
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';
840 841
        }
    }
S
Smirnov Egor 已提交
842 843 844
    lineno++;
    return ptr;
}
845

S
Smirnov Egor 已提交
846 847 848 849 850 851 852
bool FileStorage::Impl::eof() {
    if (dummy_eof)
        return true;
    if (strbuf)
        return strbufpos >= strbufsize;
    if (file)
        return feof(file) != 0;
853
#if USE_ZLIB
S
Smirnov Egor 已提交
854 855
    if (gzfile)
        return gzeof(gzfile) != 0;
856
#endif
S
Smirnov Egor 已提交
857 858
    return false;
}
859

S
Smirnov Egor 已提交
860 861 862
void FileStorage::Impl::setEof() {
    dummy_eof = true;
}
863

S
Smirnov Egor 已提交
864 865 866
void FileStorage::Impl::closeFile() {
    if (file)
        fclose(file);
867
#if USE_ZLIB
S
Smirnov Egor 已提交
868 869
    else if (gzfile)
        gzclose(gzfile);
870
#endif
S
Smirnov Egor 已提交
871 872 873 874 875 876
    file = 0;
    gzfile = 0;
    strbuf = 0;
    strbufpos = 0;
    is_opened = false;
}
877

S
Smirnov Egor 已提交
878 879 880
void FileStorage::Impl::rewind() {
    if (file)
        ::rewind(file);
881
#if USE_ZLIB
S
Smirnov Egor 已提交
882 883
    else if (gzfile)
        gzrewind(gzfile);
884
#endif
S
Smirnov Egor 已提交
885 886
    strbufpos = 0;
}
887

S
Smirnov Egor 已提交
888 889 890 891
char *FileStorage::Impl::resizeWriteBuffer(char *ptr, int len) {
    const char *buffer_end = &buffer[0] + buffer.size();
    if (ptr + len < buffer_end)
        return ptr;
892

S
Smirnov Egor 已提交
893 894
    const char *buffer_start = &buffer[0];
    int written_len = (int) (ptr - buffer_start);
895

S
Smirnov Egor 已提交
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    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;
914 915
    }

S
Smirnov Egor 已提交
916
    int indent = write_stack.back().indent;
917

S
Smirnov Egor 已提交
918 919 920 921 922 923
    if (space != indent) {
        memset(buffer_start, ' ', indent);
        space = indent;
    }
    bufofs = space;
    ptr = buffer_start + bufofs;
924

S
Smirnov Egor 已提交
925 926
    return ptr;
}
927

S
Smirnov Egor 已提交
928 929
void FileStorage::Impl::endWriteStruct() {
    CV_Assert(write_mode);
930

S
Smirnov Egor 已提交
931 932 933
    check_if_write_struct_is_delayed(false);
    if (state_of_writing_base64 != FileStorage_API::Uncertain)
        switch_to_Base64_state(FileStorage_API::Uncertain);
934

S
Smirnov Egor 已提交
935
    CV_Assert(!write_stack.empty());
936

S
Smirnov Egor 已提交
937 938 939
    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;
940

941
    getEmitter().endWriteStruct(current_struct);
942

S
Smirnov Egor 已提交
943 944 945 946
    write_stack.pop_back();
    if (!write_stack.empty())
        write_stack.back().flags &= ~FileNode::EMPTY;
}
947

S
Smirnov Egor 已提交
948 949 950
void FileStorage::Impl::startWriteStruct_helper(const char *key, int struct_flags,
                                                const char *type_name) {
    CV_Assert(write_mode);
951

S
Smirnov Egor 已提交
952 953 954 955
    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");
956

S
Smirnov Egor 已提交
957 958
    if (type_name && type_name[0] == '\0')
        type_name = 0;
959

960
    FStructData s = getEmitter().startWriteStruct(write_stack.back(), key, struct_flags, type_name);
961

S
Smirnov Egor 已提交
962 963 964 965
    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;
966

S
Smirnov Egor 已提交
967 968
    if (fmt != FileStorage::FORMAT_JSON && !FileNode::isFlow(s.flags))
        flush();
969

S
Smirnov Egor 已提交
970
    if (fmt == FileStorage::FORMAT_JSON && type_name && type_name[0] && FileNode::isMap(struct_flags)) {
971
        getEmitter().write("type_id", type_name, false);
972
    }
S
Smirnov Egor 已提交
973
}
974

S
Smirnov Egor 已提交
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
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);
1007
    }
S
Smirnov Egor 已提交
1008
}
1009

S
Smirnov Egor 已提交
1010 1011
void FileStorage::Impl::writeComment(const char *comment, bool eol_comment) {
    CV_Assert(write_mode);
1012
    getEmitter().writeComment(comment, eol_comment);
S
Smirnov Egor 已提交
1013
}
1014

S
Smirnov Egor 已提交
1015 1016 1017 1018 1019 1020
void FileStorage::Impl::startNextStream() {
    CV_Assert(write_mode);
    if (!empty_stream) {
        while (!write_stack.empty())
            endWriteStruct();
        flush();
1021
        getEmitter().startNextStream();
S
Smirnov Egor 已提交
1022 1023 1024
        empty_stream = true;
        write_stack.push_back(FStructData("", FileNode::EMPTY, 0));
        bufofs = 0;
1025
    }
S
Smirnov Egor 已提交
1026
}
1027

S
Smirnov Egor 已提交
1028 1029
void FileStorage::Impl::write(const String &key, int value) {
    CV_Assert(write_mode);
1030
    getEmitter().write(key.c_str(), value);
S
Smirnov Egor 已提交
1031
}
1032

S
Smirnov Egor 已提交
1033 1034
void FileStorage::Impl::write(const String &key, double value) {
    CV_Assert(write_mode);
1035
    getEmitter().write(key.c_str(), value);
S
Smirnov Egor 已提交
1036
}
1037

S
Smirnov Egor 已提交
1038 1039
void FileStorage::Impl::write(const String &key, const String &value) {
    CV_Assert(write_mode);
1040
    getEmitter().write(key.c_str(), value.c_str(), false);
S
Smirnov Egor 已提交
1041
}
1042

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

S
Smirnov Egor 已提交
1046 1047 1048 1049 1050 1051
    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);
    }
1052

S
Smirnov Egor 已提交
1053 1054 1055 1056
    size_t elemSize = fs::calcStructSize(dt.c_str(), 0);
    CV_Assert(elemSize);
    CV_Assert(len % elemSize == 0);
    len /= elemSize;
1057

S
Smirnov Egor 已提交
1058 1059 1060 1061
    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] = "";
1062

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

S
Smirnov Egor 已提交
1065 1066
    if (!len)
        return;
1067

S
Smirnov Egor 已提交
1068 1069
    if (!data0)
        CV_Error(cv::Error::StsNullPtr, "Null data pointer");
1070

S
Smirnov Egor 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
    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) {
1089
                    case CV_8U:
S
Smirnov Egor 已提交
1090
                        ptr = fs::itoa(*(uchar *) data, buf, 10);
1091 1092 1093
                        data++;
                        break;
                    case CV_8S:
S
Smirnov Egor 已提交
1094
                        ptr = fs::itoa(*(char *) data, buf, 10);
1095 1096 1097
                        data++;
                        break;
                    case CV_16U:
S
Smirnov Egor 已提交
1098
                        ptr = fs::itoa(*(ushort *) data, buf, 10);
1099 1100 1101
                        data += sizeof(ushort);
                        break;
                    case CV_16S:
S
Smirnov Egor 已提交
1102
                        ptr = fs::itoa(*(short *) data, buf, 10);
1103 1104 1105
                        data += sizeof(short);
                        break;
                    case CV_32S:
S
Smirnov Egor 已提交
1106
                        ptr = fs::itoa(*(int *) data, buf, 10);
1107 1108 1109
                        data += sizeof(int);
                        break;
                    case CV_32F:
S
Smirnov Egor 已提交
1110
                        ptr = fs::floatToString(buf, *(float *) data, false, explicitZero);
1111 1112 1113
                        data += sizeof(float);
                        break;
                    case CV_64F:
S
Smirnov Egor 已提交
1114
                        ptr = fs::doubleToString(buf, *(double *) data, explicitZero);
1115 1116 1117
                        data += sizeof(double);
                        break;
                    case CV_16F: /* reference */
S
Smirnov Egor 已提交
1118
                        ptr = fs::floatToString(buf, (float) *(float16_t *) data, true, explicitZero);
1119 1120 1121
                        data += sizeof(float16_t);
                        break;
                    default:
S
Smirnov Egor 已提交
1122
                        CV_Error(cv::Error::StsUnsupportedFormat, "Unsupported type");
1123 1124 1125
                        return;
                }

1126
                getEmitter().writeScalar(0, ptr);
1127
            }
S
Smirnov Egor 已提交
1128 1129

            offset = (int) (data - data0);
1130 1131
        }
    }
S
Smirnov Egor 已提交
1132
}
1133

S
Smirnov Egor 已提交
1134 1135
void FileStorage::Impl::workaround() {
    check_if_write_struct_is_delayed(false);
1136

S
Smirnov Egor 已提交
1137 1138 1139
    if (state_of_writing_base64 != FileStorage_API::Base64State::Uncertain)
        switch_to_Base64_state(FileStorage_API::Base64State::Uncertain);
}
1140

S
Smirnov Egor 已提交
1141 1142 1143
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.";
1144

S
Smirnov Egor 已提交
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 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
    /* 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;
1212 1213
    }

S
Smirnov Egor 已提交
1214 1215
    state_of_writing_base64 = new_state;
}
1216

S
Smirnov Egor 已提交
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
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);
1228 1229
    }

S
Smirnov Egor 已提交
1230 1231 1232
    if (type_name != nullptr) {
        delayed_type_name = new char[strlen(type_name) + 1U];
        strcpy(delayed_type_name, type_name);
1233 1234
    }

S
Smirnov Egor 已提交
1235 1236
    is_write_struct_delayed = true;
}
1237

S
Smirnov Egor 已提交
1238 1239 1240 1241 1242 1243
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;
1244

S
Smirnov Egor 已提交
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
        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);
        }
1273
    }
S
Smirnov Egor 已提交
1274
}
1275

S
Smirnov Egor 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284
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.");
1285 1286
    }

S
Smirnov Egor 已提交
1287 1288
    base64_writer->write(_data, len, dt);
}
1289

S
Smirnov Egor 已提交
1290 1291 1292
FileNode FileStorage::Impl::getFirstTopLevelNode() const {
    return roots.empty() ? FileNode() : roots[0];
}
1293

S
Smirnov Egor 已提交
1294 1295 1296
FileNode FileStorage::Impl::root(int streamIdx) const {
    return streamIdx >= 0 && streamIdx < (int) roots.size() ? roots[streamIdx] : FileNode();
}
1297

S
Smirnov Egor 已提交
1298 1299 1300
FileNode FileStorage::Impl::operator[](const String &nodename) const {
    return this->operator[](nodename.c_str());
}
1301

S
Smirnov Egor 已提交
1302 1303 1304
FileNode FileStorage::Impl::operator[](const char * /*nodename*/) const {
    return FileNode();
}
1305

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

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

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

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

S
Smirnov Egor 已提交
1314 1315 1316 1317 1318
void FileStorage::Impl::setBufferPtr(char *ptr) {
    char *bufferstart = bufferStart();
    CV_Assert(ptr >= bufferstart && ptr <= bufferEnd());
    bufofs = ptr - bufferstart;
}
1319

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

S
Smirnov Egor 已提交
1322 1323 1324 1325
FStructData &FileStorage::Impl::getCurrentStruct() {
    CV_Assert(!write_stack.empty());
    return write_stack.back();
}
1326

S
Smirnov Egor 已提交
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
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;
1339 1340
    }

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

S
Smirnov Egor 已提交
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
    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;
}
1355

S
Smirnov Egor 已提交
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
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;
    }
1368

S
Smirnov Egor 已提交
1369 1370
    if (*endptr == ptr || cv_isalpha(**endptr))
        processSpecialDouble(ptr, &fval, endptr);
1371

S
Smirnov Egor 已提交
1372 1373
    return fval;
}
1374

S
Smirnov Egor 已提交
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 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
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;
1455 1456
        }

S
Smirnov Egor 已提交
1457 1458
        if (ofs ==
            0)  // FileNode is a first component of this block. Resize current block instead of allocation of new one.
1459
        {
S
Smirnov Egor 已提交
1460 1461 1462 1463 1464 1465
            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;
1466 1467
        }

S
Smirnov Egor 已提交
1468 1469 1470
        shrinkBlock = true;
        shrinkBlockIdx = blockIdx;
        shrinkSize = ofs;
1471 1472
    }

S
Smirnov Egor 已提交
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
    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];
        }
1491 1492
    }

S
Smirnov Egor 已提交
1493 1494 1495 1496
    if (shrinkBlock) {
        fs_data[shrinkBlockIdx]->resize(shrinkSize);
        fs_data_blksz[shrinkBlockIdx] = shrinkSize;
    }
1497

S
Smirnov Egor 已提交
1498 1499
    return new_ptr;
}
1500

S
Smirnov Egor 已提交
1501 1502 1503 1504
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;
}
1505

S
Smirnov Egor 已提交
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
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));
        }
    }
1527

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

S
Smirnov Egor 已提交
1530 1531 1532
    size_t blockIdx = fs_data_ptrs.size() - 1;
    size_t ofs = freeSpaceOfs;
    FileNode node(fs_ext, blockIdx, ofs);
1533

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

S
Smirnov Egor 已提交
1537 1538 1539
    *ptr++ = (uchar) (elem_type | (noname ? 0 : FileNode::NAMED));
    if (elem_type == FileNode::NONE)
        freeSpaceOfs -= 8;
1540

S
Smirnov Egor 已提交
1541 1542 1543 1544
    if (!noname) {
        writeInt(ptr, (int) strofs);
        ptr += 4;
    }
1545

S
Smirnov Egor 已提交
1546 1547 1548
    if (elem_type == FileNode::SEQ || elem_type == FileNode::MAP) {
        writeInt(ptr, 4);
        writeInt(ptr, 0);
1549 1550
    }

S
Smirnov Egor 已提交
1551 1552
    if (value)
        node.setValue(elem_type, value, len);
1553

S
Smirnov Egor 已提交
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
    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;
1578 1579
        }
    }
S
Smirnov Egor 已提交
1580 1581 1582
    rawSize += freeSpaceOfs - ofs;
    writeInt(ptr, (int) rawSize);
}
1583

S
Smirnov Egor 已提交
1584 1585 1586 1587 1588
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;
1589
        }
S
Smirnov Egor 已提交
1590 1591
        ofs -= fs_data_blksz[blockIdx];
        blockIdx++;
1592
    }
S
Smirnov Egor 已提交
1593
}
1594

S
Smirnov Egor 已提交
1595 1596 1597
FileStorage::Impl::Base64State FileStorage::Impl::get_state_of_writing_base64() {
    return state_of_writing_base64;
}
1598

S
Smirnov Egor 已提交
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
int FileStorage::Impl::get_space() {
    return space;
}


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

1612 1613
void FileStorage::Impl::Base64Decoder::init(const Ptr<FileStorageParser> &_parser, char *_ptr, int _indent) {
    parser_do_not_use_direct_dereference = _parser;
S
Smirnov Egor 已提交
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
    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[] =
1625
            {
S
Smirnov Egor 已提交
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
                    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
1642 1643
            };

S
Smirnov Egor 已提交
1644 1645
    if (eos)
        return false;
1646

S
Smirnov Egor 已提交
1647 1648 1649 1650 1651 1652 1653 1654 1655
    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;

1656
    CV_Assert(ptr);
S
Smirnov Egor 已提交
1657
    char *beg = 0, *end = 0;
1658
    bool ok = getParser().getBase64Row(ptr, indent, beg, end);
S
Smirnov Egor 已提交
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
    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('=');
    }
1671

S
Smirnov Egor 已提交
1672 1673 1674 1675
    int i = 0, j, n = (int) encoded.size();
    if (n > 0) {
        const uchar *tab = base64tab;
        char *src = &encoded[0];
1676

S
Smirnov Egor 已提交
1677 1678 1679 1680
        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]];
1681

S
Smirnov Egor 已提交
1682 1683 1684 1685 1686
            decoded.push_back((uchar) ((d << 2) | (c >> 4)));
            decoded.push_back((uchar) ((c << 4) | (b >> 2)));
            decoded.push_back((uchar) ((b << 6) | a));
        }
    }
1687

S
Smirnov Egor 已提交
1688 1689 1690 1691 1692 1693
    if (i > 0 && encoded[i - 1] == '=') {
        if (i > 1 && encoded[i - 2] == '=' && !decoded.empty())
            decoded.pop_back();
        if (!decoded.empty())
            decoded.pop_back();
    }
1694

S
Smirnov Egor 已提交
1695 1696 1697 1698
    n -= i;
    for (j = 0; j < n; j++)
        encoded[j] = encoded[i + j];
    encoded.resize(n);
1699

S
Smirnov Egor 已提交
1700 1701
    return (int) decoded.size() >= needed;
}
1702

S
Smirnov Egor 已提交
1703 1704 1705 1706 1707 1708
uchar FileStorage::Impl::Base64Decoder::getUInt8() {
    size_t sz = decoded.size();
    if (ofs >= sz && !readMore(1))
        return (uchar) 0;
    return decoded[ofs++];
}
1709

S
Smirnov Egor 已提交
1710 1711 1712 1713 1714 1715 1716 1717
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;
}
1718

S
Smirnov Egor 已提交
1719 1720 1721 1722 1723 1724 1725 1726
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;
}
1727

S
Smirnov Egor 已提交
1728 1729 1730 1731 1732 1733 1734 1735
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;
}
1736

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

S
Smirnov Egor 已提交
1739
char *FileStorage::Impl::Base64Decoder::getPtr() const { return ptr; }
1740 1741


S
Smirnov Egor 已提交
1742 1743 1744
char *FileStorage::Impl::parseBase64(char *ptr, int indent, FileNode &collection) {
    const int BASE64_HDR_SIZE = 24;
    char dt[BASE64_HDR_SIZE + 1] = {0};
1745
    base64decoder.init(parser_do_not_use_direct_dereference, ptr, indent);
1746

S
Smirnov Egor 已提交
1747
    int i, k;
1748

S
Smirnov Egor 已提交
1749 1750 1751 1752 1753 1754
    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';
1755

S
Smirnov Egor 已提交
1756
    CV_Assert(!base64decoder.endOfStream());
1757

S
Smirnov Egor 已提交
1758 1759 1760 1761
    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;
1762

S
Smirnov Egor 已提交
1763 1764 1765 1766
    for (;;) {
        for (k = 0; k < fmt_pair_count; k++) {
            int elem_type = fmt_pairs[k * 2 + 1];
            int count = fmt_pairs[k * 2];
1767

S
Smirnov Egor 已提交
1768 1769 1770
            for (i = 0; i < count; i++) {
                int node_type = FileNode::INT;
                switch (elem_type) {
1771 1772 1773 1774
                    case CV_8U:
                        ival = base64decoder.getUInt8();
                        break;
                    case CV_8S:
S
Smirnov Egor 已提交
1775
                        ival = (char) base64decoder.getUInt8();
1776 1777 1778 1779 1780
                        break;
                    case CV_16U:
                        ival = base64decoder.getUInt16();
                        break;
                    case CV_16S:
S
Smirnov Egor 已提交
1781
                        ival = (short) base64decoder.getUInt16();
1782 1783 1784 1785
                        break;
                    case CV_32S:
                        ival = base64decoder.getInt32();
                        break;
S
Smirnov Egor 已提交
1786
                    case CV_32F: {
1787 1788 1789 1790
                        Cv32suf v;
                        v.i = base64decoder.getInt32();
                        fval = v.f;
                        node_type = FileNode::REAL;
S
Smirnov Egor 已提交
1791
                    }
1792 1793 1794 1795 1796 1797
                        break;
                    case CV_64F:
                        fval = base64decoder.getFloat64();
                        node_type = FileNode::REAL;
                        break;
                    case CV_16F:
S
Smirnov Egor 已提交
1798
                        fval = (float) float16_t::fromBits(base64decoder.getUInt16());
1799 1800 1801
                        node_type = FileNode::REAL;
                        break;
                    default:
S
Smirnov Egor 已提交
1802
                        CV_Error(Error::StsUnsupportedFormat, "Unsupported type");
1803
                }
S
Smirnov Egor 已提交
1804 1805 1806 1807 1808

                if (base64decoder.endOfStream())
                    break;
                addNode(collection, std::string(), node_type,
                        node_type == FileNode::INT ? (void *) &ival : (void *) &fval, -1);
1809 1810
            }
        }
S
Smirnov Egor 已提交
1811 1812
        if (base64decoder.endOfStream())
            break;
1813 1814
    }

S
Smirnov Egor 已提交
1815 1816 1817
    finalizeCollection(collection);
    return base64decoder.getPtr();
}
1818

S
Smirnov Egor 已提交
1819 1820 1821 1822 1823
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);
}
1824

S
Smirnov Egor 已提交
1825 1826 1827
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]);
1828

S
Smirnov Egor 已提交
1829 1830
    return fs_data_ptrs[blockIdx] + ofs;
}
1831

S
Smirnov Egor 已提交
1832 1833 1834 1835
std::string FileStorage::Impl::getName(size_t nameofs) const {
    CV_Assert(nameofs < str_hash_data.size());
    return std::string(&str_hash_data[nameofs]);
}
1836

S
Smirnov Egor 已提交
1837
FileStorage *FileStorage::Impl::getFS() { return fs_ext; }
1838 1839 1840


FileStorage::FileStorage()
1841
    : state(0)
1842 1843 1844 1845 1846
{
    p = makePtr<FileStorage::Impl>(this);
}

FileStorage::FileStorage(const String& filename, int flags, const String& encoding)
1847
    : state(0)
1848 1849 1850 1851 1852 1853 1854 1855 1856
{
    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 已提交
1857
    p->startWriteStruct(name.size() ? name.c_str() : 0, struct_flags, typeName.size() ? typeName.c_str() : 0);
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
    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)
{
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
    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
    }
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 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
}

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 已提交
1932
        CV_Error( cv::Error::StsBadArg, "Invalid filename" );
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962

    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
{
1963
    return this->operator[](std::string(key));
1964 1965 1966 1967
}

FileNode FileStorage::operator [](const std::string& key) const
{
1968 1969 1970 1971 1972 1973 1974 1975
    FileNode res;
    for (size_t i = 0; i < p->roots.size(); i++)
    {
        res = p->roots[i][key];
        if (!res.empty())
            break;
    }
    return res;
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 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
}

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 已提交
2055 2056 2057
            CV_Error_( cv::Error::StsError, ("Extra closing '%c'", *_str) );

        fs_impl->workaround();
2058 2059 2060 2061

        int struct_flags = fs_impl->write_stack.back().flags;
        char expected_bracket = FileNode::isMap(struct_flags) ? '}' : ']';
        if( c != expected_bracket )
S
Smirnov Egor 已提交
2062
            CV_Error_( cv::Error::StsError, ("The closing '%c' does not match the opening '%c'", c, expected_bracket));
2063 2064 2065 2066 2067 2068 2069 2070 2071
        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 已提交
2072
            CV_Error_( cv::Error::StsError, ("Incorrect element name %s; should start with a letter or '_'", _str) );
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
        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 已提交
2101
        CV_Error( cv::Error::StsError, "Invalid fs.state" );
2102 2103 2104 2105 2106
    return fs;
}


FileNode::FileNode()
2107
    : fs(NULL)
2108 2109 2110 2111
{
    blockIdx = ofs = 0;
}

2112 2113
FileNode::FileNode(FileStorage::Impl* _fs, size_t _blockIdx, size_t _ofs)
    : fs(_fs)
2114 2115 2116 2117 2118
{
    blockIdx = _blockIdx;
    ofs = _ofs;
}

2119 2120 2121 2122 2123 2124
FileNode::FileNode(const FileStorage* _fs, size_t _blockIdx, size_t _ofs)
    : FileNode(_fs->p.get(), _blockIdx, _ofs)
{
    // nothing
}

2125 2126 2127 2128 2129 2130 2131
FileNode::FileNode(const FileNode& node)
{
    fs = node.fs;
    blockIdx = node.blockIdx;
    ofs = node.ofs;
}

2132 2133 2134 2135 2136 2137 2138 2139
FileNode& FileNode::operator=(const FileNode& node)
{
    fs = node.fs;
    blockIdx = node.blockIdx;
    ofs = node.ofs;
    return *this;
}

2140 2141 2142 2143 2144 2145 2146
FileNode FileNode::operator[](const std::string& nodename) const
{
    if(!fs)
        return FileNode();

    CV_Assert( isMap() );

2147
    unsigned key = fs->getStringOfs(nodename);
2148 2149 2150 2151 2152 2153 2154 2155
    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);
2156
        CV_Assert( key2 < fs->str_hash_data.size() );
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
        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;
}

2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
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;
}

2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
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);
2232
    return fs->getName(nameofs);
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 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
}

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;
}

2298 2299
double FileNode::real() const  { return double(*this); }
std::string FileNode::string() const
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 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
{
    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()
{
2357
    return !fs ? 0 : (uchar*)fs->getNodePtr(blockIdx, ofs);
2358 2359 2360 2361
}

const uchar* FileNode::ptr() const
{
2362
    return !fs ? 0 : fs->getNodePtr(blockIdx, ofs);
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
}

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");

2393
    p = fs->reserveNodeSpace(*this, sz);
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 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
    *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;
            }
        }
2467 2468
        fs->normalizeNodeOfs(blockIdx, ofs);
        blockSize = fs->fs_data_blksz[blockIdx];
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
    }
}

FileNodeIterator::FileNodeIterator(const FileNodeIterator& it)
{
    fs = it.fs;
    blockIdx = it.blockIdx;
    ofs = it.ofs;
    blockSize = it.blockSize;
    nodeNElems = it.nodeNElems;
    idx = it.idx;
}
2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491

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;
}
2492 2493 2494

FileNode FileNodeIterator::operator *() const
{
2495
    return FileNode(idx < nodeNElems ? fs : NULL, blockIdx, ofs);
2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
}

FileNodeIterator& FileNodeIterator::operator ++ ()
{
    if( idx == nodeNElems || !fs )
        return *this;
    idx++;
    FileNode n(fs, blockIdx, ofs);
    ofs += n.rawSize();
    if( ofs >= blockSize )
    {
2507 2508
        fs->normalizeNodeOfs(blockIdx, ofs);
        blockSize = fs->fs_data_blksz[blockIdx];
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 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
    }
    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();
}

}

2725
}