1 /*
2 * Copyright 2009-2020 Max Kellermann <max.kellermann@gmail.com>
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the
14 * distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
19 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
20 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
25 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
27 * OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30 #include "StringStrip.hxx"
31 #include "CharUtil.hxx"
32
33 #include <cstring>
34
35 const char *
StripLeft(const char * p)36 StripLeft(const char *p) noexcept
37 {
38 while (IsWhitespaceNotNull(*p))
39 ++p;
40
41 return p;
42 }
43
44 const char *
StripLeft(const char * p,const char * end)45 StripLeft(const char *p, const char *end) noexcept
46 {
47 while (p < end && IsWhitespaceOrNull(*p))
48 ++p;
49
50 return p;
51 }
52
53 const char *
StripRight(const char * p,const char * end)54 StripRight(const char *p, const char *end) noexcept
55 {
56 while (end > p && IsWhitespaceOrNull(end[-1]))
57 --end;
58
59 return end;
60 }
61
62 std::size_t
StripRight(const char * p,std::size_t length)63 StripRight(const char *p, std::size_t length) noexcept
64 {
65 while (length > 0 && IsWhitespaceOrNull(p[length - 1]))
66 --length;
67
68 return length;
69 }
70
71 void
StripRight(char * p)72 StripRight(char *p) noexcept
73 {
74 std::size_t old_length = std::strlen(p);
75 std::size_t new_length = StripRight(p, old_length);
76 p[new_length] = 0;
77 }
78
79 char *
Strip(char * p)80 Strip(char *p) noexcept
81 {
82 p = StripLeft(p);
83 StripRight(p);
84 return p;
85 }
86