Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
jdgarciauc3m opened this issue Apr 16, 2023 · 2 comments
Closed

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

jdgarciauc3m opened this issue Apr 16, 2023 · 2 comments

Comments

@jdgarciauc3m
Copy link

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.

@dmitrykobets-msft
Copy link
Member

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.

@hsutter
Copy link
Collaborator

hsutter commented Oct 18, 2023

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.

@hsutter hsutter closed this as completed Oct 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants