microsoft / GSL

Guidelines Support Library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Provide a "safe" and "simple" way for binary I/O

jdgarciauc3m opened this issue · comments

The iostream library offers a classical interface for binary read/write, which requires a char* and a size. This is an error-prone interface. Besides it does not integrate well with buffers represented as spans of std::byte.

There are, at least, a couple of alternatives that could be integrated in the GSL:

  1. Provide wrapper functions for read() and write().
  2. Provide a function as_buffer along the lines of the as_bytes function in Programming Principles and Practice 2nd Ed (Bjarne Stroustrup).

Wrapper functions

We might offer global functions

template <typename T>
void read(istream & is, T & value);

template <typename T>
void write(ostream & os, T const & value);

We might need specializations for specific types (e.g.: span)

Buffer convenience function

Programming Principles and Practice offers the following function:

template<class T>
char* as_bytes(T& i)    // treat a T as a sequence of bytes
{
void* addr = &i;    // get the address of the first byte
                                // of memory used to store the object
return static_cast<char*>(addr);     // treat that memory as bytes
}

We might name such a function as_buffer.

An addition might be to offer an specialization when T is a span of bytes.

Hi @jdgarciauc3m,
Thanks for submitting this issue 😃. Since the questions here are discussing interfaces that aren't fully specified by the Core Guidelines, I've forwarded the question to that repo (isocpp/CppCoreGuidelines#2067), along with some thoughts/comments.

Maintainers call: The Core Guidelines maintainers prefer not to add individual span overloads/wrappers for standard library interfaces that take raw pointers and lengths, that should be in the standard. We've asked the standards committee to do this and there is interest in making span interfaces throughout the standard library including this example.