Skip to content
This repository was archived by the owner on Jul 4, 2025. It is now read-only.

chore: add validation for numeric input and handle out of range values #2030

Merged
merged 3 commits into from
Mar 4, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 31 additions & 4 deletions engine/utils/cli_selection_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,24 @@ inline void PrintMenu(
std::endl(std::cout);
}

inline std::optional<int> GetNumericValue(const std::string& sval) {
try {
return std::stoi(sval);
} catch (const std::invalid_argument&) {
// Not a valid number
return std::nullopt;
} catch (const std::out_of_range&) {
// Number out of range
return std::nullopt;
}
}

inline std::optional<std::string> PrintModelSelection(
const std::vector<std::string>& downloaded,
const std::vector<std::string>& availables,
const std::optional<std::string> default_selection = std::nullopt) {

std::string selection{""};
std::string selection;
if (!downloaded.empty()) {
std::cout << "Downloaded models:\n";
for (const auto& option : downloaded) {
Expand Down Expand Up @@ -60,7 +72,15 @@ inline std::optional<std::string> PrintModelSelection(
return std::nullopt;
}

if (std::stoi(selection) > availables.size() || std::stoi(selection) < 1) {
// Validate if the selection consists solely of numeric characters
if(!std::all_of(selection.begin(), selection.end(), ::isdigit)){
return std::nullopt;
}

// deal with out of range numeric values
std::optional<int> numeric_value = GetNumericValue(selection);

if (!numeric_value.has_value() || numeric_value.value() > availables.size() || numeric_value.value() < 1) {
return std::nullopt;
}

Expand All @@ -71,7 +91,7 @@ inline std::optional<std::string> PrintSelection(
const std::vector<std::string>& options,
const std::string& title = "Select an option") {
std::cout << title << "\n";
std::string selection{""};
std::string selection;
PrintMenu(options);
std::cout << "Select an option (" << 1 << "-" << options.size() << "): ";
std::getline(std::cin, selection);
Expand All @@ -80,7 +100,14 @@ inline std::optional<std::string> PrintSelection(
return std::nullopt;
}

if (std::stoi(selection) > options.size() || std::stoi(selection) < 1) {
// Validate if the selection consists solely of numeric characters
if(!std::all_of(selection.begin(), selection.end(), ::isdigit)){
return std::nullopt;
}

// deal with out of range numeric values
std::optional<int> numeric_value = GetNumericValue(selection);
if (!numeric_value.has_value() || numeric_value.value() > options.size() || numeric_value.value() < 1) {
return std::nullopt;
}

Expand Down
Loading