aboutsummaryrefslogtreecommitdiffstats
path: root/liblfjail/string_utils.hh
blob: 04e29d3b184c9ff9c5f5aeb4ba1bc457dd1cf7c5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
 * This source code is released into the public domain.
 */

#ifndef	LFJAIL_STRING_UTILS_HH
#define	LFJAIL_STRING_UTILS_HH

#include <algorithm>
#include <ranges>
#include <string>
#include <utility>

#include "ctype.hh"

namespace lfjail {

/*
 * Remove leading whitespace from the given string_view.
 */

template<typename Char>
std::basic_string_view<Char>
skipws(std::basic_string_view<Char> text) {
	auto isspace = ctype_is(std::ctype_base::space);
	auto first_nonws = std::ranges::find_if_not(text, isspace);
	return {first_nonws, end(text)};
}

template<typename Char>
void skipws(std::basic_string_view<Char> *text) {
	auto ret = skipws(*text);
	*text = ret;
}

/*
 * Split a string on a predicate.  Specifically, divide the string into two
 * strings at the first character where the predicate matches, and return
 * both strings.  If the predicate matched, the matching character will be
 * discarded.
 */

template<typename Char,
	 std::indirect_unary_predicate<
	 	typename std::basic_string_view<Char>::iterator> Pred>
std::pair<std::basic_string_view<Char>, std::basic_string_view<Char>>
split(std::basic_string_view<Char> text, Pred pred)
{
	auto split_point = std::ranges::find_if(text, pred);

	if (split_point == end(text))
		return {text, {}};
	else
		return {{begin(text), split_point},
			{std::next(split_point), end(text)}};
}

template<typename Char,
	 std::indirect_unary_predicate<
	 	typename std::basic_string_view<Char>::iterator> Pred>
std::basic_string_view<Char>
split(std::basic_string_view<Char> *text, Pred pred)
{
	auto [str, rest] = split(*text, pred);
	*text = rest;
	return str;
}

/*
 * Return the next word from a string_view.  The by-value version returns
 * a pair<next-word, remainder>, while the pointer version returns next-word
 * and sets the input string to remainder.
 */

template<typename Char>
std::pair<std::basic_string_view<Char>, std::basic_string_view<Char>>
next_word(std::basic_string_view<Char> text)
{
	return (split(skipws(text), ctype_is(std::ctype_base::space)));
}

template<typename Char>
std::basic_string_view<Char>
next_word(std::basic_string_view<Char> *text) {
	skipws(text);
	return (split(text, ctype_is(std::ctype_base::space)));
}

} // namespace lfjail

#endif	// LFJAIL_STRING_UTILS_HH