1 /* utils.cc: string conversion utility functions for omega
3 * Copyright 1999,2000,2001 BrightStation PLC
4 * Copyright 2003,2004,2006,2010,2011 Olly Betts
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation; either version 2 of the
9 * License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
27 #include <stdio.h> // for sprintf/snprintf
34 // This ought to be enough for any of the conversions below.
38 #define CONVERT_TO_STRING(FMT) \
40 int len = SNPRINTF(buf, BUFSIZE, (FMT), val);\
41 if (len == -1 || len > BUFSIZE) return string(buf, BUFSIZE);\
42 return string(buf, len);
44 #define CONVERT_TO_STRING(FMT) \
46 buf[BUFSIZE - 1] = '\0';\
47 sprintf(buf, (FMT), val);\
48 if (buf[BUFSIZE - 1]) abort(); /* Uh-oh, buffer overrun */ \
53 string_to_int(const string
&s
)
55 return atoi(s
.c_str());
59 double_to_string(double val
)
61 CONVERT_TO_STRING("%f")
65 date_to_string(int y
, int m
, int d
)
68 if (y
< 0) y
= 0; else if (y
> 9999) y
= 9999;
69 if (m
< 1) m
= 1; else if (m
> 12) m
= 12;
70 if (d
< 1) d
= 1; else if (d
> 31) d
= 31;
72 int len
= SNPRINTF(buf
, sizeof(buf
), "%04d%02d%02d", y
, m
, d
);
73 if (len
== -1 || len
> int(sizeof(buf
))) return string(buf
, sizeof(buf
));
74 return string(buf
, len
);
76 buf
[sizeof(buf
) - 1] = '\0';
77 sprintf(buf
, "%04d%02d%02d", y
, m
, d
);
78 if (buf
[sizeof(buf
) - 1]) abort(); /* Uh-oh, buffer overrun */
86 string::size_type first_nonspace
;
87 first_nonspace
= s
.find_first_not_of(" \t\r\n\v");
88 if (first_nonspace
== string::npos
) {
89 // String is all whitespace.
92 // Remove any trailing whitespace.
93 string::size_type len
= s
.find_last_not_of(" \t\r\n\v");
94 assert(len
!= string::npos
);
95 if (len
< s
.size() - 1)
97 // Remove any leading whitespace.
98 if (first_nonspace
> 0)
99 s
.erase(0, first_nonspace
);