1/*
2 * Copyright 2012 Sebastian Annies, Hamburg
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 */
16package com.coremedia.iso;
17
18import java.io.UnsupportedEncodingException;
19
20/**
21 * Converts <code>byte[]</code> -> <code>String</code> and vice versa.
22 */
23public final class Utf8 {
24    public static byte[] convert(String s) {
25        try {
26            if (s != null) {
27                return s.getBytes("UTF-8");
28            } else {
29                return null;
30            }
31        } catch (UnsupportedEncodingException e) {
32            throw new Error(e);
33        }
34    }
35
36    public static String convert(byte[] b) {
37        try {
38            if (b != null) {
39                return new String(b, "UTF-8");
40            } else {
41                return null;
42            }
43        } catch (UnsupportedEncodingException e) {
44            throw new Error(e);
45        }
46    }
47
48    public static int utf8StringLengthInBytes(String utf8) {
49        try {
50            if (utf8 != null) {
51                return utf8.getBytes("UTF-8").length;
52            } else {
53                return 0;
54            }
55        } catch (UnsupportedEncodingException e) {
56            throw new RuntimeException();
57        }
58    }
59}
60