1 /* 2 * Copyright (C) 2014 Square, Inc. 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 okio; 17 18 import java.nio.charset.Charset; 19 20 final class Util { 21 /** A cheap and type-safe constant for the UTF-8 Charset. */ 22 public static final Charset UTF_8 = Charset.forName("UTF-8"); 23 24 private Util() { 25 } 26 27 public static void checkOffsetAndCount(long arrayLength, long offset, long count) { 28 if ((offset | count) < 0 || offset > arrayLength || arrayLength - offset < count) { 29 throw new ArrayIndexOutOfBoundsException(); 30 } 31 } 32 33 public static short reverseBytesShort(short s) { 34 int i = s & 0xffff; 35 int reversed = (i & 0xff00) >>> 8 36 | (i & 0x00ff) << 8; 37 return (short) reversed; 38 } 39 40 public static int reverseBytesInt(int i) { 41 return (i & 0xff000000) >>> 24 42 | (i & 0x00ff0000) >>> 8 43 | (i & 0x0000ff00) << 8 44 | (i & 0x000000ff) << 24; 45 } 46 47 public static long reverseBytesLong(long v) { 48 return (v & 0xff00000000000000L) >>> 56 49 | (v & 0x00ff000000000000L) >>> 40 50 | (v & 0x0000ff0000000000L) >>> 24 51 | (v & 0x000000ff00000000L) >>> 8 52 | (v & 0x00000000ff000000L) << 8 53 | (v & 0x0000000000ff0000L) << 24 54 | (v & 0x000000000000ff00L) << 40 55 | (v & 0x00000000000000ffL) << 56; 56 } 57 58 /** 59 * Throws {@code t}, even if the declared throws clause doesn't permit it. 60 * This is a terrible but terribly convenient hack that makes it easy to 61 * catch and rethrow exceptions after cleanup. See Java Puzzlers #43. 62 */ 63 public static void sneakyRethrow(Throwable t) { 64 Util.<Error>sneakyThrow2(t); 65 } 66 67 @SuppressWarnings("unchecked") 68 private static <T extends Throwable> void sneakyThrow2(Throwable t) throws T { 69 throw (T) t; 70 } 71 } 72