diff --git a/stdlib/mem.jou b/stdlib/mem.jou index 888fd711..890cf53b 100644 --- a/stdlib/mem.jou +++ b/stdlib/mem.jou @@ -2,12 +2,12 @@ # Heap allocations # TODO: write a tutorial about using these and add a link -declare malloc(size: long) -> void* -declare calloc(a: long, b: long) -> void* -declare realloc(ptr: void*, new_size: long) -> void* -declare free(ptr: void*) -> None +declare malloc(size: long) -> void* # allocate memory +declare calloc(a: long, b: long) -> void* # allocate a*b bytes of memory and zero it +declare realloc(ptr: void*, new_size: long) -> void* # grow/shrink allocated memory +declare free(ptr: void*) -> None # release allocated memory so it can be reused -# Fill a memory region with the given byte. +# This function fills a memory region with the given byte. # The most common way use case for this function is zeroing memory: # # memset(&foo, 0, sizeof(foo)) @@ -26,4 +26,13 @@ declare memcpy(dest: void*, source: void*, size: long) -> void* # copy memory, declare memmove(dest: void*, source: void*, size: long) -> void* # copy memory, overlaps are ok # Swaps the contents of two memory regions of the same size. -# This does nothing if the memory regions +# This does nothing if the same memory region is passed twice. +# This may not work correctly if two different but overlapping regions are given. +def memswap(a: void*, b: void*, size: long) -> None: + a_bytes: byte* = a + b_bytes: byte* = b + + for i = 0L; i < size; i++: + old_a = a_bytes[i] + a_bytes[i] = b_bytes[i] + b_bytes[i] = old_a diff --git a/tests/should_succeed/memlibtest.jou b/tests/should_succeed/memlibtest.jou new file mode 100644 index 00000000..3954d80b --- /dev/null +++ b/tests/should_succeed/memlibtest.jou @@ -0,0 +1,15 @@ +import "stdlib/mem.jou" +import "stdlib/io.jou" + + +def main() -> int: + a = 123 + b = 456 + + memswap(&a, &b, sizeof(a)) + printf("%d %d\n", a, b) # Output: 456 123 + + memswap(&a, &a, sizeof(a)) # does nothing + printf("%d %d\n", a, b) # Output: 456 123 + + return 0