constinfo for unittest too
[xapian.git] / xapian-applications / omega / utils.cc
blobbd4db3d22af213fe7d6f355c0781014b38ad84ab
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
19 * USA
22 #include <config.h>
24 #include "utils.h"
26 #include <cassert>
27 #include <stdio.h> // for sprintf/snprintf
28 #include <cstdlib>
30 #include <string>
32 using namespace std;
34 // This ought to be enough for any of the conversions below.
35 #define BUFSIZE 100
37 #ifdef SNPRINTF
38 #define CONVERT_TO_STRING(FMT) \
39 char buf[BUFSIZE];\
40 int len = SNPRINTF(buf, BUFSIZE, (FMT), val);\
41 if (len == -1 || len > BUFSIZE) return string(buf, BUFSIZE);\
42 return string(buf, len);
43 #else
44 #define CONVERT_TO_STRING(FMT) \
45 char buf[BUFSIZE];\
46 buf[BUFSIZE - 1] = '\0';\
47 sprintf(buf, (FMT), val);\
48 if (buf[BUFSIZE - 1]) abort(); /* Uh-oh, buffer overrun */ \
49 return string(buf);
50 #endif
52 int
53 string_to_int(const string &s)
55 return atoi(s.c_str());
58 string
59 double_to_string(double val)
61 CONVERT_TO_STRING("%f")
64 string
65 date_to_string(int y, int m, int d)
67 char buf[11];
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;
71 #ifdef SNPRINTF
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);
75 #else
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 */
79 return string(buf);
80 #endif
83 void
84 trim(string & s)
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.
90 s.resize(0);
91 } else {
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)
96 s.resize(len + 1);
97 // Remove any leading whitespace.
98 if (first_nonspace > 0)
99 s.erase(0, first_nonspace);