1 /* 2 * Copyright (C) 2018 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 com.android.providers.contacts.util; 17 18 import android.util.Log; 19 20 import com.android.providers.contacts.AbstractContactsProvider; 21 22 public class CappedStringBuilder { 23 private final int mCapSize; 24 private boolean mOver; 25 private final StringBuilder mStringBuilder = new StringBuilder(); 26 27 public CappedStringBuilder(int capSize) { 28 mCapSize = capSize; 29 } 30 31 public void clear() { 32 mOver = false; 33 mStringBuilder.setLength(0); 34 } 35 36 public int length() { 37 return mStringBuilder.length(); 38 } 39 40 @Override 41 public String toString() { 42 return mStringBuilder.toString(); 43 } 44 45 public CappedStringBuilder append(char ch) { 46 if (canAppend(mStringBuilder.length() + 1)) { 47 mStringBuilder.append(ch); 48 } 49 return this; 50 } 51 52 public CappedStringBuilder append(String s) { 53 if (canAppend(mStringBuilder.length() + s.length())) { 54 mStringBuilder.append(s); 55 } 56 return this; 57 } 58 59 private boolean canAppend(int length) { 60 if (mOver || length > mCapSize) { 61 if (!mOver && AbstractContactsProvider.VERBOSE_LOGGING) { 62 Log.w(AbstractContactsProvider.TAG, "String too long! new length=" + length); 63 } 64 mOver = true; 65 return false; 66 } 67 return true; 68 } 69 } 70