-
I'm looking at the possibility of converting some code we've currently got from RapidXml to pugixml. At the moment, we have a function that uses this sort of idea: bool myclass::myfunc(char *buffer)
{
char *end = rapidxml::print(buffer, m_doc, 0);
// do some stuff
} so it's called with a pointer to a block of memory that's (hopefully!) big enough to just write to. As far as I can see, there's no direct equivalent in pugixml, so I'd need to use an alternative mechanism. I've been playing around with 2 x different options, but wonder if I'm missing something! The first one is to override std::streambuf, something like this (but probably with a load of other extra overridden virtual functions): bool myclass::myfunc(char *buffer)
{
struct membuf : public std::streambuf
{
membuf(char *p, size_t size)
{
setp(p, p + size);
}
size_t written()
{
return pptr() - pbase();
};
};
membuf savbuf(buffer, 512); // mmm - size is an issue; it's not passed into this function!
std::ostream out(&savbuf);
m_pdoc.save(out);
char *end = buffer + savbuf.written();
// do stuff Or, alternatively, but overriding the xml_writer base class, something like: bool myclass::myfunc(char *buffer)
{
class xml_writer_buf : public pugi::xml_writer
{
public:
xml_writer_buf(char *p)
{
m_current = p;
}
void write(const void *data, size_t size)
{
memcpy(reinterpret_cast<void*>(m_current), data, size);
m_numberWritten += size;
}
size_t written()
{
return m_numberWritten;
}
private:
size_t m_numberWritten { 0u };
char *m_current { nullptr };
};
xml_writer_buf out { buffer };
m_pdoc.save(out);
char *end = buffer + out.written(); I'm just wondering if there's a 'simpler' way. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Either of these two are more or less how this is intended to work, yes. pugixml doesn't have a built-in function to do this; I'm not sure what exactly |
Beta Was this translation helpful? Give feedback.
Either of these two are more or less how this is intended to work, yes. pugixml doesn't have a built-in function to do this; I'm not sure what exactly
rapidxml::print
does in case the amount of bytes it needs to write is larger than the sizebuf
has allocated, but either way pugixml expects you to manage this in the writer implementation yourself (for example, by flushing chunks to the external output as the pre-allocated memory gets exhausted, or by reallocating memory to fit). The specific example implementation ofxml_write_buf
doesn't handle this safely (it's fine if it's just an example to illustrate the concept of course).