001: /*
002: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
003: * (http://h2database.com/html/license.html).
004: * Initial Developer: H2 Group
005: */
006: package org.h2.util;
007:
008: import java.math.BigDecimal;
009: import java.sql.SQLException;
010:
011: import org.h2.engine.Constants;
012: import org.h2.message.Message;
013:
014: /**
015: * This is a utility class with mathematical helper functions.
016: */
017: public class MathUtils {
018: // with blockSizePowerOf2 8: 0 > 0; 1..8 > 8, 9..16 > 16, ...
019: public static int roundUp(int x, int blockSizePowerOf2) {
020: return (x + blockSizePowerOf2 - 1) & (-blockSizePowerOf2);
021: }
022:
023: public static long roundUpLong(long x, long blockSizePowerOf2) {
024: return (x + blockSizePowerOf2 - 1) & (-blockSizePowerOf2);
025: }
026:
027: public static void checkPowerOf2(int len) {
028: if ((len & (len - 1)) != 0 && len > 0) {
029: throw Message.getInternalError("not a power of 2: " + len);
030: }
031: }
032:
033: public static int nextPowerOf2(int x) {
034: long i = 1;
035: while (i < x && i < (Integer.MAX_VALUE / 2)) {
036: i += i;
037: }
038: return (int) i;
039: }
040:
041: /**
042: * Increase the value by about 50%. The method is used to increase the file size
043: * in larger steps.
044: *
045: * @param start the smallest possible returned value
046: * @param min the current value
047: * @param blockSize the block size
048: * @param maxIncrease the maximum increment
049: * @return the new value
050: */
051: public static long scaleUp50Percent(long start, long min,
052: long blockSize, long maxIncrease) {
053: long len;
054: if (min > maxIncrease * 2) {
055: len = MathUtils.roundUpLong(min, maxIncrease);
056: } else {
057: len = start;
058: while (len < min) {
059: len += len / 2;
060: len += len % blockSize;
061: }
062: }
063: return len;
064: }
065:
066: public static BigDecimal setScale(BigDecimal bd, int scale)
067: throws SQLException {
068: if (scale > Constants.BIG_DECIMAL_SCALE_MAX) {
069: throw Message.getInvalidValueException("" + scale, "scale");
070: } else if (scale < 0) {
071: throw Message.getInvalidValueException("" + scale, "scale");
072: }
073: return bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
074: }
075:
076: public static byte decodeByte(String s) {
077: return Byte.decode(s).byteValue();
078: }
079:
080: public static short decodeShort(String s) {
081: return Short.decode(s).shortValue();
082: }
083:
084: public static int decodeInt(String s) {
085: return Integer.decode(s).intValue();
086: }
087:
088: public static long decodeLong(String s) {
089: return Long.decode(s).longValue();
090: }
091:
092: public static int convertLongToInt(long l) {
093: if (l <= Integer.MIN_VALUE) {
094: return Integer.MIN_VALUE;
095: } else if (l >= Integer.MAX_VALUE) {
096: return Integer.MAX_VALUE;
097: } else {
098: return (int) l;
099: }
100: }
101:
102: }
|