Add a test for a generic typed array

This commit is contained in:
Abdelrahman Said 2025-02-08 16:09:25 +00:00
parent 2bc4d3bd5e
commit f95d68f3d2
2 changed files with 77 additions and 7 deletions

View File

@ -1,4 +1,5 @@
from .codegen import test_codegen from .codegen import test_str8, test_typed_array
if __name__ == "__main__": if __name__ == "__main__":
test_codegen() test_str8()
test_typed_array()

View File

@ -12,10 +12,11 @@ from .datatypes import (
CPointerType, CPointerType,
CQualifier, CQualifier,
CInclude, CInclude,
CUserType,
) )
def test_codegen(): def test_str8():
struct = CStruct( struct = CStruct(
name="Str8", name="Str8",
cargs=[ cargs=[
@ -55,7 +56,7 @@ def test_codegen():
) )
header = CHeader( header = CHeader(
name="str.h", name="str",
includes=[ includes=[
CInclude(header="aliases.h", local=True), CInclude(header="aliases.h", local=True),
], ],
@ -64,7 +65,7 @@ def test_codegen():
) )
source = CSource( source = CSource(
name="str.c", name="str",
includes=[ includes=[
CInclude(header=header, local=True), CInclude(header=header, local=True),
CInclude(header="aliases.h", local=True), CInclude(header="aliases.h", local=True),
@ -78,5 +79,73 @@ def test_codegen():
source.save(Path(".")) source.save(Path("."))
if __name__ == "__main__": def test_typed_array():
test_codegen() datatypes = [CType.U8, CType.F32, CType.CHAR]
types: list[CUserType] = []
funcs: list[CFunc] = []
getter_func_body = """\
if(idx >= arr->size) {
return 0;
}
return arr->data[idx];"""
setter_func_body = """\
if(idx >= arr->size) {
return;
}
arr->data[idx] = val;"""
for _type in datatypes:
struct = CStruct(
name=f"Array{str(_type).title()}".strip(),
cargs=[
CArg(name="size", _type=CType.U64),
CArg(name="data", _type=_type, pointer=CPointer(_type=CPointerType.SINGLE)),
],
)
types.append(struct)
funcs.append(CFunc(
name=f"array_{str(_type)}_get",
ret_type=_type,
args=[
CArg(name="arr", _type=struct, pointer=CPointer(_type=CPointerType.SINGLE), qualifier=CQualifier.CONST),
CArg(name="idx", _type=CType.U64),
],
body=getter_func_body,
))
funcs.append(CFunc(
name=f"array_{str(_type)}_set",
ret_type=CType.VOID,
args=[
CArg(name="arr", _type=struct, pointer=CPointer(_type=CPointerType.SINGLE)),
CArg(name="idx", _type=CType.U64),
CArg(name="val", _type=_type)
],
body=setter_func_body,
))
header = CHeader(
name="typed_array",
includes=[
CInclude(header="aliases.h", local=True)
],
types=types,
funcs=funcs
)
source = CSource(
name="typed_array",
includes=[
CInclude(header="aliases.h", local=True),
CInclude(header=header, local=True)
],
funcs=funcs
)
header.save(Path("."))
source.save(Path("."))