blob: adb1a5b8508458efc60dc5b266e6c6c015d913a1 [file] [log] [blame]
Krzysztof Grobelnyb8cc78d2021-11-29 15:54:53 +01001#include "utils/generate_id.hpp"
2
3#include <sdbusplus/exception.hpp>
4
5#include <system_error>
6
7namespace utils
8{
9namespace details
10{
11
12static constexpr std::string_view allowedCharactersInId =
13 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/";
14
15}
16
17void verifyIdCharacters(std::string_view triggerId)
18{
19 if (triggerId.find_first_not_of(details::allowedCharactersInId) !=
20 std::string::npos)
21 {
22 throw sdbusplus::exception::SdBusError(
23 static_cast<int>(std::errc::invalid_argument),
24 "Invalid character in id");
25 }
26}
27
28std::string generateId(std::string_view prefix, std::string_view name,
29 const std::vector<std::string>& conflictIds,
30 size_t maxLength)
31{
32 verifyIdCharacters(prefix);
33
34 if (!prefix.empty() && !prefix.ends_with('/'))
35 {
36 return std::string(prefix);
37 }
38
39 std::string strippedId(name);
40 strippedId.erase(
41 std::remove_if(strippedId.begin(), strippedId.end(),
42 [](char c) {
43 return c == '/' ||
44 details::allowedCharactersInId.find(c) ==
45 std::string_view::npos;
46 }),
47 strippedId.end());
48 strippedId = std::string(prefix) + strippedId;
49
50 size_t idx = 0;
51 std::string tmpId = strippedId.substr(0, maxLength);
52
53 while (std::find(conflictIds.begin(), conflictIds.end(), tmpId) !=
54 conflictIds.end() ||
55 tmpId.empty())
56 {
57 tmpId = strippedId.substr(0, maxLength - std::to_string(idx).length()) +
58 std::to_string(idx);
59 ++idx;
60 }
61 return tmpId;
62}
63
64} // namespace utils