Introduce ctl::to_string()

This commit is contained in:
Justine Tunney 2024-07-01 05:40:38 -07:00
parent acbabedf27
commit e627bfa359
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
11 changed files with 432 additions and 40 deletions

View file

@ -17,28 +17,30 @@
// PERFORMANCE OF THIS SOFTWARE.
#include "ostringstream.h"
#include "dubble.h"
#include "libc/fmt/itoa.h"
#include "libc/stdio/stdio.h"
namespace ctl {
extern const double_conversion::DoubleToStringConverter kDoubleToPrintfG;
ostringstream::ostringstream() : buffer_(), write_pos_(0)
{
}
ostringstream::ostringstream(const ctl::string_view& str)
ostringstream::ostringstream(const string_view& str)
: buffer_(str), write_pos_(0)
{
}
ctl::string
string
ostringstream::str() const
{
return buffer_;
}
void
ostringstream::str(const ctl::string& s)
ostringstream::str(const string& s)
{
buffer_ = s;
write_pos_ = 0;
@ -65,7 +67,7 @@ ostringstream::operator<<(char c)
}
ostringstream&
ostringstream::operator<<(const ctl::string_view& s)
ostringstream::operator<<(const string_view& s)
{
if (good()) {
if (write_pos_ + s.size() <= buffer_.size()) {
@ -82,36 +84,40 @@ ostringstream::operator<<(const ctl::string_view& s)
ostringstream&
ostringstream::operator<<(int n)
{
char temp[12];
if (good())
*this << ctl::string_view(temp, FormatInt32(temp, n) - temp);
if (good()) {
char buf[12];
*this << string_view(buf, FormatInt32(buf, n) - buf);
}
return *this;
}
ostringstream&
ostringstream::operator<<(unsigned int n)
ostringstream::operator<<(unsigned n)
{
char temp[12];
if (good())
*this << ctl::string_view(temp, FormatUint32(temp, n) - temp);
if (good()) {
char buf[12];
*this << string_view(buf, FormatUint32(buf, n) - buf);
}
return *this;
}
ostringstream&
ostringstream::operator<<(long n)
{
char temp[21];
if (good())
*this << ctl::string_view(temp, FormatInt64(temp, n) - temp);
if (good()) {
char buf[21];
*this << string_view(buf, FormatInt64(buf, n) - buf);
}
return *this;
}
ostringstream&
ostringstream::operator<<(unsigned long n)
{
char temp[21];
if (good())
*this << ctl::string_view(temp, FormatUint64(temp, n) - temp);
if (good()) {
char buf[21];
*this << string_view(buf, FormatUint64(buf, n) - buf);
}
return *this;
}
@ -119,9 +125,11 @@ ostringstream&
ostringstream::operator<<(float f)
{
if (good()) {
char temp[32];
int len = snprintf(temp, sizeof(temp), "%g", f);
*this << ctl::string_view(temp, len);
char buf[128];
double_conversion::StringBuilder b(buf, sizeof(buf));
kDoubleToPrintfG.ToShortestSingle(f, &b);
b.Finalize();
*this << string_view(buf);
}
return *this;
}
@ -130,9 +138,11 @@ ostringstream&
ostringstream::operator<<(double d)
{
if (good()) {
char temp[32];
int len = snprintf(temp, sizeof(temp), "%g", d);
*this << ctl::string_view(temp, len);
char buf[128];
double_conversion::StringBuilder b(buf, sizeof(buf));
kDoubleToPrintfG.ToShortest(d, &b);
b.Finalize();
*this << string_view(buf);
}
return *this;
}