Skip to content

Commit 65829b9

Browse files
committed
Run a separate pass to determine whether input needs to be changed
1 parent 02f3585 commit 65829b9

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

src/main/java/com/github/packageurl/PackageURL.java

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import java.util.TreeMap;
3535
import java.util.regex.Pattern;
3636
import java.util.stream.Collectors;
37+
import java.util.stream.IntStream;
3738

3839
/**
3940
* <p>Package-URL (aka purl) is a "mostly universal" URL to describe a package. A purl is a URL composed of seven components:</p>
@@ -446,21 +447,25 @@ private static String uriEncode(String source, Charset charset) {
446447
return source;
447448
}
448449

449-
boolean changed = false;
450-
StringBuilder builder = new StringBuilder(source.length());
451450
byte[] bytes = source.getBytes(charset);
452451

452+
if (IntStream.range(0, bytes.length).allMatch(i -> isUnreserved(bytes[i]))) {
453+
return source;
454+
}
455+
456+
StringBuilder builder = new StringBuilder(source.length());
457+
453458
for (byte b : bytes) {
454459
if (isUnreserved(b)) {
455460
builder.append((char) b);
456461
} else {
457462
builder.append('%');
458463
builder.append(Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16)));
459464
builder.append(Character.toUpperCase(Character.forDigit(b & 0xF, 16)));
460-
changed = true;
461465
}
462466
}
463-
return changed ? builder.toString() : source;
467+
468+
return builder.toString();
464469
}
465470

466471
private static boolean isUnreserved(int c) {
@@ -491,7 +496,10 @@ public static String uriDecode(String source) {
491496
return source;
492497
}
493498

494-
boolean changed = false;
499+
if (source.indexOf('%') == -1) {
500+
return source;
501+
}
502+
495503
byte[] bytes = source.getBytes(StandardCharsets.UTF_8);
496504
int length = bytes.length;
497505
ByteArrayOutputStream buffer = new ByteArrayOutputStream(length);
@@ -507,13 +515,12 @@ public static String uriDecode(String source) {
507515
int b1 = Character.digit(bytes[++i], 16);
508516
int b2 = Character.digit(bytes[++i], 16);
509517
buffer.write((char) ((b1 << 4) + b2));
510-
changed = true;
511518
} else {
512519
buffer.write(b);
513520
}
514521
}
515522

516-
return changed ? new String(buffer.toByteArray(), StandardCharsets.UTF_8) : source;
523+
return new String(buffer.toByteArray(), StandardCharsets.UTF_8);
517524
}
518525

519526
/**

0 commit comments

Comments
 (0)