Index gzip-compressed SVG files
[xapian.git] / xapian-applications / omega / utils.cc
blobb54521aaecec770a5a27e0d4edf1124c59459cb8
1 /** @file
2 * @brief string conversion utility functions for omega
3 */
4 /* Copyright 1999,2000,2001 BrightStation PLC
5 * Copyright 2003,2004,2006,2010,2011 Olly Betts
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as
9 * published by the Free Software Foundation; either version 2 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
20 * USA
23 #include <config.h>
25 #include "utils.h"
27 #include <cassert>
28 #include <stdio.h> // for sprintf/snprintf
29 #include <cstdlib>
31 #include <string>
33 using namespace std;
35 // This ought to be enough for any of the conversions below.
36 #define BUFSIZE 100
38 #ifdef SNPRINTF
39 #define CONVERT_TO_STRING(FMT) \
40 char buf[BUFSIZE];\
41 int len = SNPRINTF(buf, BUFSIZE, (FMT), val);\
42 if (len == -1 || len > BUFSIZE) return string(buf, BUFSIZE);\
43 return string(buf, len);
44 #else
45 #define CONVERT_TO_STRING(FMT) \
46 char buf[BUFSIZE];\
47 buf[BUFSIZE - 1] = '\0';\
48 sprintf(buf, (FMT), val);\
49 if (buf[BUFSIZE - 1]) abort(); /* Uh-oh, buffer overrun */ \
50 return string(buf);
51 #endif
53 int
54 string_to_int(const string &s)
56 return atoi(s.c_str());
59 string
60 double_to_string(double val)
62 CONVERT_TO_STRING("%f")
65 string
66 date_to_string(int y, int m, int d)
68 char buf[11];
69 if (y < 0) y = 0; else if (y > 9999) y = 9999;
70 if (m < 1) m = 1; else if (m > 12) m = 12;
71 if (d < 1) d = 1; else if (d > 31) d = 31;
72 #ifdef SNPRINTF
73 int len = SNPRINTF(buf, sizeof(buf), "%04d%02d%02d", y, m, d);
74 if (len == -1 || len > int(sizeof(buf))) return string(buf, sizeof(buf));
75 return string(buf, len);
76 #else
77 buf[sizeof(buf) - 1] = '\0';
78 sprintf(buf, "%04d%02d%02d", y, m, d);
79 if (buf[sizeof(buf) - 1]) abort(); /* Uh-oh, buffer overrun */
80 return string(buf);
81 #endif
84 void
85 trim(string & s)
87 string::size_type first_nonspace;
88 first_nonspace = s.find_first_not_of(" \t\r\n\v");
89 if (first_nonspace == string::npos) {
90 // String is all whitespace.
91 s.resize(0);
92 } else {
93 // Remove any trailing whitespace.
94 string::size_type len = s.find_last_not_of(" \t\r\n\v");
95 assert(len != string::npos);
96 if (len < s.size() - 1)
97 s.resize(len + 1);
98 // Remove any leading whitespace.
99 if (first_nonspace > 0)
100 s.erase(0, first_nonspace);