• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2015 The Android Open Source Project
3  *
4  * <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5  * except in compliance with the License. You may obtain a copy of the License at
6  *
7  * <p>http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * <p>Unless required by applicable law or agreed to in writing, software distributed under the
10  * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11  * express or implied. See the License for the specific language governing permissions and
12  * limitations under the License.
13  */
14 package com.android.voicemail.impl.mail.utils;
15 
16 import java.io.ByteArrayInputStream;
17 import java.nio.ByteBuffer;
18 import java.nio.CharBuffer;
19 import java.nio.charset.Charset;
20 
21 /** Simple utility methods used in email functions. */
22 public class Utility {
23   public static final Charset ASCII = Charset.forName("US-ASCII");
24 
25   public static final String[] EMPTY_STRINGS = new String[0];
26 
27   /**
28    * Returns a concatenated string containing the output of every Object's toString() method, each
29    * separated by the given separator character.
30    */
combine(Object[] parts, char separator)31   public static String combine(Object[] parts, char separator) {
32     if (parts == null) {
33       return null;
34     }
35     StringBuilder sb = new StringBuilder();
36     for (int i = 0; i < parts.length; i++) {
37       sb.append(parts[i].toString());
38       if (i < parts.length - 1) {
39         sb.append(separator);
40       }
41     }
42     return sb.toString();
43   }
44 
45   /** Converts a String to ASCII bytes */
toAscii(String s)46   public static byte[] toAscii(String s) {
47     return encode(ASCII, s);
48   }
49 
50   /** Builds a String from ASCII bytes */
fromAscii(byte[] b)51   public static String fromAscii(byte[] b) {
52     return decode(ASCII, b);
53   }
54 
encode(Charset charset, String s)55   private static byte[] encode(Charset charset, String s) {
56     if (s == null) {
57       return null;
58     }
59     final ByteBuffer buffer = charset.encode(CharBuffer.wrap(s));
60     final byte[] bytes = new byte[buffer.limit()];
61     buffer.get(bytes);
62     return bytes;
63   }
64 
decode(Charset charset, byte[] b)65   private static String decode(Charset charset, byte[] b) {
66     if (b == null) {
67       return null;
68     }
69     final CharBuffer cb = charset.decode(ByteBuffer.wrap(b));
70     return new String(cb.array(), 0, cb.length());
71   }
72 
streamFromAsciiString(String ascii)73   public static ByteArrayInputStream streamFromAsciiString(String ascii) {
74     return new ByteArrayInputStream(toAscii(ascii));
75   }
76 }
77