snapshot before regression test

This commit is contained in:
t
2026-07-18 19:25:40 +08:00
commit 796222a300
2295 changed files with 206453 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
import stdio
import stdlib
import string
import binascii
import t, c
def main222():
binascii.init_binascii()
raw: str = "HelloWorld!"
raw_length: t.CInt = 11
stdio.printf("你好\n")
hex_out: str = binascii.b2a_hex(raw, raw_length)
if hex_out:
stdio.printf("Hex: %s\n", hex_out)
free(hex_out)
crc_val: t.CUnsignedInt = binascii.crc32(raw, raw_length, 0)
stdio.printf("CRC32: %u\n", crc_val)
b64_out: str = binascii.b2a_base64(raw, raw_length)
if b64_out:
stdio.printf("Base64: %s\n", b64_out)
free(b64_out)
uu_out: str = binascii.b2a_uu(raw, raw_length)
if uu_out:
stdio.printf("UU: %s\n", uu_out)
free(uu_out)
hqx_in: t.CArray[t.CChar, 4] = ['A', 'B', 'C', '\0']
hqx_crc: t.CUnsignedShort = 0
hqx_out: str
unhqx: str
hqx_out, hqx_crc = binascii.b2a_hqx(hqx_in, 3)
unhqx, hqx_crc = binascii.a2b_hqx(hqx_out)
stdio.printf("HQX Test: ABC -> %s -> %s (CRC:%u)\n", hqx_out, unhqx, hqx_crc)
free(hqx_out); free(unhqx)
adler_val: t.CUnsignedInt = binascii.adler32(raw, raw_length, 1)
stdio.printf("Adler32: %u\n", adler_val)
stdio.printf("Bye\n")

View File

@@ -0,0 +1,80 @@
import stdio
import stdlib
import string
import stdint
import t, c
import base64
import hashlib
def default_value_test_function(a: t.CInt, b: t.CInt = 1):
print(a, b)
# ==============================================
# 工具函数:打印十六进制哈希串
# ==============================================
def print_hex(buf: t.CUInt8T | t.CPtr, length: t.CInt):
for i in range(length):
stdio.printf("%02x", buf[i])
stdio.printf("\n")
# ==============================================
# 主函数测试入口
# ==============================================
def main1() -> t.CInt:
plain: str = "hello123"
print("原文", plain)
# ---------- Base64 测试 ----------
b64_out: t.CArray[t.CChar, 256]
b64_dec: t.CArray[t.CUInt8T, 256]
base64.b64encode(plain, b64_out)
print("Base64 编码:", b64_out)
dlen: t.CSizeT = base64.b64decode(b64_out, b64_dec)
b64_dec[dlen] = 0
print("Base64 解码:", b64_dec)
# ---------- MD5 测试 ----------
md5_buf: t.CArray[t.CUInt8T, hashlib.MD5_DIGEST_LEN]
mctx = hashlib.md5()
mctx.update(plain)
mctx.final(md5_buf)
print("MD5: ")
print_hex(md5_buf, hashlib.MD5_DIGEST_LEN)
# ---------- SHA1 测试 ----------
sha1_buf: t.CArray[t.CUInt8T, hashlib.SHA1_DIGEST_LEN]
s1ctx = hashlib.sha1()
s1ctx.update(plain)
s1ctx.final(sha1_buf)
print("SHA1: ")
print_hex(sha1_buf, hashlib.SHA1_DIGEST_LEN)
# ---------- SHA256 测试 ----------
sha256_buf: t.CArray[t.CUInt8T, hashlib.SHA256_DIGEST_LEN]
s2ctx = hashlib.sha256()
s2ctx.update(plain)
s2ctx.final(sha256_buf)
print("SHA256: ")
print_hex(sha256_buf, hashlib.SHA256_DIGEST_LEN)
# ---------- SHA512 测试 ----------
sha512_buf: t.CArray[t.CUInt8T, hashlib.SHA512_DIGEST_LEN]
s5ctx = hashlib.sha512()
s5ctx.update(plain)
s5ctx.final(sha512_buf)
print("SHA512: ")
print_hex(sha512_buf, hashlib.SHA512_DIGEST_LEN)
default_value_test_function(b=2, a=1)
return 0

View File

@@ -0,0 +1,24 @@
import stdint
import t, c
A: t.CChar | t.CPtr = "你好"
class BIT_TEST(t.Object):
a: t.CInt | t.Bit(1)
b: t.CInt | t.Bit(1)
c: t.CInt | t.Bit(1)
d: t.CInt | t.Bit(5)
class OOP_TEST(t.Object):
a: t.CInt
def __init__(self):
self.a = 0
def __call__(self) -> stdint.UINT:
return 123
class ENUM_TEST(t.CEnum):
A: t.State = 0
B: t.State
C: t.State
Len: t.State

View File

@@ -0,0 +1,220 @@
import stdio
import stdint
import zc.config as config
import zc.test as test
import zc.logic_test as logic
import zc.class_test as class_test
import testcheck
import test_numpy
def main() -> stdint.INT:
testcheck.begin("Hello World!")
testcheck.section("Cross-module macros")
stdio.printf(" POSMAX: %d\n", config.POSMAX)
stdio.printf(" MATH_SCALE: %d\n", config.MATH_SCALE)
stdio.printf(" THRESHOLD: %d\n", config.THRESHOLD)
stdio.printf(" SHIFT_AMOUNT: %d\n", config.SHIFT_AMOUNT)
stdio.printf(" MASK_VALUE: 0x%x\n", config.MASK_VALUE)
testcheck.ok("config macros accessible")
testcheck.section("While Loop Test")
test.AboutSizeTWhileTest(10)
testcheck.ok("While Loop Test (10)")
testcheck.section("Math Basic Test (20, 6)")
test.MathBasicTest(20, 6)
testcheck.ok("Math Basic Test (20, 6)")
testcheck.section("Math Advanced Test (value=15)")
test.MathAdvancedTest(15)
testcheck.ok("Math Advanced Test (value=15)")
testcheck.section("While with Elif-Else Test (-2 to 12)")
test.WhileWithElifElseTest(-2, 12)
testcheck.ok("While with Elif-Else Test (-2 to 12)")
testcheck.section("Nested While with Macros Test")
test.NestedWhileWithMacrosTest(3, 4)
testcheck.ok("Nested While with Macros Test (3, 4)")
testcheck.section("Complex Condition Test (1, 2, 3)")
test.ComplexConditionTest(1, 2, 3)
testcheck.ok("Complex Condition Test (1, 2, 3)")
testcheck.section("Retry Loop Test (8)")
test.RetryLoopTest(8)
testcheck.ok("Retry Loop Test (8)")
testcheck.section("Bitwise Operations Test (0b1101101)")
test.BitwiseOperationsTest(109)
testcheck.ok("Bitwise Operations Test (109)")
testcheck.section("Compound Assignment Math Test (15, 4)")
test.CompoundAssignmentMathTest(15, 4)
testcheck.ok("Compound Assignment Math Test (15, 4)")
testcheck.section("Power and Modulo Test (2, 8)")
test.PowerAndModuloTest(2, 8)
testcheck.ok("Power and Modulo Test (2, 8)")
testcheck.section("Mixed Arithmetic Test (5, 3, 4)")
test.MixedArithmeticTest(5, 3, 4)
testcheck.ok("Mixed Arithmetic Test (5, 3, 4)")
testcheck.section("Math with While Loop Test (start=1, count=5)")
test.MathWithWhileLoopTest(1, 5)
testcheck.ok("Math with While Loop Test (1, 5)")
testcheck.section("Complex Nested Math Test (7, 3)")
test.ComplexNestedMathTest(7, 3)
testcheck.ok("Complex Nested Math Test (7, 3)")
testcheck.section("Conditional Math Chain Test (value=10)")
test.ConditionalMathChainTest(10)
testcheck.ok("Conditional Math Chain Test (value=10)")
testcheck.section("Bit Manipulation Math Test (0xABCD)")
test.BitManipulationMathTest(0xABCD)
testcheck.ok("Bit Manipulation Math Test (0xABCD)")
testcheck.section("COMPLEX LOGIC TESTS")
testcheck.section("For Range Basic Test (stop=5)")
logic.ForRangeBasicTest(5)
testcheck.ok("For Range Basic Test (5)")
testcheck.section("For Range With Start Stop Step (start=1, stop=10, step=2)")
logic.ForRangeWithStartStop(1, 10, 2)
testcheck.ok("For Range With Start Stop (1, 10, 2)")
testcheck.section("Nested For Range Test (rows=2, cols=3)")
logic.NestedForRangeTest(2, 3)
testcheck.ok("Nested For Range Test (2, 3)")
testcheck.section("For With If Break Test (size=8)")
logic.ForWithIfBreakTest(8)
testcheck.ok("For With If Break Test (8)")
testcheck.section("For With If Continue Test (n=10)")
logic.ForWithIfContinueTest(10)
testcheck.ok("For With If Continue Test (10)")
testcheck.section("For With Elif Branch Test (value=10)")
logic.ForWithElifBranchTest(10)
testcheck.ok("For With Elif Branch Test (10)")
testcheck.section("While With If Elif Else Test (iterations=7)")
logic.WhileWithIfElifElseTest(7)
testcheck.ok("While With If Elif Else Test (7)")
testcheck.section("While With Nested If Test (limit=4)")
logic.WhileWithNestedIfTest(4)
testcheck.ok("While With Nested If Test (4)")
testcheck.section("While With Match Case Test (value=2)")
logic.WhileWithMatchCaseTest(2)
testcheck.ok("While With Match Case Test (2)")
testcheck.section("While With Match Case Test (value=99)")
logic.WhileWithMatchCaseTest(99)
testcheck.ok("While With Match Case Test (99)")
testcheck.section("While With Match Case NoBreak Test (value=3)")
logic.WhileWithMatchCaseNoBreakTest(3)
testcheck.ok("While With Match Case NoBreak Test (3)")
testcheck.section("Complex For While Match Test (outer=3, inner=3)")
logic.ComplexForWhileMatchTest(3, 3)
testcheck.ok("Complex For While Match Test (3, 3)")
testcheck.section("For With Case And NoBreak Test (n=5)")
logic.ForWithCaseAndNoBreakTest(5)
testcheck.ok("For With Case And NoBreak Test (5)")
testcheck.section("While With Break Condition Test (limit=6)")
logic.WhileWithBreakConditionTest(6)
testcheck.ok("While With Break Condition Test (6)")
testcheck.section("Nested While With Multiple BreakPoints (depth=3, width=4)")
logic.NestedWhileWithMultipleBreakPoints(3, 4)
testcheck.ok("Nested While With Multiple BreakPoints (3, 4)")
testcheck.section("For With Match Case In Loop Test (iterations=9)")
logic.ForWithMatchCaseInLoopTest(9)
testcheck.ok("For With Match Case In Loop Test (9)")
testcheck.section("Complex Logic With Elif Chains (a=3, b=5, c=7)")
logic.ComplexLogicWithElifChains(3, 5, 7)
testcheck.ok("Complex Logic With Elif Chains (3, 5, 7)")
testcheck.section("For Range With Step And Condition (n=12, step=2)")
logic.ForRangeWithStepAndCondition(12, 2)
testcheck.ok("For Range With Step And Condition (12, 2)")
testcheck.section("Match Case With Guard Conditions (value=1)")
logic.MatchCaseWithGuardConditions(1)
testcheck.ok("Match Case With Guard Conditions (1)")
testcheck.section("While With Multiple Match Cases (iterations=12)")
logic.WhileWithMultipleMatchCases(12)
testcheck.ok("While With Multiple Match Cases (12)")
testcheck.section("For While Mix With Break And Continue (n=5)")
logic.ForWhileMixWithBreakAndContinue(5)
testcheck.ok("For While Mix With Break And Continue (5)")
testcheck.section("Complex Case Matching With Ranges (start=0, end=35)")
logic.ComplexCaseMatchingWithRanges(0, 35)
testcheck.ok("Complex Case Matching With Ranges (0, 35)")
testcheck.section("While With Elif In Elif Chain (limit=7)")
logic.WhileWithElifInElifChain(7)
testcheck.ok("While With Elif In Elif Chain (7)")
testcheck.section("For With Case NoBreak Nested (inner_limit=4)")
logic.ForWithCaseNoBreakNested(4)
testcheck.ok("For With Case NoBreak Nested (4)")
testcheck.section("CLASS TESTS")
class_test.TestBasicDataClass()
testcheck.ok("TestBasicDataClass")
class_test.TestPoint3DClass()
testcheck.ok("TestPoint3DClass")
class_test.TestStudentClass()
testcheck.ok("TestStudentClass")
class_test.TestCounterClass()
testcheck.ok("TestCounterClass")
class_test.TestStackAllocation()
testcheck.ok("TestStackAllocation")
class_test.TestHeapAllocation()
testcheck.ok("TestHeapAllocation")
class_test.TestHeapObjectWithInit()
testcheck.ok("TestHeapObjectWithInit")
class_test.TestMultipleStackObjects()
testcheck.ok("TestMultipleStackObjects")
class_test.TestImplicitInitCall()
testcheck.ok("TestImplicitInitCall")
class_test.TestClassWithBitFields()
testcheck.ok("TestClassWithBitFields")
testcheck.section("ARRAY TESTS")
class_test.TestIntArray()
testcheck.ok("TestIntArray")
class_test.TestFloatArray()
testcheck.ok("TestFloatArray")
class_test.TestCharArray()
testcheck.ok("TestCharArray")
class_test.TestNestedArray()
testcheck.ok("TestNestedArray")
class_test.TestArrayWithStruct()
testcheck.ok("TestArrayWithStruct")
class_test.TestArrayPointer()
testcheck.ok("TestArrayPointer")
class_test.TestDynamicString()
testcheck.ok("TestDynamicString")
testcheck.section("numpy Correctness Tests")
test_numpy.test_numpy_correct()
return testcheck.end()

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,883 @@
from stdint import *
import zlib.pyzlib as pyzlib
import zlib.zhuff as zhuff
import zlib.zdef as zdef
from stdio import printf
from string import strlen, memcmp, memcpy, memset
from stdlib import malloc, free, realloc
import stdlib
import string
import memhub
import t, c
pool: t.CPtr = None
test_passed: t.CInt = 0
test_failed: t.CInt = 0
def check(name: str, condition: t.CInt, detail: str):
global test_passed, test_failed
if condition:
test_passed += 1
printf(" [PASS] %s\n", name)
else:
test_failed += 1
printf(" [FAIL] %s -- %s\n", name, detail if detail else "")
def print_hex_test(data: BYTEPTR, length: t.CSizeT, max_show: t.CSizeT):
if not data or length == 0:
printf("(empty)\n")
return
show: t.CSizeT = max_show if (length > max_show) else length
i: t.CSizeT
for i in range(show):
printf("%02X ", data[i])
if length > max_show:
printf("... (%zu bytes total)", length)
printf("\n")
def print_separator():
printf(" -------------------------------------------\n")
def section_header(title: str):
printf("\n+-- %s --+\n", title)
def section_footer():
printf("+--------------------------------------------+\n")
# ============================================================
def test_version():
section_header("Version Info")
ver: str = pyzlib.ZLIB_VERSION
printf(" ZLIB_VERSION (compile-time) : %s\n", ver)
check("ZLIB_VERSION not None", ver != None, "version string is None")
check("ZLIB_VERSION not empty", strlen(ver) > 0, "version string is empty")
runtime_ver: str = pyzlib.runtime_version()
printf(" ZLIB_RUNTIME_VERSION : %s\n", runtime_ver)
check("runtime version not None", runtime_ver != None, "runtime version is None")
check("runtime version not empty", strlen(runtime_ver) > 0, "runtime version is empty")
section_footer()
def test_compress_decompress():
section_header("compress / decompress")
inp: str = "Hello, World! This is a test of zlib compression and decompression."
input_length: t.CSizeT = strlen(inp)
printf(" Input (%zu bytes): \"%s\"\n", input_length, inp)
out_length: t.CSizeT = 0
compressed: BYTEPTR = pyzlib.compress(pool, BYTEPTR(inp), input_length,
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
check("compress returns non-None", compressed != None, "compress returned None")
check("compress output size > 0", out_length > 0, "compressed size is 0")
check("compress output produced", out_length > 0, "compressed size is 0")
printf(" Compressed (%zu bytes): ", out_length)
print_hex_test(compressed, out_length, 32)
printf(" Compression ratio: %.1f%%\n", t.CDouble(out_length) / input_length * 100)
dec_length: t.CSizeT = 0
decompressed: BYTEPTR = pyzlib.decompress(pool, compressed, out_length,
pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
check("decompress returns non-None", decompressed != None, "decompress returned None")
check("decompress output size matches input", dec_length == input_length, "size mismatch")
check("decompress output matches input", decompressed != None and memcmp(decompressed, inp, input_length) == 0, "content mismatch")
printf(" Decompressed (%zu bytes): \"%.*s\"\n", dec_length, t.CInt(dec_length), str(decompressed))
free(compressed)
free(decompressed)
section_footer()
def test_compress_levels():
section_header("Compression Levels")
inp: str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
input_length: t.CSizeT = strlen(inp)
printf(" Input (%zu bytes): \"%s\"\n", input_length, inp)
out_length: t.CSizeT = 0
c0: BYTEPTR = pyzlib.compress(pool, BYTEPTR(inp), input_length,
pyzlib.Z_NO_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
check("level 0 compress OK", c0 != None, "level 0 returned None")
printf(" Level 0 (Z_NO_COMPRESSION): %zu bytes\n", out_length)
length0: t.CSizeT = out_length
free(c0)
c1: BYTEPTR = pyzlib.compress(pool, BYTEPTR(inp), input_length,
pyzlib.Z_BEST_SPEED, pyzlib.MAX_WBITS, c.Addr(out_length))
check("level 1 compress OK", c1 != None, "level 1 returned None")
printf(" Level 1 (Z_BEST_SPEED) : %zu bytes\n", out_length)
free(c1)
c6: BYTEPTR = pyzlib.compress(pool, BYTEPTR(inp), input_length,
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
check("level -1 compress OK", c6 != None, "default level returned None")
printf(" Level -1 (DEFAULT) : %zu bytes\n", out_length)
free(c6)
c9: BYTEPTR = pyzlib.compress(pool, BYTEPTR(inp), input_length,
pyzlib.Z_BEST_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
check("level 9 compress OK", c9 != None, "level 9 returned None")
printf(" Level 9 (Z_BEST_COMPRESS) : %zu bytes\n", out_length)
length9: t.CSizeT = out_length
free(c9)
check("level 9 smaller than level 0", length9 < length0, "level 9 not smaller than level 0")
section_footer()
def test_compressobj():
section_header("compressobj (incremental)")
part1: str = "Hello, "
part2: str = "World!"
printf(" Part 1: \"%s\"\n", part1)
printf(" Part 2: \"%s\"\n", part2)
out_length: t.CSizeT = 0
s: pyzlib.Compress | t.CPtr = pyzlib.compressobj(pool, pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.DEFLATED,
pyzlib.MAX_WBITS, pyzlib.DEF_MEM_LEVEL,
pyzlib.Z_DEFAULT_STRATEGY, None, 0)
check("compressobj created", s != None, "compressobj is None")
print_separator()
c1: BYTEPTR = s.compress(BYTEPTR(part1), strlen(part1), c.Addr(out_length))
check("compress part1 OK", c1 != None, "compress part1 failed")
printf(" Compressed part1: %zu bytes -> ", out_length)
print_hex_test(c1, out_length, 16)
total: t.CSizeT = out_length
all: BYTEPTR = None
if out_length > 0 and c1:
all = BYTEPTR(malloc(total))
if all: memcpy(all, c1, out_length)
free(c1)
c2: BYTEPTR = s.compress(BYTEPTR(part2),
strlen(part2), c.Addr(out_length))
check("compress part2 OK", c2 != None, "compress part2 failed")
printf(" Compressed part2: %zu bytes -> ", out_length)
print_hex_test(c2, out_length, 16)
if out_length > 0 and c2:
new_all: BYTEPTR = BYTEPTR(realloc(all, total + out_length))
if new_all:
all = new_all
memcpy(all + total, c2, out_length)
total += out_length
free(c2)
c3: BYTEPTR = s.flush(pyzlib.Z_FINISH, c.Addr(out_length))
check("flush (Z_FINISH) OK", c3 != None, "flush failed")
printf(" Flush result : %zu bytes -> ", out_length)
print_hex_test(c3, out_length, 16)
if out_length > 0 and c3:
new_all: BYTEPTR = realloc(all, total + out_length) # 隐式转换
if new_all:
all = new_all
memcpy(all + total, c3, out_length)
total += out_length
free(c3)
print_separator()
if all:
dec_length: t.CSizeT = 0
dec: BYTEPTR = pyzlib.decompress(pool, all, total, pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
check("decompress incremental OK", dec != None, "decompress returned None")
check("decompress incremental size", dec != None and dec_length == strlen(part1) + strlen(part2), "size mismatch")
check("decompress incremental content",
dec != None and memcmp(dec, "Hello, World!", dec_length) == 0, "content mismatch")
if dec:
printf(" Decompressed: \"%.*s\" (%zu bytes)\n", t.CInt(dec_length), str(dec), dec_length)
free(dec)
free(all)
s.delete() # del s
section_footer()
def test_decompressobj():
section_header("decompressobj")
inp: str = "Test data for decompress object."
input_length: t.CSizeT = strlen(inp)
printf(" Input (%zu bytes): \"%s\"\n", input_length, inp)
out_length: t.CSizeT = 0
compressed: BYTEPTR = pyzlib.compress(pool, BYTEPTR(inp), input_length,
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
printf(" Compressed: %zu bytes\n", out_length)
d: pyzlib.Decompress | t.CPtr = pyzlib.decompressobj(pool, pyzlib.MAX_WBITS, None, 0)
check("decompressobj created", d != None, "decompressobj is None")
check("eof is false initially", d.eof == 0, "eof should be 0")
print_separator()
dec_length: t.CSizeT = 0
dec: BYTEPTR = d.decompress(compressed, out_length,
0, c.Addr(dec_length))
check("decompress OK", dec != None, "decompress returned None")
check("decompress size", dec != None and dec_length == input_length, "size mismatch")
check("decompress content", dec != None and memcmp(dec, inp, input_length) == 0, "content mismatch")
check("eof is true after stream end", d.eof == 1, "eof should be 1")
if dec:
printf(" Decompressed (%zu bytes): \"%.*s\"\n", dec_length, t.CInt(dec_length), str(dec))
printf(" eof = %d\n", d.eof)
free(dec)
free(compressed)
d.delete()
section_footer()
def test_decompressobj_max_lengthgth():
section_header("decompressobj max_lengthgth")
inp: str = "This is a longer string for testing max_lengthgth parameter in decompress."
input_length: t.CSizeT = strlen(inp)
printf(" Input (%zu bytes): \"%s\"\n", input_length, inp)
out_length: t.CSizeT = 0
compressed: BYTEPTR = pyzlib.compress(pool, BYTEPTR(inp), input_length,
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
printf(" Compressed: %zu bytes\n", out_length)
d: pyzlib.Decompress | t.CPtr = pyzlib.decompressobj(pool, pyzlib.MAX_WBITS, None, 0)
dec_length: t.CSizeT = 0
dec: BYTEPTR = d.decompress(compressed, out_length,
10, c.Addr(dec_length))
check("max_lengthgth decompress OK", dec != None, "decompress returned None")
check("max_lengthgth limits output", dec_length <= 10, "output exceeded max_lengthgth")
if dec:
printf(" First chunk (max_lengthgth=10): \"%.*s\" (%zu bytes)\n", t.CInt(dec_length), str(dec), dec_length)
free(dec)
tail_length: t.CSizeT = 0
tail: BYTEPTR = d.unconsumed_tail(c.Addr(tail_length))
check("unconsumed_tail exists", tail != None or tail_length == 0, "no unconsumed_tail")
printf(" unconsumed_tail: %zu bytes remaining\n", tail_length)
printf(" eof = %d\n", d.eof)
if tail_length > 0 or not d.eof:
flushed: BYTEPTR = d.flush(pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
check("flush after max_lengthgth OK", flushed != None, "flush returned None")
if flushed: printf(" Flushed (%zu bytes): \"%.*s\"\n", dec_length, t.CInt(dec_length), str(flushed))
free(flushed)
printf(" eof after flush = %d\n", d.eof)
d.delete()
free(compressed)
section_footer()
def test_decompressobj_unused_data():
section_header("decompressobj unused_data")
inp: str = "Hello"
input_length: t.CSizeT = strlen(inp)
printf(" Input: \"%s\"\n", inp)
out_length: t.CSizeT = 0
compressed: BYTEPTR = pyzlib.compress(pool, BYTEPTR(inp), input_length,
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
printf(" Compressed: %zu bytes\n", out_length)
total_length: t.CSizeT = out_length + 5
combined: BYTEPTR = BYTEPTR(malloc(total_length))
memcpy(combined, compressed, out_length)
memcpy(combined + out_length, "EXTRA", 5)
free(compressed)
printf(" Combined (compressed + \"EXTRA\"): %zu bytes\n", total_length)
d: pyzlib.Decompress | t.CPtr = pyzlib.decompressobj(pool, pyzlib.MAX_WBITS, None, 0)
dec_length: t.CSizeT = 0
dec: BYTEPTR = d.decompress(combined, total_length,
0, c.Addr(dec_length))
check("decompress with extra OK", dec != None, "decompress returned None")
check("eof after stream end", d.eof == 1, "eof should be 1")
if dec:
printf(" Decompressed: \"%.*s\" (%zu bytes)\n", t.CInt(dec_length), str(dec), dec_length)
free(dec)
print_separator()
unused_length: t.CSizeT = 0
unused: BYTEPTR = d.unused_data(c.Addr(unused_length))
check("unused_data exists", unused != None and unused_length > 0, "no unused_data")
check("unused_data is EXTRA", unused_length == 5 and unused != None and memcmp(unused, "EXTRA", 5) == 0, "unused_data mismatch")
printf(" unused_data (%zu bytes): \"%.*s\"\n", unused_length, t.CInt(unused_length), str(unused))
d.delete()
free(combined)
section_footer()
def test_compress_copy():
section_header("Compress.copy()")
inp: str = "Copy test data for compress object"
input_length: t.CSizeT = strlen(inp)
printf(" Input: \"%s\"\n", inp)
out_length: t.CSizeT = 0
c1: pyzlib.Compress | t.CPtr = pyzlib.compressobj(pool, pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.DEFLATED,
pyzlib.MAX_WBITS, pyzlib.DEF_MEM_LEVEL,
pyzlib.Z_DEFAULT_STRATEGY, None, 0)
c1.compress(BYTEPTR(inp), input_length, c.Addr(out_length))
printf(" Original: compressed %zu bytes so far\n", out_length)
c2: pyzlib.Compress | t.CPtr = c1.copy()
check("compress copy OK", c2 != None, "copy returned None")
printf(" Copied compressobj\n")
print_separator()
f1: BYTEPTR = c1.flush(pyzlib.Z_FINISH, c.Addr(out_length))
check("flush original OK", f1 != None, "flush original failed")
length1: t.CSizeT = out_length
printf(" Original flush: %zu bytes\n", length1)
free(f1)
f2: BYTEPTR = c2.flush(pyzlib.Z_FINISH, c.Addr(out_length))
check("flush copy OK", f2 != None, "flush copy failed")
length2: t.CSizeT = out_length
printf(" Copy flush : %zu bytes\n", length2)
free(f2)
check("copy produces same output", length1 == length2, "output lengthgths differ")
c1.delete()
c2.delete()
section_footer()
def test_decompress_copy():
section_header("Decompress.copy()")
inp: str = "Decompress copy test"
input_length: t.CSizeT = strlen(inp)
printf(" Input: \"%s\"\n", inp)
out_length: t.CSizeT = 0
compressed: BYTEPTR = pyzlib.compress(pool, BYTEPTR(inp), input_length,
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
printf(" Compressed: %zu bytes\n", out_length)
d1: pyzlib.Decompress | t.CPtr = pyzlib.decompressobj(pool, pyzlib.MAX_WBITS, None, 0)
d2: pyzlib.Decompress | t.CPtr = d1.copy()
check("decompress copy OK", d2 != None, "copy returned None")
printf(" Copied decompressobj\n")
print_separator()
dec_length1: t.CSizeT = 0
dec_length2: t.CSizeT = 0
dec1: BYTEPTR = d1.decompress(compressed, out_length,
0, c.Addr(dec_length1))
dec2: BYTEPTR = d2.decompress(compressed, out_length,
0, c.Addr(dec_length2))
check("decompress copy output size", dec_length1 == dec_length2, "sizes differ")
check("decompress copy output content",
dec1 and dec2 and memcmp(dec1, dec2, dec_length1) == 0, "content differs")
if dec1: printf(" Original: \"%.*s\" (%zu bytes)\n", t.CInt(dec_length1), str(dec1), dec_length1)
if dec2: printf(" Copy : \"%.*s\" (%zu bytes)\n", t.CInt(dec_length2), str(dec2), dec_length2)
free(dec1)
free(dec2)
free(compressed)
d1.delete()
d2.delete()
section_footer()
def test_adler32():
section_header("adler32 checksum")
checksum: ULONG = pyzlib.zlib_adler32(BYTEPTR("Hello"), 5, 1)
printf(" adler32(\"Hello\") = 0x%08lX (%lu)\n", checksum, checksum)
check("adler32 returns non-zero", checksum != 0, "checksum is 0")
incremental: ULONG = pyzlib.zlib_adler32(BYTEPTR("Hel"), 3, 1)
printf(" adler32(\"Hel\") = 0x%08lX\n", incremental)
incremental = pyzlib.zlib_adler32(BYTEPTR("lo"), 2, incremental)
printf(" adler32(\"lo\", prev) = 0x%08lX\n", incremental)
check("adler32 incremental matches one-shot", incremental == checksum, "incremental != one-shot")
printf(" Incremental == One-shot: %s\n", incremental == "YES" if checksum else "NO")
section_footer()
def test_crc32():
section_header("crc32 checksum")
checksum: ULONG = pyzlib.zlib_crc32(BYTEPTR("Hello"), 5, 0)
printf(" crc32(\"Hello\") = 0x%08lX (%lu)\n", checksum, checksum)
check("crc32 returns non-zero", checksum != 0, "checksum is 0")
incremental: ULONG = pyzlib.zlib_crc32(BYTEPTR("Hel"), 3, 0)
printf(" crc32(\"Hel\") = 0x%08lX\n", incremental)
incremental = pyzlib.zlib_crc32(BYTEPTR("lo"), 2, incremental)
printf(" crc32(\"lo\", prev) = 0x%08lX\n", incremental)
check("crc32 incremental matches one-shot", incremental == checksum, "incremental != one-shot")
printf(" Incremental == One-shot: %s\n", incremental == "YES" if checksum else "NO")
section_footer()
def test_empty_compress():
section_header("Empty data compress/decompress")
out_length: t.CSizeT = 0
compressed: BYTEPTR = pyzlib.compress(pool, BYTEPTR(""), 0,
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
check("compress empty OK", compressed != None, "compress empty returned None")
check("compress empty output > 0", out_length > 0, "compressed empty is 0 bytes")
printf(" Empty input compressed: %zu bytes (header only)\n", out_length)
printf(" Hex: ")
print_hex_test(compressed, out_length, 32)
dec_length: t.CSizeT = 0
decompressed: BYTEPTR = pyzlib.decompress(pool, compressed, out_length,
pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
check("decompress empty OK", decompressed != None, "decompress empty returned None")
check("decompress empty size == 0", dec_length == 0, "decompressed size != 0")
printf(" Decompressed back: %zu bytes\n", dec_length)
free(compressed)
free(decompressed)
section_footer()
def test_gzip_format():
section_header("Gzip format (wbits=31)")
inp: str = "Gzip format test"
input_length: t.CSizeT = strlen(inp)
printf(" Input: \"%s\" (%zu bytes)\n", inp, input_length)
gzip_wbits: t.CInt = pyzlib.MAX_WBITS + 16
printf(" wbits = MAX_WBITS + 16 = %d\n", gzip_wbits)
out_length: t.CSizeT = 0
compressed: BYTEPTR = pyzlib.compress(pool, BYTEPTR(inp), input_length,
pyzlib.Z_DEFAULT_COMPRESSION, gzip_wbits, c.Addr(out_length))
check("gzip compress OK", compressed != None, "gzip compress failed")
printf(" Gzip compressed: %zu bytes\n", out_length)
printf(" Header bytes: ")
print_hex_test(compressed, 4 if (out_length > 4) else out_length, 4)
dec_length: t.CSizeT = 0
decompressed: BYTEPTR = pyzlib.decompress(pool, compressed, out_length,
gzip_wbits, pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
check("gzip decompress OK", decompressed != None, "gzip decompress failed")
check("gzip decompress size", dec_length == input_length, "size mismatch")
check("gzip decompress content", decompressed != None and memcmp(decompressed, inp, input_length) == 0, "content mismatch")
if decompressed: printf(" Decompressed: \"%.*s\" (%zu bytes)\n", t.CInt(dec_length), str(decompressed), dec_length)
free(compressed)
free(decompressed)
section_footer()
def test_raw_deflate():
section_header("Raw deflate (wbits=-15)")
inp: str = "Raw deflate test"
input_length: t.CSizeT = strlen(inp)
printf(" Input: \"%s\" (%zu bytes)\n", inp, input_length)
raw_wbits: t.CInt = -pyzlib.MAX_WBITS
printf(" wbits = -MAX_WBITS = %d\n", raw_wbits)
out_length: t.CSizeT = 0
compressed: BYTEPTR = pyzlib.compress(pool, BYTEPTR(inp), input_length,
pyzlib.Z_DEFAULT_COMPRESSION, raw_wbits, c.Addr(out_length))
check("raw deflate compress OK", compressed != None, "raw deflate compress failed")
printf(" Raw compressed: %zu bytes\n", out_length)
dec_length: t.CSizeT = 0
decompressed: BYTEPTR = pyzlib.decompress(pool, compressed, out_length,
raw_wbits, pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
check("raw deflate decompress OK", decompressed != None, "raw deflate decompress failed")
check("raw deflate decompress size", dec_length == input_length, "size mismatch")
check("raw deflate decompress content", decompressed != None and memcmp(decompressed, inp, input_length) == 0, "content mismatch")
if decompressed: printf(" Decompressed: \"%.*s\" (%zu bytes)\n", t.CInt(dec_length), str(decompressed), dec_length)
free(compressed)
free(decompressed)
section_footer()
def test_zdict():
section_header("Preset dictionary (zdict)")
dict: str = "common words that appear frequently in the data"
inp: str = "common words that appear frequently"
input_length: t.CSizeT = strlen(inp)
printf(" Dictionary: \"%s\" (%zu bytes)\n", dict, strlen(dict))
printf(" Input : \"%s\" (%zu bytes)\n", inp, input_length)
out_length: t.CSizeT = 0
s: pyzlib.Compress | t.CPtr = pyzlib.compressobj(pool, pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.DEFLATED,
pyzlib.MAX_WBITS, pyzlib.DEF_MEM_LEVEL,
pyzlib.Z_DEFAULT_STRATEGY,
BYTEPTR(dict), strlen(dict))
check("compressobj with zdict OK", s != None, "compressobj with zdict failed")
comp_data: BYTEPTR = s.compress(BYTEPTR(inp),
input_length, c.Addr(out_length))
check("compress with zdict OK", comp_data != None, "compress with zdict failed")
printf(" Compressed with zdict: %zu bytes\n", out_length)
free(comp_data)
flush_data: BYTEPTR = s.flush(pyzlib.Z_FINISH, c.Addr(out_length))
check("flush with zdict OK", flush_data != None, "flush with zdict failed")
printf(" Flush: %zu bytes\n", out_length)
free(flush_data)
print_separator()
total_comp: t.CSizeT = out_length
s.delete()
s = pyzlib.compressobj(pool, pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.DEFLATED,
pyzlib.MAX_WBITS, pyzlib.DEF_MEM_LEVEL,
pyzlib.Z_DEFAULT_STRATEGY, None, 0)
comp_no_dict: BYTEPTR = s.compress(BYTEPTR(inp),
input_length, c.Addr(out_length))
flush_no_dict: BYTEPTR = s.flush(pyzlib.Z_FINISH, c.Addr(out_length))
no_dict_total: t.CSizeT = 0
if comp_no_dict: no_dict_total += out_length
if flush_no_dict: no_dict_total += out_length
printf(" Without zdict: ~%zu bytes compressed\n", no_dict_total)
printf(" With zdict : %zu bytes compressed\n", total_comp)
free(comp_no_dict)
free(flush_no_dict)
s.delete()
section_footer()
def test_huffman_tree():
section_header("Huffman tree construction")
printf(" --- Fixed Huffman tree (literal/lengthgth) ---\n")
lit_tree = zhuff.zhuff_tree()
lit_tree.build_fixed_lit_tree()
check("fixed lit tree count == 288", lit_tree.count == 288, "count mismatch")
check("fixed lit tree max_bits == 9", lit_tree.max_bits == 9, "max_bits mismatch")
has_8bit: t.CInt = 0
has_9bit: t.CInt = 0
has_7bit: t.CInt = 0
for i in range(143 + 1):
if lit_tree.codes[i].bits == 8:
has_8bit += 1
for i in range(143 + 1, 255 + 1):
if lit_tree.codes[i].bits == 9:
has_9bit += 1
for i in range(255 + 1, 279 + 1):
if lit_tree.codes[i].bits == 7:
has_7bit += 1
check("0-143 are 8-bit", has_8bit == 144, "wrong count")
check("144-255 are 9-bit", has_9bit == 112, "wrong count")
check("256-279 are 7-bit", has_7bit == 24, "wrong count")
printf(" 0-143: %d codes with 8 bits\n", has_8bit)
printf(" 144-255: %d codes with 9 bits\n", has_9bit)
printf(" 256-279: %d codes with 7 bits\n", has_7bit)
printf(" 280-287: 8-bit (end-of-block 256 = 7-bit)\n")
printf(" EOB (256): code=0x%X, bits=%d\n", lit_tree.codes[256].code, lit_tree.codes[256].bits)
printf("\n --- Fixed Huffman tree (distance) ---\n")
dist_tree = zhuff.zhuff_tree()
dist_tree.build_fixed_dist_tree()
check("fixed dist tree count == 32", dist_tree.count == 32, "count mismatch")
check("fixed dist tree max_bits == 5", dist_tree.max_bits == 5, "max_bits mismatch")
all_5bit: t.CInt = 1
for i in range(32):
if dist_tree.codes[i].bits != 5:
all_5bit = 0
check("all 32 distance codes are 5-bit", all_5bit, "not all 5-bit")
printf(" All 32 distance codes: 5 bits each\n")
printf("\n --- Dynamic Huffman tree from frequencies ---\n")
freqs: t.CArray[t.CInt, 257]
memset(freqs, 0, freqs.__sizeof__())
freqs['A'] = 50
freqs['B'] = 25
freqs['C'] = 12
freqs['D'] = 6
freqs['E'] = 3
freqs['F'] = 1
freqs[256] = 1
dyn_tree = zhuff.zhuff_tree()
dyn_tree.build_codes(freqs, 257, 15)
check("dynamic tree count == 257", dyn_tree.count == 257, "count mismatch")
check("dynamic tree max_bits <= 15", dyn_tree.max_bits <= 15, "max_bits overflow")
total_codes: t.CInt = 0
max_length_found: t.CInt = 0
for i in range(257):
if dyn_tree.codes[i].bits > 0:
total_codes += 1
if dyn_tree.codes[i].bits > max_length_found:
max_length_found = dyn_tree.codes[i].bits
check("dynamic tree has 7 active codes", total_codes == 7, "wrong active count")
check("dynamic tree max code lengthgth found <= 15", max_length_found <= 15, "code lengthgth overflow")
printf(" Frequencies: A=50, B=25, C=12, D=6, E=3, F=1, EOB=1\n")
printf(" Active codes: %d, max code lengthgth: %d\n", total_codes, max_length_found)
printf(" Code assignments:\n")
names: t.CArray[str, None] = ["A","B","C","D","E","F"] # 一个都是char* 的数组
syms: t.CArray[t.CInt, None] = ['A','B','C','D','E','F']
for i in range(6):
printf(" '%s' (freq=%3d): code=0x%04X, bits=%d\n",
names[i], freqs[syms[i]],
dyn_tree.codes[syms[i]].code,
dyn_tree.codes[syms[i]].bits)
printf(" EOB (freq=1): code=0x%04X, bits=%d\n",
dyn_tree.codes[256].code, dyn_tree.codes[256].bits)
a_bits: t.CInt = dyn_tree.codes['A'].bits
f_bits: t.CInt = dyn_tree.codes['F'].bits
check("high-freq symbol has shorter code", a_bits <= f_bits, "A should be <= F")
printf(" High-freq 'A' (%d bits) <= low-freq 'F' (%d bits): %s\n",
a_bits, f_bits, "YES" if (a_bits <= f_bits) else "NO")
printf("\n --- Huffman encode/decode roundtrip ---\n")
freqs: t.CArray[t.CInt, 288]
memset(freqs, 0, freqs.__sizeof__())
freqs['H'] = 10
freqs['e'] = 8
freqs['l'] = 20
freqs['o'] = 8
freqs[' '] = 5
freqs['W'] = 3
freqs['r'] = 5
freqs['d'] = 3
freqs['!'] = 2
freqs[256] = 1
enc_tree = zhuff.zhuff_tree()
enc_tree.build_codes(freqs, 257, 15)
dec_tree = zhuff.zhuff_decode_tree()
dec_tree.build_decode_tree(c.Addr(enc_tree))
writer = zdef.zbit_writer()
symbols: t.CArray[t.CInt, 16]
symbols[0] = 'H'; symbols[1] = 'e'; symbols[2] = 'l'; symbols[3] = 'l'
symbols[4] = 'o'; symbols[5] = ' '; symbols[6] = 'W'; symbols[7] = 'o'
symbols[8] = 'r'; symbols[9] = 'l'; symbols[10] = 'd'; symbols[11] = '!'
symbols[12] = 256
num_symbols: t.CInt = 13
for i in range(num_symbols):
enc_tree.encode_symbol(symbols[i], c.Addr(writer))
reader = zdef.zbit_reader()
reader.buf = writer.buf
reader.length = writer.byte_pos + (1 if (writer.bit_pos > 0) else 0)
reader.byte_pos = 0
reader.bit_pos = 0
roundtrip_ok: t.CInt = 1
for i in range(num_symbols):
decoded: t.CInt = dec_tree.decode_symbol(c.Addr(reader))
if decoded != symbols[i]:
roundtrip_ok = 0
printf(" MISMATCH at symbol %d: expected %d, got %d\n", i, symbols[i], decoded)
break
check("encode/decode roundtrip matches", roundtrip_ok, "roundtrip failed")
printf(" Encoded %d symbols into %zu bytes, decoded all correctly\n",
num_symbols, writer.byte_pos + (1 if (writer.bit_pos > 0) else 0))
free(writer.buf)
printf("\n --- Overflow handling (many symbols, limited max_bits) ---\n")
freqs: t.CArray[t.CInt, 257]
for i in range(256):
freqs[i] = 1
freqs[256] = 1
tree = zhuff.zhuff_tree()
tree.build_codes(freqs, 257, 15)
overflow_ok: t.CInt = 1
for i in range(257):
if tree.codes[i].bits > 15 or tree.codes[i].bits < 0:
overflow_ok = 0
break
check("all code lengthgths <= 15 with 257 symbols", overflow_ok, "code lengthgth overflow")
bl_count: t.CArray[t.CInt, 16] = [0]
for i in range(257):
if tree.codes[i].bits > 0:
bl_count[tree.codes[i].bits] += 1
printf(" Code lengthgth distribution (257 equal-freq symbols, max_bits=15):\n")
for i in range(1, 15 + 1):
if bl_count[i] > 0:
printf(" %2d bits: %3d codes\n", i, bl_count[i])
dt = zhuff.zhuff_decode_tree()
dt.build_decode_tree(c.Addr(tree))
w = zdef.zbit_writer()
tree.encode_symbol(0, c.Addr(w))
tree.encode_symbol(128, c.Addr(w))
tree.encode_symbol(255, c.Addr(w))
tree.encode_symbol(256, c.Addr(w))
r = zdef.zbit_reader()
r.buf = w.buf
r.length = w.byte_pos + (1 if (w.bit_pos > 0) else 0)
r.byte_pos = 0
r.bit_pos = 0
s0: t.CInt = dt.decode_symbol(c.Addr(r))
s1: t.CInt = dt.decode_symbol(c.Addr(r))
s2: t.CInt = dt.decode_symbol(c.Addr(r))
s3: t.CInt = dt.decode_symbol(c.Addr(r))
check("overflow roundtrip: symbol 0", s0 == 0, "decode mismatch")
check("overflow roundtrip: symbol 128", s1 == 128, "decode mismatch")
check("overflow roundtrip: symbol 255", s2 == 255, "decode mismatch")
check("overflow roundtrip: symbol 256 (EOB)", s3 == 256, "decode mismatch")
free(w.buf)
printf("\n --- Kraft inequality check ---\n")
freqs: t.CArray[t.CInt, 257]
memset(freqs, 0, freqs.__sizeof__())
freqs['X'] = 100
freqs['Y'] = 50
freqs['Z'] = 25
freqs[256] = 1
tree = zhuff.zhuff_tree()
tree.build_codes(freqs, 257, 15)
kraft_sum: t.CDouble = 0.0
for i in range(257):
if tree.codes[i].bits > 0:
kraft_sum += 1.0 / (t.CDouble(ULONGLONG(1) << tree.codes[i].bits))
check("Kraft inequality: sum <= 1.0", kraft_sum <= 1.0 + 1e-9, "Kraft violated")
printf(" Kraft sum = %.10f (must be <= 1.0)\n", kraft_sum)
section_footer()
def test_error_handling():
section_header("Error handling")
out_length: t.CSizeT = 0
printf(" Trying to decompress garbage data...\n")
result: BYTEPTR = pyzlib.decompress(pool, BYTEPTR("garbage"), 7,
pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, c.Addr(out_length))
check("decompress garbage returns None", result == None, "should have returned None")
printf(" Error code : %d\n", pyzlib.get_error_code())
printf(" Error message: \"%s\"\n", pyzlib.get_error())
check("error message set", strlen(pyzlib.get_error()) > 0, "error message is empty")
check("error code is set", pyzlib.get_error_code() != pyzlib.Z_OK, "error code is Z_OK")
print_separator()
pyzlib.clear_error()
check("clear error clears code", pyzlib.get_error_code() == 0, "error code not cleared")
printf(" After clear: code=%d, msg=\"%s\"\n", pyzlib.get_error_code(), pyzlib.get_error())
section_footer()
def test_constants():
section_header("Constants")
printf(" Compression Levels:\n")
printf(" Z_NO_COMPRESSION = %d\n", pyzlib.Z_NO_COMPRESSION)
printf(" Z_BEST_SPEED = %d\n", pyzlib.Z_BEST_SPEED)
printf(" Z_BEST_COMPRESSION = %d\n", pyzlib.Z_BEST_COMPRESSION)
printf(" Z_DEFAULT_COMPRESSION = %d\n", pyzlib.Z_DEFAULT_COMPRESSION)
printf(" Methods:\n")
printf(" DEFLATED = %d\n", pyzlib.DEFLATED)
printf(" Flush Modes:\n")
printf(" Z_NO_FLUSH = %d\n", pyzlib.Z_NO_FLUSH)
printf(" Z_PARTIAL_FLUSH = %d\n", pyzlib.Z_PARTIAL_FLUSH)
printf(" Z_SYNC_FLUSH = %d\n", pyzlib.Z_SYNC_FLUSH)
printf(" Z_FULL_FLUSH = %d\n", pyzlib.Z_FULL_FLUSH)
printf(" Z_FINISH = %d\n", pyzlib.Z_FINISH)
printf(" Z_BLOCK = %d\n", pyzlib.Z_BLOCK)
printf(" Z_TREES = %d\n", pyzlib.Z_TREES)
printf(" Strategies:\n")
printf(" Z_DEFAULT_STRATEGY = %d\n", pyzlib.Z_DEFAULT_STRATEGY)
printf(" Z_FILTERED = %d\n", pyzlib.Z_FILTERED)
printf(" Z_HUFFMAN_ONLY = %d\n", pyzlib.Z_HUFFMAN_ONLY)
printf(" Z_RLE = %d\n", pyzlib.Z_RLE)
printf(" Z_FIXED = %d\n", pyzlib.Z_FIXED)
printf(" Return Codes:\n")
printf(" Z_OK = %d\n", pyzlib.Z_OK)
printf(" Z_STREAM_END = %d\n", pyzlib.Z_STREAM_END)
printf(" Z_NEED_DICT = %d\n", pyzlib.Z_NEED_DICT)
printf(" Z_ERRNO = %d\n", pyzlib.Z_ERRNO)
printf(" Z_STREAM_ERROR = %d\n", pyzlib.Z_STREAM_ERROR)
printf(" Z_DATA_ERROR = %d\n", pyzlib.Z_DATA_ERROR)
printf(" Z_MEM_ERROR = %d\n", pyzlib.Z_MEM_ERROR)
printf(" Z_BUF_ERROR = %d\n", pyzlib.Z_BUF_ERROR)
printf(" Z_VERSION_ERROR = %d\n", pyzlib.Z_VERSION_ERROR)
printf(" Window / Buffer:\n")
printf(" MAX_WBITS = %d\n", pyzlib.MAX_WBITS)
printf(" DEF_BUF_SIZE = %d\n", pyzlib.DEF_BUF_SIZE)
printf(" DEF_MEM_LEVEL = %d\n", pyzlib.DEF_MEM_LEVEL)
section_footer()
def main123456() -> t.CInt:
printf("==============================================\n")
printf(" Python zlib - C Implementation Tests\n")
printf("==============================================\n")
test_constants()
test_version()
test_compress_decompress()
test_compress_levels()
test_compressobj()
test_decompressobj()
test_decompressobj_max_lengthgth()
test_decompressobj_unused_data()
test_compress_copy()
test_decompress_copy()
test_adler32()
test_crc32()
test_empty_compress()
test_gzip_format()
test_raw_deflate()
test_zdict()
test_huffman_tree()
test_error_handling()
printf("\n==============================================\n")
printf(" Results: %d passed, %d failed\n", test_passed, test_failed)
printf("==============================================\n")
return 1 if test_failed > 0 else 0

View File

@@ -0,0 +1,245 @@
import stdio
import stdint
import t, c
class SimpleData(t.Object):
x: t.CInt
y: t.CInt
class Point3D(t.Object):
x: t.CFloat
y: t.CFloat
z: t.CFloat
class Student(t.Object):
name: t.CChar | t.CPtr
age: t.CInt
score: t.CInt
def __init__(self, n: t.CChar | t.CPtr, a: t.CInt, s: t.CInt):
self.name = n
self.age = a
self.score = s
def get_age(self) -> t.CInt:
return self.age
def get_score(self) -> t.CInt:
return self.score
class Counter(t.Object):
value: t.CInt
def __init__(self, initial: t.CInt):
self.value = initial
def increment(self):
self.value += 1
def get_value(self) -> t.CInt:
return self.value
class StackObj(t.Object):
data: t.CInt
next_ptr: t.CVoid | t.CPtr
def TestBasicDataClass():
stdio.printf("=== Test Basic Data Class ===\n")
p: SimpleData = SimpleData()
p.x = 10
p.y = 20
stdio.printf("SimpleData: x=%d, y=%d\n", p.x, p.y)
def TestPoint3DClass():
stdio.printf("=== Test Point3D Class ===\n")
pt: Point3D = Point3D()
pt.x = 1.5
pt.y = 2.5
pt.z = 3.5
stdio.printf("Point3D: x=%.1f, y=%.1f, z=%.1f\n", pt.x, pt.y, pt.z)
def TestStudentClass():
stdio.printf("=== Test Student Class ===\n")
s: Student = Student("Alice", 20, 95)
stdio.printf("Student: name=%s, age=%d, score=%d\n", s.name, s.age, s.score)
stdio.printf(" get_age()=%d, get_score()=%d\n", s.get_age(), s.get_score())
def TestCounterClass():
stdio.printf("=== Test Counter Class ===\n")
cnt: Counter = Counter(0)
stdio.printf("Initial value: %d\n", cnt.get_value())
cnt.increment()
cnt.increment()
cnt.increment()
stdio.printf("After 3 increments: %d\n", cnt.get_value())
def TestStackAllocation():
stdio.printf("=== Test Stack Allocation ===\n")
obj1: SimpleData = SimpleData()
obj1.x = 100
obj1.y = 200
stdio.printf("Stack obj1: x=%d, y=%d\n", obj1.x, obj1.y)
obj2: Point3D = Point3D()
obj2.x = 10.0
obj2.y = 20.0
obj2.z = 30.0
stdio.printf("Stack obj2: x=%.1f, y=%.1f, z=%.1f\n", obj2.x, obj2.y, obj2.z)
def TestHeapAllocation():
stdio.printf("=== Test Heap Allocation ===\n")
ptr: t.CVoid | t.CPtr = c.malloc(1024)
if ptr != 0:
stdio.printf("Allocated 1024 bytes at %p\n", ptr)
c.free(ptr)
stdio.printf("Freed memory\n")
else:
stdio.printf("malloc failed\n")
def TestHeapObjectWithInit():
stdio.printf("=== Test Heap Object with Init ===\n")
mem_size: t.CSizeT = 256
ptr: t.CVoid | t.CPtr = c.malloc(mem_size)
if ptr != 0:
stdio.printf("Allocated %d bytes\n", mem_size)
c.free(ptr)
else:
stdio.printf("malloc failed\n")
def TestMultipleStackObjects():
stdio.printf("=== Test Multiple Stack Objects ===\n")
objs: SimpleData = SimpleData()
objs.x = 1
objs.y = 2
obj2: Point3D = Point3D()
obj2.x = 5.0
obj2.y = 10.0
obj2.z = 15.0
obj3: Counter = Counter(42)
stdio.printf("objs: x=%d, y=%d\n", objs.x, objs.y)
stdio.printf("obj2: x=%.1f, y=%.1f, z=%.1f\n", obj2.x, obj2.y, obj2.z)
stdio.printf("obj3 initial: %d\n", obj3.get_value())
obj3.increment()
obj3.increment()
stdio.printf("obj3 after 2 increments: %d\n", obj3.get_value())
def TestImplicitInitCall():
stdio.printf("=== Test Implicit Init Call ===\n")
stu1: Student = Student("Bob", 22, 88)
stu2: Student = Student("Charlie", 19, 77)
stdio.printf("stu1: name=%s, age=%d, score=%d\n", stu1.name, stu1.age, stu1.score)
stdio.printf("stu2: name=%s, age=%d, score=%d\n", stu2.name, stu2.age, stu2.score)
def TestClassWithBitFields():
stdio.printf("=== Test Class with Bit Fields ===\n")
flags: StackObj = StackObj()
flags.data = 0
flags.next_ptr = 0
stdio.printf("StackObj: data=%d, next_ptr=%p\n", flags.data, flags.next_ptr)
def TestIntArray():
stdio.printf("=== Test Int Array ===\n")
arr: t.CArray[t.CInt, 5] = t.CArray[t.CInt, 5]()
i: t.CInt = 0
while i < 5:
arr[i] = i * 10
i += 1
i = 0
while i < 5:
stdio.printf("arr[%d]=%d\n", i, arr[i])
i += 1
def TestFloatArray():
stdio.printf("=== Test Float Array ===\n")
farr: t.CArray[t.CFloat, 4] = t.CArray[t.CFloat, 4]()
farr[0] = 1.5
farr[1] = 2.5
farr[2] = 3.5
farr[3] = 4.5
i: t.CInt = 0
while i < 4:
stdio.printf("farr[%d]=%.1f\n", i, farr[i])
i += 1
def TestCharArray():
stdio.printf("=== Test Char Array (String) ===\n")
str_arr: t.CArray[t.CChar, 32] = t.CArray[t.CChar, 32]()
str_arr[0] = 'H'
str_arr[1] = 'e'
str_arr[2] = 'l'
str_arr[3] = 'l'
str_arr[4] = 'o'
str_arr[5] = '\0'
stdio.printf("String: %s\n", str_arr)
def TestNestedArray():
stdio.printf("=== Test Nested Array (Array of Arrays) ===\n")
row0: t.CArray[t.CInt, 3] = t.CArray[t.CInt, 3]()
row1: t.CArray[t.CInt, 3] = t.CArray[t.CInt, 3]()
row0[0] = 0
row0[1] = 1
row0[2] = 2
row1[0] = 10
row1[1] = 11
row1[2] = 12
i: t.CInt = 0
while i < 3:
stdio.printf("row0[%d]=%d ", i, row0[i])
i += 1
stdio.printf("\n")
i = 0
while i < 3:
stdio.printf("row1[%d]=%d ", i, row1[i])
i += 1
stdio.printf("\n")
def TestArrayWithStruct():
stdio.printf("=== Test Array with Struct ===\n")
points: t.CArray[SimpleData, 3] = t.CArray[SimpleData, 3]()
i: t.CInt = 0
while i < 3:
points[i].x = i * 10
points[i].y = i * 100
i += 1
i = 0
while i < 3:
stdio.printf("Point[%d]: x=%d, y=%d\n", i, points[i].x, points[i].y)
i += 1
def TestArrayPointer():
stdio.printf("=== Test Array Pointer ===\n")
data: t.CArray[t.CInt, 8] = t.CArray[t.CInt, 8]()
data[0] = 100
data[1] = 200
data[2] = 300
ptr: t.CInt | t.CPtr = data
stdio.printf("ptr[0]=%d\n", ptr[0])
stdio.printf("ptr[1]=%d\n", ptr[1])
stdio.printf("ptr[2]=%d\n", ptr[2])
def TestDynamicString():
stdio.printf("=== Test Dynamic String ===\n")
name: str = "TransPyC"
stdio.printf("Hello %s!\n", name)

View File

@@ -0,0 +1,24 @@
import t, c
POSMAX: t.CDefine = 100
MAX_RETRY: t.CDefine = 5
BUFFER_SIZE: t.CDefine = 256
PI: t.CDefine = 3.14159
EULER: t.CDefine = 2.71828
TRUE: t.CDefine = 1
FALSE: t.CDefine = 0
NULL: t.CDefine = 0
MATH_OFFSET: t.CDefine = 10
MATH_SCALE: t.CDefine = 2
THRESHOLD: t.CDefine = 50
LOOP_LIMIT: t.CDefine = 20
SHIFT_AMOUNT: t.CDefine = 2
MASK_VALUE: t.CDefine = 0xFF
BIT_RANGE: t.CDefine = 4
EXPONENT_BASE: t.CDefine = 3
MODULO_DIVISOR: t.CDefine = 7
SCALE_SHIFT: t.CDefine = 4
HALF_SCALE: t.CDefine = 0.5

View File

@@ -0,0 +1,372 @@
import config
import t, c
def ForRangeBasicTest(stop: t.CInt):
i: t.CInt = 0
for i in range(stop):
print("For range: ", i)
print("Done")
def ForRangeWithStartStop(start: t.CInt, stop: t.CInt, step: t.CInt):
i: t.CInt = 0
for i in range(start, stop, step):
print("Range: ", i)
print("Done")
def NestedForRangeTest(rows: t.CInt, cols: t.CInt):
r: t.CInt = 0
c_val: t.CInt = 0
for r in range(rows):
for c_val in range(cols):
print("Cell: ", r, c_val)
print("Grid done")
def ForWithIfBreakTest(data_size: t.CInt):
i: t.CInt = 0
found: t.CInt = 0
for i in range(data_size):
if i == 5:
print("Found at: ", i)
found = 1
break
print("Checking: ", i)
if found == 0:
print("Not found")
def ForWithIfContinueTest(n: t.CInt):
i: t.CInt = 0
count: t.CInt = 0
for i in range(n):
if i % 2 == 0:
continue
print("Odd: ", i)
count += 1
print("Total odd: ", count)
def ForWithElifBranchTest(value: t.CInt):
i: t.CInt = 0
result: t.CInt = 0
for i in range(value):
if i < 3:
result += 1
elif i < 6:
result += 2
elif i < 9:
result += 3
else:
result += 4
print("Elif branch result: ", result)
def WhileWithIfElifElseTest(iterations: t.CInt):
counter: t.CInt = 0
while counter < iterations:
if counter < 2:
print("Phase 1: ", counter)
elif counter < 4:
print("Phase 2: ", counter)
elif counter < 6:
print("Phase 3: ", counter)
else:
print("Phase 4: ", counter)
counter += 1
print("While done")
def WhileWithNestedIfTest(limit: t.CInt):
outer: t.CInt = 0
while outer < limit:
inner: t.CInt = 0
while inner < limit:
if inner == 2 and outer == 1:
print("Target: ", outer, inner)
inner += 1
continue
if inner > 3:
break
print("Inner: ", inner)
inner += 1
outer += 1
def WhileWithMatchCaseTest(value: t.CInt):
result: t.CInt = 0
match value:
case 1:
result = 100
print("Case 1")
case 2:
result = 200
print("Case 2")
case 3:
result = 300
print("Case 3")
case _:
result = 999
print("Default case")
print("Match result: ", result)
def WhileWithMatchCaseNoBreakTest(value: t.CInt):
result: t.CInt = 0
match value:
case 1:
result = 10
print("Case 1: ", result)
case 2:
result = 20
print("Case 2: ", result)
result += 5
case 3:
result = 30
print("Case 3: ", result)
case _:
result = 0
print("No break match result: ", result)
def ComplexForWhileMatchTest(outer_limit: t.CInt, inner_limit: t.CInt):
i: t.CInt = 0
j: t.CInt = 0
result: t.CInt = 0
for i in range(outer_limit):
j = 0
while j < inner_limit:
match (i, j):
case (0, 0):
result += 1
case (1, 1):
result += 10
case (2, _):
result += 100
case (_, 0):
result += 1000
case _:
result += 10000
j += 1
print("Complex match result: ", result)
def ForWithCaseAndNoBreakTest(n: t.CInt):
i: t.CInt = 0
result: t.CInt = 0
for i in range(n):
match i:
case 0:
result += 1
case 1:
result += 2
case 2:
result += 3
result += 10
case _:
result += i
c.NoBreak
print("NoBreak result: ", result)
def WhileWithBreakConditionTest(limit: t.CInt):
i: t.CInt = 0
early_exit: t.CInt = 0
while i < limit:
if i == 3:
early_exit = 1
break
if i == 2:
i += 1
continue
print("While i: ", i)
i += 1
def NestedWhileWithMultipleBreakPoints(depth: t.CInt, width: t.CInt):
d: t.CInt = 0
w: t.CInt = 0
count: t.CInt = 0
while d < depth:
w = 0
while w < width:
if w == 2:
break
if d == 1 and w == 1:
c.Break
count += 1
w += 1
d += 1
print("Nested break count: ", count)
def ForWithMatchCaseInLoopTest(iterations: t.CInt):
i: t.CInt = 0
sum_even: t.CInt = 0
sum_odd: t.CInt = 0
for i in range(iterations):
match i % 3:
case 0:
sum_even += i
case 1:
sum_odd += i
case 2:
sum_even += i * 2
case _:
pass
print("Sum even: ", sum_even)
print("Sum odd: ", sum_odd)
def ComplexLogicWithElifChains(a: t.CInt, b: t.CInt, c_val: t.CInt):
i: t.CInt = 0
result: t.CInt = 0
while i < 10:
if i < a:
if i < b:
result += 1
elif i < c_val:
result += 2
else:
result += 3
elif i < b:
if i < c_val:
result += 4
else:
result += 5
elif i < c_val:
result += 6
else:
result += 7
i += 1
print("Complex elif chain result: ", result)
def ForRangeWithStepAndCondition(n: t.CInt, step: t.CInt):
i: t.CInt = 0
count: t.CInt = 0
for i in range(0, n, step):
if i % 2 == 0:
print("Even step: ", i)
count += 1
else:
if i > 5:
print("Large odd: ", i)
else:
print("Small odd: ", i)
print("Total steps: ", count)
def MatchCaseWithGuardConditions(value: t.CInt):
result: t.CInt = 0
match value:
case 1 if config.TRUE == 1:
result = 100
case 2 if config.FALSE == 0:
result = 200
case 3:
result = 300
case _:
result = 0
print("Guard match result: ", result)
def WhileWithMultipleMatchCases(iterations: t.CInt):
i: t.CInt = 0
state: t.CInt = 0
while i < iterations:
match state:
case 0:
if i > 3:
state = 1
case 1:
if i > 6:
state = 2
case 2:
if i > 9:
state = 0
print("State at i=", i, ": ", state)
i += 1
def ForWhileMixWithBreakAndContinue(n: t.CInt):
i: t.CInt = 0
j: t.CInt = 0
count: t.CInt = 0
for i in range(n):
j = 0
while j < n:
if j == 2:
j += 1
continue
if i == 3 and j == 3:
break
count += 1
j += 1
print("Mix break continue count: ", count)
def ComplexCaseMatchingWithRanges(start: t.CInt, end: t.CInt):
i: t.CInt = 0
bucket0: t.CInt = 0
bucket1: t.CInt = 0
bucket2: t.CInt = 0
bucket3: t.CInt = 0
for i in range(start, end):
match i:
case _ if i < 10:
bucket0 += 1
case _ if i < 20:
bucket1 += 1
case _ if i < 30:
bucket2 += 1
case _:
bucket3 += 1
print("Bucket0 (<10): ", bucket0)
print("Bucket1 (10-19): ", bucket1)
print("Bucket2 (20-29): ", bucket2)
print("Bucket3 (>=30): ", bucket3)
def WhileWithElifInElifChain(limit: t.CInt):
i: t.CInt = 0
result: t.CInt = 0
while i < limit:
if i < 2:
if i == 0:
result = 1
else:
result = 2
elif i < 4:
if i == 2:
result = 3
else:
result = 4
elif i < 6:
if i == 4:
result = 5
else:
result = 6
else:
result = 7
print("Chain result[", i, "]: ", result)
i += 1
def ForWithCaseNoBreakNested(inner_limit: t.CInt):
i: t.CInt = 0
j: t.CInt = 0
result: t.CInt = 0
for i in range(3):
for j in range(inner_limit):
match j:
case 0:
result += 1
case 1:
result += 2
case _:
result += 3
c.NoBreak
print("Nested NoBreak result: ", result)

View File

@@ -0,0 +1,298 @@
import config
import t, c
def AboutSizeTWhileTest(length: t.CSizeT):
pos: t.CSizeT = 0
while pos < length:
print("Pos: ", pos)
if pos > config.POSMAX: break
pos += 1
while pos < length:
if pos > config.POSMAX:
print("Pos: ", pos)
pos += 1
else:
print("Pos: ", pos)
pos += 1
if pos > config.POSMAX: break
else:
pos += 1
print("Pos: ", pos)
while pos < length:
print("Pos: ", pos)
pos += 1
def MathBasicTest(x: t.CInt, y: t.CInt) -> t.CInt:
result: t.CInt = 0
result = x + y
print("Add: ", result)
result = x - y
print("Sub: ", result)
result = x * y
print("Mul: ", result)
if y != 0:
result = x / y
print("Div: ", result)
result = x % y if y != 0 else 0
print("Mod: ", result)
return result
def MathAdvancedTest(value: t.CInt) -> t.CInt:
counter: t.CInt = 0
scaled: t.CInt = 0
offset: t.CInt = 0
scaled = value * config.MATH_SCALE
print("Scaled: ", scaled)
offset = scaled + config.MATH_OFFSET
print("Offset: ", offset)
threshold: t.CInt = config.THRESHOLD
if offset > threshold:
print("Above threshold")
counter = 1
elif offset == threshold:
print("At threshold")
counter = 0
else:
print("Below threshold")
counter = -1
return counter
def WhileWithElifElseTest(start: t.CInt, end: t.CInt):
idx: t.CInt = start
while idx < end:
if idx < 0:
print("Negative: ", idx)
elif idx == 0:
print("Zero: ", idx)
elif idx > 0 and idx < 5:
print("Small positive: ", idx)
elif idx >= 5 and idx < 10:
print("Medium positive: ", idx)
else:
print("Large: ", idx)
idx += 1
def NestedWhileWithMacrosTest(outer_limit: t.CInt, inner_limit: t.CInt):
outer: t.CInt = 0
inner: t.CInt = 0
total_ops: t.CInt = 0
while outer < outer_limit:
inner = 0
while inner < inner_limit:
if inner == config.TRUE:
print("Inner loop break condition at: ", inner)
total_ops += 1
inner += 1
outer += 1
print("Total operations: ", total_ops)
def ComplexConditionTest(a: t.CInt, b: t.CInt, c_val: t.CInt):
x: t.CInt = a
y: t.CInt = b
z: t.CInt = c_val
while x < config.LOOP_LIMIT:
if x > 0 and y > 0 and z > 0:
print("All positive: ", x, y, z)
elif x <= 0 and y <= 0 and z <= 0:
print("All non-positive: ", x, y, z)
else:
if x > 0:
print("X positive")
elif y > 0:
print("Y positive")
else:
print("Z positive")
x += 1
y += 1
z += 1
def RetryLoopTest(retry_count: t.CInt) -> t.CInt:
attempt: t.CInt = 0
success: t.CInt = 0
while attempt < retry_count:
if attempt < config.MAX_RETRY:
print("Attempt: ", attempt, " less than max")
success = attempt * 2
elif attempt == config.MAX_RETRY:
print("At max retry")
success = -1
else:
print("Beyond max retry")
success = -2
attempt += 1
return success
def BitwiseOperationsTest(value: t.CInt) -> t.CInt:
shifted: t.CInt = 0
masked: t.CInt = 0
xored: t.CInt = 0
anded: t.CInt = 0
ored: t.CInt = 0
shifted = value << config.SHIFT_AMOUNT
print("Left shift: ", shifted)
shifted = value >> config.SHIFT_AMOUNT
print("Right shift: ", shifted)
masked = value & config.MASK_VALUE
print("Bitwise AND mask: ", masked)
xored = value ^ config.MASK_VALUE
print("Bitwise XOR: ", xored)
anded = value & (config.MASK_VALUE >> config.SHIFT_AMOUNT)
print("Bitwise AND shifted mask: ", anded)
ored = value | config.SHIFT_AMOUNT
print("Bitwise OR shift: ", ored)
return masked
def CompoundAssignmentMathTest(a: t.CInt, b: t.CInt) -> t.CInt:
x: t.CInt = a
y: t.CInt = b
result: t.CInt = 0
x += y
print("x += y: ", x)
x -= y
print("x -= y: ", x)
x *= y
print("x *= y: ", x)
x = a
y = b
if b != 0:
x /= b
print("x /= y: ", x)
x = a
if b != 0:
x %= b
print("x %%= y: ", x)
x = a
x <<= config.SHIFT_AMOUNT
print("x <<= shift: ", x)
x >>= config.SHIFT_AMOUNT
print("x >>= shift: ", x)
x &= config.MASK_VALUE
print("x &= mask: ", x)
x |= config.SHIFT_AMOUNT
print("x |= shift: ", x)
result = (a + b) * config.MATH_SCALE - config.MATH_OFFSET
print("Compound: (a+b)*scale-offset: ", result)
result = (a * b) + (config.MATH_OFFSET / 2)
print("Compound: a*b+offset/2: ", result)
return result
def PowerAndModuloTest(base: t.CInt, exponent: t.CInt) -> t.CInt:
result: t.CInt = 1
temp: t.CInt = 0
i: t.CInt = 0
while i < exponent:
result *= base
i += 1
print("Power: ", result)
temp = result % config.MODULO_DIVISOR
print("Power mod: ", temp)
temp = (base * config.EXPONENT_BASE) % config.MODULO_DIVISOR
print("base*exp %% divisor: ", temp)
temp = ((base + config.MATH_OFFSET) * config.MATH_SCALE) % config.MODULO_DIVISOR
print("(base+offset)*scale %% divisor: ", temp)
return result
def MixedArithmeticTest(x: t.CInt, y: t.CInt, z: t.CInt) -> t.CInt:
result: t.CInt = 0
result = (x + y) * z
print("(x+y)*z: ", result)
result = x + (y * z)
print("x+(y*z): ", result)
result = ((x + y) * config.MATH_SCALE) - config.MATH_OFFSET
print("((x+y)*scale)-offset: ", result)
result = (x * config.MATH_SCALE) + (y * config.MATH_SCALE)
print("x*scale + y*scale: ", result)
result = ((x % config.MODULO_DIVISOR) + (y % config.MODULO_DIVISOR)) * config.MATH_SCALE
print("(x%%mod + y%%mod)*scale: ", result)
temp: t.CInt = 0
temp = x | y & z
print("x | y & z: ", temp)
temp = (x | y) & z
print("(x | y) & z: ", temp)
temp = x ^ y ^ z
print("x ^ y ^ z: ", temp)
return result
def MathWithWhileLoopTest(start: t.CInt, count: t.CInt) -> t.CInt:
idx: t.CInt = 0
accumulator: t.CInt = 0
multiplier: t.CInt = config.MATH_SCALE
while idx < count:
temp: t.CInt = (start + idx) * multiplier
temp = temp + config.MATH_OFFSET
if temp > config.THRESHOLD:
temp = config.THRESHOLD
accumulator += temp
multiplier += 1
idx += 1
print("Accumulator: ", accumulator)
return accumulator
def ComplexNestedMathTest(a: t.CInt, b: t.CInt) -> t.CInt:
layer1: t.CInt = 0
layer2: t.CInt = 0
layer3: t.CInt = 0
i: t.CInt = 0
layer1 = (a + b) * config.MATH_SCALE
print("Layer1: ", layer1)
while i < config.BIT_RANGE:
layer2 += layer1 >> 1
i += 1
print("Layer2: ", layer2)
layer3 = layer1 + layer2 - config.MATH_OFFSET
print("Layer3: ", layer3)
layer3 = layer3 * config.MATH_SCALE / 2 if config.MATH_SCALE != 0 else layer3
print("Layer3 scaled: ", layer3)
return layer3
def ConditionalMathChainTest(value: t.CInt) -> t.CInt:
result: t.CInt = 0
step: t.CInt = 0
while step < config.LOOP_LIMIT:
if step < 5:
result += step * config.MATH_SCALE
print("step<5: ", result)
elif step < 10:
result -= step - config.MATH_OFFSET
print("step<10: ", result)
elif step < 15:
result += (step * config.MATH_OFFSET) / config.MATH_SCALE
print("step<15: ", result)
else:
result = result * config.EXPONENT_BASE % config.MODULO_DIVISOR
print("step>=15: ", result)
step += 1
return result
def BitManipulationMathTest(value: t.CInt) -> t.CInt:
original: t.CInt = value
nibble: t.CInt = 0
result: t.CInt = 0
result = (value << config.SHIFT_AMOUNT) | (value >> (8 - config.SHIFT_AMOUNT))
print("Rotate left: ", result)
result = (value >> config.SHIFT_AMOUNT) | (value << (8 - config.SHIFT_AMOUNT))
print("Rotate right: ", result)
nibble = value & 0xF
print("Lower nibble: ", nibble)
nibble = (value >> config.BIT_RANGE) & 0xF
print("Upper nibble: ", nibble)
result = ((value & config.MASK_VALUE) + config.MATH_OFFSET) * config.MATH_SCALE
print("Masked and scaled: ", result)
result = ((original << config.SHIFT_AMOUNT) ^ original) & config.MASK_VALUE
print("XOR shifted: ", result)
return result