blob: f2aa0463e24578ee52439016367719908c7e02f6 [file] [log] [blame]
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.mojo.bindings;
/**
* Helper functions.
*/
public class BindingsHelper {
/**
* Alignment in byte for mojo serialization.
*/
public static final int ALIGNMENT = 8;
/**
* Align |size| on {@link BindingsHelper#ALIGNMENT}.
*/
public static int align(int size) {
return (size + ALIGNMENT - 1) & ~(ALIGNMENT - 1);
}
/**
* Compute the size in bytes of the given string encoded as utf8.
*/
public static int utf8StringSizeInBytes(String s) {
int res = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
int codepoint = c;
if (isSurrogate(c)) {
i++;
char c2 = s.charAt(i);
codepoint = Character.toCodePoint(c, c2);
}
res += 1;
if (codepoint > 0x7f) {
res += 1;
if (codepoint > 0x7ff) {
res += 1;
if (codepoint > 0xffff) {
res += 1;
if (codepoint > 0x1fffff) {
res += 1;
if (codepoint > 0x3ffffff) {
res += 1;
}
}
}
}
}
}
return res;
}
/**
* Determines if the given {@code char} value is a Unicode <i>surrogate code unit</i>. See
* {@link Character#isSurrogate}. Extracting here because the method only exists at API level
* 19.
*/
private static boolean isSurrogate(char c) {
return c >= Character.MIN_SURROGATE && c < (Character.MAX_SURROGATE + 1);
}
}