1 /** 2 * \file Utility.hpp 3 * \brief Header for GeographicLib::Utility class 4 * 5 * Copyright (c) Charles Karney (2011-2020) <charles@karney.com> and licensed 6 * under the MIT/X11 License. For more information, see 7 * https://geographiclib.sourceforge.io/ 8 **********************************************************************/ 9 10 #if !defined(GEOGRAPHICLIB_UTILITY_HPP) 11 #define GEOGRAPHICLIB_UTILITY_HPP 1 12 13 #include <GeographicLib/Constants.hpp> 14 #include <iomanip> 15 #include <vector> 16 #include <sstream> 17 #include <cctype> 18 #include <ctime> 19 #include <cstring> 20 21 #if defined(_MSC_VER) 22 // Squelch warnings about constant conditional expressions and unsafe gmtime 23 # pragma warning (push) 24 # pragma warning (disable: 4127 4996) 25 #endif 26 27 namespace GeographicLib { 28 29 /** 30 * \brief Some utility routines for %GeographicLib 31 * 32 * Example of use: 33 * \include example-Utility.cpp 34 **********************************************************************/ 35 class GEOGRAPHICLIB_EXPORT Utility { 36 private: gregorian(int y,int m,int d)37 static bool gregorian(int y, int m, int d) { 38 // The original cut over to the Gregorian calendar in Pope Gregory XIII's 39 // time had 1582-10-04 followed by 1582-10-15. Here we implement the 40 // switch over used by the English-speaking world where 1752-09-02 was 41 // followed by 1752-09-14. We also assume that the year always begins 42 // with January 1, whereas in reality it often was reckoned to begin in 43 // March. 44 return 100 * (100 * y + m) + d >= 17520914; // or 15821015 45 } gregorian(int s)46 static bool gregorian(int s) { 47 return s >= 639799; // 1752-09-14 48 } 49 public: 50 51 /** 52 * Convert a date to the day numbering sequentially starting with 53 * 0001-01-01 as day 1. 54 * 55 * @param[in] y the year (must be positive). 56 * @param[in] m the month, Jan = 1, etc. (must be positive). Default = 1. 57 * @param[in] d the day of the month (must be positive). Default = 1. 58 * @return the sequential day number. 59 **********************************************************************/ day(int y,int m=1,int d=1)60 static int day(int y, int m = 1, int d = 1) { 61 // Convert from date to sequential day and vice versa 62 // 63 // Here is some code to convert a date to sequential day and vice 64 // versa. The sequential day is numbered so that January 1, 1 AD is day 1 65 // (a Saturday). So this is offset from the "Julian" day which starts the 66 // numbering with 4713 BC. 67 // 68 // This is inspired by a talk by John Conway at the John von Neumann 69 // National Supercomputer Center when he described his Doomsday algorithm 70 // for figuring the day of the week. The code avoids explicitly doing ifs 71 // (except for the decision of whether to use the Julian or Gregorian 72 // calendar). Instead the equivalent result is achieved using integer 73 // arithmetic. I got this idea from the routine for the day of the week 74 // in MACLisp (I believe that that routine was written by Guy Steele). 75 // 76 // There are three issues to take care of 77 // 78 // 1. the rules for leap years, 79 // 2. the inconvenient placement of leap days at the end of February, 80 // 3. the irregular pattern of month lengths. 81 // 82 // We deal with these as follows: 83 // 84 // 1. Leap years are given by simple rules which are straightforward to 85 // accommodate. 86 // 87 // 2. We simplify the calculations by moving January and February to the 88 // previous year. Here we internally number the months March–December, 89 // January, February as 0–9, 10, 11. 90 // 91 // 3. The pattern of month lengths from March through January is regular 92 // with a 5-month period—31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31. The 93 // 5-month period is 153 days long. Since February is now at the end of 94 // the year, we don't need to include its length in this part of the 95 // calculation. 96 bool greg = gregorian(y, m, d); 97 y += (m + 9) / 12 - 1; // Move Jan and Feb to previous year, 98 m = (m + 9) % 12; // making March month 0. 99 return 100 (1461 * y) / 4 // Julian years converted to days. Julian year is 365 + 101 // 1/4 = 1461/4 days. 102 // Gregorian leap year corrections. The 2 offset with respect to the 103 // Julian calendar synchronizes the vernal equinox with that at the 104 // time of the Council of Nicea (325 AD). 105 + (greg ? (y / 100) / 4 - (y / 100) + 2 : 0) 106 + (153 * m + 2) / 5 // The zero-based start of the m'th month 107 + d - 1 // The zero-based day 108 - 305; // The number of days between March 1 and December 31. 109 // This makes 0001-01-01 day 1 110 } 111 112 /** 113 * Convert a date to the day numbering sequentially starting with 114 * 0001-01-01 as day 1. 115 * 116 * @param[in] y the year (must be positive). 117 * @param[in] m the month, Jan = 1, etc. (must be positive). Default = 1. 118 * @param[in] d the day of the month (must be positive). Default = 1. 119 * @param[in] check whether to check the date. 120 * @exception GeographicErr if the date is invalid and \e check is true. 121 * @return the sequential day number. 122 **********************************************************************/ day(int y,int m,int d,bool check)123 static int day(int y, int m, int d, bool check) { 124 int s = day(y, m, d); 125 if (!check) 126 return s; 127 int y1, m1, d1; 128 date(s, y1, m1, d1); 129 if (!(s > 0 && y == y1 && m == m1 && d == d1)) 130 throw GeographicErr("Invalid date " + 131 str(y) + "-" + str(m) + "-" + str(d) 132 + (s > 0 ? "; use " + 133 str(y1) + "-" + str(m1) + "-" + str(d1) : 134 " before 0001-01-01")); 135 return s; 136 } 137 138 /** 139 * Given a day (counting from 0001-01-01 as day 1), return the date. 140 * 141 * @param[in] s the sequential day number (must be positive) 142 * @param[out] y the year. 143 * @param[out] m the month, Jan = 1, etc. 144 * @param[out] d the day of the month. 145 **********************************************************************/ date(int s,int & y,int & m,int & d)146 static void date(int s, int& y, int& m, int& d) { 147 int c = 0; 148 bool greg = gregorian(s); 149 s += 305; // s = 0 on March 1, 1BC 150 if (greg) { 151 s -= 2; // The 2 day Gregorian offset 152 // Determine century with the Gregorian rules for leap years. The 153 // Gregorian year is 365 + 1/4 - 1/100 + 1/400 = 146097/400 days. 154 c = (4 * s + 3) / 146097; 155 s -= (c * 146097) / 4; // s = 0 at beginning of century 156 } 157 y = (4 * s + 3) / 1461; // Determine the year using Julian rules. 158 s -= (1461 * y) / 4; // s = 0 at start of year, i.e., March 1 159 y += c * 100; // Assemble full year 160 m = (5 * s + 2) / 153; // Determine the month 161 s -= (153 * m + 2) / 5; // s = 0 at beginning of month 162 d = s + 1; // Determine day of month 163 y += (m + 2) / 12; // Move Jan and Feb back to original year 164 m = (m + 2) % 12 + 1; // Renumber the months so January = 1 165 } 166 167 /** 168 * Given a date as a string in the format yyyy, yyyy-mm, or yyyy-mm-dd, 169 * return the numeric values for the year, month, and day. No checking is 170 * done on these values. The string "now" is interpreted as the present 171 * date (in UTC). 172 * 173 * @param[in] s the date in string format. 174 * @param[out] y the year. 175 * @param[out] m the month, Jan = 1, etc. 176 * @param[out] d the day of the month. 177 * @exception GeographicErr is \e s is malformed. 178 **********************************************************************/ date(const std::string & s,int & y,int & m,int & d)179 static void date(const std::string& s, int& y, int& m, int& d) { 180 if (s == "now") { 181 std::time_t t = std::time(0); 182 struct tm* now = gmtime(&t); 183 y = now->tm_year + 1900; 184 m = now->tm_mon + 1; 185 d = now->tm_mday; 186 return; 187 } 188 int y1, m1 = 1, d1 = 1; 189 const char* digits = "0123456789"; 190 std::string::size_type p1 = s.find_first_not_of(digits); 191 if (p1 == std::string::npos) 192 y1 = val<int>(s); 193 else if (s[p1] != '-') 194 throw GeographicErr("Delimiter not hyphen in date " + s); 195 else if (p1 == 0) 196 throw GeographicErr("Empty year field in date " + s); 197 else { 198 y1 = val<int>(s.substr(0, p1)); 199 if (++p1 == s.size()) 200 throw GeographicErr("Empty month field in date " + s); 201 std::string::size_type p2 = s.find_first_not_of(digits, p1); 202 if (p2 == std::string::npos) 203 m1 = val<int>(s.substr(p1)); 204 else if (s[p2] != '-') 205 throw GeographicErr("Delimiter not hyphen in date " + s); 206 else if (p2 == p1) 207 throw GeographicErr("Empty month field in date " + s); 208 else { 209 m1 = val<int>(s.substr(p1, p2 - p1)); 210 if (++p2 == s.size()) 211 throw GeographicErr("Empty day field in date " + s); 212 d1 = val<int>(s.substr(p2)); 213 } 214 } 215 y = y1; m = m1; d = d1; 216 } 217 218 /** 219 * Given the date, return the day of the week. 220 * 221 * @param[in] y the year (must be positive). 222 * @param[in] m the month, Jan = 1, etc. (must be positive). 223 * @param[in] d the day of the month (must be positive). 224 * @return the day of the week with Sunday, Monday--Saturday = 0, 225 * 1--6. 226 **********************************************************************/ dow(int y,int m,int d)227 static int dow(int y, int m, int d) { return dow(day(y, m, d)); } 228 229 /** 230 * Given the sequential day, return the day of the week. 231 * 232 * @param[in] s the sequential day (must be positive). 233 * @return the day of the week with Sunday, Monday--Saturday = 0, 234 * 1--6. 235 **********************************************************************/ dow(int s)236 static int dow(int s) { 237 return (s + 5) % 7; // The 5 offset makes day 1 (0001-01-01) a Saturday. 238 } 239 240 /** 241 * Convert a string representing a date to a fractional year. 242 * 243 * @tparam T the type of the argument. 244 * @param[in] s the string to be converted. 245 * @exception GeographicErr if \e s can't be interpreted as a date. 246 * @return the fractional year. 247 * 248 * The string is first read as an ordinary number (e.g., 2010 or 2012.5); 249 * if this is successful, the value is returned. Otherwise the string 250 * should be of the form yyyy-mm or yyyy-mm-dd and this is converted to a 251 * number with 2010-01-01 giving 2010.0 and 2012-07-03 giving 2012.5. 252 **********************************************************************/ fractionalyear(const std::string & s)253 template<typename T> static T fractionalyear(const std::string& s) { 254 try { 255 return val<T>(s); 256 } 257 catch (const std::exception&) {} 258 int y, m, d; 259 date(s, y, m, d); 260 int t = day(y, m, d, true); 261 return T(y) + T(t - day(y)) / T(day(y + 1) - day(y)); 262 } 263 264 /** 265 * Convert a object of type T to a string. 266 * 267 * @tparam T the type of the argument. 268 * @param[in] x the value to be converted. 269 * @param[in] p the precision used (default −1). 270 * @exception std::bad_alloc if memory for the string can't be allocated. 271 * @return the string representation. 272 * 273 * If \e p ≥ 0, then the number fixed format is used with p bits of 274 * precision. With p < 0, there is no manipulation of the format. 275 **********************************************************************/ str(T x,int p=-1)276 template<typename T> static std::string str(T x, int p = -1) { 277 std::ostringstream s; 278 if (p >= 0) s << std::fixed << std::setprecision(p); 279 s << x; return s.str(); 280 } 281 282 /** 283 * Convert a Math::real object to a string. 284 * 285 * @param[in] x the value to be converted. 286 * @param[in] p the precision used (default −1). 287 * @exception std::bad_alloc if memory for the string can't be allocated. 288 * @return the string representation. 289 * 290 * If \e p ≥ 0, then the number fixed format is used with p bits of 291 * precision. With p < 0, there is no manipulation of the format. This is 292 * an overload of str<T> which deals with inf and nan. 293 **********************************************************************/ str(Math::real x,int p=-1)294 static std::string str(Math::real x, int p = -1) { 295 using std::isfinite; 296 if (!isfinite(x)) 297 return x < 0 ? std::string("-inf") : 298 (x > 0 ? std::string("inf") : std::string("nan")); 299 std::ostringstream s; 300 #if GEOGRAPHICLIB_PRECISION == 4 301 // boost-quadmath treats precision == 0 as "use as many digits as 302 // necessary" (see https://svn.boost.org/trac/boost/ticket/10103), so... 303 using std::floor; using std::fmod; 304 if (p == 0) { 305 x += Math::real(0.5); 306 Math::real ix = floor(x); 307 // Implement the "round ties to even" rule 308 x = (ix == x && fmod(ix, Math::real(2)) == 1) ? ix - 1 : ix; 309 s << std::fixed << std::setprecision(1) << x; 310 std::string r(s.str()); 311 // strip off trailing ".0" 312 return r.substr(0, (std::max)(int(r.size()) - 2, 0)); 313 } 314 #endif 315 if (p >= 0) s << std::fixed << std::setprecision(p); 316 s << x; return s.str(); 317 } 318 319 /** 320 * Trim the white space from the beginning and end of a string. 321 * 322 * @param[in] s the string to be trimmed 323 * @return the trimmed string 324 **********************************************************************/ trim(const std::string & s)325 static std::string trim(const std::string& s) { 326 unsigned 327 beg = 0, 328 end = unsigned(s.size()); 329 while (beg < end && isspace(s[beg])) 330 ++beg; 331 while (beg < end && isspace(s[end - 1])) 332 --end; 333 return std::string(s, beg, end-beg); 334 } 335 336 /** 337 * Convert a string to type T. 338 * 339 * @tparam T the type of the return value. 340 * @param[in] s the string to be converted. 341 * @exception GeographicErr is \e s is not readable as a T. 342 * @return object of type T. 343 * 344 * White space at the beginning and end of \e s is ignored. 345 * 346 * Special handling is provided for some types. 347 * 348 * If T is a floating point type, then inf and nan are recognized. 349 * 350 * If T is bool, then \e s should either be string a representing 0 (false) 351 * or 1 (true) or one of the strings 352 * - "false", "f", "nil", "no", "n", "off", or "" meaning false, 353 * - "true", "t", "yes", "y", or "on" meaning true; 354 * . 355 * case is ignored. 356 * 357 * If T is std::string, then \e s is returned (with the white space at the 358 * beginning and end removed). 359 **********************************************************************/ val(const std::string & s)360 template<typename T> static T val(const std::string& s) { 361 // If T is bool, then the specialization val<bool>() defined below is 362 // used. 363 T x; 364 std::string errmsg, t(trim(s)); 365 do { // Executed once (provides the ability to break) 366 std::istringstream is(t); 367 if (!(is >> x)) { 368 errmsg = "Cannot decode " + t; 369 break; 370 } 371 int pos = int(is.tellg()); // Returns -1 at end of string? 372 if (!(pos < 0 || pos == int(t.size()))) { 373 errmsg = "Extra text " + t.substr(pos) + " at end of " + t; 374 break; 375 } 376 return x; 377 } while (false); 378 x = std::numeric_limits<T>::is_integer ? 0 : nummatch<T>(t); 379 if (x == 0) 380 throw GeographicErr(errmsg); 381 return x; 382 } 383 /** 384 * \deprecated An old name for val<T>(s). 385 **********************************************************************/ 386 template<typename T> 387 GEOGRAPHICLIB_DEPRECATED("Use Utility::val<T>(s)") num(const std::string & s)388 static T num(const std::string& s) { 389 return val<T>(s); 390 } 391 392 /** 393 * Match "nan" and "inf" (and variants thereof) in a string. 394 * 395 * @tparam T the type of the return value (this should be a floating point 396 * type). 397 * @param[in] s the string to be matched. 398 * @return appropriate special value (±∞, nan) or 0 if none is 399 * found. 400 * 401 * White space is not allowed at the beginning or end of \e s. 402 **********************************************************************/ nummatch(const std::string & s)403 template<typename T> static T nummatch(const std::string& s) { 404 if (s.length() < 3) 405 return 0; 406 std::string t(s); 407 for (std::string::iterator p = t.begin(); p != t.end(); ++p) 408 *p = char(std::toupper(*p)); 409 for (size_t i = s.length(); i--;) 410 t[i] = char(std::toupper(s[i])); 411 int sign = t[0] == '-' ? -1 : 1; 412 std::string::size_type p0 = t[0] == '-' || t[0] == '+' ? 1 : 0; 413 std::string::size_type p1 = t.find_last_not_of('0'); 414 if (p1 == std::string::npos || p1 + 1 < p0 + 3) 415 return 0; 416 // Strip off sign and trailing 0s 417 t = t.substr(p0, p1 + 1 - p0); // Length at least 3 418 if (t == "NAN" || t == "1.#QNAN" || t == "1.#SNAN" || t == "1.#IND" || 419 t == "1.#R") 420 return Math::NaN<T>(); 421 else if (t == "INF" || t == "1.#INF") 422 return sign * Math::infinity<T>(); 423 return 0; 424 } 425 426 /** 427 * Read a simple fraction, e.g., 3/4, from a string to an object of type T. 428 * 429 * @tparam T the type of the return value. 430 * @param[in] s the string to be converted. 431 * @exception GeographicErr is \e s is not readable as a fraction of type 432 * T. 433 * @return object of type T 434 * 435 * \note The msys shell under Windows converts arguments which look like 436 * pathnames into their Windows equivalents. As a result the argument 437 * "-1/300" gets mangled into something unrecognizable. A workaround is to 438 * use a floating point number in the numerator, i.e., "-1.0/300". (Recent 439 * versions of the msys shell appear \e not to have this problem.) 440 **********************************************************************/ fract(const std::string & s)441 template<typename T> static T fract(const std::string& s) { 442 std::string::size_type delim = s.find('/'); 443 return 444 !(delim != std::string::npos && delim >= 1 && delim + 2 <= s.size()) ? 445 val<T>(s) : 446 // delim in [1, size() - 2] 447 val<T>(s.substr(0, delim)) / val<T>(s.substr(delim + 1)); 448 } 449 450 /** 451 * Lookup up a character in a string. 452 * 453 * @param[in] s the string to be searched. 454 * @param[in] c the character to look for. 455 * @return the index of the first occurrence character in the string or 456 * −1 is the character is not present. 457 * 458 * \e c is converted to upper case before search \e s. Therefore, it is 459 * intended that \e s should not contain any lower case letters. 460 **********************************************************************/ lookup(const std::string & s,char c)461 static int lookup(const std::string& s, char c) { 462 std::string::size_type r = s.find(char(std::toupper(c))); 463 return r == std::string::npos ? -1 : int(r); 464 } 465 466 /** 467 * Lookup up a character in a char*. 468 * 469 * @param[in] s the char* string to be searched. 470 * @param[in] c the character to look for. 471 * @return the index of the first occurrence character in the string or 472 * −1 is the character is not present. 473 * 474 * \e c is converted to upper case before search \e s. Therefore, it is 475 * intended that \e s should not contain any lower case letters. 476 **********************************************************************/ lookup(const char * s,char c)477 static int lookup(const char* s, char c) { 478 const char* p = std::strchr(s, std::toupper(c)); 479 return p != NULL ? int(p - s) : -1; 480 } 481 482 /** 483 * Read data of type ExtT from a binary stream to an array of type IntT. 484 * The data in the file is in (bigendp ? big : little)-endian format. 485 * 486 * @tparam ExtT the type of the objects in the binary stream (external). 487 * @tparam IntT the type of the objects in the array (internal). 488 * @tparam bigendp true if the external storage format is big-endian. 489 * @param[in] str the input stream containing the data of type ExtT 490 * (external). 491 * @param[out] array the output array of type IntT (internal). 492 * @param[in] num the size of the array. 493 * @exception GeographicErr if the data cannot be read. 494 **********************************************************************/ 495 template<typename ExtT, typename IntT, bool bigendp> readarray(std::istream & str,IntT array[],size_t num)496 static void readarray(std::istream& str, IntT array[], size_t num) { 497 #if GEOGRAPHICLIB_PRECISION < 4 498 if (sizeof(IntT) == sizeof(ExtT) && 499 std::numeric_limits<IntT>::is_integer == 500 std::numeric_limits<ExtT>::is_integer) 501 { 502 // Data is compatible (aside from the issue of endian-ness). 503 str.read(reinterpret_cast<char*>(array), num * sizeof(ExtT)); 504 if (!str.good()) 505 throw GeographicErr("Failure reading data"); 506 if (bigendp != Math::bigendian) { // endian mismatch -> swap bytes 507 for (size_t i = num; i--;) 508 array[i] = Math::swab<IntT>(array[i]); 509 } 510 } 511 else 512 #endif 513 { 514 const int bufsize = 1024; // read this many values at a time 515 ExtT buffer[bufsize]; // temporary buffer 516 int k = int(num); // data values left to read 517 int i = 0; // index into output array 518 while (k) { 519 int n = (std::min)(k, bufsize); 520 str.read(reinterpret_cast<char*>(buffer), n * sizeof(ExtT)); 521 if (!str.good()) 522 throw GeographicErr("Failure reading data"); 523 for (int j = 0; j < n; ++j) 524 // fix endian-ness and cast to IntT 525 array[i++] = IntT(bigendp == Math::bigendian ? buffer[j] : 526 Math::swab<ExtT>(buffer[j])); 527 k -= n; 528 } 529 } 530 return; 531 } 532 533 /** 534 * Read data of type ExtT from a binary stream to a vector array of type 535 * IntT. The data in the file is in (bigendp ? big : little)-endian 536 * format. 537 * 538 * @tparam ExtT the type of the objects in the binary stream (external). 539 * @tparam IntT the type of the objects in the array (internal). 540 * @tparam bigendp true if the external storage format is big-endian. 541 * @param[in] str the input stream containing the data of type ExtT 542 * (external). 543 * @param[out] array the output vector of type IntT (internal). 544 * @exception GeographicErr if the data cannot be read. 545 **********************************************************************/ 546 template<typename ExtT, typename IntT, bool bigendp> readarray(std::istream & str,std::vector<IntT> & array)547 static void readarray(std::istream& str, std::vector<IntT>& array) { 548 if (array.size() > 0) 549 readarray<ExtT, IntT, bigendp>(str, &array[0], array.size()); 550 } 551 552 /** 553 * Write data in an array of type IntT as type ExtT to a binary stream. 554 * The data in the file is in (bigendp ? big : little)-endian format. 555 * 556 * @tparam ExtT the type of the objects in the binary stream (external). 557 * @tparam IntT the type of the objects in the array (internal). 558 * @tparam bigendp true if the external storage format is big-endian. 559 * @param[out] str the output stream for the data of type ExtT (external). 560 * @param[in] array the input array of type IntT (internal). 561 * @param[in] num the size of the array. 562 * @exception GeographicErr if the data cannot be written. 563 **********************************************************************/ 564 template<typename ExtT, typename IntT, bool bigendp> writearray(std::ostream & str,const IntT array[],size_t num)565 static void writearray(std::ostream& str, const IntT array[], size_t num) 566 { 567 #if GEOGRAPHICLIB_PRECISION < 4 568 if (sizeof(IntT) == sizeof(ExtT) && 569 std::numeric_limits<IntT>::is_integer == 570 std::numeric_limits<ExtT>::is_integer && 571 bigendp == Math::bigendian) 572 { 573 // Data is compatible (including endian-ness). 574 str.write(reinterpret_cast<const char*>(array), num * sizeof(ExtT)); 575 if (!str.good()) 576 throw GeographicErr("Failure writing data"); 577 } 578 else 579 #endif 580 { 581 const int bufsize = 1024; // write this many values at a time 582 ExtT buffer[bufsize]; // temporary buffer 583 int k = int(num); // data values left to write 584 int i = 0; // index into output array 585 while (k) { 586 int n = (std::min)(k, bufsize); 587 for (int j = 0; j < n; ++j) 588 // cast to ExtT and fix endian-ness 589 buffer[j] = bigendp == Math::bigendian ? ExtT(array[i++]) : 590 Math::swab<ExtT>(ExtT(array[i++])); 591 str.write(reinterpret_cast<const char*>(buffer), n * sizeof(ExtT)); 592 if (!str.good()) 593 throw GeographicErr("Failure writing data"); 594 k -= n; 595 } 596 } 597 return; 598 } 599 600 /** 601 * Write data in an array of type IntT as type ExtT to a binary stream. 602 * The data in the file is in (bigendp ? big : little)-endian format. 603 * 604 * @tparam ExtT the type of the objects in the binary stream (external). 605 * @tparam IntT the type of the objects in the array (internal). 606 * @tparam bigendp true if the external storage format is big-endian. 607 * @param[out] str the output stream for the data of type ExtT (external). 608 * @param[in] array the input vector of type IntT (internal). 609 * @exception GeographicErr if the data cannot be written. 610 **********************************************************************/ 611 template<typename ExtT, typename IntT, bool bigendp> writearray(std::ostream & str,std::vector<IntT> & array)612 static void writearray(std::ostream& str, std::vector<IntT>& array) { 613 if (array.size() > 0) 614 writearray<ExtT, IntT, bigendp>(str, &array[0], array.size()); 615 } 616 617 /** 618 * Parse a KEY [=] VALUE line. 619 * 620 * @param[in] line the input line. 621 * @param[out] key the KEY. 622 * @param[out] value the VALUE. 623 * @param[in] delim delimiter to separate KEY and VALUE, if NULL use first 624 * space character. 625 * @exception std::bad_alloc if memory for the internal strings can't be 626 * allocated. 627 * @return whether a key was found. 628 * 629 * A "#" character and everything after it are discarded and the result 630 * trimmed of leading and trailing white space. Use the delimiter 631 * character (or, if it is NULL, the first white space) to separate \e key 632 * and \e value. \e key and \e value are trimmed of leading and trailing 633 * white space. If \e key is empty, then \e value is set to "" and false 634 * is returned. 635 **********************************************************************/ 636 static bool ParseLine(const std::string& line, 637 std::string& key, std::string& value, 638 char delim); 639 640 /** 641 * Parse a KEY VALUE line. 642 * 643 * @param[in] line the input line. 644 * @param[out] key the KEY. 645 * @param[out] value the VALUE. 646 * @exception std::bad_alloc if memory for the internal strings can't be 647 * allocated. 648 * @return whether a key was found. 649 * 650 * \note This is a transition routine. At some point \e delim will be made 651 * an optional argument in the previous version of ParseLine and this 652 * version will be removed. 653 **********************************************************************/ 654 655 static bool ParseLine(const std::string& line, 656 std::string& key, std::string& value); 657 658 /** 659 * Set the binary precision of a real number. 660 * 661 * @param[in] ndigits the number of bits of precision. If ndigits is 0 662 * (the default), then determine the precision from the environment 663 * variable GEOGRAPHICLIB_DIGITS. If this is undefined, use ndigits = 664 * 256 (i.e., about 77 decimal digits). 665 * @return the resulting number of bits of precision. 666 * 667 * This only has an effect when GEOGRAPHICLIB_PRECISION = 5. The 668 * precision should only be set once and before calls to any other 669 * GeographicLib functions. (Several functions, for example Math::pi(), 670 * cache the return value in a static local variable. The precision needs 671 * to be set before a call to any such functions.) In multi-threaded 672 * applications, it is necessary also to set the precision in each thread 673 * (see the example GeoidToGTX.cpp). 674 **********************************************************************/ 675 static int set_digits(int ndigits = 0); 676 677 }; 678 679 /** 680 * The specialization of Utility::val<T>() for strings. 681 **********************************************************************/ val(const std::string & s)682 template<> inline std::string Utility::val<std::string>(const std::string& s) 683 { return trim(s); } 684 685 /** 686 * The specialization of Utility::val<T>() for bools. 687 **********************************************************************/ val(const std::string & s)688 template<> inline bool Utility::val<bool>(const std::string& s) { 689 std::string t(trim(s)); 690 if (t.empty()) return false; 691 bool x; 692 { 693 std::istringstream is(t); 694 if (is >> x) { 695 int pos = int(is.tellg()); // Returns -1 at end of string? 696 if (!(pos < 0 || pos == int(t.size()))) 697 throw GeographicErr("Extra text " + t.substr(pos) + 698 " at end of " + t); 699 return x; 700 } 701 } 702 for (std::string::iterator p = t.begin(); p != t.end(); ++p) 703 *p = char(std::tolower(*p)); 704 switch (t[0]) { // already checked that t isn't empty 705 case 'f': 706 if (t == "f" || t == "false") return false; 707 break; 708 case 'n': 709 if (t == "n" || t == "nil" || t == "no") return false; 710 break; 711 case 'o': 712 if (t == "off") return false; 713 else if (t == "on") return true; 714 break; 715 case 't': 716 if (t == "t" || t == "true") return true; 717 break; 718 case 'y': 719 if (t == "y" || t == "yes") return true; 720 break; 721 default: 722 break; 723 } 724 throw GeographicErr("Cannot decode " + t + " as a bool"); 725 } 726 727 } // namespace GeographicLib 728 729 #if defined(_MSC_VER) 730 # pragma warning (pop) 731 #endif 732 733 #endif // GEOGRAPHICLIB_UTILITY_HPP 734