Skip to content

Commit

Permalink
Use short-circuiting content comparison instead of hash comparison wh…
Browse files Browse the repository at this point in the history
…en possible
  • Loading branch information
jpenilla committed Nov 17, 2023
1 parent c7d0820 commit f9b0dda
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.PathMatcher
import java.nio.file.attribute.DosFileAttributeView
import java.util.Arrays
import java.util.stream.Collectors
import java.util.stream.Stream
import java.util.stream.StreamSupport
Expand Down Expand Up @@ -160,6 +161,38 @@ fun Path.hashFile(algorithm: HashingAlgorithm): ByteArray = inputStream().use {

fun Path.sha256asHex(): String = hashFile(HashingAlgorithm.SHA256).asHexString()

fun Path.contentEquals(file: Path, bufferSizeBytes: Int = 8192): Boolean {
inputStream().use { one ->
file.inputStream().use { two ->

val bufOne = ByteArray(bufferSizeBytes)
val bufTwo = ByteArray(bufferSizeBytes)

while (true) {
val readOne = one.read(bufOne)
val readTwo = two.read(bufTwo)

if (readOne != readTwo) {
// length differs
return false
}

if (readOne == -1) {
// end of content
break
}

if (!Arrays.equals(bufOne, 0, readOne, bufTwo, 0, readOne)) {
// content differs
return false
}
}
}
}

return true
}

fun Path.withDifferentExtension(ext: String): Path = resolveSibling("$nameWithoutExtension.$ext")

// Returns true if our process already owns the lock
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,12 @@ private fun upToDate(
binaryIn: Path,
xmlIn: String
): Boolean {
val bin = binDest.isRegularFile() && binDest.sha256asHex() == binaryIn.sha256asHex()
val bin = binDest.isRegularFile() && binDest.contentEquals(binaryIn)
val xml = ivyXml.isRegularFile() && ivyXml.readText(Charsets.UTF_8) == xmlIn
val sources = if (sourcesIn == null) {
sourcesDest.notExists()
} else {
sourcesDest.isRegularFile() && sourcesDest.sha256asHex() == sourcesIn.sha256asHex()
sourcesDest.isRegularFile() && sourcesDest.contentEquals(sourcesIn)
}
return bin && xml && sources
}
Expand Down

0 comments on commit f9b0dda

Please sign in to comment.