/*
* Copyright (C) 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package antil.util;
import antil.annotation.Beta;
/**
* A {@linkplain SizeUnit} represents the unit of a given size and provides a
* utility method to convert that size to bytes.
* <p>
* Example usage:
*
* <pre>
* // Converts 2 megabytes to bytes:
* long bytes = SizeUnit.MB.toBytes(2);
* </pre>
*
* @see #BYTE
* @see #KB
* @see #MB
* @see #KiB
* @see #MiB
*
* @since 1.0
*/
@Beta
public interface SizeUnit {
/**
* Byte
*/
public static final SizeUnit BYTE = new SizeUnit() {
@Override
public long toBytes(long quantity) {
return quantity;
}
};
/**
* Kibibyte
* <p>
* 1 KiB = 2<sup>10</sup> bytes = 1024 bytes
*
* @see #KB
*/
public static final SizeUnit KiB = new SizeUnit() {
@Override
public long toBytes(long quantity) {
return BYTE.toBytes(quantity * 1024);
}
};
/**
* Mebibyte
* <p>
* 1 MiB = 2<sup>20</sup> bytes = 1024 kibibytes = 1 048 576 bytes
*
* @see #MB
*/
public static final SizeUnit MiB = new SizeUnit() {
@Override
public long toBytes(long quantity) {
return KiB.toBytes(quantity * 1024);
}
};
/**
* Kilobyte
* <p>
* 1 KB = 10<sup>3</sup> bytes = 1000 bytes
*
* @see #KiB
*/
public static final SizeUnit KB = new SizeUnit() {
@Override
public long toBytes(long quantity) {
return BYTE.toBytes(quantity * 1000);
}
};
/**
* Megabyte
* <p>
* 1 MB = 10<sup>6</sup> bytes = 1 000 000 bytes
*
* @see #MiB
*/
public static final SizeUnit MB = new SizeUnit() {
@Override
public long toBytes(long quantity) {
return KB.toBytes(quantity * 1000);
}
};
/**
* Converts the given size in {@link this} unit to bytes.
* <p>
* For example: {@code SizeUnit.KB.toBytes(2)} means convert 2 kilobytes to
* bytes.
*
* @param size the size in {@link this} unit.
* @return the size in bytes.
*/
long toBytes(long size);
}
|