blob: 31fbe97da0e992175dc6032d5449433dcee7e315 [file] [log] [blame]
Elliott Hughes814e4032011-08-23 12:07:56 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
3#include "utf.h"
4
Elliott Hughesb465ab02011-08-24 11:21:21 -07005#include "logging.h"
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006#include "object.h"
Elliott Hughesb465ab02011-08-24 11:21:21 -07007
Elliott Hughes814e4032011-08-23 12:07:56 -07008namespace art {
9
10size_t CountModifiedUtf8Chars(const char* utf8) {
11 size_t len = 0;
12 int ic;
13 while ((ic = *utf8++) != '\0') {
14 len++;
15 if ((ic & 0x80) == 0) {
16 // one-byte encoding
17 continue;
18 }
19 // two- or three-byte encoding
20 utf8++;
21 if ((ic & 0x20) == 0) {
22 // two-byte encoding
23 continue;
24 }
25 // three-byte encoding
26 utf8++;
27 }
28 return len;
29}
30
31void ConvertModifiedUtf8ToUtf16(uint16_t* utf16_data_out, const char* utf8_data_in) {
32 while (*utf8_data_in != '\0') {
33 *utf16_data_out++ = GetUtf16FromUtf8(&utf8_data_in);
34 }
35}
36
Elliott Hughesb465ab02011-08-24 11:21:21 -070037void ConvertUtf16ToModifiedUtf8(char* utf8_out, const uint16_t* utf16_in, size_t char_count) {
38 while (char_count--) {
39 uint16_t ch = *utf16_in++;
40 if (ch > 0 && ch <= 0x7f) {
41 *utf8_out++ = ch;
42 } else {
43 if (ch > 0x07ff) {
44 *utf8_out++ = (ch >> 12) | 0xe0;
45 *utf8_out++ = ((ch >> 6) & 0x3f) | 0x80;
46 *utf8_out++ = (ch & 0x3f) | 0x80;
47 } else /*(ch > 0x7f || ch == 0)*/ {
48 *utf8_out++ = (ch >> 6) | 0xc0;
49 *utf8_out++ = (ch & 0x3f) | 0x80;
50 }
51 }
52 }
53}
54
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070055int32_t ComputeUtf16Hash(const CharArray* chars, int32_t offset,
56 size_t char_count) {
57 int32_t hash = 0;
58 for (size_t i = 0; i < char_count; i++) {
59 hash = hash * 31 + chars->Get(offset + i);
60 }
61 return hash;
62}
63
Elliott Hughes814e4032011-08-23 12:07:56 -070064int32_t ComputeUtf16Hash(const uint16_t* chars, size_t char_count) {
65 int32_t hash = 0;
66 while (char_count--) {
67 hash = hash * 31 + *chars++;
68 }
69 return hash;
70}
71
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070072
Elliott Hughes814e4032011-08-23 12:07:56 -070073uint16_t GetUtf16FromUtf8(const char** utf8_data_in) {
74 uint8_t one = *(*utf8_data_in)++;
75 if ((one & 0x80) == 0) {
76 // one-byte encoding
77 return one;
78 }
79 // two- or three-byte encoding
80 uint8_t two = *(*utf8_data_in)++;
81 if ((one & 0x20) == 0) {
82 // two-byte encoding
83 return ((one & 0x1f) << 6) | (two & 0x3f);
84 }
85 // three-byte encoding
86 uint8_t three = *(*utf8_data_in)++;
87 return ((one & 0x0f) << 12) | ((two & 0x3f) << 6) | (three & 0x3f);
88}
89
90size_t CountUtf8Bytes(const uint16_t* chars, size_t char_count) {
91 size_t result = 0;
92 while (char_count--) {
93 uint16_t ch = *chars++;
94 if (ch > 0 && ch <= 0x7f) {
95 ++result;
96 } else {
97 if (ch > 0x7ff) {
98 result += 3;
99 } else {
100 result += 2;
101 }
102 }
103 }
104 return result;
105}
106
107} // namespace art