ryu icon indicating copy to clipboard operation
ryu copied to clipboard

Feature request: add bounded versions of f2s(), d2s() et al

Open biojppm opened this issue 5 years ago • 1 comments

A very common usage pattern of such functions is the following

// the output buffer; could be another type, eg char*
std::string s;
// how large is enough? We can never 100% sure in advance
// that the buffer size is enough for a safe write
s.resize(5);
// s is not enough for this:
float value = 1234567.f;

// So make s2f() aware of how much space we can write on.
// The requested function receives how large the write buffer is,
// so it can safely stop writing to it when the space is exhausted,
// but does not return and in fact proceeds
// through the algorithm /as if/ if it was writing, so it can find the needed size,
// which would be the return value:
int needed_size = f2s_buffered_sz(value, s.data(), (int)s.size()); 

// With this we now know the needed size, so we call the function again if the
// buffer was not large enough:
if(needed_size >= (int)s.size()) {
     s.resize(needed_size + 1); 
     needed_size = f2s_buffered_sz(value, s.data(), (int)s.size());
     assert(needed_size < s.size()); // there!
}

But to have this, we would require a version of such functions taking the buffer size and returning the required size.

Would you be open to a PR for this feature?

biojppm avatar Oct 12 '20 17:10 biojppm

FWIW I just saw #149 which is a different approach but in the same spirit.

biojppm avatar Oct 12 '20 18:10 biojppm