1 // 2017 and later: Unicode, Inc. and others. 2 // License & terms of use: http://www.unicode.org/copyright.html#License 3 package com.ibm.icu.impl.number; 4 5 import com.ibm.icu.text.NumberFormat.Field; 6 7 /** 8 * The canonical implementation of {@link Modifier}, containing a prefix and suffix string. 9 */ 10 public class ConstantAffixModifier implements Modifier { 11 12 // TODO: Avoid making a new instance by default if prefix and suffix are empty 13 public static final ConstantAffixModifier EMPTY = new ConstantAffixModifier(); 14 15 private final String prefix; 16 private final String suffix; 17 private final Field field; 18 private final boolean strong; 19 20 /** 21 * Constructs an instance with the given strings. 22 * 23 * <p> 24 * The arguments need to be Strings, not CharSequences, because Strings are immutable but CharSequences are not. 25 * 26 * @param prefix 27 * The prefix string. 28 * @param suffix 29 * The suffix string. 30 * @param field 31 * The field type to be associated with this modifier. Can be null. 32 * @param strong 33 * Whether this modifier should be strongly applied. 34 * @see Field 35 */ 36 public ConstantAffixModifier(String prefix, String suffix, Field field, boolean strong) { 37 // Use an empty string instead of null if we are given null 38 // TODO: Consider returning a null modifier if both prefix and suffix are empty. 39 this.prefix = (prefix == null ? "" : prefix); 40 this.suffix = (suffix == null ? "" : suffix); 41 this.field = field; 42 this.strong = strong; 43 } 44 45 /** Constructs a new instance with an empty prefix, suffix, and field. */ 46 public ConstantAffixModifier() { 47 prefix = ""; 48 suffix = ""; 49 field = null; 50 strong = false; 51 } 52 53 @Override 54 public int apply(NumberStringBuilder output, int leftIndex, int rightIndex) { 55 // Insert the suffix first since inserting the prefix will change the rightIndex 56 int length = output.insert(rightIndex, suffix, field); 57 length += output.insert(leftIndex, prefix, field); 58 return length; 59 } 60 61 @Override 62 public int getPrefixLength() { 63 return prefix.length(); 64 } 65 66 @Override 67 public int getCodePointCount() { 68 return prefix.codePointCount(0, prefix.length()) + suffix.codePointCount(0, suffix.length()); 69 } 70 71 @Override 72 public boolean isStrong() { 73 return strong; 74 } 75 76 @Override 77 public String toString() { 78 return String.format("<ConstantAffixModifier prefix:'%s' suffix:'%s'>", prefix, suffix); 79 } 80 } 81