C++: validating untrusted input with std::from_chars

All input from users, files, and networks is untrusted. Validate it before use: check that it has the right form, that the whole string was consumed, and that the value is in the allowed range. Reject what does not match, rather than trying to repair it.

C++
#include <charconv>
#include <iostream>
#include <optional>
#include <string_view>

std::optional<int> parse_port(std::string_view text) {
  int value = 0;
  const char* end = text.data() + text.size();
  auto [ptr, ec] = std::from_chars(text.data(), end, value);
  if (ec != std::errc() || ptr != end) {
    return std::nullopt;
  }
  if (value < 1 || value > 65535) {
    return std::nullopt;
  }
  return value;
}

int main() {
  for (std::string_view input : {"8080", "0", "70000", "80a", "", " 22"}) {
    auto port = parse_port(input);
    std::cout << "'" << input << "' -> ";
    if (port) {
      std::cout << *port << "\n";
    } else {
      std::cout << "rejected\n";
    }
  }
}
Read the full lesson