blob: 8fd8edc1ec6f98a192d70af28075eaf79df9ef11 [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// 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
19namespace absl {
Austin Schuhb4691e92020-12-31 12:37:18 -080020ABSL_NAMESPACE_BEGIN
Austin Schuh36244a12019-09-21 17:52:38 -070021namespace strings_internal {
22
23size_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
Austin Schuhb4691e92020-12-31 12:37:18 -080052ABSL_NAMESPACE_END
Austin Schuh36244a12019-09-21 17:52:38 -070053} // namespace absl