-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrim.hh
99 lines (78 loc) · 2.65 KB
/
trim.hh
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
91
92
93
94
95
96
97
98
99
// Copyright (c) 2022 Mikael Simonsson <https://mikaelsimonsson.com>.
// SPDX-License-Identifier: BSL-1.0
// # Trim characters
// Trim by predicate, a single character or all ASCII control and whitespace.
#pragma once
#include "snn-core/array_view.fwd.hh"
#include "snn-core/strcore.fwd.hh"
#include "snn-core/chr/common.hh"
#include "snn-core/fn/common.hh"
#include "snn-core/math/common.hh"
namespace snn::ascii
{
// ## Functions
// ### trim_left_inplace_if
template <typename Buf, typename OneArgPred>
constexpr void trim_left_inplace_if(strcore<Buf>& s, OneArgPred p)
{
const usize pos = s.find_if(fn::_not{std::move(p)}).value_or_npos();
s.drop_at(0, pos);
}
template <character Char, typename OneArgPred>
constexpr void trim_left_inplace_if(array_view<Char>& s, OneArgPred p)
{
const usize pos = s.find_if(fn::_not{std::move(p)}).value_or_npos();
s.drop_front_n(pos);
}
// ### trim_left_inplace
template <typename String>
constexpr void trim_left_inplace(String& s, const char c) noexcept
{
trim_left_inplace_if(s, fn::is{fn::equal_to{}, c});
}
template <typename String>
constexpr void trim_left_inplace(String& s) noexcept
{
trim_left_inplace_if(s, chr::is_ascii_control_or_space);
}
// ### trim_right_inplace_if
template <typename String, typename OneArgPred>
constexpr void trim_right_inplace_if(String& s, OneArgPred p)
{
static_assert(std::is_same_v<front_value_t<String&>, char>);
const usize pos = s.find_in_reverse_if(fn::_not{std::move(p)}).value_or_npos();
static_assert(constant::npos + 1 == 0);
s.truncate(math::add_with_overflow(pos, 1));
}
// ### trim_right_inplace
template <typename String>
constexpr void trim_right_inplace(String& s, const char c) noexcept
{
trim_right_inplace_if(s, fn::is{fn::equal_to{}, c});
}
template <typename String>
constexpr void trim_right_inplace(String& s) noexcept
{
trim_right_inplace_if(s, chr::is_ascii_control_or_space);
}
// ### trim_inplace_if
template <typename String, typename OneArgPred>
constexpr void trim_inplace_if(String& s, OneArgPred p)
{
trim_left_inplace_if(s, p);
trim_right_inplace_if(s, p);
}
// ### trim_inplace
template <typename String>
constexpr void trim_inplace(String& s, const char c) noexcept
{
trim_left_inplace(s, c);
trim_right_inplace(s, c);
}
template <typename String>
constexpr void trim_inplace(String& s) noexcept
{
trim_left_inplace(s);
trim_right_inplace(s);
}
}