Quantities { public static long parseMemory(String memory) { boolean seenDot = false; boolean seenE = false; boolean seenm = false; long factor = 1L; int end = memory.length(); for (int i = 0; i < memory.length(); i++) { char ch = memory.charAt(i); if (ch == 'e') { seenE = true; } else if (ch == '.') { seenDot = true; } else if (ch == 'm') { seenm = true; end = i; break; } else if (ch < '0' || '9' < ch) { end = i; factor = memoryFactor(memory.substring(i)); break; } } long result; String numberPart = memory.substring(0, end); if (seenDot || seenE) { result = (long) (Double.parseDouble(numberPart) * factor); } else if (seenm) { result = (long) Math.floor(Double.parseDouble(numberPart) / 1000); } else { result = Long.parseLong(numberPart) * factor; } return result; } private  Quantities(); static long parseMemory(String memory); static String formatMemory(long bytes); static String normalizeMemory(String memory); static int parseCpuAsMilliCpus(String cpu); static String formatMilliCpu(int milliCpu); static String normalizeCpu(String milliCpu);  }
@Test public void testParseMemory() { assertThat(parseMemory("1234"), is(1234L)); assertThat(parseMemory("0"), is(0L)); assertThat(parseMemory("1K"), is(1000L)); assertThat(parseMemory("1Ki"), is(1024L)); assertThat(parseMemory("512Ki"), is(512 * 1024L)); assertThat(parseMemory("1e6"), is(1_000_000L)); assertThat(parseMemory("3060164198400m"), is(parseMemory("2.85Gi"))); assertThat(parseMemory("3081639034880m"), is(parseMemory("2.87Gi"))); assertThat(parseMemory("0"), is(0L)); assertThat(parseMemory("0K"), is(0L)); assertThat(parseMemory("0e6"), is(0L)); assertThat(parseMemory("500Mi"), is(524288000L)); assertThat(parseMemory("1.1Gi"), is(1181116006L)); assertThat(parseMemory("1.1G"), is(1100000000L)); assertThat(parseMemory("1.1e3K"), is(1100000L)); try { parseMemory("-1K"); fail(); } catch (IllegalArgumentException e) { } try { parseMemory("K"); fail(); } catch (IllegalArgumentException e) { } try { parseMemory("1Kb"); fail(); } catch (IllegalArgumentException e) { } try { parseMemory("foo"); fail(); } catch (IllegalArgumentException e) { } try { parseMemory("1.1x"); fail(); } catch (IllegalArgumentException e) { } try { parseMemory("1.1e-1"); fail(); } catch (IllegalArgumentException e) { } }