Libkleo

stringutils.cpp
1/*
2 utils/stringutils.cpp
3
4 This file is part of libkleopatra
5 SPDX-FileCopyrightText: 2021 g10 Code GmbH
6 SPDX-FileContributor: Ingo Klöcker <dev@ingo-kloecker.de>
7
8 SPDX-License-Identifier: GPL-2.0-or-later
9*/
10
11#include <config-libkleo.h>
12
13#include "stringutils.h"
14
15#include <libkleo_debug.h>
16
17#include <algorithm>
18#include <charconv>
19#include <system_error>
20
21std::vector<std::string_view> Kleo::split(std::string_view sv, char c, unsigned maxParts)
22{
23 if (maxParts == 1) {
24 return {sv};
25 }
26
27 std::vector<std::string_view> result;
28 result.reserve(std::min(maxParts, static_cast<unsigned>(std::count(sv.begin(), sv.end(), c))));
29
30 auto start = 0;
31 auto end = sv.find(c, start);
32 while ((end != sv.npos) && (maxParts == 0 || result.size() < maxParts - 1)) {
33 result.push_back(sv.substr(start, end - start));
34 start = end + 1;
35 end = sv.find(c, start);
36 }
37 result.push_back(sv.substr(start));
38
39 return result;
40}
41
42std::vector<std::string> Kleo::toStrings(const std::vector<std::string_view> &stringViews)
43{
44 std::vector<std::string> result;
45 result.reserve(stringViews.size());
46 for (const auto &sv : stringViews) {
47 result.emplace_back(sv);
48 }
49 return result;
50}
51
52std::optional<int> Kleo::svToInt(std::string_view sv)
53{
54 std::optional<int> result;
55 int tmp;
56 const auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), tmp);
57 if (ec != std::errc()) {
58 qCDebug(LIBKLEO_LOG) << __func__ << "Error: Failed to convert" << sv << "to int (" << std::make_error_code(ec).message() << ")";
59 } else if (ptr != sv.data() + sv.size()) {
60 qCDebug(LIBKLEO_LOG) << __func__ << "Error: Failed to convert" << sv << "to int ( invalid character at position" << (ptr - sv.data()) << ")";
61 } else {
62 result = tmp;
63 }
64 return result;
65}
Q_SCRIPTABLE Q_NOREPLY void start()
const QList< QKeySequence > & end()
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Sat Dec 21 2024 16:56:14 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.