blob: c97e181527cdd6514761242430992f886b743752 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.builder.xml.dom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.yahoo.text.Lowercase.toLowerCase;
/**
* @author tonytv
*/
public class BinaryUnit {
//The pattern must match the one given in the schema
private static Pattern pattern = Pattern.compile("(\\d+(\\.\\d*)?)\\s*([kmgKMG])?");
public static double valueOf(String valueString) {
Matcher matcher = pattern.matcher(valueString);
matcher.matches();
double value = Double.valueOf(matcher.group(1));
String unit = matcher.group(3);
if (unit != null) {
value *= unitToValue(toLowerCase(unit).charAt(0));
}
return value;
}
private static double unitToValue(char unit) {
final char units[] = {'k', 'm', 'g'};
for (int i=0; i<units.length; ++i) {
if (units[i] == unit) {
return Math.pow(2, 10*(i+1));
}
}
throw new RuntimeException("No such unit: '" + unit + "'");
}
}
|