Reputation: 1841
I am using the c++/17 std::string_view to pass around a raw memory buffer I obtained from the system through a locking operation (IMFMediaBuffer.Lock(..) in Windows Media foundation) and am passing the contents of that view to a function that takes a std::istream& as input - to that end I am currently constructing a new std::istringstream initialized with the view contents as follows:
std::string_view strv{(char*)buffer, length};
{
std::istringstream strs{(const std::string)strv};
auto foo = parse(ss); // parse takes std::istream& as input
} // strs out of scope and destroyed before strv so any copy operation constructing strs was waisted!
Which does the job for now but includes a totally redundant memory copy that I would very much like to avoid since am dealing with several hundred kilobytes (JPEG image data that is only required during the parsing).
Is there any way to achieve this using standard libraries or am I going to have to write something extra to get around it?
Upvotes: 0
Views: 200
Reputation: 69892
The boost libraries are not 'standard c++' but are very useful and historically pivotal to the success of c++ as a language.
boost.iostreams is a library of composable templates that allow you to construct standard iostream-compatible streams with layers of functionality.
You don't need most of it, but a class that matches your requirement comes shrink-wrapped:
This code has been modified from the boost documentation to match your requirements.
#include <cassert>
#include <string_view>
#include <string>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/range/iterator_range.hpp>
namespace io = boost::iostreams;
int main()
{
std::string_view input = "Hello World!";
std::string output;
io::filtering_istream in(boost::make_iterator_range(input));
getline(in, output);
assert(input == output);
}
Note that the filtering_istream is derived from std::istream
so it should work with your parse
function.
https://www.boost.org/doc/libs/1_71_0/libs/iostreams/doc/index.html
section 2.2.1 - bottom of page
Upvotes: 1