code wiki / (root) / nx_bencode_test.nx

nx_bencode_test.nx source

↩ module page · 59 lines · 2003 B

1// nx_bencode_test.nx -- KAT for the bencode parser on real .torrent structure. 2// Native sovereign lane; exit 0 = pass, N = assertion N failed. 3 4import "nx_str.nx" 5import "nx_bencode.nx" 6 7func _streq(buf: *u8, off: i64, s: *u8) -> i64 { 8 let n: i64 = nx_str_len(s) 9 var i: i64 = 0 10 while i < n { if (buf[off + i] as i64) != (s[i] as i64) { return 0 } i = i + 1 } 11 return 1 12} 13 14func main() -> i64 { 15 // a mini .torrent metainfo: announce + nested info{name, piece length, length} 16 let mi: *u8 = "d8:announce17:http://tracker/x/4:infod4:name4:test12:piece lengthi16384e6:lengthi1024eee" 17 let n: i64 = nx_str_len(mi) 18 let so: *i64 = sys_mmap(8) as *i64 19 let sl: *i64 = sys_mmap(8) as *i64 20 let iv: *i64 = sys_mmap(8) as *i64 21 22 if nx_bc_type(mi, 0, n) != NX_BC_DICT { return 1 } 23 24 // announce -> string "http://tracker/x/" 25 let ann: i64 = nx_bc_dict_get(mi, 0, n, "announce", 8) 26 if ann < 0 { return 2 } 27 if nx_bc_str(mi, ann, n, so, sl) < 0 { return 3 } 28 if sl[0] != 17 { return 4 } 29 if _streq(mi, so[0], "http://tracker/x/") != 1 { return 5 } 30 31 // info -> dict 32 let info: i64 = nx_bc_dict_get(mi, 0, n, "info", 4) 33 if info < 0 { return 6 } 34 if nx_bc_type(mi, info, n) != NX_BC_DICT { return 7 } 35 36 // info.name -> "test" 37 let nm: i64 = nx_bc_dict_get(mi, info, n, "name", 4) 38 if nm < 0 { return 8 } 39 nx_bc_str(mi, nm, n, so, sl) 40 if sl[0] != 4 { return 9 } 41 if _streq(mi, so[0], "test") != 1 { return 10 } 42 43 // info.'piece length' -> 16384 44 let pl: i64 = nx_bc_dict_get(mi, info, n, "piece length", 12) 45 if pl < 0 { return 11 } 46 if nx_bc_int(mi, pl, n, iv) < 0 { return 12 } 47 if iv[0] != 16384 { return 13 } 48 49 // info.length -> 1024 50 let ln: i64 = nx_bc_dict_get(mi, info, n, "length", 6) 51 if ln < 0 { return 14 } 52 nx_bc_int(mi, ln, n, iv) 53 if iv[0] != 1024 { return 15 } 54 55 // a key that doesn't exist -> -1 56 if nx_bc_dict_get(mi, 0, n, "nope", 4) != (0 - 1) { return 16 } 57 58 return 0 59}