Utility.hpp 30 KB

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