blob: f19dbe4e78f0e5d3c17e8482eae342ac203dc6d7 [file] [log] [blame]
Songchun Fan59eee562019-10-24 16:46:06 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include <string_view>
20#include <vector>
21
22namespace android::incfs {
23
24// Splits a string and calls |onSplitCb| for each occurrence of a substring
25// between delimiters (including empty ones for two delimiters in a row)
26//
27// |delimiters| can either be a list of delimiters in something string-like
28// or a single character (which is more efficient).
29//
Yurii Zubrytskyi003751d2020-04-16 12:45:39 -070030// An empty string is not a valid delimiter.
Songchun Fan59eee562019-10-24 16:46:06 -070031//
32template <class Callback, class Separator>
33void Split(std::string_view s, Separator delimiters, Callback&& onSplitCb) {
34 size_t base = 0;
35 for (;;) {
36 const auto found = s.find_first_of(delimiters, base);
37 onSplitCb(s.substr(base, found - base));
38 if (found == std::string_view::npos) {
39 break;
40 }
41 base = found + 1;
42 }
43}
44
45// Splits a string into a vector of string views.
46//
47// The string is split at each occurrence of a character in |delimiters|.
48//
49// The empty string is not a valid delimiter list.
50//
51template <class Separator>
Yurii Zubrytskyid6688852019-11-26 17:39:08 -080052void Split(std::string_view s, Separator delimiters, std::vector<std::string_view>* out) {
53 out->clear();
54 Split(s, delimiters, [out](std::string_view split) { out->emplace_back(split); });
55}
56
57template <class Separator>
Songchun Fan59eee562019-10-24 16:46:06 -070058std::vector<std::string_view> Split(std::string_view s, Separator delimiters) {
59 std::vector<std::string_view> result;
Yurii Zubrytskyid6688852019-11-26 17:39:08 -080060 Split(s, delimiters, &result);
Songchun Fan59eee562019-10-24 16:46:06 -070061 return result;
62}
63
64} // namespace android::incfs