master
h 83 lines 2.48 KB
Raw
1 /*++
2
3 Copyright (c) Microsoft. All rights reserved.
4
5 Module Name:
6
7 ArgumentValidation.h
8
9 Abstract:
10
11 Declaration of argument validation functions.
12
13 --*/
14 #pragma once
15
16 #include "Exceptions.h"
17 #include "ContainerModel.h"
18 #include "InspectModel.h"
19 #include "ArgumentConvertedTypes.h"
20 #include "SpecParsing.h"
21 #include <string>
22 #include <string_view>
23 #include <tuple>
24 #include <vector>
25 #include <charconv>
26 #include <wslc.h>
27 #include <string.hpp>
28 #include "Localization.h"
29
30 using namespace wsl::windows::wslc::models;
31
32 namespace wsl::windows::wslc::validation {
33
34 template <typename T>
35 void ValidateIntegerFromString(
36 const std::vector<std::wstring>& values, const std::wstring& argName, const std::function<bool(T)>& validate = [](T) {
37 return true;
38 })
39 {
40 for (const auto& value : values)
41 {
42 std::ignore = GetIntegerFromString<T>(value, argName, validate);
43 }
44 }
45
46 template <typename T>
47 T GetIntegerFromString(
48 const std::wstring& value, const std::wstring& argName = {}, const std::function<bool(T)>& validate = [](T) { return true; })
49 {
50 std::string narrowValue = wsl::windows::common::string::WideToMultiByte(value);
51
52 T convertedValue{};
53 const char* begin = narrowValue.c_str();
54 const char* end = begin + narrowValue.size();
55 auto result = std::from_chars(begin, end, convertedValue);
56
57 // Reject conversion errors and partial parses (e.g. "1.5", "9abc")
58 if (result.ec != std::errc() || result.ptr != end || !validate(convertedValue))
59 {
60 throw ArgumentException(wsl::shared::Localization::WSLCCLI_InvalidIntegerArgumentError(argName, value));
61 }
62
63 return convertedValue;
64 }
65
66 void ValidateWSLCSignalFromString(const std::vector<std::wstring>& values, const std::wstring& argName);
67
68 void ValidateMemorySize(const std::vector<std::wstring>& values, const std::wstring& argName);
69
70 void ValidateDuration(const std::vector<std::wstring>& values, const std::wstring& argName);
71
72 void ValidateTimestamp(const std::vector<std::wstring>& values, const std::wstring& argName);
73 void ValidateNanoCpus(const std::vector<std::wstring>& values, const std::wstring& argName);
74
75 void ValidateUlimit(const std::vector<std::wstring>& values, const std::wstring& argName);
76
77 void ValidateFormatTypeFromString(const std::vector<std::wstring>& values, const std::wstring& argName);
78
79 void ValidateGpus(const std::vector<std::wstring>& values, const std::wstring& argName);
80
81 void ValidateFilter(const std::vector<std::wstring>& values);
82
83 } // namespace wsl::windows::wslc::validation