static int piece_layer_sort(const void*, const void*);
static int torrent_bencode_piece_layers(FILE*,struct file*);
+static int torrent_piece_layers(struct torrent*);
#define PIECE_LAYER_BENCODED_LENGTH 2+1+32+2+1+32
return 1;
}
-int torrent_file_piece_layers(FILE *fp, struct torrent *p) {
- const unsigned char **hashes;
- size_t index, pieces;
+static int torrent_piece_layers(struct torrent *p) {
struct file *file_p;
+ struct block *block_p;
+ size_t index, pieces;
pieces = 0;
for(size_t i=0;i<p->files.roots->size;i++) {
}
}
- hashes = malloc(sizeof(const unsigned char*)*pieces);
- if(NULL==hashes) { return -1; }
+ // sort hashes first
+ qsort(hashes,pieces,sizeof(const unsigned char*),&piece_layers_sort);
+
+ torrent->pieces = malloc(sizeof(struct piece)*pieces);
+ if(NULL==torrent->pieces) { return -1; }
index = 0;
for(size_t i=0;i<p->files.roots->size;i++) {
file_p = (struct file*)p->files.roots->map[i];
if(file_p!=NULL) {
if(file_p->size>p->piece_length) {
- hashes[index] = file_p->root->hash;
- index++;
+ block_p = file_p->piece_layers;
+ while(block_p!=NULL) {
+ torrent->pieces[index] = file_p->root->hash;
+ index++;
+ }
}
}
}
- qsort(hashes,pieces,sizeof(const unsigned char*),&piece_layer_sort);
+ return -1;
+}
- for(size_t i=0;i<pieces;i++) {
- file_p = hashmap_find(p->files.roots,hashes[i],crypto_hash_sha256_BYTES);
- if(NULL==file_p) { goto clean; }
+int torrent_file_piece_layers(FILE *fp, struct torrent *p) {
+ if(torrent_piece_layers(p)<0) { return -1; }
- if(torrent_bencode_piece_layers(fp,file_p)<0) { goto clean; }
+ for(size_t i=0;i<p->pieces_size;i++) {
+ if(torrent_bencode_piece_layers(fp,file_p)<0) { return -1; }
}
- free(hashes);
-
return 1;
-clean:
- free(hashes);
- return -1;
}
-static int piece_layer_sort(const void *p1, const void *p2) {
+static int piece_layers_sort(const void *p1, const void *p2) {
if(NULL==p1) { return 1; }
if(NULL==p2) { return -1; }