code wiki / _hdl_build / _huffman_authored.nx
_huffman_authored.nx source
↩ module page · 25 lines · 1726 B
1// AUTHORED BY THE NISHI BUILDER (nx_module_author huffman template) -- canonical Huffman, bits-up
2import "nx_syscalls.nx"
3func hbr(buf: *u8, len: i64, cursor: *i64, n: i64) -> i64 { var val: i64=0; var got: i64=0; while got<n { let bp: i64=cursor[0]>>3; if bp>=len { return 0-1 } let bit: i64=((buf[bp] as i64)>>(cursor[0]&7))&1; val=val|(bit<<got); cursor[0]=cursor[0]+1; got=got+1 } return val }
4func hbuild(lengths: *i64, n: i64, counts: *i64, symbols: *i64) -> i64 {
5 var i: i64=0; while i<=15 { counts[i]=0; i=i+1 }
6 i=0; while i<n { counts[lengths[i]]=counts[lengths[i]]+1; i=i+1 }
7 let offs: *i64=sys_mmap(8*17) as *i64; offs[1]=0; var l: i64=1
8 while l<15 { offs[l+1]=offs[l]+counts[l]; l=l+1 }
9 i=0; while i<n { if lengths[i]!=0 { symbols[offs[lengths[i]]]=i; offs[lengths[i]]=offs[lengths[i]]+1 } i=i+1 } return 0
10}
11func hdecode(buf: *u8, len: i64, cursor: *i64, counts: *i64, symbols: *i64) -> i64 {
12 var code: i64=0; var first: i64=0; var index: i64=0; var l: i64=1
13 while l<=15 { code=code|hbr(buf,len,cursor,1); let cnt: i64=counts[l]; if code-first<cnt { return symbols[index+(code-first)] } index=index+cnt; first=first+cnt; first=first<<1; code=code<<1; l=l+1 } return 0-1
14}
15func main() -> i64 {
16 let lengths: *i64=sys_mmap(8*4) as *i64; lengths[0]=2; lengths[1]=1; lengths[2]=3; lengths[3]=3
17 let counts: *i64=sys_mmap(8*17) as *i64; let symbols: *i64=sys_mmap(8*4) as *i64
18 hbuild(lengths, 4, counts, symbols)
19 let buf: *u8=sys_mmap(8); buf[0]=0x02 as u8; let cur: *i64=sys_mmap(8) as *i64; cur[0]=0
20 let s1: i64=hdecode(buf,1,cur,counts,symbols)
21 let s2: i64=hdecode(buf,1,cur,counts,symbols)
22 if s1==1 { if s2==0 { sys_exit(0) } }
23 sys_exit(1)
24 return 1
25}