refactor X-Have decoding logic

This commit is contained in:
Zlatin Balevsky
2019-06-21 09:32:10 +01:00
parent 8f9996848b
commit 56125f6df8
2 changed files with 17 additions and 13 deletions

View File

@@ -123,7 +123,9 @@ class DownloadSession {
// parse X-Have if present
if (headers.containsKey("X-Have")) {
updateAvailablePieces(headers["X-Have"])
DataUtil.decodeXHave(headers["X-Have"]).each {
available.add(it)
}
if (!available.contains(piece))
return true // try again next time
} else {
@@ -224,16 +226,4 @@ class DownloadSession {
totalRead += reads[idx]
(int)(totalRead * 1000.0 / interval)
}
private void updateAvailablePieces(String xHave) {
byte [] availablePieces = Base64.decode(xHave)
availablePieces.eachWithIndex {b, i ->
for (int j = 0; j < 8 ; j++) {
byte mask = 0x80 >>> j
if ((b & mask) == mask) {
available.add(i * 8 + j)
}
}
}
}
}

View File

@@ -95,4 +95,18 @@ class DataUtil {
}
Base64.encode(raw)
}
public static List<Integer> decodeXHave(String xHave) {
byte [] availablePieces = Base64.decode(xHave)
List<Integer> available = new ArrayList<>()
availablePieces.eachWithIndex {b, i ->
for (int j = 0; j < 8 ; j++) {
byte mask = 0x80 >>> j
if ((b & mask) == mask) {
available.add(i * 8 + j)
}
}
}
available
}
}