Parses 'str' for a 32-bit signed integer. If successful, writes the result to *value and returns true; otherwise leaves *value unchanged and returns false.
| 9758 | // the result to *value and returns true; otherwise leaves *value |
| 9759 | // unchanged and returns false. |
| 9760 | bool ParseInt32(const Message& src_text, const char* str, Int32* value) { |
| 9761 | // Parses the environment variable as a decimal integer. |
| 9762 | char* end = NULL; |
| 9763 | const long long_value = strtol(str, &end, 10); // NOLINT |
| 9764 | |
| 9765 | // Has strtol() consumed all characters in the string? |
| 9766 | if (*end != '\0') { |
| 9767 | // No - an invalid character was encountered. |
| 9768 | Message msg; |
| 9769 | msg << "WARNING: " << src_text |
| 9770 | << " is expected to be a 32-bit integer, but actually" |
| 9771 | << " has value \"" << str << "\".\n"; |
| 9772 | printf("%s", msg.GetString().c_str()); |
| 9773 | fflush(stdout); |
| 9774 | return false; |
| 9775 | } |
| 9776 | |
| 9777 | // Is the parsed value in the range of an Int32? |
| 9778 | const Int32 result = static_cast<Int32>(long_value); |
| 9779 | if (long_value == LONG_MAX || long_value == LONG_MIN || |
| 9780 | // The parsed value overflows as a long. (strtol() returns |
| 9781 | // LONG_MAX or LONG_MIN when the input overflows.) |
| 9782 | result != long_value |
| 9783 | // The parsed value overflows as an Int32. |
| 9784 | ) { |
| 9785 | Message msg; |
| 9786 | msg << "WARNING: " << src_text |
| 9787 | << " is expected to be a 32-bit integer, but actually" |
| 9788 | << " has value " << str << ", which overflows.\n"; |
| 9789 | printf("%s", msg.GetString().c_str()); |
| 9790 | fflush(stdout); |
| 9791 | return false; |
| 9792 | } |
| 9793 | |
| 9794 | *value = result; |
| 9795 | return true; |
| 9796 | } |
| 9797 | |
| 9798 | // Reads and returns the Boolean environment variable corresponding to |
| 9799 | // the given flag; if it's not set, returns default_value. |
no test coverage detected