| 10 | namespace ada::checkers { |
| 11 | |
| 12 | ada_really_inline constexpr bool is_ipv4(std::string_view view) noexcept { |
| 13 | // The string is not empty and does not contain upper case ASCII characters. |
| 14 | // |
| 15 | // Optimization. To be considered as a possible ipv4, the string must end |
| 16 | // with 'x' or a lowercase hex character. |
| 17 | // Most of the time, this will be false so this simple check will save a lot |
| 18 | // of effort. |
| 19 | // If the address ends with a dot, we need to prune it (special case). |
| 20 | if (view.ends_with('.')) { |
| 21 | view.remove_suffix(1); |
| 22 | if (view.empty()) { |
| 23 | return false; |
| 24 | } |
| 25 | } |
| 26 | char last_char = view.back(); |
| 27 | bool possible_ipv4 = (last_char >= '0' && last_char <= '9') || |
| 28 | (last_char >= 'a' && last_char <= 'f') || |
| 29 | last_char == 'x'; |
| 30 | if (!possible_ipv4) { |
| 31 | return false; |
| 32 | } |
| 33 | // From the last character, find the last dot. |
| 34 | size_t last_dot = view.rfind('.'); |
| 35 | if (last_dot != std::string_view::npos) { |
| 36 | // We have at least one dot. |
| 37 | view = view.substr(last_dot + 1); |
| 38 | } |
| 39 | /** Optimization opportunity: we have basically identified the last number of |
| 40 | the ipv4 if we return true here. We might as well parse it and have at |
| 41 | least one number parsed when we get to parse_ipv4. */ |
| 42 | if (std::ranges::all_of(view, ada::checkers::is_digit)) { |
| 43 | return true; |
| 44 | } |
| 45 | // It could be hex (0x), but not if there is a single character. |
| 46 | if (view.size() == 1) { |
| 47 | return false; |
| 48 | } |
| 49 | // It must start with 0x. |
| 50 | if (!view.starts_with("0x")) { |
| 51 | return false; |
| 52 | } |
| 53 | // We must allow "0x". |
| 54 | if (view.size() == 2) { |
| 55 | return true; |
| 56 | } |
| 57 | // We have 0x followed by some characters, we need to check that they are |
| 58 | // hexadecimals. |
| 59 | view.remove_prefix(2); |
| 60 | return std::ranges::all_of(view, ada::unicode::is_lowercase_hex); |
| 61 | } |
| 62 | |
| 63 | // for use with path_signature, we include all characters that need percent |
| 64 | // encoding. |
no test coverage detected