63 lines
1.5 KiB
Python
63 lines
1.5 KiB
Python
import t, c
|
|
from stdint import *
|
|
import stdio
|
|
import stdlib
|
|
import memhub
|
|
import hashlib
|
|
|
|
|
|
POOL_SIZE: t.CDefine = 16777480
|
|
|
|
|
|
@t.CExport
|
|
def main() -> int:
|
|
arena: bytes = stdlib.malloc(POOL_SIZE)
|
|
if arena is None:
|
|
return 1
|
|
mb: memhub.MemBuddy | t.CPtr = memhub.MemBuddy(arena, POOL_SIZE)
|
|
if mb is None:
|
|
return 1
|
|
hashlib._mbuddy = (memhub.MemManager | t.CPtr)(mb)
|
|
|
|
# 测试 "abc" 的 SHA1
|
|
# 期望: a9993e364706816aba3e25717850c26c9cd0d89d
|
|
s: str = "abc"
|
|
stdio.printf("input: %s\n", s)
|
|
|
|
# 计算 len(s)
|
|
n: t.CSizeT = len(s)
|
|
stdio.printf("len=%d\n", n)
|
|
|
|
# 构造 sha1 对象
|
|
ctx: hashlib.sha1 | t.CPtr = hashlib.sha1()
|
|
if ctx is None:
|
|
stdio.printf("ctx is None\n")
|
|
return 1
|
|
|
|
ctx.update(s)
|
|
|
|
digest: bytes = mb.alloc(hashlib.SHA1_DIGEST_LEN)
|
|
if digest is None:
|
|
stdio.printf("digest alloc failed\n")
|
|
return 1
|
|
|
|
ctx.final(digest)
|
|
|
|
# 打印 digest(十六进制)
|
|
stdio.printf("SHA1: ")
|
|
for i in range(hashlib.SHA1_DIGEST_LEN):
|
|
b: t.CUInt8T = digest[i]
|
|
hi: t.CInt = (b >> 4) & 0xF
|
|
lo: t.CInt = b & 0xF
|
|
if hi < 10:
|
|
stdio.printf("%c", '0' + hi)
|
|
else:
|
|
stdio.printf("%c", 'a' + (hi - 10))
|
|
if lo < 10:
|
|
stdio.printf("%c", '0' + lo)
|
|
else:
|
|
stdio.printf("%c", 'a' + (lo - 10))
|
|
stdio.printf("\n")
|
|
stdio.printf("expect: a9993e364706816aba3e25717850c26c9cd0d89d\n")
|
|
return 0
|