Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * Licensed to the Apache Software Foundation (ASF) under one or more
0003  * contributor license agreements.  See the NOTICE file distributed with
0004  * this work for additional information regarding copyright ownership.
0005  * The ASF licenses this file to You under the Apache License, Version 2.0
0006  * (the "License"); you may not use this file except in compliance with
0007  * the License.  You may obtain a copy of the License at
0008  *
0009  *    http://www.apache.org/licenses/LICENSE-2.0
0010  *
0011  * Unless required by applicable law or agreed to in writing, software
0012  * distributed under the License is distributed on an "AS IS" BASIS,
0013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014  * See the License for the specific language governing permissions and
0015  * limitations under the License.
0016  */
0017 package org.apache.spark.network.util;
0018 
0019 public enum ByteUnit {
0020   BYTE(1),
0021   KiB(1L << 10),
0022   MiB(1L << 20),
0023   GiB(1L << 30),
0024   TiB(1L << 40),
0025   PiB(1L << 50);
0026 
0027   ByteUnit(long multiplier) {
0028     this.multiplier = multiplier;
0029   }
0030 
0031   // Interpret the provided number (d) with suffix (u) as this unit type.
0032   // E.g. KiB.interpret(1, MiB) interprets 1MiB as its KiB representation = 1024k
0033   public long convertFrom(long d, ByteUnit u) {
0034     return u.convertTo(d, this);
0035   }
0036 
0037   // Convert the provided number (d) interpreted as this unit type to unit type (u).
0038   public long convertTo(long d, ByteUnit u) {
0039     if (multiplier > u.multiplier) {
0040       long ratio = multiplier / u.multiplier;
0041       if (Long.MAX_VALUE / ratio < d) {
0042         throw new IllegalArgumentException("Conversion of " + d + " exceeds Long.MAX_VALUE in "
0043           + name() + ". Try a larger unit (e.g. MiB instead of KiB)");
0044       }
0045       return d * ratio;
0046     } else {
0047       // Perform operations in this order to avoid potential overflow
0048       // when computing d * multiplier
0049       return d / (u.multiplier / multiplier);
0050     }
0051   }
0052 
0053   public long toBytes(long d) {
0054     if (d < 0) {
0055       throw new IllegalArgumentException("Negative size value. Size must be positive: " + d);
0056     }
0057     return d * multiplier;
0058   }
0059 
0060   public long toKiB(long d) { return convertTo(d, KiB); }
0061   public long toMiB(long d) { return convertTo(d, MiB); }
0062   public long toGiB(long d) { return convertTo(d, GiB); }
0063   public long toTiB(long d) { return convertTo(d, TiB); }
0064   public long toPiB(long d) { return convertTo(d, PiB); }
0065 
0066   private final long multiplier;
0067 }