Tries to parse a floating point number located at s. s_end should be a location in the string where reading should absolutely stop. For example at the end of the string, to prevent buffer overflows. Parses the following EBNF grammar: sign = "+" | "-" ; END = ? anything not in digit ? digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; integer = [sign] , digit , {digit} ;
| 134 | // - parse failure. |
| 135 | // |
| 136 | static bool tryParseDouble(const char* s, const char* s_end, double* result) |
| 137 | { |
| 138 | if (s >= s_end) |
| 139 | { |
| 140 | return false; |
| 141 | } |
| 142 | |
| 143 | double mantissa = 0.0; |
| 144 | // This exponent is base 2 rather than 10. |
| 145 | // However the exponent we parse is supposed to be one of ten, |
| 146 | // thus we must take care to convert the exponent/and or the |
| 147 | // mantissa to a * 2^E, where a is the mantissa and E is the |
| 148 | // exponent. |
| 149 | // To get the final double we will use ldexp, it requires the |
| 150 | // exponent to be in base 2. |
| 151 | int exponent = 0; |
| 152 | |
| 153 | // NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED |
| 154 | // TO JUMP OVER DEFINITIONS. |
| 155 | char sign = '+'; |
| 156 | char exp_sign = '+'; |
| 157 | char const* curr = s; |
| 158 | |
| 159 | // How many characters were read in a loop. |
| 160 | int read = 0; |
| 161 | // Tells whether a loop terminated due to reaching s_end. |
| 162 | bool end_not_reached = false; |
| 163 | |
| 164 | /* |
| 165 | BEGIN PARSING. |
| 166 | */ |
| 167 | |
| 168 | // Find out what sign we've got. |
| 169 | if (*curr == '+' || *curr == '-') |
| 170 | { |
| 171 | sign = *curr; |
| 172 | curr++; |
| 173 | } |
| 174 | else if (isdigit(*curr)) |
| 175 | { /* Pass through. */ |
| 176 | } |
| 177 | else |
| 178 | { |
| 179 | goto fail; |
| 180 | } |
| 181 | |
| 182 | // Read the integer part. |
| 183 | while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) |
| 184 | { |
| 185 | mantissa *= 10; |
| 186 | mantissa += static_cast<int>(*curr - 0x30); |
| 187 | curr++; |
| 188 | read++; |
| 189 | } |
| 190 | |
| 191 | // We must make sure we actually got something. |
| 192 | if (read == 0) |
| 193 | goto fail; |