1/* 2 * Copyright (C) 2010 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.phone.common.mail.store.imap; 18 19import com.android.phone.common.mail.FixedLengthInputStream; 20import com.android.phone.vvm.omtp.VvmLog; 21 22import java.io.ByteArrayInputStream; 23import java.io.IOException; 24import java.io.InputStream; 25import java.io.UnsupportedEncodingException; 26 27/** 28 * Subclass of {@link ImapString} used for literals backed by an in-memory byte array. 29 */ 30public class ImapMemoryLiteral extends ImapString { 31 private final String TAG = "ImapMemoryLiteral"; 32 private byte[] mData; 33 34 /* package */ ImapMemoryLiteral(FixedLengthInputStream in) throws IOException { 35 // We could use ByteArrayOutputStream and IOUtils.copy, but it'd perform an unnecessary 36 // copy.... 37 mData = new byte[in.getLength()]; 38 int pos = 0; 39 while (pos < mData.length) { 40 int read = in.read(mData, pos, mData.length - pos); 41 if (read < 0) { 42 break; 43 } 44 pos += read; 45 } 46 if (pos != mData.length) { 47 VvmLog.w(TAG, "length mismatch"); 48 } 49 } 50 51 @Override 52 public void destroy() { 53 mData = null; 54 super.destroy(); 55 } 56 57 @Override 58 public String getString() { 59 try { 60 return new String(mData, "US-ASCII"); 61 } catch (UnsupportedEncodingException e) { 62 VvmLog.e(TAG, "Unsupported encoding: ", e); 63 } 64 return null; 65 } 66 67 @Override 68 public InputStream getAsStream() { 69 return new ByteArrayInputStream(mData); 70 } 71 72 @Override 73 public String toString() { 74 return String.format("{%d byte literal(memory)}", mData.length); 75 } 76}