1 /* 2 * Copyright (C) 2017 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 package androidx.emoji.util; 17 18 import java.util.ArrayList; 19 import java.util.List; 20 21 /** 22 * Utility class used to create strings with emojis during tests. 23 */ 24 public class TestString { 25 26 private static final List<Integer> EMPTY_LIST = new ArrayList<>(); 27 28 private static final String EXTRA = "ab"; 29 private final List<Integer> mCodePoints; 30 private String mString; 31 private final String mValue; 32 private boolean mHasSuffix; 33 private boolean mHasPrefix; 34 35 public TestString(int... codePoints) { 36 if (codePoints.length == 0) { 37 mCodePoints = EMPTY_LIST; 38 } else { 39 mCodePoints = new ArrayList<>(); 40 append(codePoints); 41 } 42 mValue = null; 43 } 44 45 public TestString(Emoji.EmojiMapping emojiMapping) { 46 this(emojiMapping.codepoints()); 47 } 48 49 public TestString(String string) { 50 mCodePoints = EMPTY_LIST; 51 mValue = string; 52 } 53 54 public TestString append(int... codePoints) { 55 for (int i = 0; i < codePoints.length; i++) { 56 mCodePoints.add(codePoints[i]); 57 } 58 return this; 59 } 60 61 public TestString prepend(int... codePoints) { 62 for (int i = codePoints.length - 1; i >= 0; i--) { 63 mCodePoints.add(0, codePoints[i]); 64 } 65 return this; 66 } 67 68 public TestString append(Emoji.EmojiMapping emojiMapping) { 69 return append(emojiMapping.codepoints()); 70 } 71 72 public TestString withSuffix() { 73 mHasSuffix = true; 74 return this; 75 } 76 77 public TestString withPrefix() { 78 mHasPrefix = true; 79 return this; 80 } 81 82 @SuppressWarnings("ForLoopReplaceableByForEach") 83 @Override 84 public String toString() { 85 StringBuilder builder = new StringBuilder(); 86 if (mHasPrefix) { 87 builder.append(EXTRA); 88 } 89 90 for (int index = 0; index < mCodePoints.size(); index++) { 91 builder.append(Character.toChars(mCodePoints.get(index))); 92 } 93 94 if (mValue != null) { 95 builder.append(mValue); 96 } 97 98 if (mHasSuffix) { 99 builder.append(EXTRA); 100 } 101 mString = builder.toString(); 102 return mString; 103 } 104 105 public int emojiStartIndex() { 106 if (mHasPrefix) return EXTRA.length(); 107 return 0; 108 } 109 110 public int emojiEndIndex() { 111 if (mHasSuffix) return mString.lastIndexOf(EXTRA); 112 return mString.length(); 113 } 114 } 115