Skip to content

Commit dc7fda6

Browse files
committed
Run a separate pass to determine whether input needs to be changed
1 parent 15a0e6f commit dc7fda6

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>
@@ -449,21 +450,25 @@ private static String uriEncode(String source, Charset charset) {
449450
return source;
450451
}
451452

452-
boolean changed = false;
453-
StringBuilder builder = new StringBuilder(source.length());
454453
byte[] bytes = source.getBytes(charset);
455454

455+
if (IntStream.range(0, bytes.length).allMatch(i -> isUnreserved(bytes[i]))) {
456+
return source;
457+
}
458+
459+
StringBuilder builder = new StringBuilder(source.length());
460+
456461
for (byte b : bytes) {
457462
if (isUnreserved(b)) {
458463
builder.append((char) b);
459464
} else {
460465
builder.append('%');
461466
builder.append(Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16)));
462467
builder.append(Character.toUpperCase(Character.forDigit(b & 0xF, 16)));
463-
changed = true;
464468
}
465469
}
466-
return changed ? builder.toString() : source;
470+
471+
return builder.toString();
467472
}
468473

469474
private static boolean isUnreserved(int c) {
@@ -537,7 +542,10 @@ public static String uriDecode(String source) {
537542
return source;
538543
}
539544

540-
boolean changed = false;
545+
if (source.indexOf('%') == -1) {
546+
return source;
547+
}
548+
541549
byte[] bytes = source.getBytes(StandardCharsets.UTF_8);
542550
int length = bytes.length;
543551
ByteArrayOutputStream buffer = new ByteArrayOutputStream(length);
@@ -553,13 +561,12 @@ public static String uriDecode(String source) {
553561
int b1 = Character.digit(bytes[++i], 16);
554562
int b2 = Character.digit(bytes[++i], 16);
555563
buffer.write((char) ((b1 << 4) + b2));
556-
changed = true;
557564
} else {
558565
buffer.write(b);
559566
}
560567
}
561568

562-
return changed ? new String(buffer.toByteArray(), StandardCharsets.UTF_8) : source;
569+
return new String(buffer.toByteArray(), StandardCharsets.UTF_8);
563570
}
564571

565572
/**

0 commit comments

Comments
 (0)