Skip to content

Commit

Permalink
add more path comparators
Browse files Browse the repository at this point in the history
  • Loading branch information
iTitus committed May 26, 2021
1 parent caa6ef3 commit c9d3e92
Showing 1 changed file with 37 additions and 6 deletions.
43 changes: 37 additions & 6 deletions src/main/java/io/github/ititus/io/PathUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,47 @@

public final class PathUtil {

public static final Comparator<Path> ASCIIBETICAL = (p1, p2) -> {
public static final Comparator<Path> ASCIIBETICAL = PathUtil::compareAsciibetical;
public static final Comparator<Path> ASCIIBETICAL_NORMALIZE = (p1, p2) -> compareAsciibetical(p1.normalize(), p2.normalize());
public static final Comparator<Path> ASCIIBETICAL_REAL = (p1, p2) -> compareAsciibetical(toRealPath(p1), toRealPath(p2));
public static final Comparator<Path> ASCIIBETICAL_FILES_FIRST = PathUtil::compareAsciibeticalFilesFirst;
public static final Comparator<Path> ASCIIBETICAL_NORMALIZE_FILES_FIRST = (p1, p2) -> compareAsciibeticalFilesFirst(p1.normalize(), p2.normalize());
public static final Comparator<Path> ASCIIBETICAL_REAL_FILES_FIRST = (p1, p2) -> compareAsciibeticalFilesFirst(toRealPath(p1), toRealPath(p2));

private PathUtil() {
}

public static Path toRealPath(Path p) {
try {
p1 = p1.toRealPath();
p2 = p2.toRealPath();
return p.toRealPath();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

public static int compareAsciibetical(Path p1, Path p2) {
if (p1.isAbsolute() != p2.isAbsolute()) {
throw new IllegalArgumentException("both paths must either be absolute or relative");
}

int c1 = p1.getNameCount();
int c2 = p2.getNameCount();

int last = Math.min(c1, c2);
for (int i = 0; i < last; i++) {
int c = p1.getName(i).toString().compareTo(p2.getName(i).toString());
if (c != 0) {
return c;
}
}

return c1 - c2;
}

public static int compareAsciibeticalFilesFirst(Path p1, Path p2) {
if (p1.isAbsolute() != p2.isAbsolute()) {
throw new IllegalArgumentException("both paths must either be absolute or relative");
}

int c1 = p1.getNameCount();
int c2 = p2.getNameCount();
Expand All @@ -39,9 +73,6 @@ public final class PathUtil {
}

return c;
};

private PathUtil() {
}

public static Optional<String> getExtension(Path p) {
Expand Down

0 comments on commit c9d3e92

Please sign in to comment.