1 /*
2 * Copyright (c) 2018, The OpenThread Authors.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * 3. Neither the name of the copyright holder nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28
29 /**
30 * @file
31 * This file implements OpenThread String class and functions.
32 */
33
34 #include "string.hpp"
35 #include "debug.hpp"
36
37 #include <string.h>
38
39 namespace ot {
40
41 namespace {
42
43 // The definitions below are included in an unnamed namespace
44 // to limit their scope to this translation unit (this file).
45
46 enum MatchType : uint8_t
47 {
48 kNoMatch,
49 kPrefixMatch,
50 kFullMatch,
51 };
52
Match(const char * aString,const char * aPrefixString,StringMatchMode aMode)53 MatchType Match(const char *aString, const char *aPrefixString, StringMatchMode aMode)
54 {
55 // This is file private function that is used by other functions.
56 // It matches @p aString with @p aPrefixString using match @ aMode.
57 //
58 // If @p aString and @p aPrefixString match and have the
59 // same length `kFullMatch` is returned. If @p aString starts
60 // with @p aPrefixString but contains more characters, then
61 // `kPrefixMatch` is returned. Otherwise `kNoMatch` is returned.
62
63 MatchType match = kNoMatch;
64
65 switch (aMode)
66 {
67 case kStringExactMatch:
68 while (*aPrefixString != kNullChar)
69 {
70 VerifyOrExit(*aString++ == *aPrefixString++);
71 }
72 break;
73
74 case kStringCaseInsensitiveMatch:
75 while (*aPrefixString != kNullChar)
76 {
77 VerifyOrExit(ToLowercase(*aString++) == ToLowercase(*aPrefixString++));
78 }
79 break;
80 }
81
82 match = (*aString == kNullChar) ? kFullMatch : kPrefixMatch;
83
84 exit:
85 return match;
86 }
87
88 } // namespace
89
StringLength(const char * aString,uint16_t aMaxLength)90 uint16_t StringLength(const char *aString, uint16_t aMaxLength)
91 {
92 uint16_t ret;
93
94 for (ret = 0; (ret < aMaxLength) && (aString[ret] != kNullChar); ret++)
95 {
96 // Empty loop.
97 }
98
99 return ret;
100 }
101
StringFind(const char * aString,char aChar)102 const char *StringFind(const char *aString, char aChar)
103 {
104 const char *ret = nullptr;
105
106 for (; *aString != kNullChar; aString++)
107 {
108 if (*aString == aChar)
109 {
110 ret = aString;
111 break;
112 }
113 }
114
115 return ret;
116 }
117
StringFind(const char * aString,const char * aSubString,StringMatchMode aMode)118 const char *StringFind(const char *aString, const char *aSubString, StringMatchMode aMode)
119 {
120 const char *ret = nullptr;
121 size_t len = strlen(aString);
122 size_t subLen = strlen(aSubString);
123
124 VerifyOrExit(subLen <= len);
125
126 for (size_t index = 0; index <= static_cast<size_t>(len - subLen); index++)
127 {
128 if (Match(&aString[index], aSubString, aMode) != kNoMatch)
129 {
130 ExitNow(ret = &aString[index]);
131 }
132 }
133
134 exit:
135 return ret;
136 }
137
StringStartsWith(const char * aString,const char * aPrefixString,StringMatchMode aMode)138 bool StringStartsWith(const char *aString, const char *aPrefixString, StringMatchMode aMode)
139 {
140 return Match(aString, aPrefixString, aMode) != kNoMatch;
141 }
142
StringEndsWith(const char * aString,char aChar)143 bool StringEndsWith(const char *aString, char aChar)
144 {
145 size_t len = strlen(aString);
146
147 return (len > 0) && (aString[len - 1] == aChar);
148 }
149
StringEndsWith(const char * aString,const char * aSubString,StringMatchMode aMode)150 bool StringEndsWith(const char *aString, const char *aSubString, StringMatchMode aMode)
151 {
152 size_t len = strlen(aString);
153 size_t subLen = strlen(aSubString);
154
155 return (subLen > 0) && (len >= subLen) && (Match(&aString[len - subLen], aSubString, aMode) != kNoMatch);
156 }
157
StringMatch(const char * aFirstString,const char * aSecondString,StringMatchMode aMode)158 bool StringMatch(const char *aFirstString, const char *aSecondString, StringMatchMode aMode)
159 {
160 return Match(aFirstString, aSecondString, aMode) == kFullMatch;
161 }
162
StringParseUint8(const char * & aString,uint8_t & aUint8)163 Error StringParseUint8(const char *&aString, uint8_t &aUint8)
164 {
165 return StringParseUint8(aString, aUint8, NumericLimits<uint8_t>::kMax);
166 }
167
StringParseUint8(const char * & aString,uint8_t & aUint8,uint8_t aMaxValue)168 Error StringParseUint8(const char *&aString, uint8_t &aUint8, uint8_t aMaxValue)
169 {
170 Error error = kErrorParse;
171 const char *cur = aString;
172 uint16_t value = 0;
173
174 for (; (*cur >= '0') && (*cur <= '9'); cur++)
175 {
176 value *= 10;
177 value += static_cast<uint8_t>(*cur - '0');
178 VerifyOrExit(value <= aMaxValue, error = kErrorParse);
179 error = kErrorNone;
180 }
181
182 aString = cur;
183 aUint8 = static_cast<uint8_t>(value);
184
185 exit:
186 return error;
187 }
188
StringConvertToLowercase(char * aString)189 void StringConvertToLowercase(char *aString)
190 {
191 for (; *aString != kNullChar; aString++)
192 {
193 *aString = ToLowercase(*aString);
194 }
195 }
196
StringConvertToUppercase(char * aString)197 void StringConvertToUppercase(char *aString)
198 {
199 for (; *aString != kNullChar; aString++)
200 {
201 *aString = ToUppercase(*aString);
202 }
203 }
204
ToLowercase(char aChar)205 char ToLowercase(char aChar)
206 {
207 if ((aChar >= 'A') && (aChar <= 'Z'))
208 {
209 aChar += 'a' - 'A';
210 }
211
212 return aChar;
213 }
214
ToUppercase(char aChar)215 char ToUppercase(char aChar)
216 {
217 if ((aChar >= 'a') && (aChar <= 'z'))
218 {
219 aChar -= 'a' - 'A';
220 }
221
222 return aChar;
223 }
224
ToYesNo(bool aBool)225 const char *ToYesNo(bool aBool)
226 {
227 static const char *const kYesNoStrings[] = {"no", "yes"};
228
229 return kYesNoStrings[aBool];
230 }
231
StringWriter(char * aBuffer,uint16_t aSize)232 StringWriter::StringWriter(char *aBuffer, uint16_t aSize)
233 : mBuffer(aBuffer)
234 , mLength(0)
235 , mSize(aSize)
236 {
237 mBuffer[0] = kNullChar;
238 }
239
Clear(void)240 StringWriter &StringWriter::Clear(void)
241 {
242 mBuffer[0] = kNullChar;
243 mLength = 0;
244 return *this;
245 }
246
Append(const char * aFormat,...)247 StringWriter &StringWriter::Append(const char *aFormat, ...)
248 {
249 va_list args;
250 va_start(args, aFormat);
251 AppendVarArgs(aFormat, args);
252 va_end(args);
253
254 return *this;
255 }
256
AppendVarArgs(const char * aFormat,va_list aArgs)257 StringWriter &StringWriter::AppendVarArgs(const char *aFormat, va_list aArgs)
258 {
259 int len;
260
261 len = vsnprintf(mBuffer + mLength, (mSize > mLength ? (mSize - mLength) : 0), aFormat, aArgs);
262 OT_ASSERT(len >= 0);
263
264 mLength += static_cast<uint16_t>(len);
265
266 if (IsTruncated())
267 {
268 mBuffer[mSize - 1] = kNullChar;
269 }
270
271 return *this;
272 }
273
AppendHexBytes(const uint8_t * aBytes,uint16_t aLength)274 StringWriter &StringWriter::AppendHexBytes(const uint8_t *aBytes, uint16_t aLength)
275 {
276 while (aLength--)
277 {
278 Append("%02x", *aBytes++);
279 }
280
281 return *this;
282 }
283
IsValidUtf8String(const char * aString)284 bool IsValidUtf8String(const char *aString) { return IsValidUtf8String(aString, strlen(aString)); }
285
IsValidUtf8String(const char * aString,size_t aLength)286 bool IsValidUtf8String(const char *aString, size_t aLength)
287 {
288 bool ret = true;
289 uint8_t byte;
290 uint8_t continuationBytes = 0;
291 size_t position = 0;
292
293 while (position < aLength)
294 {
295 byte = *reinterpret_cast<const uint8_t *>(aString + position);
296 ++position;
297
298 if ((byte & 0x80) == 0)
299 {
300 // We don't allow control characters.
301 VerifyOrExit(!iscntrl(byte), ret = false);
302 continue;
303 }
304
305 // This is a leading byte 1xxx-xxxx.
306
307 if ((byte & 0x40) == 0) // 10xx-xxxx
308 {
309 // We got a continuation byte pattern without seeing a leading byte earlier.
310 ExitNow(ret = false);
311 }
312 else if ((byte & 0x20) == 0) // 110x-xxxx
313 {
314 continuationBytes = 1;
315 }
316 else if ((byte & 0x10) == 0) // 1110-xxxx
317 {
318 continuationBytes = 2;
319 }
320 else if ((byte & 0x08) == 0) // 1111-0xxx
321 {
322 continuationBytes = 3;
323 }
324 else // 1111-1xxx (invalid pattern).
325 {
326 ExitNow(ret = false);
327 }
328
329 while (continuationBytes-- != 0)
330 {
331 VerifyOrExit(position < aLength, ret = false);
332
333 byte = *reinterpret_cast<const uint8_t *>(aString + position);
334 ++position;
335
336 // Verify the continuation byte pattern 10xx-xxxx
337 VerifyOrExit((byte & 0xc0) == 0x80, ret = false);
338 }
339 }
340
341 exit:
342 return ret;
343 }
344
345 } // namespace ot
346