bd19c9befbb83949f1e49b73f274d39a6ad4a8b2
[folly.git] / folly / Unicode.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/Unicode.h>
18
19 namespace folly {
20
21 //////////////////////////////////////////////////////////////////////
22
23 fbstring codePointToUtf8(char32_t cp) {
24   fbstring result;
25
26   // Based on description from http://en.wikipedia.org/wiki/UTF-8.
27
28   if (cp <= 0x7f) {
29     result.resize(1);
30     result[0] = static_cast<char>(cp);
31   } else if (cp <= 0x7FF) {
32     result.resize(2);
33     result[1] = static_cast<char>(0x80 | (0x3f & cp));
34     result[0] = static_cast<char>(0xC0 | (cp >> 6));
35   } else if (cp <= 0xFFFF) {
36     result.resize(3);
37     result[2] = static_cast<char>(0x80 | (0x3f & cp));
38     result[1] = (0x80 | static_cast<char>((0x3f & (cp >> 6))));
39     result[0] = (0xE0 | static_cast<char>(cp >> 12));
40   } else if (cp <= 0x10FFFF) {
41     result.resize(4);
42     result[3] = static_cast<char>(0x80 | (0x3f & cp));
43     result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
44     result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
45     result[0] = static_cast<char>(0xF0 | (cp >> 18));
46   }
47
48   return result;
49 }
50
51 //////////////////////////////////////////////////////////////////////
52
53 }