86 lines
2.3 KiB
Plaintext
86 lines
2.3 KiB
Plaintext
import t
|
|
import stdio
|
|
import string
|
|
import testcheck
|
|
import win32.win32memory
|
|
|
|
# Define structs
|
|
class Point():
|
|
x: int
|
|
y: int
|
|
|
|
class Rect():
|
|
origin: Point
|
|
size: Point
|
|
|
|
class Node():
|
|
value: int
|
|
next: t.CPtr # Node* type
|
|
|
|
def test_struct_basic():
|
|
testcheck.section("Test 1: struct basic")
|
|
p: Point = Point()
|
|
p.x = 10
|
|
p.y = 20
|
|
testcheck.check(p.x == 10 and p.y == 20, "struct basic (x=10 y=20)", "struct basic (x y expect 10 20)")
|
|
|
|
def test_struct_nested():
|
|
testcheck.section("Test 2: struct nested")
|
|
r: Rect = Rect()
|
|
r.origin.x = 1
|
|
r.origin.y = 2
|
|
r.size.x = 100
|
|
r.size.y = 200
|
|
testcheck.check(r.origin.x == 1 and r.origin.y == 2 and r.size.x == 100 and r.size.y == 200, "struct nested (origin=1,2 size=100,200)", "struct nested (mismatch)")
|
|
|
|
def test_struct_pointer():
|
|
testcheck.section("Test 3: struct pointer")
|
|
p: Point = Point()
|
|
p.x = 42
|
|
p.y = 84
|
|
# Take a struct pointer
|
|
pp: Point* = t.CPtr(uint64(p))
|
|
# Modify through the pointer
|
|
pp.x = 100
|
|
pp.y = 200
|
|
# Check whether the original struct changed
|
|
testcheck.check(p.x == 100 and p.y == 200, "struct pointer (x=100 y=200)", "struct pointer (x y expect 100 200)")
|
|
|
|
def test_struct_param():
|
|
testcheck.section("Test 4: struct as parameter")
|
|
p: Point = Point()
|
|
p.x = 5
|
|
p.y = 15
|
|
sum_val: int = point_sum(p)
|
|
testcheck.check(sum_val == 20, "struct param (sum=20)", "struct param (sum expect 20)")
|
|
|
|
def point_sum(p: Point) -> int:
|
|
return p.x + p.y
|
|
|
|
def test_struct_array():
|
|
testcheck.section("Test 5: struct array")
|
|
# Allocate a struct array
|
|
buf: uint8* = win32.win32memory.VirtualAlloc(None, 256, 12288, 4)
|
|
if uint64(buf) == 0:
|
|
stdio.printf("SKIP: VirtualAlloc returned NULL\n")
|
|
return
|
|
string.memset(buf, 0, 256)
|
|
# Reinterpret the buffer as a Point array
|
|
pts: Point* = (Point*)(buf)
|
|
pts[0].x = 1
|
|
pts[0].y = 2
|
|
pts[1].x = 3
|
|
pts[1].y = 4
|
|
total: int = pts[0].x + pts[0].y + pts[1].x + pts[1].y
|
|
testcheck.check(total == 10, "struct array (total=10)", "struct array (total expect 10)")
|
|
|
|
|
|
def main() -> int:
|
|
testcheck.begin("StructTest: 结构体操作基准测试")
|
|
test_struct_basic()
|
|
test_struct_nested()
|
|
test_struct_pointer()
|
|
test_struct_param()
|
|
test_struct_array()
|
|
return testcheck.end()
|