Skip to content

Commit

Permalink
Compile patterns.
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshRosen committed May 31, 2024
1 parent de8ba85 commit bf133c8
Showing 1 changed file with 10 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,8 @@ private static boolean isSymlink(File file) throws IOException {
Map.entry("pb", ByteUnit.PiB));
}

private static final Pattern TIME_STRING_PATTERN = Pattern.compile("(-?[0-9]+)([a-z]+)?");

/**
* Convert a passed time string (e.g. 50s, 100ms, or 250us) to a time count in the given unit.
* The unit is also considered the default if the given string does not specify a unit.
Expand All @@ -236,7 +238,7 @@ public static long timeStringAs(String str, TimeUnit unit) {
String lower = str.toLowerCase(Locale.ROOT).trim();

try {
Matcher m = Pattern.compile("(-?[0-9]+)([a-z]+)?").matcher(lower);
Matcher m = TIME_STRING_PATTERN.matcher(lower);
if (!m.matches()) {
throw new NumberFormatException("Failed to parse time string: " + str);
}
Expand Down Expand Up @@ -276,6 +278,11 @@ public static long timeStringAsSec(String str) {
return timeStringAs(str, TimeUnit.SECONDS);
}

private static final Pattern BYTE_STRING_PATTERN =
Pattern.compile("([0-9]+)([a-z]+)?");
private static final Pattern BYTE_STRING_FRACTION_PATTERN =
Pattern.compile("([0-9]+\\.[0-9]+)([a-z]+)?");

/**
* Convert a passed byte string (e.g. 50b, 100kb, or 250mb) to the given. If no suffix is
* provided, a direct conversion to the provided unit is attempted.
Expand All @@ -284,8 +291,8 @@ public static long byteStringAs(String str, ByteUnit unit) {
String lower = str.toLowerCase(Locale.ROOT).trim();

try {
Matcher m = Pattern.compile("([0-9]+)([a-z]+)?").matcher(lower);
Matcher fractionMatcher = Pattern.compile("([0-9]+\\.[0-9]+)([a-z]+)?").matcher(lower);
Matcher m = BYTE_STRING_PATTERN.matcher(lower);
Matcher fractionMatcher = BYTE_STRING_FRACTION_PATTERN.matcher(lower);

if (m.matches()) {
long val = Long.parseLong(m.group(1));
Expand Down

0 comments on commit bf133c8

Please sign in to comment.