Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

Custom streambuf instead of istringstream for read_model(string model) (#30334)

Bartlomiej Filipek6715f0e41e85
diff --git a/src/common/util/include/openvino/util/common_util.hpp b/src/common/util/include/openvino/util/common_util.hpp
index 34ca2673d3a..4efd9774669 100644
--- a/src/common/util/include/openvino/util/common_util.hpp
+++ b/src/common/util/include/openvino/util/common_util.hpp
@@ -206,5 +206,55 @@ constexpr bool may_i_use_dynamic_code() {
}
#endif
+/**
+ * @brief A custom stream buffer that provides read-only access to a string view.
+ *
+ * This class inherits from `std::streambuf` and is designed to facilitate
+ * input operations directly on a `std::string_view` without copying the
+ * underlying string data. It allows for efficient reading and seeking
+ * operations within the string view.
+ *
+ * @note This stream buffer is intended for input operations only.
+ * @see pyopenvino/utils/utils.hpp for a similar implementation
+ */
+class StringViewStreamBuf : public std::streambuf {
+public:
+ explicit StringViewStreamBuf(std::string_view sv) {
+ char* begin = const_cast<char*>(sv.data());
+ setg(begin, begin, begin + sv.size());
+ }
+
+protected:
+ pos_type seekoff(off_type off,
+ std::ios_base::seekdir dir,
+ std::ios_base::openmode which = std::ios_base::in) override {
+ if (which != std::ios_base::in) {
+ return off_type(-1);
+ }
+
+ switch (dir) {
+ case std::ios_base::beg:
+ setg(eback(), eback() + off, egptr());
+ break;
+ case std::ios_base::end:
+ setg(eback(), egptr() + off, egptr());
+ break;
+ case std::ios_base::cur:
+ setg(eback(), gptr() + off, egptr());
+ break;
+ default:
+ return off_type(-1);
+ }
+ if (gptr() < eback() || gptr() > egptr())
+ return off_type(-1);
+
+ return gptr() - eback();
+ }
+
+ pos_type seekpos(pos_type pos, std::ios_base::openmode which) override {
+ return seekoff(pos, std::ios_base::beg, which);
+ }
+};
+
} // namespace util
} // namespace ov
diff --git a/src/inference/src/model_reader.cpp b/src/inference/src/model_reader.cpp
index de8e865d23d..a7622a2423a 100644
--- a/src/inference/src/model_reader.cpp
+++ b/src/inference/src/model_reader.cpp
@@ -10,6 +10,7 @@
#include "openvino/frontend/manager.hpp"
#include "openvino/runtime/aligned_buffer.hpp"
#include "openvino/runtime/shared_buffer.hpp"
+#include "openvino/util/common_util.hpp"
#include "openvino/util/file_util.hpp"
#include "transformations/utils/utils.hpp"
@@ -164,8 +165,8 @@ std::shared_ptr<ov::Model> read_model(const std::string& model,
const ov::Tensor& weights,
const std::vector<ov::Extension::Ptr>& ov_exts,
bool frontendMode) {
- std::istringstream modelStringStream(model);
- std::istream& modelStream = modelStringStream;
+ StringViewStreamBuf mb(std::string_view{model});
+ std::istream modelStream(&mb);
// Try to load with FrontEndManager
ov::frontend::FrontEndManager manager;