Skip to content

Commit 660bce8

Browse files
committed
Run a separate pass to determine whether input needs to be changed
1 parent 64ec5b2 commit 660bce8

1 file changed

Lines changed: 14 additions & 7 deletions

File tree

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

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import java.util.function.IntPredicate;
3636
import java.util.regex.Pattern;
3737
import java.util.stream.Collectors;
38+
import java.util.stream.IntStream;
3839

3940
/**
4041
* <p>Package-URL (aka purl) is a "mostly universal" URL to describe a package. A purl is a URL composed of seven components:</p>
@@ -475,21 +476,25 @@ private static String uriEncode(String source, Charset charset) {
475476
return source;
476477
}
477478

478-
boolean changed = false;
479-
StringBuilder builder = new StringBuilder(source.length());
480479
byte[] bytes = source.getBytes(charset);
481480

481+
if (IntStream.range(0, bytes.length).allMatch(i -> isUnreserved(bytes[i]))) {
482+
return source;
483+
}
484+
485+
StringBuilder builder = new StringBuilder(source.length());
486+
482487
for (byte b : bytes) {
483488
if (isUnreserved(b)) {
484489
builder.append((char) b);
485490
} else {
486491
builder.append('%');
487492
builder.append(Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16)));
488493
builder.append(Character.toUpperCase(Character.forDigit(b & 0xF, 16)));
489-
changed = true;
490494
}
491495
}
492-
return changed ? builder.toString() : source;
496+
497+
return builder.toString();
493498
}
494499

495500
private static boolean isUnreserved(int c) {
@@ -567,7 +572,10 @@ public static String uriDecode(String source) {
567572
return source;
568573
}
569574

570-
boolean changed = false;
575+
if (source.indexOf('%') == -1) {
576+
return source;
577+
}
578+
571579
byte[] bytes = source.getBytes(StandardCharsets.UTF_8);
572580
int length = bytes.length;
573581
ByteArrayOutputStream buffer = new ByteArrayOutputStream(length);
@@ -583,13 +591,12 @@ public static String uriDecode(String source) {
583591
int b1 = Character.digit(bytes[++i], 16);
584592
int b2 = Character.digit(bytes[++i], 16);
585593
buffer.write((char) ((b1 << 4) + b2));
586-
changed = true;
587594
} else {
588595
buffer.write(b);
589596
}
590597
}
591598

592-
return changed ? new String(buffer.toByteArray(), StandardCharsets.UTF_8) : source;
599+
return new String(buffer.toByteArray(), StandardCharsets.UTF_8);
593600
}
594601

595602
/**

0 commit comments

Comments
 (0)