Upstream version 9.37.197.0
[platform/framework/web/crosswalk.git] / src / mojo / bindings / java / src / org / chromium / mojo / bindings / BindingsHelper.java
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 package org.chromium.mojo.bindings;
6
7 /**
8  * Helper functions.
9  */
10 public class BindingsHelper {
11     /**
12      * Alignment in byte for mojo serialization.
13      */
14     public static final int ALIGNMENT = 8;
15
16     /**
17      * Align |size| on {@link BindingsHelper#ALIGNMENT}.
18      */
19     public static int align(int size) {
20         return (size + ALIGNMENT - 1) & ~(ALIGNMENT - 1);
21     }
22
23     /**
24      * Compute the size in bytes of the given string encoded as utf8.
25      */
26     public static int utf8StringSizeInBytes(String s) {
27         int res = 0;
28         for (int i = 0; i < s.length(); ++i) {
29             char c = s.charAt(i);
30             int codepoint = c;
31             if (isSurrogate(c)) {
32                 i++;
33                 char c2 = s.charAt(i);
34                 codepoint = Character.toCodePoint(c, c2);
35             }
36             res += 1;
37             if (codepoint > 0x7f) {
38                 res += 1;
39                 if (codepoint > 0x7ff) {
40                     res += 1;
41                     if (codepoint > 0xffff) {
42                         res += 1;
43                         if (codepoint > 0x1fffff) {
44                             res += 1;
45                             if (codepoint > 0x3ffffff) {
46                                 res += 1;
47                             }
48                         }
49                     }
50                 }
51             }
52         }
53         return res;
54     }
55
56     /**
57      * Determines if the given {@code char} value is a Unicode <i>surrogate code unit</i>. See
58      * {@link Character#isSurrogate}. Extracting here because the method only exists at API level
59      * 19.
60      */
61     private static boolean isSurrogate(char c) {
62         return c >= Character.MIN_SURROGATE && c < (Character.MAX_SURROGATE + 1);
63     }
64 }