1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #pragma once
16
17 #include <stddef.h>
18 #include <stdint.h>
19
20 #include <string>
21 #include <string_view>
22
23 namespace bt_lib_cpp_string {
24
IsValidCodepoint(uint32_t code_point)25 inline bool IsValidCodepoint(uint32_t code_point) {
26 // Excludes the surrogate code points ([0xD800, 0xDFFF]) and
27 // codepoints larger than 0x10FFFF (the highest codepoint allowed).
28 // Non-characters and unassigned codepoints are allowed.
29 return code_point < 0xD800u ||
30 (code_point >= 0xE000u && code_point <= 0x10FFFFu);
31 }
32
IsValidCharacter(uint32_t code_point)33 inline bool IsValidCharacter(uint32_t code_point) {
34 // Excludes non-characters (U+FDD0..U+FDEF, and all codepoints ending in
35 // 0xFFFE or 0xFFFF) from the set of valid code points.
36 return code_point < 0xD800u ||
37 (code_point >= 0xE000u && code_point < 0xFDD0u) ||
38 (code_point > 0xFDEFu && code_point <= 0x10FFFFu &&
39 (code_point & 0xFFFEu) != 0xFFFEu);
40 }
41
42 bool IsStringUTF8(std::string_view str);
43
44 // ReadUnicodeCharacter --------------------------------------------------------
45
46 // Reads a UTF-8 stream, placing the next code point into the given output
47 // |*code_point|. |src| represents the entire string to read, and |*char_index|
48 // is the character offset within the string to start reading at. |*char_index|
49 // will be updated to index the last character read, such that incrementing it
50 // (as in a for loop) will take the reader to the next character.
51 //
52 // Returns true on success. On false, |*code_point| will be invalid.
53 bool ReadUnicodeCharacter(const char* src,
54 size_t src_len,
55 size_t* char_index,
56 uint32_t* code_point_out);
57
58 // WriteUnicodeCharacter -------------------------------------------------------
59
60 // Appends a UTF-8 character to the given 8-bit string. Returns the number of
61 // bytes written.
62 size_t WriteUnicodeCharacter(uint32_t code_point, std::string* output);
63
64 } // namespace bt_lib_cpp_string
65