#include<stdlib.h>
+#include<bencode.h>
#include<file.h>
struct tree_entry {
ssize_t bencode_string(const uint8_t *str, size_t len, uint8_t *output, size_t output_size) {
size_t i;
- int ret;
if(NULL==str) { return -1; }
- if(len<=0) { return -1; }
if(NULL==output) { return -1; }
- if(len>output_size) { return -1; }
i = size_int(len);
- i++;
+ i += 2; // account for ':' and '\0'
i += len;
- if((ret = snprintf((char*)output,output_size,"%lu:%s",len,(const char*)str))<0) { return -1; }
-
- if(ret!=i) { return -1; }
+ if(i>output_size) { return -1; }
- return i;
+ return snprintf((char*)output,i,"%lu:%s",len,(const char*)str);
}
static size_t size_int(int i) {
i = abs(i);
size_t j = 0;
+
+ if(0==i) { return 1; }
+
while(i>0) {
i /= 10;
j++;
ssize_t tree_bencode(struct tree *tree, uint8_t *buf, size_t buf_len) {
struct tree_entry *p;
+ ssize_t i;
p = tree->entries;
while(p!=NULL) {
+ i = bencode_string((const uint8_t*)p->name,strlen(p->name),buf,buf_len);
+ if(i<0) { return -1; }
+
+ buf += i;
+ buf_len -= i;
+
if(p->children!=NULL) {
// write directory
// recurse into subdirectory
tree_tests_SOURCES = \
$(common_SOURCES) \
tree.tests.c \
+ $(top_srcdir)/src/bencode/encode.c \
$(top_srcdir)/src/block.c \
$(top_srcdir)/src/file.c \
$(top_srcdir)/src/hash.c \
uint8_t str1[] = "testlkajslfkdjasdfl test string";
assert(bencode_string(NULL,31,buf,1024)==-1);
- assert(bencode_string(str1,0,buf,1024)==-1);
assert(bencode_string(str1,31,NULL,1024)==-1);
assert(bencode_string(str1,31,buf,0)==-1);
- assert(bencode_string(str1,31,buf,1024)==34);
+
+ assert(bencode_string(str1,0,buf,1024)==2);
+ assert(memcmp("0:",buf,2)==0);
+ assert(bencode_string(str1,31,buf,1024)==34);
assert(memcmp("31:testlkajslfkdjasdfl test string",buf,34)==0);
}