1/*
2 * Copyright (C) 2014 The Android Open Source Project
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
17package com.android.inputmethod.latin.common;
18
19import javax.annotation.Nonnull;
20
21/**
22 * An immutable class that encapsulates a snapshot of word composition data.
23 */
24public class ComposedData {
25    @Nonnull
26    public final InputPointers mInputPointers;
27    public final boolean mIsBatchMode;
28    @Nonnull
29    public final String mTypedWord;
30
31    public ComposedData(@Nonnull final InputPointers inputPointers, final boolean isBatchMode,
32            @Nonnull final String typedWord) {
33        mInputPointers = inputPointers;
34        mIsBatchMode = isBatchMode;
35        mTypedWord = typedWord;
36    }
37
38    /**
39     * Copy the code points in the typed word to a destination array of ints.
40     *
41     * If the array is too small to hold the code points in the typed word, nothing is copied and
42     * -1 is returned.
43     *
44     * @param destination the array of ints.
45     * @return the number of copied code points.
46     */
47    public int copyCodePointsExceptTrailingSingleQuotesAndReturnCodePointCount(
48            @Nonnull final int[] destination) {
49        // lastIndex is exclusive
50        final int lastIndex = mTypedWord.length()
51                - StringUtils.getTrailingSingleQuotesCount(mTypedWord);
52        if (lastIndex <= 0) {
53            // The string is empty or contains only single quotes.
54            return 0;
55        }
56
57        // The following function counts the number of code points in the text range which begins
58        // at index 0 and extends to the character at lastIndex.
59        final int codePointSize = Character.codePointCount(mTypedWord, 0, lastIndex);
60        if (codePointSize > destination.length) {
61            return -1;
62        }
63        return StringUtils.copyCodePointsAndReturnCodePointCount(destination, mTypedWord, 0,
64                lastIndex, true /* downCase */);
65    }
66}
67