• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of 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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 // UTF8 utilities, implemented to reduce dependencies.
16 
17 #include "absl/strings/internal/utf8.h"
18 
19 namespace absl {
20 ABSL_NAMESPACE_BEGIN
21 namespace strings_internal {
22 
EncodeUTF8Char(char * buffer,char32_t utf8_char)23 size_t EncodeUTF8Char(char *buffer, char32_t utf8_char) {
24   if (utf8_char <= 0x7F) {
25     *buffer = static_cast<char>(utf8_char);
26     return 1;
27   } else if (utf8_char <= 0x7FF) {
28     buffer[1] = 0x80 | (utf8_char & 0x3F);
29     utf8_char >>= 6;
30     buffer[0] = 0xC0 | utf8_char;
31     return 2;
32   } else if (utf8_char <= 0xFFFF) {
33     buffer[2] = 0x80 | (utf8_char & 0x3F);
34     utf8_char >>= 6;
35     buffer[1] = 0x80 | (utf8_char & 0x3F);
36     utf8_char >>= 6;
37     buffer[0] = 0xE0 | utf8_char;
38     return 3;
39   } else {
40     buffer[3] = 0x80 | (utf8_char & 0x3F);
41     utf8_char >>= 6;
42     buffer[2] = 0x80 | (utf8_char & 0x3F);
43     utf8_char >>= 6;
44     buffer[1] = 0x80 | (utf8_char & 0x3F);
45     utf8_char >>= 6;
46     buffer[0] = 0xF0 | utf8_char;
47     return 4;
48   }
49 }
50 
51 }  // namespace strings_internal
52 ABSL_NAMESPACE_END
53 }  // namespace absl
54