+ public static boolean isValidMemoryString(String text)
+ {
+ if (text.length() > 0)
+ {
+ char lastChar = text.charAt(text.length() - 1);
+ char[] otherChars = text.substring(0, text.length() - 1)
+ .toCharArray();
+ for (char c : otherChars)
+ {
+ if (c < '0' || c > '9')
+ {
+ return false;
+ }
+ }
+ if ((lastChar < '0' || lastChar > '9') && memorySuffixes
+ .indexOf(Character.toLowerCase(lastChar)) == -1)
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public static long memoryStringToLong(String memString)
+ throws NumberFormatException
+ {
+ if (!isValidMemoryString(memString)) // not valid
+ {
+ throw (new NumberFormatException("Not a valid memory string"));
+ }
+ char suffix = Character
+ .toLowerCase(memString.charAt(memString.length() - 1));
+ if ('0' <= suffix && suffix <= '9') // no suffix
+ {
+ return Long.valueOf(memString);
+ }
+ if (memorySuffixes.indexOf(suffix) == -1) // suffix is unknown
+ {
+ return -1;
+ }
+
+ long multiplier = (long) Math.pow(2,
+ memorySuffixes.indexOf(suffix) * 10); // note order of suffixes in
+ // memorySuffixes important
+ // here!
+ // parse the arg. NumberFormatExceptions passed on to calling method
+ long mem = Long
+ .parseLong(memString.substring(0, memString.length() - 1));
+ if (mem == 0)
+ {
+ return 0;
+ }
+
+ // apply multiplier only if result is not too big (i.e. bigger than a long)
+ if (Long.MAX_VALUE / mem > multiplier)
+ {
+ return multiplier * mem;
+ }
+ else
+ {
+ // number too big for a Long. Limit to Long.MAX_VALUE
+ System.out.println("Memory parsing of '" + memString
+ + "' produces number too big. Limiting to Long.MAX_VALUE="
+ + Long.MAX_VALUE);
+ return Long.MAX_VALUE;
+ }
+ }
+
+ public static String memoryLongToString(long mem)
+ {
+ return memoryLongToString(mem, "%.3f");
+ }
+
+ public static String memoryLongToString(long mem, String format)
+ {
+ int exponent = 0;
+ float num = mem;
+ char suffix = 'b';
+
+ for (int i = 0; i < memorySuffixes.length(); i++)
+ {
+ char s = Character.toUpperCase(memorySuffixes.charAt(i));
+ if (mem < (long) Math.pow(2, exponent + 10)
+ || i == memorySuffixes.length() - 1) // last suffix
+ {
+ suffix = s;
+ num = (float) (mem / Math.pow(2, exponent));
+ break;
+ }
+ exponent += 10;
+ }
+
+ return String.format(format, num) + suffix;
+ }
+
+ private static String ADJUSTMENT_MESSAGE = null;
+
+ private static void setAdjustmentMessage(String reason, boolean quiet)
+ {
+ ADJUSTMENT_MESSAGE = reason;
+ if (!quiet)
+ {
+ System.out.println(reason);
+ }
+ }
+
+ public static void clearAdjustmentMessage()
+ {
+ ADJUSTMENT_MESSAGE = null;
+ }
+
+ public static String getAdjustmentMessage()
+ {
+ return ADJUSTMENT_MESSAGE;
+ }
+
+}