nareshmlx/opencv-pr huggingface dataset:
**File:** modules/videoio/src/container_avi.cpp
**Change Type:** modified
**Context:** PR #11964: AVI container fixes - Resolves #11841 ### This pullrequest changes * use C++ streams for file I/O * added check for integer overflows in so...
**Review Line:** 22

**Code Changes:**
```diff
+    typedef std::numeric_limits<S> st;
+    typedef std::numeric_limits<D> dt;
+    CV_StaticAssert(st::is_integer && dt::is_integer, "Integer type is expected");
+    const bool in_range_r = (double)val <= (double)dt::max();
+    const bool in_range_l = (double)val >= (double)dt::min();
+    if (!in_range_r || !in_range_l)
+    {
+        CV_Error_(cv::Error::StsOutOfRange, ("Can not convert integer values (%s -> %s), value 0x%llx is out of range", typeid(S).name(), typeid(D).name(), val));
+    }
+    return static_cast<D>(val);
+}
```

Review comment:
BTW, It would be nice to have similar function for other part of code too, at least `imgcodecs`.
**File:** samples/cpp/gstreamer_pipeline.cpp
**Change Type:** modified
**Context:** PR #11804: GStreamer sample: fixes and refactoring - ### This pullrequest changes * in some modes incorrect pipelines have been generated * refactored...
**Review Line:** 364

**Code Changes:**
```diff
-};
-
-int main(int argc, char *argv[])
-{
-    try
+    total.stop();
+    if (tick.getCounter() == 0)
     {
-        GStreamerPipeline pipe(argc, argv);
-        return pipe.run();
+        cout << "No frames have been processed" << endl;
```

Review comment:
Before stop it is better to release capture and/or writer to cancel/flush pending operations. Without that measurement is not accurate.
**File:** samples/cpp/gstreamer_pipeline.cpp
**Change Type:** modified
**Context:** PR #11804: GStreamer sample: fixes and refactoring - ### This pullrequest changes * in some modes incorrect pipelines have been generated * refactored...
**Review Line:** 255

**Code Changes:**
```diff
-    // Choose a libav codec
-    string getGstAvCodePlugin()
+    bool fast_measure = cmd_parser.has("fast");               // fast measure fps
+    unsigned fix_fps      = cmd_parser.get<unsigned>("fps");      // fixed frame per second
+    string backend     = cmd_parser.get<string>("backend");   // video backend
+    string mode         = cmd_parser.get<string>("mode");       // coding mode
+    string codec        = cmd_parser.get<string>("codec");      // codec type
+    string file_name    = cmd_parser.get<string>("file");       // path to videofile
+    string resolution   = cmd_parser.get<string>("resolution"); // video resolution
+    if (!cmd_parser.check())
     {
```

Review comment:
Please fix "columns" (space formatting) or remove them at all.
**File:** modules/imgproc/include/opencv2/imgproc.hpp
**Change Type:** modified
**Context:** PR #13843: LineIterator witout a Mat - cv::LineIterator can be used without being attached to any cv::Mat, it only needs the size and type of data. An...
**Review Line:** 4696

**Code Changes:**
```diff
-                  int connectivity = 8, bool leftToRight = false );
+                  int connectivity = 8, bool leftToRight = false ) {
+      init(img.size(), img.type(), (uchar*)img.ptr(), img.step1()*img.elemSize1(), pt1, pt2, connectivity, leftToRight);
+    }
+    LineIterator( const Size& size, int type, Point pt1, Point pt2,
+                  int connectivity = 8, bool leftToRight = false ) {
+      init(size, type, 0, CV_ELEM_SIZE(type)*size.width, pt1, pt2, connectivity, leftToRight);
+    }
+    void init(const Size& size, int type, uchar* data, size_t dataStep, Point pt1, Point pt2, int connectivity = 8, bool leftToRight = false);
+
     /** @brief returns pointer to the current pixel
```

Review comment:
`type` is not needed for this interface at all.
**File:** modules/imgproc/include/opencv2/imgproc.hpp
**Change Type:** modified
**Context:** PR #13843: LineIterator witout a Mat - cv::LineIterator can be used without being attached to any cv::Mat, it only needs the size and type of data. An...
**Review Line:** 4729

**Code Changes:**
```diff
@@ -4718,7 +4726,7 @@ class CV_EXPORTS LineIterator
 inline
 uchar* LineIterator::operator *()
 {
-    return ptr;
+    return !ptr0 ? 0 : ptr;//when no Mat is attached, ptr is just a dummy address and should not be dereferenced
 }
 
 inline
```

Review comment:
"Contact" of this call has been changed. This patch allows "NULL" as a result. At least this would produces static analyzers issues which need to be resolved after this patch.
**File:** modules/core/include/opencv2/core/persistence.hpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 313

**Code Changes:**
```diff
@@ -314,7 +310,7 @@ class CV_EXPORTS_W FileStorage
         WRITE       = 1, //!< value, open the file for writing
         APPEND      = 2, //!< value, open the file for appending
         MEMORY      = 4, //!< flag, read data from source or write data to the internal buffer (which is
-                         //!< returned by FileStorage::release)
+        //!< returned by FileStorage::release)
         FORMAT_MASK = (7<<3), //!< mask for format flags
         FORMAT_AUTO = 0,      //!< flag, auto format
         FORMAT_XML  = (1<<3), //!< flag, XML format
@@ -334,105 +330,77 @@ class CV_EXPORTS_W FileStorage
 
```

Review comment:
unnecessary change
**File:** modules/core/include/opencv2/core/persistence.hpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 334

**Code Changes:**
```diff
     /** @brief The constructors.
 
-    The full constructor opens the file. Alternatively you can use the default constructor and then
-    call FileStorage::open.
+     The full constructor opens the file. Alternatively you can use the default constructor and then
+     call FileStorage::open.
      */
     CV_WRAP FileStorage();
 
     /** @overload
-    @copydoc open()
```

Review comment:
unnecessary indentation changes here and below
**File:** modules/core/include/opencv2/core/persistence.hpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 454

**Code Changes:**
```diff
-    String elname; //!< the currently written element
-    std::vector<char> structs; //!< the stack of written structures
-    int state; //!< the writer state
-};
+    int state;
+    std::string elname;
 
-template<> struct DefaultDeleter<CvFileStorage>{ CV_EXPORTS void operator ()(CvFileStorage* obj) const; };
+    class Impl;
+    Ptr<Impl> p;
+};
```

Review comment:
Private implementation details should be avoided. Also related enum (line 321) should go away from public headers: ``` enum { UNDEFINED = 0, VALUE_EXPECTED = 1, NAME_EXPECTED = 2, INSIDE_MAP = 4 }; ``` Especially it is re-implemented [here](https://github.com/opencv/opencv/pull/13011/files#diff-e5fc6851ac1f5df04e2f42ed3570cf75R343).
**File:** modules/core/include/opencv2/core/persistence.hpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 530

**Code Changes:**
```diff
-    CV_WRAP std::vector<String> keys() const;
+    CV_WRAP_AS(at) FileNode operator[](int i) const;
 
     /** @brief Returns type of the node.
-    @returns Type of the node. See FileNode::Type
+     @returns Type of the node. See FileNode::Type
      */
     CV_WRAP int type() const;
 
@@ -571,9 +548,11 @@ class CV_EXPORTS_W_SIMPLE FileNode
     //! returns true if the node has a name
```

Review comment:
> FileNode::Type Reference is broken because [name of enum is dropped](https://github.com/opencv/opencv/pull/13011/files#diff-0d97f3ae80657b8562299cb90a037692R476). Why?
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 321

**Code Changes:**
```diff
+    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
```

Review comment:
API of these functions doesn't look safe. Who controls and **checks** size of available buffer?
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 346

**Code Changes:**
```diff
+{
+public:
+    enum State
+    {
+        UNDEFINED      = 0,
+        VALUE_EXPECTED = 1,
+        NAME_EXPECTED  = 2,
+        INSIDE_MAP     = 4
+    };
+
+    void init()
```

Review comment:
Remove "enum" duplicate from the public header.
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 474

**Code Changes:**
```diff
+        std::vector<std::string> params;
+        //if ( !mem_mode )
+        {
+            analyze_file_name( filename_or_buf, params );
+            if( !params.empty() )
+                filename = params[0];
+
+            /*if( !write_base64 && params.size() >= 2 &&
+                std::find(params.begin()+1, params.end(), std::string("base64")) != params.end())
+                write_base64 = (write_mode || append);*/
+        }
```

Review comment:
1. 'bool' return value looks more convenient: ``` if (analyze_file_name(filename_or_buf, params)) { CV_Assert(!params.empty()); CV_Assert(!params[0].empty()); filename = params[0]; } else { // not a filename, ensure that user specify FileStorage::MEMORY flag if (!mem_mode) CV_Error(Error::StsError, "malformed filename for FileStorage or missing FileStorage::MEMORY flag"); } ``` 2. "const char*" for buffers without "size" is insecure API.
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 478

**Code Changes:**
```diff
+            if( !params.empty() )
+                filename = params[0];
+
+            /*if( !write_base64 && params.size() >= 2 &&
+                std::find(params.begin()+1, params.end(), std::string("base64")) != params.end())
+                write_base64 = (write_mode || append);*/
+        }
+
+        if( filename.size() == 0 && !mem_mode && !write_mode )
+            CV_Error( CV_StsNullPtr, "NULL or empty filename" );
+
```

Review comment:
Commented out code is dead and must be removed from codebase. For history purposes there is "git".
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 481

**Code Changes:**
```diff
+            /*if( !write_base64 && params.size() >= 2 &&
+                std::find(params.begin()+1, params.end(), std::string("base64")) != params.end())
+                write_base64 = (write_mode || append);*/
+        }
+
+        if( filename.size() == 0 && !mem_mode && !write_mode )
+            CV_Error( CV_StsNullPtr, "NULL or empty filename" );
+
+        if( mem_mode && append )
+            CV_Error( CV_StsBadFlag, "FileStorage::APPEND and FileStorage::MEMORY are not currently compatible" );
+
```

Review comment:
> `filename.size() == 0` `filename.empty()`
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 482

**Code Changes:**
```diff
+                std::find(params.begin()+1, params.end(), std::string("base64")) != params.end())
+                write_base64 = (write_mode || append);*/
+        }
+
+        if( filename.size() == 0 && !mem_mode && !write_mode )
+            CV_Error( CV_StsNullPtr, "NULL or empty filename" );
+
+        if( mem_mode && append )
+            CV_Error( CV_StsBadFlag, "FileStorage::APPEND and FileStorage::MEMORY are not currently compatible" );
+
+        flags = _flags;
```

Review comment:
> write_mode > "NULL or empty filename" Message doesn't look relevant to used condition.
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 568

**Code Changes:**
```diff
+                fmt = FileStorage::FORMAT_XML;
+            }
+
+            // 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;
+
+            if (append)
+            {
+                fseek( file, 0, SEEK_END );
+                if (ftell(file) == 0)
```

Review comment:
and 1024 for missing buffer limit checks...
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 581

**Code Changes:**
```diff
+
+            write_stack.clear();
+            empty_stream = true;
+            write_stack.push_back(FStructData("", FileNode::MAP | FileNode::EMPTY, 0));
+            buffer.reserve(buf_size + 1024);
+            buffer.resize(buf_size);
+            bufofs = 0;
+
+            if( fmt == FileStorage::FORMAT_XML )
+            {
+                size_t file_size = file ? (size_t)ftell(file) : (size_t)0;
```

Review comment:
`buf_size` vs `buffer.size()` mess.
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 594

**Code Changes:**
```diff
+                    if( encoding && *encoding != '\0' )
+                    {
+                        if( fs::strcasecmp(encoding, "UTF-16" ) == 0 )
+                        {
+                            release();
+                            CV_Error( CV_StsBadArg, "UTF-16 XML encoding is not supported! Use 8-bit encoding\n");
+                        }
+
+                        CV_Assert( strlen(encoding) < 1000 );
+                        char buf[1100];
+                        sprintf(buf, "<?xml version=\"1.0\" encoding=\"%s\"?>\n", encoding);
```

Review comment:
1. Is UTF-32 supported? Or `UTF-7`? `Windows-1252`? IMHO, we should have whitelist here. Proper check should be: ``` if (fs::strcasecmp(encoding, "utf-8") != 0) { CV_Error( CV_StsBadArg, "UTF-8 XML encoding is supported only!"); } ``` 2. `release()` must be called automatically. Otherwise implementation of other `CV_Assert()` statement are incorrect.
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 693

**Code Changes:**
```diff
+                    {
+                        CV_Error( CV_StsError, "Could not find '}' in the end of file.\n" );
+                    }
+                }
+                write_stack.back().indent = 4;
+                emitter = createJSONEmitter(this);
+            }
+            is_opened = true;
+        }
+        else
+        {
```

Review comment:
30 lines above should be handled by implementation of `createJSONEmitter`. Functions over 400 lines should be avoided.
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 724

**Code Changes:**
```diff
+            else if(strncmp( bufPtr, xml_signature, strlen(xml_signature) ) == 0)
+                fmt = FileStorage::FORMAT_XML;
+            else if(strbufsize  == bufOffset)
+                CV_Error(CV_BADARG_ERR, "Input file is empty");
+            else
+                CV_Error(CV_BADARG_ERR, "Unsupported file storage format");
+
+            if( !isGZ )
+            {
+                if( !mem_mode )
+                {
```

Review comment:
> CV_BADARG_ERR It is not in the list of approved error codes for `CV_Error()` macro
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 942

**Code Changes:**
```diff
+
+        CV_Assert(written_len <= (int)buffer.size());
+        int new_size = (int)((buffer_end - buffer_start)*3/2);
+        new_size = MAX( written_len + len, new_size );
+        buffer.reserve( new_size + 256 );
+        buffer.resize( new_size );
+        bufofs = written_len;
+        return &buffer[0] + bufofs;
+    }
+
+    char* flush()
```

Review comment:
Do we have somewhere another 256 errors? It is better to zero that buggy tails and capture memory errors via valgrind.
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 932

**Code Changes:**
```diff
+    }
+
+    char* resizeWriteBuffer( char* ptr, int len )
+    {
+        const char* buffer_end = &buffer[0] + buffer.size();
+        if( ptr + len < buffer_end )
+            return ptr;
+
+        const char* buffer_start = &buffer[0];
+        int written_len = (int)(ptr - buffer_start);
+
```

Review comment:
> &buffer[0] Without `.empty()` check static code analyzers reports UB here. It is better to use `.data` instead (https://en.cppreference.com/w/cpp/container/vector/data) ``` const char* buffer_start = buffer.data(); const char* buffer_end = buffer_start + buffer.size(); CV_Assert(ptr >= buffer_start && ptr < buffer_end); ```
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 947

**Code Changes:**
```diff
+        buffer.resize( new_size );
+        bufofs = written_len;
+        return &buffer[0] + bufofs;
+    }
+
+    char* flush()
+    {
+        char* buffer_start = &buffer[0];
+        char* ptr = buffer_start + bufofs;
+
+        if( ptr > buffer_start + space )
```

Review comment:
ambiguous name. Implementation looks like `writeBufferLine()` `puts()` for working with external stream `...` for processing buffer and `write*()` as external API It is better to separate "stream", "buffer" and external API calls somehow.
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 982

**Code Changes:**
```diff
+
+        FStructData& current_struct = write_stack.back();
+        if( fmt == FileStorage::FORMAT_JSON && !FileNode::isFlow(current_struct.flags) && write_stack.size() > 1 )
+            current_struct.indent = write_stack[write_stack.size() - 2].indent;
+
+        emitter->endWriteStruct(current_struct);
+
+        write_stack.pop_back();
+        if( !write_stack.empty() )
+            write_stack.back().flags &= ~FileNode::EMPTY;
+    }
```

Review comment:
> fmt == FileStorage::FORMAT_JSON Such conditions should be handled by "emitter" implementation.
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 1128

**Code Changes:**
```diff
+                        break;
+                    case CV_64F:
+                        ptr = fs::doubleToString( buf, *(double*)data, explicitZero );
+                        data += sizeof(double);
+                        break;
+                    case CV_16F: /* reference */
+                        ptr = fs::floatToString( buf, (float)*(float16_t*)data, true, explicitZero );
+                        data += sizeof(float16_t);
+                        break;
+                    default:
+                        CV_Error( CV_StsUnsupportedFormat, "Unsupported type" );
```

Review comment:
> reference Not anymore
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 1148

**Code Changes:**
```diff
+    }
+
+    void writeRawDataBase64(const void* /*data*/, int /*len*/, const char* /*dt*/ )
+    {
+
+    }
+
+    String releaseAndGetString();
+
+    FileNode getFirstTopLevelNode() const
+    {
```

Review comment:
Lost implementation ? or add comment: `/* nothing */`
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 1213

**Code Changes:**
```diff
+        if( c != '.' )
+            CV_PARSE_ERROR_CPP( "Bad format of floating-point constant" );
+
+        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" );
```

Review comment:
Missing buffer size check.
**File:** modules/core/src/persistence.cpp
**Change Type:** modified
**Context:** PR #13011: completely new C++ persistence implementation - replaced the old persistence (CvMemStorage, CvSeq-based) with the new C++ implementation. T...
**Review Line:** 1219

**Code Changes:**
```diff
+            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;
+    }
+
+    double strtod( char* ptr, char** endptr )
+    {
```

Review comment:
I didn't see any problems which block using of `std::numeric_limits<double>::infinity()` and `std::numeric_limits<double>::quiet_NaN()` here instead of `inf_hi = c == '-' ? 0xfff00000 : 0x7ff00000`.